diff options
author | Bart Visscher <bartv@thisnet.nl> | 2012-08-11 00:43:26 +0200 |
---|---|---|
committer | Bart Visscher <bartv@thisnet.nl> | 2012-08-11 00:43:26 +0200 |
commit | c2160433cd171a25c0ddb92959b8ae986d8aaf78 (patch) | |
tree | e14d147438204a593e9d78a59f677759b589df3d /lib | |
parent | 87d1cdb94567d5514e0a2988f69935d932b58ff6 (diff) | |
parent | d3427be5e40b8889fd2b23b9f716e596de29694b (diff) | |
download | nextcloud-server-c2160433cd171a25c0ddb92959b8ae986d8aaf78.tar.gz nextcloud-server-c2160433cd171a25c0ddb92959b8ae986d8aaf78.zip |
Merge branch 'master' into routing
Conflicts:
lib/base.php
Diffstat (limited to 'lib')
43 files changed, 1553 insertions, 282 deletions
diff --git a/lib/app.php b/lib/app.php index 56132c08671..1c91818ca75 100755 --- a/lib/app.php +++ b/lib/app.php @@ -183,7 +183,7 @@ class OC_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)){ - OC_Installer::installShippedApp($app); + $app = OC_Installer::installShippedApp($app); }else{ $download=OC_OCSClient::getApplicationDownload($app,1); if(isset($download['downloadlink']) and $download['downloadlink']!='') { @@ -205,6 +205,7 @@ class OC_App{ }else{ return false; } + return $app; } /** @@ -298,10 +299,15 @@ class OC_App{ // settings menu $settings[]=array( "id" => "settings", "order" => 1000, "href" => OC_Helper::linkTo( "settings", "settings.php" ), "name" => $l->t("Settings"), "icon" => OC_Helper::imagePath( "settings", "settings.svg" )); - // if the user is an admin - if(OC_Group::inGroup( $_SESSION["user_id"], "admin" )) { + //SubAdmins are also allowed to access user management + 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" )); + } + + + // if the user is an admin + if(OC_Group::inGroup( $_SESSION["user_id"], "admin" )) { // admin apps menu $settings[] = array( "id" => "core_apps", "order" => 3, "href" => OC_Helper::linkTo( "settings", "apps.php" ).'?installed', "name" => $l->t("Apps"), "icon" => OC_Helper::imagePath( "settings", "apps.svg" )); @@ -389,7 +395,7 @@ class OC_App{ return trim($version); }else{ $appData=self::getAppInfo($appid); - return $appData['version']; + return isset($appData['version'])? $appData['version'] : ''; } } diff --git a/lib/backgroundjob/queuedtask.php b/lib/backgroundjob/queuedtask.php new file mode 100644 index 00000000000..da5d4ddc694 --- /dev/null +++ b/lib/backgroundjob/queuedtask.php @@ -0,0 +1,104 @@ +<?php +/** +* ownCloud +* +* @author Jakob Sack +* @copyright 2012 Jakob Sack owncloud@jakobsack.de +* +* 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/>. +* +*/ + +/** + * This class manages our queued tasks. + */ +class OC_BackgroundJob_QueuedTask{ + /** + * @brief Gets one queued task + * @param $id ID of the task + * @return associative array + */ + public static function find( $id ){ + $stmt = OC_DB::prepare( 'SELECT * FROM *PREFIX*queuedtasks WHERE id = ?' ); + $result = $stmt->execute(array($id)); + return $result->fetchRow(); + } + + /** + * @brief Gets all queued tasks + * @return array with associative arrays + */ + 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()){ + $return[] = $row; + } + + return $return; + } + + /** + * @brief Gets all queued tasks of a specific app + * @param $app app name + * @return array with associative arrays + */ + 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()){ + $return[] = $row; + } + + // Und weg damit + return $return; + } + + /** + * @brief queues a task + * @param $app app name + * @param $klass class name + * @param $method method name + * @param $parameters all useful data as text + * @return id of task + */ + public static function add( $task, $klass, $method, $parameters ){ + $stmt = OC_DB::prepare( 'INSERT INTO *PREFIX*queuedtasks (app, klass, method, parameters) VALUES(?,?,?,?)' ); + $result = $stmt->execute(array($app, $klass, $method, $parameters, time)); + + return OC_DB::insertid(); + } + + /** + * @brief deletes a queued task + * @param $id id of task + * @return true/false + * + * Deletes a report + */ + public static function delete( $id ){ + $stmt = OC_DB::prepare( 'DELETE FROM *PREFIX*queuedtasks WHERE id = ?' ); + $result = $stmt->execute(array($id)); + + return true; + } +} diff --git a/lib/backgroundjob/regulartask.php b/lib/backgroundjob/regulartask.php new file mode 100644 index 00000000000..53bd4eb5e9b --- /dev/null +++ b/lib/backgroundjob/regulartask.php @@ -0,0 +1,52 @@ +<?php +/** +* ownCloud +* +* @author Jakob Sack +* @copyright 2012 Jakob Sack owncloud@jakobsack.de +* +* 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/>. +* +*/ + +/** + * This class manages the regular tasks. + */ +class OC_BackgroundJob_RegularTask{ + static private $registered = array(); + + /** + * @brief creates a regular task + * @param $klass class name + * @param $method method name + * @return true + */ + static public function register( $klass, $method ){ + // Create the data structure + self::$registered["$klass-$method"] = array( $klass, $method ); + + // No chance for failure ;-) + return true; + } + + /** + * @brief gets all regular tasks + * @return associative array + * + * key is string "$klass-$method", value is array( $klass, $method ) + */ + static public function all(){ + return self::$registered; + } +} diff --git a/lib/backgroundjob/worker.php b/lib/backgroundjob/worker.php new file mode 100644 index 00000000000..b4f0429b319 --- /dev/null +++ b/lib/backgroundjob/worker.php @@ -0,0 +1,118 @@ +<?php +/** +* ownCloud +* +* @author Jakob Sack +* @copyright 2012 Jakob Sack owncloud@jakobsack.de +* +* 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/>. +* +*/ + +/** + * This class does the dirty work. + * + * TODO: locking in doAllSteps + */ +class OC_BackgroundJob_Worker{ + /** + * @brief executes all tasks + * @return boolean + * + * This method executes all regular tasks and then all queued tasks. + * This method should be called by cli scripts that do not let the user + * wait. + */ + 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 ){ + // Set "restart here" config value + OC_Appconfig::setValue( 'core', 'backgroundjobs_task', $key ); + call_user_func( $value ); + } + } + // Reset "start here" config value + OC_Appconfig::setValue( 'core', 'backgroundjobs_task', '' ); + + // Do our queued tasks + $queued_tasks = OC_BackgroundJob_QueuedTask::all(); + foreach( $queued_tasks as $task ){ + OC_BackgroundJob_QueuedTask::delete( $task['id'] ); + call_user_func( array( $task['klass'], $task['method'] ), $task['parameters'] ); + } + + return true; + } + + /** + * @brief does a single task + * @return boolean + * + * This method executes one task. It saves the last state and continues + * with the next step. This method should be used by webcron and ajax + * services. + */ + public static function doNextStep(){ + $laststep = OC_Appconfig::getValue( 'core', 'backgroundjobs_step', 'regular_tasks' ); + + if( $laststep == 'regular_tasks' ){ + // get last app + $lasttask = OC_Appconfig::getValue( 'core', 'backgroundjobs_task', '' ); + + // What's the next step? + $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 ){ + OC_Appconfig::setValue( 'core', 'backgroundjobs_task', $key ); + $done = true; + call_user_func( $value ); + break; + } + } + + 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 )){ + $task = $tasks[0]; + // delete job before we execute it. This prevents endless loops + // of failing jobs. + OC_BackgroundJob_QueuedTask::delete($task['id']); + + // execute job + call_user_func( array( $task['klass'], $task['method'] ), $task['parameters'] ); + } + else{ + // Next time load queued tasks + OC_Appconfig::setValue( 'core', 'backgroundjobs_step', 'regular_tasks' ); + OC_Appconfig::setValue( 'core', 'backgroundjobs_task', '' ); + } + } + + return true; + } +} diff --git a/lib/base.php b/lib/base.php index 0d9ececc0c9..b276cf5924d 100644 --- a/lib/base.php +++ b/lib/base.php @@ -116,7 +116,8 @@ class OC{ 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]!=='/'){ OC::$WEBROOT='/'.OC::$WEBROOT; @@ -179,11 +180,25 @@ 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){ - $url = 'http://'.$_SERVER['SERVER_NAME'].OC::$WEBROOT.'/index.php'; - header("Location: $url"); + if (!OC_Config::getValue('installed', false)) { + if (OC::$SUBURI != '/index.php') { + if(!OC::$CLI){ + $url = 'http://'.$_SERVER['SERVER_NAME'].OC::$WEBROOT.'/index.php'; + header("Location: $url"); + } + exit(); } + // 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 ); + $_POST['install'] = 'true'; + $_POST = array_merge ($_POST, $AUTOCONFIG); + unlink($autosetup_file); + } + OC_Util::addScript('setup'); + require_once('setup.php'); exit(); } } @@ -192,8 +207,8 @@ class OC{ // redirect to https site if configured if( OC_Config::getValue( "forcessl", false )){ ini_set("session.cookie_secure", "on"); - if(OC_Helper::serverProtocol()<>'https' and !OC::$CLI) { - $url = "https://". OC_Helper::serverHost() . $_SERVER['REQUEST_URI']; + if(OC_Request::serverProtocol()<>'https' and !OC::$CLI) { + $url = "https://". OC_Request::serverHost() . $_SERVER['REQUEST_URI']; header("Location: $url"); exit(); } @@ -239,6 +254,13 @@ class OC{ OC_Util::addScript( "config" ); //OC_Util::addScript( "multiselect" ); OC_Util::addScript('search','result'); + + 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" ); @@ -250,31 +272,6 @@ class OC{ session_start(); } - public static function loadapp(){ - if(file_exists(OC_App::getAppPath(OC::$REQUESTEDAPP) . '/index.php')){ - require_once(OC_App::getAppPath(OC::$REQUESTEDAPP) . '/index.php'); - }else{ - trigger_error('The requested App was not found.', E_USER_ERROR);//load default app instead? - } - } - - public static function loadfile(){ - if(file_exists(OC_App::getAppPath(OC::$REQUESTEDAPP) . '/' . OC::$REQUESTEDFILE)){ - if(substr(OC::$REQUESTEDFILE, -3) == 'css'){ - $file = OC_App::getAppWebPath(OC::$REQUESTEDAPP). '/' . OC::$REQUESTEDFILE; - $minimizer = new OC_Minimizer_CSS(); - $minimizer->output(array(array(OC_App::getAppPath(OC::$REQUESTEDAPP), OC_App::getAppWebPath(OC::$REQUESTEDAPP), OC::$REQUESTEDFILE)),$file); - exit; - }elseif(substr(OC::$REQUESTEDFILE, -3) == 'php'){ - require_once(OC_App::getAppPath(OC::$REQUESTEDAPP). '/' . OC::$REQUESTEDFILE); - } - }else{ - die(); - header('HTTP/1.0 404 Not Found'); - exit; - } - } - public static function getRouter() { if (!isset(OC::$router)) { OC::$router = new OC_Router(); @@ -347,10 +344,10 @@ class OC{ stream_wrapper_register('static', 'OC_StaticStreamWrapper'); stream_wrapper_register('close', 'OC_CloseStreamWrapper'); + self::initTemplateEngine(); self::checkInstalled(); self::checkSSL(); self::initSession(); - self::initTemplateEngine(); self::checkUpgrade(); $errors=OC_Util::checkServer(); @@ -389,7 +386,7 @@ class OC{ 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){ $app = substr(self::$REQUESTEDAPP, 0, strpos(self::$REQUESTEDAPP, '?')); - $param = substr(self::$REQUESTEDAPP, strpos(self::$REQUESTEDAPP, '?') + 1); + $param = substr($_GET['app'], strpos($_GET['app'], '?') + 1); parse_str($param, $get); $_GET = array_merge($_GET, $get); self::$REQUESTEDAPP = $app; @@ -414,12 +411,154 @@ class OC{ } } } + + /** + * @brief Handle the request + */ + public static function handleRequest() { + // Handle WebDAV + if($_SERVER['REQUEST_METHOD']=='PROPFIND'){ + header('location: '.OC_Helper::linkToRemote('webdav')); + return; + } + // Handle app css files + if(substr(OC::$REQUESTEDFILE,-3) == 'css') { + self::loadCSSFile(); + return; + } + // Someone is logged in : + if(OC_User::isLoggedIn()) { + OC_App::loadApps(); + if(isset($_GET["logout"]) and ($_GET["logout"])) { + OC_User::logout(); + header("Location: ".OC::$WEBROOT.'/'); + }else{ + $app = OC::$REQUESTEDAPP; + $file = OC::$REQUESTEDFILE; + if(is_null($file)) { + $file = 'index.php'; + } + $file_ext = substr($file, -3); + if ($file_ext != 'php' + || !self::loadAppScriptFile($app, $file)) { + header('HTTP/1.0 404 Not Found'); + } + } + return; + } + // Not handled and not logged in + self::handleLogin(); + } + + protected static function loadAppScriptFile($app, $file) { + $app_path = OC_App::getAppPath($app); + $file = $app_path . '/' . $file; + unset($app, $app_path); + if (file_exists($file)) { + require_once($file); + return true; + } + return false; + } + + protected static function loadCSSFile() { + $app = OC::$REQUESTEDAPP; + $file = OC::$REQUESTEDFILE; + $app_path = OC_App::getAppPath($app); + if (file_exists($app_path . '/' . $file)) { + $app_web_path = OC_App::getAppWebPath($app); + $filepath = $app_web_path . '/' . $file; + $minimizer = new OC_Minimizer_CSS(); + $info = array($app_path, $app_web_path, $file); + $minimizer->output(array($info), $filepath); + } + } + + protected static function handleLogin() { + OC_App::loadApps(array('prelogin')); + $error = false; + // remember was checked after last login + if (OC::tryRememberLogin()) { + // nothing more to do + + // 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; + } + OC_Util::displayLoginPage($error); + } + + protected static function tryRememberLogin() { + if(!isset($_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); + } + // 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_User::setUserId($_COOKIE['oc_username']); + OC_Util::redirectToDefaultPage(); + } + else { + OC_User::unsetMagicInCookie(); + } + return true; + } + + protected static function tryFormLogin() { + if(!isset($_POST["user"]) + || !isset($_POST['password']) + || !isset($_SESSION['sectoken']) + || !isset($_POST['sectoken']) + || ($_SESSION['sectoken']!=$_POST['sectoken']) ) { + return false; + } + OC_App::loadApps(); + if(OC_User::login($_POST["user"], $_POST["password"])) { + if(!empty($_POST["remember_login"])){ + if(defined("DEBUG") && 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); + OC_User::setMagicInCookie($_POST["user"], $token); + } + else { + OC_User::unsetMagicInCookie(); + } + OC_Util::redirectToDefaultPage(); + } + return true; + } + + protected static function tryBasicAuthLogin() { + if (!isset($_SERVER["PHP_AUTH_USER"]) + || !isset($_SERVER["PHP_AUTH_PW"])){ + return false; + } + OC_App::loadApps(array('authentication')); + 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']:''); + OC_Util::redirectToDefaultPage(); + } + return true; + } + } // define runtime variables - unless this already has been done -if( !isset( $RUNTIME_NOSETUPFS )){ - $RUNTIME_NOSETUPFS = false; -} if( !isset( $RUNTIME_NOAPPS )){ $RUNTIME_NOAPPS = false; } diff --git a/lib/connector/sabre/directory.php b/lib/connector/sabre/directory.php index 0842fc4fc65..09c65f19b80 100644 --- a/lib/connector/sabre/directory.php +++ b/lib/connector/sabre/directory.php @@ -48,11 +48,23 @@ class OC_Connector_Sabre_Directory extends OC_Connector_Sabre_Node implements Sa * @return null|string */ public function createFile($name, $data = null) { + if (isset($_SERVER['HTTP_OC_CHUNKED'])) { + $info = OC_FileChunking::decodeName($name); + $chunk_handler = new OC_FileChunking($info); + $chunk_handler->store($info['index'], $data); + if ($chunk_handler->isComplete()) { + $newPath = $this->path . '/' . $info['name']; + $f = OC_Filesystem::fopen($newPath, 'w'); + $chunk_handler->assemble($f); + return OC_Connector_Sabre_Node::getETagPropertyForPath($newPath); + } + } else { + $newPath = $this->path . '/' . $name; + OC_Filesystem::file_put_contents($newPath,$data); + return OC_Connector_Sabre_Node::getETagPropertyForPath($newPath); + } - $newPath = $this->path . '/' . $name; - OC_Filesystem::file_put_contents($newPath,$data); - - return OC_Connector_Sabre_Node::getETagPropertyForFile($newPath); + return null; } /** @@ -170,5 +182,25 @@ class OC_Connector_Sabre_Directory extends OC_Connector_Sabre_Node implements Sa } + /** + * Returns a list of properties for this nodes.; + * + * The properties list is a list of propertynames the client requested, + * encoded as xmlnamespace#tagName, for example: + * http://www.example.org/namespace#author + * If the array is empty, all properties should be returned + * + * @param array $properties + * @return void + */ + 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); + } + return $props; + } } diff --git a/lib/connector/sabre/file.php b/lib/connector/sabre/file.php index 80f0a0ab4d8..9d571fceb0d 100644 --- a/lib/connector/sabre/file.php +++ b/lib/connector/sabre/file.php @@ -47,7 +47,7 @@ class OC_Connector_Sabre_File extends OC_Connector_Sabre_Node implements Sabre_D OC_Filesystem::file_put_contents($this->path,$data); - return OC_Connector_Sabre_Node::getETagPropertyForFile($this->path); + return OC_Connector_Sabre_Node::getETagPropertyForPath($this->path); } /** @@ -98,7 +98,16 @@ class OC_Connector_Sabre_File extends OC_Connector_Sabre_Node implements Sabre_D if (isset($properties[self::GETETAG_PROPERTYNAME])) { return $properties[self::GETETAG_PROPERTYNAME]; } - return $this->getETagPropertyForFile($this->path); + return $this->getETagPropertyForPath($this->path); + } + + /** + * Creates a ETag for this path. + * @param string $path Path of the file + * @return string|null Returns null if the ETag can not effectively be determined + */ + static protected function createETag($path) { + return OC_Filesystem::hash('md5', $path); } /** diff --git a/lib/connector/sabre/locks.php b/lib/connector/sabre/locks.php index e95dcf02d27..1db4fc09446 100644 --- a/lib/connector/sabre/locks.php +++ b/lib/connector/sabre/locks.php @@ -41,8 +41,11 @@ class OC_Connector_Sabre_Locks extends Sabre_DAV_Locks_Backend_Abstract { // NOTE: the following 10 lines or so could be easily replaced by // pure sql. MySQL's non-standard string concatination prevents us // from doing this though. - $query = 'SELECT * FROM *PREFIX*locks WHERE userid = ? AND (created + timeout) > ? AND ((uri = ?)'; - $params = array(OC_User::getUser(),time(),$uri); + // NOTE: SQLite requires time() to be inserted directly. That's ugly + // 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); // We need to check locks for every part in the uri. $uriParts = explode('/',$uri); @@ -70,8 +73,8 @@ class OC_Connector_Sabre_Locks extends Sabre_DAV_Locks_Backend_Abstract { } $query.=')'; - $stmt = OC_DB::prepare($query); - $result = $stmt->execute($params); + $stmt = OC_DB::prepare($query ); + $result = $stmt->execute( $params ); $lockList = array(); while( $row = $result->fetchRow()){ diff --git a/lib/connector/sabre/node.php b/lib/connector/sabre/node.php index 663970487fb..f268f8b57c4 100644 --- a/lib/connector/sabre/node.php +++ b/lib/connector/sabre/node.php @@ -204,12 +204,21 @@ abstract class OC_Connector_Sabre_Node implements Sabre_DAV_INode, Sabre_DAV_IPr } /** + * Creates a ETag for this path. + * @param string $path Path of the file + * @return string|null Returns null if the ETag can not effectively be determined + */ + static protected function createETag($path) { + return uniqid('', true); + } + + /** * Returns the ETag surrounded by double-quotes for this path. * @param string $path Path of the file * @return string|null Returns null if the ETag can not effectively be determined */ - static public function getETagPropertyForFile($path) { - $tag = OC_Filesystem::hash('md5', $path); + static public function getETagPropertyForPath($path) { + $tag = self::createETag($path); if (empty($tag)) { return null; } @@ -223,8 +232,24 @@ abstract class OC_Connector_Sabre_Node implements Sabre_DAV_INode, Sabre_DAV_IPr * Remove the ETag from the cache. * @param string $path Path of the file */ - static public function removeETagPropertyForFile($path) { - $query = OC_DB::prepare( 'DELETE FROM *PREFIX*properties WHERE userid = ? AND propertypath = ? AND propertyname = ?' ); - $query->execute( array( OC_User::getUser(), $path, self::GETETAG_PROPERTYNAME )); + static public function removeETagPropertyForPath($path) { + // remove tags from this and parent paths + $paths = array(); + while ($path != '/' && $path != '') { + $paths[] = $path; + $path = dirname($path); + } + if (empty($paths)) { + return; + } + $paths[] = $path; + $path_placeholders = join(',', array_fill(0, count($paths), '?')); + $query = OC_DB::prepare( 'DELETE FROM *PREFIX*properties' + .' WHERE userid = ?' + .' AND propertyname = ?' + .' AND propertypath IN ('.$path_placeholders.')' + ); + $vals = array( OC_User::getUser(), self::GETETAG_PROPERTYNAME ); + $query->execute(array_merge( $vals, $paths )); } } diff --git a/lib/db.php b/lib/db.php index 6971fe4a583..f1928e68236 100644 --- a/lib/db.php +++ b/lib/db.php @@ -43,7 +43,7 @@ class OC_DB { */ private static function getDBBackend(){ $backend=self::BACKEND_MDB2; - if(class_exists('PDO') && OC_Config::getValue('installed', false)){//check if we can use PDO, else use MDB2 (instalation always needs to be done my mdb2) + 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) $type = OC_Config::getValue( "dbtype", "sqlite" ); if($type=='sqlite3') $type='sqlite'; $drivers=PDO::getAvailableDrivers(); diff --git a/lib/exception.php b/lib/exception.php deleted file mode 100644 index db516fc12d2..00000000000 --- a/lib/exception.php +++ /dev/null @@ -1,93 +0,0 @@ -<?php -/** - * ownCloud - * - * @author Georg Ehrke - * @copyright 2012 georg@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_Exception extends Exception{ - - function __construct($message = null, $code = 0, $file = null, $line = null){ - parent::__construct($message, $code); - if(!is_null($file)){ - $this->file = $file; - } - if(!is_null($line)){ - $this->line = $line; - } - $this->writelog(); - } - - private function writelog(){ - @OC_Log::write(OC_App::getCurrentApp(), $this->getMessage() . '-' . $this->getFile() . '-' . $this->getLine(), OC_Log::FATAL); - } - - private function generatesysinfo(){ - return array('phpversion' => PHP_VERSION, - 'os' => php_uname('s'), - 'osrelease' => php_uname('r'), - 'osarchitecture' => php_uname('m'), - 'phpserverinterface' => php_sapi_name(), - 'serverprotocol' => $_SERVER['SERVER_PROTOCOL'], - 'requestmethod' => $_SERVER['REQUEST_METHOD'], - 'https' => ($_SERVER['HTTPS']==''?'false':'true'), - 'database'=>(@OC_Config::getValue('dbtype')!=''?@OC_Config::getValue('dbtype'):'') - ); - } - - function __toString(){ - $tmpl = new OC_Template('core', 'exception', 'guest'); - $tmpl->assign('showsysinfo', true); - $tmpl->assign('message', $this->getMessage()); - $tmpl->assign('code', $this->getCode()); - $tmpl->assign('file', $this->getFile()); - $tmpl->assign('line', $this->getLine()); - $tmpl->assign('sysinfo', $this->generatesysinfo()); - $tmpl->printPage(); - } -} - -function oc_exceptionhandler($exception){ - switch($exception->getCode()){ - case E_NOTICE: - case E_DEPRECATED: - case E_USER_NOTICE: - case E_USER_DEPRECATED: - break; - default: - throw new OC_Exception($exception->getMessage(), $exception->getCode(), $exception->getFile(), $exception->getLine()); - break; - } - return true; -} - -function oc_errorhandler($errno , $errstr , $errfile , $errline){ - switch($errno){ - case E_NOTICE: - case E_DEPRECATED: - case E_USER_NOTICE: - case E_USER_DEPRECATED: - break; - default: - throw new OC_Exception($errstr, $errno, $errfile, $errline); - break; - } - return true; -} -set_exception_handler('oc_exceptionhandler'); -set_error_handler('oc_errorhandler'); -error_reporting(E_ERROR | E_WARNING | E_PARSE);
\ No newline at end of file diff --git a/lib/filecache.php b/lib/filecache.php index 22f7427ae42..e8b17e254e1 100644 --- a/lib/filecache.php +++ b/lib/filecache.php @@ -65,19 +65,27 @@ class OC_FileCache{ if($root===false){ $root=OC_Filesystem::getRoot(); } - $path=$root.$path; - $parent=self::getParentId($path); - $id=self::getId($path,''); - if(isset(OC_FileCache_Cached::$savedData[$path])){ - $data=array_merge(OC_FileCache_Cached::$savedData[$path],$data); - unset(OC_FileCache_Cached::$savedData[$path]); + $fullpath=$root.$path; + $parent=self::getParentId($fullpath); + $id=self::getId($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){ 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 - OC_FileCache_Cached::$savedData[$path]=$data; + OC_FileCache_Cached::$savedData[$fullpath]=$data; return; } if(!isset($data['encrypted'])){ @@ -94,13 +102,13 @@ class OC_FileCache{ $data['versioned']=(int)$data['versioned']; $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($path),$path,md5($path),$data['size'],$data['mtime'],$data['ctime'],$data['mimetype'],$mimePart,$user,$data['writable'],$data['encrypted'],$data['versioned'])); + $result=$query->execute(array($parent,basename($fullpath),$fullpath,md5($fullpath),$data['size'],$data['mtime'],$data['ctime'],$data['mimetype'],$mimePart,$user,$data['writable'],$data['encrypted'],$data['versioned'])); if(OC_DB::isError($result)){ - OC_Log::write('files','error while writing file('.$path.') to cache',OC_Log::ERROR); + OC_Log::write('files','error while writing file('.$fullpath.') to cache',OC_Log::ERROR); } if($cache=OC_Cache::getUserCache(true)){ - $cache->remove('fileid/'.$path);//ensure we don't have -1 cached + $cache->remove('fileid/'.$fullpath);//ensure we don't have -1 cached } } @@ -343,7 +351,7 @@ class OC_FileCache{ * @param string $path * @param OC_EventSource $enventSource (optional) * @param int count (optional) - * @param string root (optionak) + * @param string root (optional) */ public static function scan($path,$eventSource=false,&$count=0,$root=false){ if($eventSource){ diff --git a/lib/filecache/update.php b/lib/filecache/update.php index 93b632acb4e..0b5ff8e2446 100644 --- a/lib/filecache/update.php +++ b/lib/filecache/update.php @@ -152,8 +152,8 @@ class OC_FileCache_Update{ $size=0; $cached=OC_FileCache_Cached::get($path,$root); $cachedSize=isset($cached['size'])?$cached['size']:0; - - if($mimetype=='httpd/unix-directory'){ + + if($view->is_dir($path.'/')){ if(OC_FileCache::inCache($path,$root)){ $cachedContent=OC_FileCache_Cached::getFolderContent($path,$root); foreach($cachedContent as $file){ diff --git a/lib/filechunking.php b/lib/filechunking.php new file mode 100644 index 00000000000..d03af226d8b --- /dev/null +++ b/lib/filechunking.php @@ -0,0 +1,94 @@ +<?php +/** + * Copyright (c) 2012 Bart Visscher <bartv@thisnet.nl> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + + +class OC_FileChunking { + protected $info; + protected $cache; + + static public function decodeName($name) { + preg_match('/(?P<name>.*)-chunking-(?P<transferid>\d+)-(?P<chunkcount>\d+)-(?P<index>\d+)/', $name, $matches); + return $matches; + } + + public function __construct($info) { + $this->info = $info; + } + + public function getPrefix() { + $name = $this->info['name']; + $transferid = $this->info['transferid']; + + return $name.'-chunking-'.$transferid.'-'; + } + + protected function getCache() { + if (!isset($this->cache)) { + $this->cache = new OC_Cache_File(); + } + return $this->cache; + } + + public function store($index, $data) { + $cache = $this->getCache(); + $name = $this->getPrefix().$index; + $cache->set($name, $data); + } + + public function isComplete() { + $prefix = $this->getPrefix(); + $parts = 0; + $cache = $this->getCache(); + for($i=0; $i < $this->info['chunkcount']; $i++) { + if ($cache->hasKey($prefix.$i)) { + $parts ++; + } + } + return $parts == $this->info['chunkcount']; + } + + public function assemble($f) { + $cache = $this->getCache(); + $prefix = $this->getPrefix(); + for($i=0; $i < $this->info['chunkcount']; $i++) { + $chunk = $cache->get($prefix.$i); + $cache->remove($prefix.$i); + fwrite($f,$chunk); + } + fclose($f); + } + + public function signature_split($orgfile, $input) { + $info = unpack('n', fread($input, 2)); + $blocksize = $info[1]; + $this->info['transferid'] = mt_rand(); + $count = 0; + $needed = array(); + $cache = $this->getCache(); + $prefix = $this->getPrefix(); + while (!feof($orgfile)) { + $new_md5 = fread($input, 16); + if (feof($input)) { + break; + } + $data = fread($orgfile, $blocksize); + $org_md5 = md5($data, true); + if ($org_md5 == $new_md5) { + $cache->set($prefix.$count, $data); + } else { + $needed[] = $count; + } + $count++; + } + return array( + 'transferid' => $this->info['transferid'], + 'needed' => $needed, + 'count' => $count, + ); + } +} diff --git a/lib/filestorage.php b/lib/filestorage.php index e786127d525..fd4ad36530e 100644 --- a/lib/filestorage.php +++ b/lib/filestorage.php @@ -45,7 +45,7 @@ abstract class OC_Filestorage{ abstract public function copy($path1,$path2); abstract public function fopen($path,$mode); abstract public function getMimeType($path); - abstract public function hash($type,$path,$raw); + abstract public function hash($type,$path,$raw = false); abstract public function free_space($path); abstract public function search($query); abstract public function touch($path, $mtime=null); diff --git a/lib/filestorage/common.php b/lib/filestorage/common.php index fd389d3e2d7..c77df38e6b1 100644 --- a/lib/filestorage/common.php +++ b/lib/filestorage/common.php @@ -195,7 +195,7 @@ abstract class OC_Filestorage_Common extends OC_Filestorage { unlink($tmpFile); return $mime; } - public function hash($type,$path,$raw){ + public function hash($type,$path,$raw = false){ $tmpFile=$this->getLocalFile(); $hash=hash($type,$tmpFile,$raw); unlink($tmpFile); diff --git a/lib/filesystem.php b/lib/filesystem.php index a5edcf5bab3..47626c05ae2 100644 --- a/lib/filesystem.php +++ b/lib/filesystem.php @@ -452,8 +452,8 @@ class OC_Filesystem{ static public function getMimeType($path){ return self::$defaultInstance->getMimeType($path); } - static public function hash($type,$path){ - return self::$defaultInstance->hash($type,$path); + static public function hash($type,$path, $raw = false){ + return self::$defaultInstance->hash($type,$path, $raw); } static public function free_space($path='/'){ @@ -474,8 +474,12 @@ class OC_Filesystem{ } static public function removeETagHook($params) { - $path=$params['path']; - OC_Connector_Sabre_Node::removeETagPropertyForFile($path); + if (isset($params['path'])) { + $path=$params['path']; + } else { + $path=$params['oldpath']; + } + OC_Connector_Sabre_Node::removeETagPropertyForPath($path); } } OC_Hook::connect('OC_Filesystem','post_write', 'OC_Filesystem','removeETagHook'); diff --git a/lib/filesystemview.php b/lib/filesystemview.php index 9beda01e5a1..faf3f0bd4cc 100644 --- a/lib/filesystemview.php +++ b/lib/filesystemview.php @@ -223,49 +223,54 @@ class OC_FilesystemView { } public function file_put_contents($path, $data) { if(is_resource($data)) {//not having to deal with streams in file_put_contents makes life easier - $exists = $this->file_exists($path); - $run = true; - if(!$exists) { + $absolutePath = $this->getAbsolutePath($path); + if (OC_FileProxy::runPreProxies('file_put_contents', $absolutePath, $data) && OC_Filesystem::isValidPath($path)) { + $path = $this->getRelativePath($absolutePath); + $exists = $this->file_exists($path); + $run = true; + if(!$exists) { + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + OC_Filesystem::signal_create, + array( + OC_Filesystem::signal_param_path => $path, + OC_Filesystem::signal_param_run => &$run + ) + ); + } OC_Hook::emit( OC_Filesystem::CLASSNAME, - OC_Filesystem::signal_create, + OC_Filesystem::signal_write, array( OC_Filesystem::signal_param_path => $path, OC_Filesystem::signal_param_run => &$run ) ); - } - OC_Hook::emit( - OC_Filesystem::CLASSNAME, - OC_Filesystem::signal_write, - array( - OC_Filesystem::signal_param_path => $path, - OC_Filesystem::signal_param_run => &$run - ) - ); - if(!$run) { - return false; - } - $target=$this->fopen($path, 'w'); - if($target) { - $count=OC_Helper::streamCopy($data, $target); - fclose($target); - fclose($data); - if(!$exists) { + if(!$run) { + return false; + } + $target=$this->fopen($path, 'w'); + if($target) { + $count=OC_Helper::streamCopy($data, $target); + fclose($target); + fclose($data); + if(!$exists) { + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + OC_Filesystem::signal_post_create, + array( OC_Filesystem::signal_param_path => $path) + ); + } OC_Hook::emit( OC_Filesystem::CLASSNAME, - OC_Filesystem::signal_post_create, + OC_Filesystem::signal_post_write, array( OC_Filesystem::signal_param_path => $path) ); + OC_FileProxy::runPostProxies('file_put_contents', $absolutePath, $count); + return $count > 0; + }else{ + return false; } - OC_Hook::emit( - OC_Filesystem::CLASSNAME, - OC_Filesystem::signal_post_write, - array( OC_Filesystem::signal_param_path => $path) - ); - return $count > 0; - }else{ - return false; } }else{ return $this->basicOperation('file_put_contents', $path, array('create', 'write'), $data); @@ -465,8 +470,27 @@ class OC_FilesystemView { public function getMimeType($path) { return $this->basicOperation('getMimeType', $path); } - public function hash($type, $path) { - return $this->basicOperation('hash', $path, array('read'), $type); + public function hash($type, $path, $raw = false) { + $absolutePath = $this->getAbsolutePath($path); + if (OC_FileProxy::runPreProxies('hash', $absolutePath) && OC_Filesystem::isValidPath($path)) { + $path = $this->getRelativePath($absolutePath); + if ($path == null) { + return false; + } + if (OC_Filesystem::$loaded && $this->fakeRoot == OC_Filesystem::getRoot()) { + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + OC_Filesystem::signal_read, + array( OC_Filesystem::signal_param_path => $path) + ); + } + if ($storage = $this->getStorage($path)) { + $result = $storage->hash($type, $this->getInternalPath($path), $raw); + $result = OC_FileProxy::runPostProxies('hash', $absolutePath, $result); + return $result; + } + } + return null; } public function free_space($path='/') { diff --git a/lib/group.php b/lib/group.php index 12e5f5ebb30..7b137f0f8f1 100644 --- a/lib/group.php +++ b/lib/group.php @@ -271,4 +271,17 @@ class OC_Group { } return $users; } + + /** + * @brief get a list of all users in several groups + * @param array $gids + * @returns array with user ids + */ + public static function usersInGroups($gids){ + $users = array(); + foreach($gids as $gid){ + $users = array_merge(array_diff(self::usersInGroup($gid), $users), $users); + } + return $users; + } } diff --git a/lib/helper.php b/lib/helper.php index 666bc6badfc..8c362747a27 100644 --- a/lib/helper.php +++ b/lib/helper.php @@ -65,52 +65,6 @@ class OC_Helper { } /** - * @brief Returns the server host - * @returns the server host - * - * Returns the server host, even if the website uses one or more - * reverse proxies - */ - public static function serverHost() { - if(OC::$CLI){ - return 'localhost'; - } - if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) { - if (strpos($_SERVER['HTTP_X_FORWARDED_HOST'], ",") !== false) { - $host = trim(array_pop(explode(",", $_SERVER['HTTP_X_FORWARDED_HOST']))); - } - else{ - $host=$_SERVER['HTTP_X_FORWARDED_HOST']; - } - } - else{ - $host = $_SERVER['HTTP_HOST']; - } - return $host; - } - - - /** - * @brief Returns the server protocol - * @returns the server protocol - * - * Returns the server protocol. It respects reverse proxy servers and load balancers - */ - public static function serverProtocol() { - if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) { - $proto = strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']); - }else{ - if(isset($_SERVER['HTTPS']) and !empty($_SERVER['HTTPS']) and ($_SERVER['HTTPS']!='off')) { - $proto = 'https'; - }else{ - $proto = 'http'; - } - } - return($proto); - } - - - /** * @brief Creates an absolute url * @param $app app * @param $file file @@ -120,8 +74,19 @@ class OC_Helper { */ public static function linkToAbsolute( $app, $file ) { $urlLinkTo = self::linkTo( $app, $file ); - $urlLinkTo = self::serverProtocol(). '://' . self::serverHost() . $urlLinkTo; - return $urlLinkTo; + return self::makeURLAbsolute($urlLinkTo); + } + + /** + * @brief Makes an $url absolute + * @param $url the url + * @returns the absolute url + * + * Returns a absolute url to the given app and file. + */ + public static function makeURLAbsolute( $url ) + { + return OC_Request::serverProtocol(). '://' . OC_Request::serverHost() . $url; } /** diff --git a/lib/installer.php b/lib/installer.php index a8b56cb34f2..b8a3226aa0b 100644 --- a/lib/installer.php +++ b/lib/installer.php @@ -60,7 +60,7 @@ class OC_Installer{ OC_Log::write('core','No source specified when installing app',OC_Log::ERROR); return false; } - + //download the file if necesary if($data['source']=='http'){ $path=OC_Helper::tmpFile(); @@ -76,7 +76,7 @@ class OC_Installer{ } $path=$data['path']; } - + //detect the archive type $mime=OC_Helper::getMimeType($path); if($mime=='application/zip'){ @@ -89,7 +89,7 @@ class OC_Installer{ OC_Log::write('core','Archives of type '.$mime.' are not supported',OC_Log::ERROR); return false; } - + //extract the archive in a temporary folder $extractDir=OC_Helper::tmpFolder(); OC_Helper::rmdirr($extractDir); @@ -104,7 +104,7 @@ class OC_Installer{ } return false; } - + //load the info.xml file of the app if(!is_file($extractDir.'/appinfo/info.xml')){ //try to find it in a subdir @@ -134,7 +134,7 @@ class OC_Installer{ } // check if the app is compatible with this version of ownCloud - $version=OC_Util::getVersion(); + $version=OC_Util::getVersion(); if(!isset($info['require']) or ($version[0]>$info['require'])){ 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); @@ -161,11 +161,11 @@ class OC_Installer{ } return false; } - + if(isset($data['pretent']) and $data['pretent']==true){ return false; } - + //copy the app to the correct place if(@!mkdir($basedir)){ OC_Log::write('core','Can\'t create app folder. Please fix permissions. ('.$basedir.')',OC_Log::ERROR); @@ -176,34 +176,34 @@ class OC_Installer{ return false; } OC_Helper::copyr($extractDir,$basedir); - + //remove temporary files OC_Helper::rmdirr($extractDir); - + //install the database 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')){ include($basedir.'/appinfo/install.php'); } - + //set the installed version OC_Appconfig::setValue($info['id'],'installed_version',OC_App::getAppVersion($info['id'])); OC_Appconfig::setValue($info['id'],'enabled','no'); //set remote/public handelers foreach($info['remote'] as $name=>$path){ - OCP\CONFIG::setAppValue('core', 'remote_'.$name, $app.'/'.$path); + OCP\CONFIG::setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path); } foreach($info['public'] as $name=>$path){ - OCP\CONFIG::setAppValue('core', 'public_'.$name, $app.'/'.$path); + OCP\CONFIG::setAppValue('core', 'public_'.$name, $info['id'].'/'.$path); } OC_App::setAppTypes($info['id']); - + return $info['id']; } @@ -324,7 +324,7 @@ class OC_Installer{ } $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){ OCP\CONFIG::setAppValue('core', 'remote_'.$name, $app.'/'.$path); @@ -332,10 +332,10 @@ class OC_Installer{ foreach($info['public'] as $name=>$path){ OCP\CONFIG::setAppValue('core', 'public_'.$name, $app.'/'.$path); } - + OC_App::setAppTypes($info['id']); - - return $info; + + return $info['id']; } @@ -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'); @@ -375,7 +375,7 @@ class OC_Installer{ } } return true; - + }else{ return true; } diff --git a/lib/json.php b/lib/json.php index b46878375d5..3d9d5c96fa3 100644 --- a/lib/json.php +++ b/lib/json.php @@ -64,6 +64,18 @@ class OC_JSON{ exit(); } } + + /** + * Check if the user is a subadmin, send json error msg if not + */ + 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'); + self::error(array( 'data' => array( 'message' => $l->t('Authentication error') ))); + exit(); + } + } /** * Send json error msg diff --git a/lib/l10n/ca.php b/lib/l10n/ca.php new file mode 100644 index 00000000000..8e4c30caec9 --- /dev/null +++ b/lib/l10n/ca.php @@ -0,0 +1,25 @@ +<?php $TRANSLATIONS = array( +"Help" => "Ajuda", +"Personal" => "Personal", +"Settings" => "Configuració", +"Users" => "Usuaris", +"Apps" => "Aplicacions", +"Admin" => "Administració", +"ZIP download is turned off." => "La baixada en ZIP està desactivada.", +"Files need to be downloaded one by one." => "Els fitxers s'han de baixar d'un en un.", +"Back to Files" => "Torna a Fitxers", +"Selected files too large to generate zip file." => "Els fitxers seleccionats son massa grans per generar un fitxer zip.", +"Application is not enabled" => "L'aplicació no està habilitada", +"Authentication error" => "Error d'autenticació", +"Token expired. Please reload page." => "El testimoni ha expirat. Torneu a carregar la pàgina.", +"seconds ago" => "segons enrere", +"1 minute ago" => "fa 1 minut", +"%d minutes ago" => "fa %d minuts", +"today" => "avui", +"yesterday" => "ahir", +"%d days ago" => "fa %d dies", +"last month" => "el mes passat", +"months ago" => "mesos enrere", +"last year" => "l'any passat", +"years ago" => "fa anys" +); diff --git a/lib/l10n/de.php b/lib/l10n/de.php new file mode 100644 index 00000000000..d3548c7a134 --- /dev/null +++ b/lib/l10n/de.php @@ -0,0 +1,25 @@ +<?php $TRANSLATIONS = array( +"Help" => "Hilfe", +"Personal" => "Persönlich", +"Settings" => "Einstellungen", +"Users" => "Benutzer", +"Apps" => "Apps", +"Admin" => "Administrator", +"ZIP download is turned off." => "ZIP-Download ist deaktiviert.", +"Files need to be downloaded one by one." => "Die Dateien müssen einzeln heruntergeladen werden.", +"Back to Files" => "Zurück zu \"Dateien\"", +"Selected files too large to generate zip file." => "Die gewählten Dateien sind zu groß, um eine zip-Datei zu generieren.", +"Application is not enabled" => "Anwendung ist nicht aktiviert", +"Authentication error" => "Authentifizierungs-Fehler", +"Token expired. Please reload page." => "Token abgelaufen. Bitte Seite neuladen.", +"seconds ago" => "vor wenigen Sekunden", +"1 minute ago" => "Vor einer Minute", +"%d minutes ago" => "Vor %d Minuten", +"today" => "Heute", +"yesterday" => "Gestern", +"%d days ago" => "Vor %d Tagen", +"last month" => "Letzten Monat", +"months ago" => "Vor Monaten", +"last year" => "Letztes Jahr", +"years ago" => "Vor Jahren" +); diff --git a/lib/l10n/el.php b/lib/l10n/el.php new file mode 100644 index 00000000000..d9f272258e1 --- /dev/null +++ b/lib/l10n/el.php @@ -0,0 +1,25 @@ +<?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" => "1 λεπτό πριν", +"%d minutes ago" => "%d λεπτά πριν", +"today" => "σήμερα", +"yesterday" => "χθές", +"%d days ago" => "%d ημέρες πριν", +"last month" => "τον προηγούμενο μήνα", +"months ago" => "μήνες πριν", +"last year" => "τον προηγούμενο χρόνο", +"years ago" => "χρόνια πριν" +); diff --git a/lib/l10n/eo.php b/lib/l10n/eo.php new file mode 100644 index 00000000000..96bcb06a8d7 --- /dev/null +++ b/lib/l10n/eo.php @@ -0,0 +1,24 @@ +<?php $TRANSLATIONS = array( +"Help" => "Helpo", +"Personal" => "Persona", +"Settings" => "Agordo", +"Users" => "Uzantoj", +"Apps" => "Aplikaĵoj", +"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", +"Selected files too large to generate zip file." => "La elektitaj dosieroj tro grandas por genero de ZIP-dosiero.", +"Application is not enabled" => "La aplikaĵo ne estas kapabligita", +"Authentication error" => "Aŭtentiga eraro", +"Token expired. Please reload page." => "Ĵetono eksvalidiĝis. Bonvolu reŝargi la paĝon.", +"seconds ago" => "sekundojn antaŭe", +"1 minute ago" => "antaŭ 1 minuto", +"%d minutes ago" => "antaŭ %d minutoj", +"today" => "hodiaŭ", +"yesterday" => "hieraŭ", +"%d days ago" => "antaŭ %d tagoj", +"last month" => "lasta monato", +"months ago" => "monatojn antaŭe", +"last year" => "lasta jaro", +"years ago" => "jarojn antaŭe" +); diff --git a/lib/l10n/es.php b/lib/l10n/es.php new file mode 100644 index 00000000000..174fe0720fd --- /dev/null +++ b/lib/l10n/es.php @@ -0,0 +1,25 @@ +<?php $TRANSLATIONS = array( +"Help" => "Ayuda", +"Personal" => "Personal", +"Settings" => "Ajustes", +"Users" => "Usuarios", +"Apps" => "Aplicaciones", +"Admin" => "Administración", +"ZIP download is turned off." => "La descarga en ZIP está desactivada.", +"Files need to be downloaded one by one." => "Los archivos deben ser descargados uno por uno.", +"Back to Files" => "Volver a Archivos", +"Selected files too large to generate zip file." => "Los archivos seleccionados son demasiado grandes para generar el archivo zip.", +"Application is not enabled" => "La aplicación no está habilitada", +"Authentication error" => "Error de autenticación", +"Token expired. Please reload page." => "Token expirado. Por favor, recarga la página.", +"seconds ago" => "hace segundos", +"1 minute ago" => "hace 1 minuto", +"%d minutes ago" => "hace %d minutos", +"today" => "hoy", +"yesterday" => "ayer", +"%d days ago" => "hace %d días", +"last month" => "este mes", +"months ago" => "hace meses", +"last year" => "este año", +"years ago" => "hace años" +); diff --git a/lib/l10n/et_EE.php b/lib/l10n/et_EE.php new file mode 100644 index 00000000000..d8da90a3cbf --- /dev/null +++ b/lib/l10n/et_EE.php @@ -0,0 +1,25 @@ +<?php $TRANSLATIONS = array( +"Help" => "Abiinfo", +"Personal" => "Isiklik", +"Settings" => "Seaded", +"Users" => "Kasutajad", +"Apps" => "Rakendused", +"Admin" => "Admin", +"ZIP download is turned off." => "ZIP-ina allalaadimine on välja lülitatud.", +"Files need to be downloaded one by one." => "Failid tuleb alla laadida ükshaaval.", +"Back to Files" => "Tagasi failide juurde", +"Selected files too large to generate zip file." => "Valitud failid on ZIP-faili loomiseks liiga suured.", +"Application is not enabled" => "Rakendus pole sisse lülitatud", +"Authentication error" => "Autentimise viga", +"Token expired. Please reload page." => "Kontrollkood aegus. Paelun lae leht uuesti.", +"seconds ago" => "sekundit tagasi", +"1 minute ago" => "1 minut tagasi", +"%d minutes ago" => "%d minutit tagasi", +"today" => "täna", +"yesterday" => "eile", +"%d days ago" => "%d päeva tagasi", +"last month" => "eelmisel kuul", +"months ago" => "kuud tagasi", +"last year" => "eelmisel aastal", +"years ago" => "aastat tagasi" +); diff --git a/lib/l10n/fi_FI.php b/lib/l10n/fi_FI.php new file mode 100644 index 00000000000..dda2c760373 --- /dev/null +++ b/lib/l10n/fi_FI.php @@ -0,0 +1,25 @@ +<?php $TRANSLATIONS = array( +"Help" => "Ohje", +"Personal" => "Henkilökohtainen", +"Settings" => "Asetukset", +"Users" => "Käyttäjät", +"Apps" => "Sovellukset", +"Admin" => "Ylläpitäjä", +"ZIP download is turned off." => "ZIP-lataus on poistettu käytöstä.", +"Files need to be downloaded one by one." => "Tiedostot on ladattava yksittäin.", +"Back to Files" => "Takaisin tiedostoihin", +"Selected files too large to generate zip file." => "Valitut tiedostot ovat liian suurikokoisia mahtuakseen zip-tiedostoon.", +"Application is not enabled" => "Sovellusta ei ole otettu käyttöön", +"Authentication error" => "Todennusvirhe", +"Token expired. Please reload page." => "Valtuutus vanheni. Lataa sivu uudelleen.", +"seconds ago" => "sekuntia sitten", +"1 minute ago" => "1 minuutti sitten", +"%d minutes ago" => "%d minuuttia sitten", +"today" => "tänään", +"yesterday" => "eilen", +"%d days ago" => "%d päivää sitten", +"last month" => "viime kuussa", +"months ago" => "kuukautta sitten", +"last year" => "viime vuonna", +"years ago" => "vuotta sitten" +); diff --git a/lib/l10n/fr.php b/lib/l10n/fr.php new file mode 100644 index 00000000000..c674b79b959 --- /dev/null +++ b/lib/l10n/fr.php @@ -0,0 +1,25 @@ +<?php $TRANSLATIONS = array( +"Help" => "Aide", +"Personal" => "Personnel", +"Settings" => "Paramètres", +"Users" => "Utilisateurs", +"Apps" => "Applications", +"Admin" => "Administration", +"ZIP download is turned off." => "Téléchargement ZIP désactivé.", +"Files need to be downloaded one by one." => "Les fichiers nécessitent d'être téléchargés un par un.", +"Back to Files" => "Retour aux Fichiers", +"Selected files too large to generate zip file." => "Les fichiers sélectionnés sont trop volumineux pour être compressés.", +"Application is not enabled" => "L'application n'est pas activée", +"Authentication error" => "Erreur d'authentification", +"Token expired. Please reload page." => "La session a expiré. Veuillez recharger la page.", +"seconds ago" => "à l'instant", +"1 minute ago" => "il y a 1 minute", +"%d minutes ago" => "il y a %d minutes", +"today" => "aujourd'hui", +"yesterday" => "hier", +"%d days ago" => "il y a %d jours", +"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" +); diff --git a/lib/l10n/it.php b/lib/l10n/it.php new file mode 100644 index 00000000000..2c88818dc6c --- /dev/null +++ b/lib/l10n/it.php @@ -0,0 +1,25 @@ +<?php $TRANSLATIONS = array( +"Help" => "Aiuto", +"Personal" => "Personale", +"Settings" => "Impostazioni", +"Users" => "Utenti", +"Apps" => "Applicazioni", +"Admin" => "Admin", +"ZIP download is turned off." => "Lo scaricamento in formato ZIP è stato disabilitato.", +"Files need to be downloaded one by one." => "I file devono essere scaricati uno alla volta.", +"Back to Files" => "Torna ai file", +"Selected files too large to generate zip file." => "I file selezionati sono troppo grandi per generare un file zip.", +"Application is not enabled" => "L'applicazione non è abilitata", +"Authentication error" => "Errore di autenticazione", +"Token expired. Please reload page." => "Token scaduto. Ricarica la pagina.", +"seconds ago" => "secondi fa", +"1 minute ago" => "1 minuto fa", +"%d minutes ago" => "%d minuti fa", +"today" => "oggi", +"yesterday" => "ieri", +"%d days ago" => "%d giorni fa", +"last month" => "il mese scorso", +"months ago" => "mesi fa", +"last year" => "l'anno scorso", +"years ago" => "anni fa" +); diff --git a/lib/l10n/sl.php b/lib/l10n/sl.php new file mode 100644 index 00000000000..7889335d975 --- /dev/null +++ b/lib/l10n/sl.php @@ -0,0 +1,22 @@ +<?php $TRANSLATIONS = array( +"Help" => "Pomoč", +"Personal" => "Osebno", +"Settings" => "Nastavitve", +"Users" => "Uporabniki", +"Apps" => "Aplikacije", +"Admin" => "Skrbnik", +"ZIP download is turned off." => "ZIP prenos je onemogočen.", +"Files need to be downloaded one by one." => "Datoteke morajo biti prenešene posamezno.", +"Back to Files" => "Nazaj na datoteke", +"Selected files too large to generate zip file." => "Izbrane datoteke so prevelike, da bi lahko ustvarili zip datoteko.", +"Application is not enabled" => "Aplikacija ni omogočena", +"Authentication error" => "Napaka overitve", +"Token expired. Please reload page." => "Žeton je potekel. Prosimo, če spletno stran znova naložite.", +"1 minute ago" => "pred minuto", +"%d minutes ago" => "pred %d minutami", +"today" => "danes", +"yesterday" => "včeraj", +"%d days ago" => "pred %d dnevi", +"last month" => "prejšnji mesec", +"last year" => "lani" +); diff --git a/lib/l10n/sv.php b/lib/l10n/sv.php new file mode 100644 index 00000000000..4d9a63c34b1 --- /dev/null +++ b/lib/l10n/sv.php @@ -0,0 +1,25 @@ +<?php $TRANSLATIONS = array( +"Help" => "Hjälp", +"Personal" => "Personligt", +"Settings" => "Inställningar", +"Users" => "Användare", +"Apps" => "Program", +"Admin" => "Admin", +"ZIP download is turned off." => "Nedladdning av ZIP är avstängd.", +"Files need to be downloaded one by one." => "Filer laddas ner en åt gången.", +"Back to Files" => "Tillbaka till Filer", +"Selected files too large to generate zip file." => "Valda filer är för stora för att skapa zip-fil.", +"Application is not enabled" => "Applikationen är inte aktiverad", +"Authentication error" => "Fel vid autentisering", +"Token expired. Please reload page." => "Ogiltig token. Ladda om sidan.", +"seconds ago" => "sekunder sedan", +"1 minute ago" => "1 minut sedan", +"%d minutes ago" => "%d minuter sedan", +"today" => "idag", +"yesterday" => "igår", +"%d days ago" => "%d dagar sedan", +"last month" => "förra månaden", +"months ago" => "månader sedan", +"last year" => "förra året", +"years ago" => "år sedan" +); diff --git a/lib/l10n/uk.php b/lib/l10n/uk.php new file mode 100644 index 00000000000..18f6a4a623d --- /dev/null +++ b/lib/l10n/uk.php @@ -0,0 +1,24 @@ +<?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" => "Помилка автентифікації", +"seconds ago" => "секунди тому", +"1 minute ago" => "1 хвилину тому", +"%d minutes ago" => "%d хвилин тому", +"today" => "сьогодні", +"yesterday" => "вчора", +"%d days ago" => "%d днів тому", +"last month" => "минулого місяця", +"months ago" => "місяці тому", +"last year" => "минулого року", +"years ago" => "роки тому" +); diff --git a/lib/mail.php b/lib/mail.php index 7eb2c4770c5..0ac9a97c1bf 100644 --- a/lib/mail.php +++ b/lib/mail.php @@ -83,7 +83,8 @@ class OC_Mail { unset($mailo); OC_Log::write('mail', 'Mail from '.$fromname.' ('.$fromaddress.')'.' to: '.$toname.'('.$toaddress.')'.' subject: '.$subject, OC_Log::DEBUG); } catch (Exception $exception) { - OC_Log::write('mail', $exception->getMessage(), OC_Log::DEBUG); + OC_Log::write('mail', $exception->getMessage(), OC_Log::ERROR); + throw($exception); } } diff --git a/lib/mimetypes.list.php b/lib/mimetypes.list.php index f7207493f7f..37d50756d57 100644 --- a/lib/mimetypes.list.php +++ b/lib/mimetypes.list.php @@ -55,6 +55,9 @@ return array( 'ods'=>'application/vnd.oasis.opendocument.spreadsheet', 'odg'=>'application/vnd.oasis.opendocument.graphics', 'odp'=>'application/vnd.oasis.opendocument.presentation', + 'pages'=>'application/x-iwork-pages-sffpages', + 'numbers'=>'application/x-iwork-numbers-sffnumbers', + 'keynote'=>'application/x-iwork-keynote-sffkey', 'kra'=>'application/x-krita', 'mp3'=>'audio/mpeg', 'doc'=>'application/msword', diff --git a/lib/public/app.php b/lib/public/app.php index 28411933beb..e74f1550740 100644 --- a/lib/public/app.php +++ b/lib/public/app.php @@ -35,6 +35,21 @@ namespace OCP; */ 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 ){ + return true; // don't do anything + } + + /** * @brief adds an entry to the navigation * @param $data array containing the data * @returns true/false diff --git a/lib/public/backgroundjob.php b/lib/public/backgroundjob.php new file mode 100644 index 00000000000..72f4557eb1a --- /dev/null +++ b/lib/public/backgroundjob.php @@ -0,0 +1,117 @@ +<?php +/** +* ownCloud +* +* @author Jakob Sack +* @copyright 2012 Jakob Sack owncloud@jakobsack.de +* +* 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/>. +* +*/ + +/** + * Public interface of ownCloud forbackground jobs. + */ + +// 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; + +/** + * This class provides functions to manage backgroundjobs in ownCloud + * + * There are two kind of background jobs in ownCloud: regular tasks and + * queued tasks. + * + * Regular tasks have to be registered in appinfo.php and + * will run on a regular base. Fetching news could be a task that should run + * frequently. + * + * Queued tasks have to be registered each time you want to execute them. + * 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 + * is done it will be deleted from the list. + */ +class BackgroundJob { + /** + * @brief creates a regular task + * @param $klass class name + * @param $method method name + * @return true + */ + public static function addRegularTask( $klass, $method ){ + return \OC_BackgroundJob_RegularTask::register( $klass, $method ); + } + + /** + * @brief gets all regular tasks + * @return associative array + * + * key is string "$klass-$method", value is array( $klass, $method ) + */ + static public function allRegularTasks(){ + return \OC_BackgroundJob_RegularTask::all(); + } + + /** + * @brief Gets one queued task + * @param $id ID of the task + * @return associative array + */ + public static function findQueuedTask( $id ){ + return \OC_BackgroundJob_QueuedTask::find( $id ); + } + + /** + * @brief Gets all queued tasks + * @return array with associative arrays + */ + public static function allQueuedTasks(){ + return \OC_BackgroundJob_QueuedTask::all(); + } + + /** + * @brief Gets all queued tasks of a specific app + * @param $app app name + * @return array with associative arrays + */ + public static function queuedTaskWhereAppIs( $app ){ + return \OC_BackgroundJob_QueuedTask::whereAppIs( $app ); + } + + /** + * @brief queues a task + * @param $app app name + * @param $klass class name + * @param $method method name + * @param $parameters all useful data as text + * @return id of task + */ + public static function addQueuedTask( $task, $klass, $method, $parameters ){ + return \OC_BackgroundJob_QueuedTask::add( $task, $klass, $method, $parameters ); + } + + /** + * @brief deletes a queued task + * @param $id id of task + * @return true/false + * + * Deletes a report + */ + public static function deleteQueuedTask( $id ){ + return \OC_BackgroundJob_QueuedTask::delete( $id ); + } +} diff --git a/lib/public/util.php b/lib/public/util.php index 75ca29f7129..9f6f6f32e1e 100644 --- a/lib/public/util.php +++ b/lib/public/util.php @@ -165,7 +165,7 @@ class Util { * reverse proxies */ public static function getServerHost() { - return(\OC_Helper::serverHost()); + return(\OC_Request::serverHost()); } /** @@ -175,7 +175,7 @@ class Util { * Returns the server protocol. It respects reverse proxy servers and load balancers */ public static function getServerProtocol() { - return(\OC_Helper::serverProtocol()); + return(\OC_Request::serverProtocol()); } /** diff --git a/lib/request.php b/lib/request.php index 0b5aaf8ef30..3fe61fbddcd 100644 --- a/lib/request.php +++ b/lib/request.php @@ -7,6 +7,79 @@ */ class OC_Request { + /** + * @brief Returns the server host + * @returns the server host + * + * Returns the server host, even if the website uses one or more + * reverse proxies + */ + public static function serverHost() { + if(OC::$CLI){ + return 'localhost'; + } + if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) { + if (strpos($_SERVER['HTTP_X_FORWARDED_HOST'], ",") !== false) { + $host = trim(array_pop(explode(",", $_SERVER['HTTP_X_FORWARDED_HOST']))); + } + else{ + $host=$_SERVER['HTTP_X_FORWARDED_HOST']; + } + } + else{ + $host = $_SERVER['HTTP_HOST']; + } + return $host; + } + + + /** + * @brief Returns the server protocol + * @returns the server protocol + * + * Returns the server protocol. It respects reverse proxy servers and load balancers + */ + public static function serverProtocol() { + if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) { + $proto = strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']); + }else{ + if(isset($_SERVER['HTTPS']) and !empty($_SERVER['HTTPS']) and ($_SERVER['HTTPS']!='off')) { + $proto = 'https'; + }else{ + $proto = 'http'; + } + } + return($proto); + } + + /** + * @brief get Path info from request + * @returns string Path info or false when not found + */ + public static function getPathInfo() { + if (array_key_exists('PATH_INFO', $_SERVER)){ + $path_info = $_SERVER['PATH_INFO']; + }else{ + $path_info = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME'])); + // following is taken from Sabre_DAV_URLUtil::decodePathSegment + $path_info = rawurldecode($path_info); + $encoding = mb_detect_encoding($path_info, array('UTF-8','ISO-8859-1')); + + switch($encoding) { + + case 'ISO-8859-1' : + $path_info = utf8_encode($path_info); + + } + // end copy + } + return $path_info; + } + + /** + * @brief Check if this is a no-cache request + * @returns true for no-cache + */ static public function isNoCache() { if (!isset($_SERVER['HTTP_CACHE_CONTROL'])) { return false; @@ -14,6 +87,10 @@ class OC_Request { return $_SERVER['HTTP_CACHE_CONTROL'] == 'no-cache'; } + /** + * @brief Check if the requestor understands gzip + * @returns true for gzip encoding supported + */ static public function acceptGZip() { if (!isset($_SERVER['HTTP_ACCEPT_ENCODING'])) { return false; diff --git a/lib/subadmin.php b/lib/subadmin.php new file mode 100644 index 00000000000..0806f27a6bd --- /dev/null +++ b/lib/subadmin.php @@ -0,0 +1,181 @@ +<?php +/** + * ownCloud + * + * @author 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 + * 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/>. + * + */ +OC_Hook::connect('OC_User', 'post_deleteUser', 'OC_SubAdmin', 'post_deleteUser'); +OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC_SubAdmin', 'post_deleteGroup'); +/** + * This class provides all methods needed for managing groups. + * + * Hooks provided: + * post_createSubAdmin($gid) + * post_deleteSubAdmin($gid) + */ +class OC_SubAdmin{ + + /** + * @brief add a SubAdmin + * @param $uid uid of the SubAdmin + * @param $gid gid of the group + * @return boolean + */ + 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 )); + return true; + } + + /** + * @brief delete a SubAdmin + * @param $uid uid of the SubAdmin + * @param $gid gid of the group + * @return boolean + */ + 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 )); + return true; + } + + /** + * @brief get groups of a SubAdmin + * @param $uid uid of the SubAdmin + * @return array + */ + 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()){ + $gids[] = $row['gid']; + } + return $gids; + } + + /** + * @brief get SubAdmins of a group + * @param $gid gid of the group + * @return array + */ + 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()){ + $uids[] = $row['uid']; + } + return $uids; + } + + /** + * @brief get all SubAdmins + * @return array + */ + public static function getAllSubAdmins(){ + $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*group_admin'); + $result = $stmt->execute(); + $subadmins = array(); + 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){ + $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){ + 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){ + $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){ + 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)){ + return false; + } + $accessiblegroups = self::getSubAdminsGroups($subadmin); + 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){ + return self::isSubAdminofGroup($subadmin, $group); + } + + /** + * @brief delete all SubAdmins by uid + * @param $parameters + * @return boolean + */ + 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; + } + + /** + * @brief delete all SubAdmins8 by gid + * @param $parameters + * @return boolean + */ + 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/user.php b/lib/user.php index e3c9c23effa..49a0a2a10ce 100644 --- a/lib/user.php +++ b/lib/user.php @@ -208,8 +208,9 @@ class OC_User { OC_Hook::emit( "OC_User", "pre_login", array( "run" => &$run, "uid" => $uid )); if( $run ){ - $uid=self::checkPassword( $uid, $password ); - if($uid){ + $uid = self::checkPassword( $uid, $password ); + $enabled = self::isEnabled($uid); + if($uid && $enabled){ session_regenerate_id(true); self::setUserId($uid); OC_Hook::emit( "OC_User", "post_login", array( "uid" => $uid, 'password'=>$password )); @@ -363,6 +364,38 @@ class OC_User { } return false; } + + /** + * disables a user + * @param string $userid the user to disable + */ + 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){ + $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){ + $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')); + return $results->numRows() ? false : true; + } /** * @brief Set cookie value to use in next page load diff --git a/lib/util.php b/lib/util.php index 0c563278cc5..732acbb9205 100755 --- a/lib/util.php +++ b/lib/util.php @@ -66,7 +66,7 @@ class OC_Util { * @return array */ public static function getVersion(){ - return array(4,80,1); + return array(4,81,2); } /** @@ -271,15 +271,26 @@ class OC_Util { return $errors; } - public static function displayLoginPage($parameters = array()){ - if(isset($_COOKIE["username"])){ - $parameters["username"] = $_COOKIE["username"]; + public static function displayLoginPage($display_lostpassword) { + $parameters = array(); + $parameters['display_lostpassword'] = $display_lostpassword; + if (!empty($_POST['user'])) { + $parameters["username"] = + OC_Util::sanitizeHTML($_POST['user']).'"'; + $parameters['user_autofocus'] = false; } else { $parameters["username"] = ''; + $parameters['user_autofocus'] = true; } $sectoken=rand(1000000,9999999); $_SESSION['sectoken']=$sectoken; $parameters["sectoken"] = $sectoken; + if (isset($_REQUEST['redirect_url'])) { + $redirect_url = OC_Util::sanitizeHTML($_REQUEST['redirect_url']); + } else { + $redirect_url = $_SERVER['REQUEST_URI']; + } + $parameters['redirect_url'] = $redirect_url; OC_Template::printGuestPage("", "login", $parameters); } @@ -319,6 +330,23 @@ 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(){ + // Check if we are a user + self::checkLoggedIn(); + if(OC_Group::inGroup(OC_User::getUser(),'admin')){ + return true; + } + if(!OC_SubAdmin::isSubAdmin(OC_User::getUser())){ + header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' )); + exit(); + } + return true; + } + + /** * Redirect to the user default page */ public static function redirectToDefaultPage(){ @@ -326,10 +354,16 @@ class OC_Util { $location = $_REQUEST['redirect_url']; } else if (isset(OC::$REQUESTEDAPP) && !empty(OC::$REQUESTEDAPP)) { - $location = OC::$WEBROOT.'/?app='.OC::$REQUESTEDAPP; + $location = OC_Helper::linkToAbsolute( OC::$REQUESTEDAPP, 'index.php' ); } else { - $location = OC::$WEBROOT.'/'.OC_Appconfig::getValue('core', 'defaultpage', '?app=files'); + $defaultpage = OC_Appconfig::getValue('core', 'defaultpage'); + if ($defaultpage) { + $location = OC_Helper::makeURLAbsolute(OC::$WEBROOT.'/'.$defaultpage); + } + else { + $location = OC_Helper::linkToAbsolute( 'files', 'index.php' ); + } } OC_Log::write('core', 'redirectToDefaultPage: '.$location, OC_Log::DEBUG); header( 'Location: '.$location ); @@ -453,7 +487,7 @@ class OC_Util { @fclose($fp); // accessing the file via http - $url = OC_Helper::serverProtocol(). '://' . OC_Helper::serverHost() . OC::$WEBROOT.'/data'.$filename; + $url = OC_Helper::makeURLAbsolute(OC::$WEBROOT.'/data'.$filename); $fp = @fopen($url, 'r'); $content=@fread($fp, 2048); @fclose($fp); |