diff options
Diffstat (limited to 'lib')
41 files changed, 1672 insertions, 851 deletions
diff --git a/lib/app.php b/lib/app.php index c6f6e92e60e..3e6cadfe2c9 100644 --- a/lib/app.php +++ b/lib/app.php @@ -174,7 +174,8 @@ class OC_App{ $apps=array('files'); $sql = 'SELECT `appid` FROM `*PREFIX*appconfig`' .' WHERE `configkey` = \'enabled\' AND `configvalue`=\'yes\''; - if (OC_Config::getValue( 'dbtype', 'sqlite' ) === 'oci') { //FIXME oracle hack + if (OC_Config::getValue( 'dbtype', 'sqlite' ) === 'oci') { + //FIXME oracle hack: need to explicitly cast CLOB to CHAR for comparison $sql = 'SELECT `appid` FROM `*PREFIX*appconfig`' .' WHERE `configkey` = \'enabled\' AND to_char(`configvalue`)=\'yes\''; } diff --git a/lib/backgroundjob/job.php b/lib/backgroundjob/job.php new file mode 100644 index 00000000000..49fbffbd684 --- /dev/null +++ b/lib/backgroundjob/job.php @@ -0,0 +1,49 @@ +<?php +/** + * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OC\BackgroundJob; + +abstract class Job { + protected $id; + protected $lastRun; + protected $argument; + + /** + * @param JobList $jobList + */ + public function execute($jobList) { + $jobList->setLastRun($this); + $this->run($this->argument); + } + + abstract protected function run($argument); + + public function setId($id) { + $this->id = $id; + } + + public function setLastRun($lastRun) { + $this->lastRun = $lastRun; + } + + public function setArgument($argument) { + $this->argument = $argument; + } + + public function getId() { + return $this->id; + } + + public function getLastRun() { + return $this->lastRun; + } + + public function getArgument() { + return $this->argument; + } +} diff --git a/lib/backgroundjob/joblist.php b/lib/backgroundjob/joblist.php new file mode 100644 index 00000000000..cc803dd9b5f --- /dev/null +++ b/lib/backgroundjob/joblist.php @@ -0,0 +1,172 @@ +<?php +/** + * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OC\BackgroundJob; + +/** + * Class QueuedJob + * + * create a background job that is to be executed once + * + * @package OC\BackgroundJob + */ +class JobList { + /** + * @param Job|string $job + * @param mixed $argument + */ + public function add($job, $argument = null) { + if (!$this->has($job, $argument)) { + if ($job instanceof Job) { + $class = get_class($job); + } else { + $class = $job; + } + $argument = json_encode($argument); + $query = \OC_DB::prepare('INSERT INTO `*PREFIX*jobs`(`class`, `argument`, `last_run`) VALUES(?, ?, 0)'); + $query->execute(array($class, $argument)); + } + } + + /** + * @param Job|string $job + * @param mixed $argument + */ + public function remove($job, $argument = null) { + if ($job instanceof Job) { + $class = get_class($job); + } else { + $class = $job; + } + if (!is_null($argument)) { + $argument = json_encode($argument); + $query = \OC_DB::prepare('DELETE FROM `*PREFIX*jobs` WHERE `class` = ? AND `argument` = ?'); + $query->execute(array($class, $argument)); + } else { + $query = \OC_DB::prepare('DELETE FROM `*PREFIX*jobs` WHERE `class` = ?'); + $query->execute(array($class)); + } + } + + /** + * check if a job is in the list + * + * @param $job + * @param mixed $argument + * @return bool + */ + public function has($job, $argument) { + if ($job instanceof Job) { + $class = get_class($job); + } else { + $class = $job; + } + $argument = json_encode($argument); + $query = \OC_DB::prepare('SELECT `id` FROM `*PREFIX*jobs` WHERE `class` = ? AND `argument` = ?'); + $result = $query->execute(array($class, $argument)); + return (bool)$result->fetchRow(); + } + + /** + * get all jobs in the list + * + * @return Job[] + */ + public function getAll() { + $query = \OC_DB::prepare('SELECT `id`, `class`, `last_run`, `argument` FROM `*PREFIX*jobs`'); + $result = $query->execute(); + $jobs = array(); + while ($row = $result->fetchRow()) { + $jobs[] = $this->buildJob($row); + } + return $jobs; + } + + /** + * get the next job in the list + * + * @return Job + */ + public function getNext() { + $lastId = $this->getLastJob(); + $query = \OC_DB::prepare('SELECT `id`, `class`, `last_run`, `argument` FROM `*PREFIX*jobs` WHERE `id` > ? ORDER BY `id` ASC', 1); + $result = $query->execute(array($lastId)); + if ($row = $result->fetchRow()) { + return $this->buildJob($row); + } else { + //begin at the start of the queue + $query = \OC_DB::prepare('SELECT `id`, `class`, `last_run`, `argument` FROM `*PREFIX*jobs` ORDER BY `id` ASC', 1); + $result = $query->execute(); + if ($row = $result->fetchRow()) { + return $this->buildJob($row); + } else { + return null; //empty job list + } + } + } + + /** + * @param int $id + * @return Job + */ + public function getById($id) { + $query = \OC_DB::prepare('SELECT `id`, `class`, `last_run`, `argument` FROM `*PREFIX*jobs` WHERE `id` = ?'); + $result = $query->execute(array($id)); + if ($row = $result->fetchRow()) { + return $this->buildJob($row); + } else { + return null; + } + } + + /** + * get the job object from a row in the db + * + * @param array $row + * @return Job + */ + private function buildJob($row) { + $class = $row['class']; + /** + * @var Job $job + */ + $job = new $class(); + $job->setId($row['id']); + $job->setLastRun($row['last_run']); + $job->setArgument(json_decode($row['argument'])); + return $job; + } + + /** + * set the job that was last ran + * + * @param Job $job + */ + public function setLastJob($job) { + \OC_Appconfig::setValue('backgroundjob', 'lastjob', $job->getId()); + } + + /** + * get the id of the last ran job + * + * @return int + */ + public function getLastJob() { + return \OC_Appconfig::getValue('backgroundjob', 'lastjob', 0); + } + + /** + * set the lastRun of $job to now + * + * @param Job $job + */ + public function setLastRun($job) { + $query = \OC_DB::prepare('UPDATE `*PREFIX*jobs` SET `last_run` = ? WHERE `id` = ?'); + $query->execute(array(time(), $job->getId())); + } +} diff --git a/lib/backgroundjob/legacy/queuedjob.php b/lib/backgroundjob/legacy/queuedjob.php new file mode 100644 index 00000000000..2bc001103b8 --- /dev/null +++ b/lib/backgroundjob/legacy/queuedjob.php @@ -0,0 +1,18 @@ +<?php +/** + * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OC\BackgroundJob\Legacy; + +class QueuedJob extends \OC\BackgroundJob\QueuedJob { + public function run($argument) { + $class = $argument['klass']; + $method = $argument['method']; + $parameters = $argument['parameters']; + call_user_func(array($class, $method), $parameters); + } +} diff --git a/lib/backgroundjob/legacy/regularjob.php b/lib/backgroundjob/legacy/regularjob.php new file mode 100644 index 00000000000..d4cfa348cea --- /dev/null +++ b/lib/backgroundjob/legacy/regularjob.php @@ -0,0 +1,15 @@ +<?php +/** + * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OC\BackgroundJob\Legacy; + +class RegularJob extends \OC\BackgroundJob\Job { + public function run($argument) { + call_user_func($argument); + } +} diff --git a/lib/backgroundjob/queuedjob.php b/lib/backgroundjob/queuedjob.php new file mode 100644 index 00000000000..1714182820d --- /dev/null +++ b/lib/backgroundjob/queuedjob.php @@ -0,0 +1,28 @@ +<?php +/** + * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OC\BackgroundJob; + +/** + * Class QueuedJob + * + * create a background job that is to be executed once + * + * @package OC\BackgroundJob + */ +abstract class QueuedJob extends Job { + /** + * run the job, then remove it from the joblist + * + * @param JobList $jobList + */ + public function execute($jobList) { + $jobList->remove($this); + $this->run($this->argument); + } +} diff --git a/lib/backgroundjob/queuedtask.php b/lib/backgroundjob/queuedtask.php deleted file mode 100644 index b2ce6f39ed8..00000000000 --- a/lib/backgroundjob/queuedtask.php +++ /dev/null @@ -1,105 +0,0 @@ -<?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( $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 )); - - 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 deleted file mode 100644 index 9976872ee13..00000000000 --- a/lib/backgroundjob/regulartask.php +++ /dev/null @@ -1,52 +0,0 @@ -<?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/timedjob.php b/lib/backgroundjob/timedjob.php new file mode 100644 index 00000000000..ae9f33505ab --- /dev/null +++ b/lib/backgroundjob/timedjob.php @@ -0,0 +1,41 @@ +<?php +/** + * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OC\BackgroundJob; + +/** + * Class QueuedJob + * + * create a background job that is to be executed at an interval + * + * @package OC\BackgroundJob + */ +abstract class TimedJob extends Job { + protected $interval = 0; + + /** + * set the interval for the job + * + * @param int $interval + */ + public function setInterval($interval) { + $this->interval = $interval; + } + + /** + * run the job if + * + * @param JobList $jobList + */ + public function execute($jobList) { + if ((time() - $this->lastRun) > $this->interval) { + $jobList->setLastRun($this); + $this->run($this->argument); + } + } +} diff --git a/lib/backgroundjob/worker.php b/lib/backgroundjob/worker.php deleted file mode 100644 index e966ac9647c..00000000000 --- a/lib/backgroundjob/worker.php +++ /dev/null @@ -1,118 +0,0 @@ -<?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 9d1d4b5e058..a6e4a47dbf5 100644 --- a/lib/base.php +++ b/lib/base.php @@ -265,6 +265,7 @@ class OC { OC_Util::addScript("jquery.infieldlabel"); OC_Util::addScript("jquery-tipsy"); OC_Util::addScript("compatibility"); + OC_Util::addScript("jquery.ocdialog"); OC_Util::addScript("oc-dialogs"); OC_Util::addScript("octemplate"); OC_Util::addScript("js"); @@ -278,6 +279,7 @@ class OC { OC_Util::addStyle("multiselect"); OC_Util::addStyle("jquery-ui-1.10.0.custom"); OC_Util::addStyle("jquery-tipsy"); + OC_Util::addStyle("jquery.ocdialog"); OC_Util::addScript("oc-requesttoken"); } @@ -441,14 +443,14 @@ class OC { stream_wrapper_register('oc', 'OC\Files\Stream\OC'); self::initTemplateEngine(); - self::checkConfig(); - self::checkInstalled(); - self::checkSSL(); if ( !self::$CLI ) { self::initSession(); } else { self::$session = new \OC\Session\Memory(''); } + self::checkConfig(); + self::checkInstalled(); + self::checkSSL(); $errors = OC_Util::checkServer(); if (count($errors) > 0) { @@ -537,9 +539,15 @@ class OC { * register hooks for the cache */ public static function registerCacheHooks() { - // register cache cleanup jobs - OC_BackgroundJob_RegularTask::register('OC_Cache_FileGlobal', 'gc'); - OC_Hook::connect('OC_User', 'post_login', 'OC_Cache_File', 'loginListener'); + if (OC_Config::getValue('installed', false)) { //don't try to do this before we are properly setup + // register cache cleanup jobs + try { //if this is executed before the upgrade to the new backgroundjob system is completed it will throw an exception + \OCP\BackgroundJob::registerJob('OC_Cache_FileGlobalGC'); + } catch (Exception $e) { + + } + OC_Hook::connect('OC_User', 'post_login', 'OC_Cache_File', 'loginListener'); + } } /** diff --git a/lib/cache/file.php b/lib/cache/file.php index f9ecf41dcac..531e1d50f40 100644 --- a/lib/cache/file.php +++ b/lib/cache/file.php @@ -14,6 +14,7 @@ class OC_Cache_File{ return $this->storage; } if(OC_User::isLoggedIn()) { + \OC\Files\Filesystem::initMountPoints(OC_User::getUser()); $subdir = 'cache'; $view = new \OC\Files\View('/'.OC_User::getUser()); if(!$view->file_exists($subdir)) { diff --git a/lib/cache/fileglobalgc.php b/lib/cache/fileglobalgc.php new file mode 100644 index 00000000000..a29c31f9063 --- /dev/null +++ b/lib/cache/fileglobalgc.php @@ -0,0 +1,8 @@ +<?php + + +class OC_Cache_FileGlobalGC extends \OC\BackgroundJob\Job{ + public function run($argument){ + OC_Cache_FileGlobal::gc(); + } +} diff --git a/lib/connector/sabre/locks.php b/lib/connector/sabre/locks.php index e58e584fb41..745523c7a5b 100644 --- a/lib/connector/sabre/locks.php +++ b/lib/connector/sabre/locks.php @@ -45,7 +45,12 @@ class OC_Connector_Sabre_Locks extends Sabre_DAV_Locks_Backend_Abstract { // but otherwise reading locks from SQLite Databases will return // nothing $query = 'SELECT * FROM `*PREFIX*locks`' - .' WHERE `userid` = ? AND (`created` + `timeout`) > '.time().' AND (( `uri` = ?)'; + .' WHERE `userid` = ? AND (`created` + `timeout`) > '.time().' AND (( `uri` = ?)'; + if (OC_Config::getValue( "dbtype") === 'oci') { + //FIXME oracle hack: need to explicitly cast CLOB to CHAR for comparison + $query = 'SELECT * FROM `*PREFIX*locks`' + .' WHERE `userid` = ? AND (`created` + `timeout`) > '.time().' AND (( to_char(`uri`) = ?)'; + } $params = array(OC_User::getUser(), $uri); // We need to check locks for every part in the uri. @@ -60,15 +65,24 @@ class OC_Connector_Sabre_Locks extends Sabre_DAV_Locks_Backend_Abstract { if ($currentPath) $currentPath.='/'; $currentPath.=$part; - - $query.=' OR (`depth` != 0 AND `uri` = ?)'; + //FIXME oracle hack: need to explicitly cast CLOB to CHAR for comparison + if (OC_Config::getValue( "dbtype") === 'oci') { + $query.=' OR (`depth` != 0 AND to_char(`uri`) = ?)'; + } else { + $query.=' OR (`depth` != 0 AND `uri` = ?)'; + } $params[] = $currentPath; } if ($returnChildLocks) { - $query.=' OR (`uri` LIKE ?)'; + //FIXME oracle hack: need to explicitly cast CLOB to CHAR for comparison + if (OC_Config::getValue( "dbtype") === 'oci') { + $query.=' OR (to_char(`uri`) LIKE ?)'; + } else { + $query.=' OR (`uri` LIKE ?)'; + } $params[] = $uri . '/%'; } diff --git a/lib/db.php b/lib/db.php index 61836551833..080e895e352 100644 --- a/lib/db.php +++ b/lib/db.php @@ -23,7 +23,8 @@ class DatabaseException extends Exception{ private $query; - public function __construct($message, $query){ + //FIXME getQuery seems to be unused, maybe use parent constructor with $message, $code and $previous + public function __construct($message, $query = null){ parent::__construct($message); $this->query = $query; } @@ -392,9 +393,59 @@ class OC_DB { } /** + * @brief execute a prepared statement, on error write log and throw exception + * @param mixed $stmt PDOStatementWrapper | MDB2_Statement_Common , + * an array with 'sql' and optionally 'limit' and 'offset' keys + * .. or a simple sql query string + * @param array $parameters + * @return result + * @throws DatabaseException + */ + static public function executeAudited( $stmt, array $parameters = null) { + if (is_string($stmt)) { + // convert to an array with 'sql' + if (stripos($stmt,'LIMIT') !== false) { //OFFSET requires LIMIT, se we only neet to check for LIMIT + // TODO try to convert LIMIT OFFSET notation to parameters, see fixLimitClauseForMSSQL + $message = 'LIMIT and OFFSET are forbidden for portability reasons,' + . ' pass an array with \'limit\' and \'offset\' instead'; + throw new DatabaseException($message); + } + $stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null); + } + if (is_array($stmt)){ + // convert to prepared statement + if ( ! array_key_exists('sql', $stmt) ) { + $message = 'statement array must at least contain key \'sql\''; + throw new DatabaseException($message); + } + if ( ! array_key_exists('limit', $stmt) ) { + $stmt['limit'] = null; + } + if ( ! array_key_exists('limit', $stmt) ) { + $stmt['offset'] = null; + } + $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']); + } + self::raiseExceptionOnError($stmt, 'Could not prepare statement'); + if ($stmt instanceof PDOStatementWrapper || $stmt instanceof MDB2_Statement_Common) { + $result = $stmt->execute($parameters); + self::raiseExceptionOnError($result, 'Could not execute statement'); + } else { + if (is_object($stmt)) { + $message = 'Expected a prepared statement or array got ' . get_class($stmt); + } else { + $message = 'Expected a prepared statement or array got ' . gettype($stmt); + } + throw new DatabaseException($message); + } + return $result; + } + + /** * @brief gets last value of autoincrement * @param string $table The optional table name (will replace *PREFIX*) and add sequence suffix * @return int id + * @throws DatabaseException * * MDB2 lastInsertID() * @@ -404,25 +455,27 @@ class OC_DB { public static function insertid($table=null) { self::connect(); $type = OC_Config::getValue( "dbtype", "sqlite" ); - if( $type == 'pgsql' ) { - $query = self::prepare('SELECT lastval() AS id'); - $row = $query->execute()->fetchRow(); + if( $type === 'pgsql' ) { + $result = self::executeAudited('SELECT lastval() AS id'); + $row = $result->fetchRow(); + self::raiseExceptionOnError($row, 'fetching row for insertid failed'); return $row['id']; - } - if( $type == 'mssql' ) { + } else if( $type === 'mssql') { if($table !== null) { $prefix = OC_Config::getValue( "dbtableprefix", "oc_" ); $table = str_replace( '*PREFIX*', $prefix, $table ); } - return self::$connection->lastInsertId($table); - }else{ + $result = self::$connection->lastInsertId($table); + } else { if($table !== null) { $prefix = OC_Config::getValue( "dbtableprefix", "oc_" ); $suffix = OC_Config::getValue( "dbsequencesuffix", "_id_seq" ); $table = str_replace( '*PREFIX*', $prefix, $table ).$suffix; } - return self::$connection->lastInsertId($table); + $result = self::$connection->lastInsertId($table); } + self::raiseExceptionOnError($result, 'insertid failed'); + return $result; } /** @@ -512,6 +565,8 @@ class OC_DB { //clean up memory unlink( $file2 ); + + self::raiseExceptionOnError($definition,'Failed to parse the database definition'); // Die in case something went wrong if( $definition instanceof MDB2_Schema_Error ) { @@ -528,11 +583,7 @@ class OC_DB { $ret=self::$schema->createDatabase( $definition ); - // Die in case something went wrong - if( $ret instanceof MDB2_Error ) { - OC_Template::printErrorPage( self::$MDB2->getDebugOutput().' '.$ret->getMessage() . ': ' - . $ret->getUserInfo() ); - } + self::raiseExceptionOnError($ret,'Failed to create the database structure'); return true; } @@ -552,13 +603,7 @@ class OC_DB { $content = file_get_contents( $file ); $previousSchema = self::$schema->getDefinitionFromDatabase(); - if (PEAR::isError($previousSchema)) { - $error = $previousSchema->getMessage(); - $detail = $previousSchema->getDebugInfo(); - $message = 'Failed to get existing database structure for updating ('.$error.', '.$detail.')'; - OC_Log::write('core', $message, OC_Log::FATAL); - throw new Exception($message); - } + self::raiseExceptionOnError($previousSchema,'Failed to get existing database structure for updating'); // Make changes and save them to an in-memory file $file2 = 'static://db_scheme'; @@ -582,13 +627,7 @@ class OC_DB { //clean up memory unlink( $file2 ); - if (PEAR::isError($op)) { - $error = $op->getMessage(); - $detail = $op->getDebugInfo(); - $message = 'Failed to update database structure ('.$error.', '.$detail.')'; - OC_Log::write('core', $message, OC_Log::FATAL); - throw new Exception($message); - } + self::raiseExceptionOnError($op,'Failed to update database structure'); return true; } @@ -641,15 +680,9 @@ class OC_DB { } $query = substr($query, 0, strlen($query) - 5); try { - $stmt = self::prepare($query); - $result = $stmt->execute($inserts); - - } catch(PDOException $e) { - $entry = 'DB Error: "'.$e->getMessage() . '"<br />'; - $entry .= 'Offending command was: ' . $query . '<br />'; - OC_Log::write('core', $entry, OC_Log::FATAL); - error_log('DB error: '.$entry); - OC_Template::printErrorPage( $entry ); + $result = self::executeAudited($query, $inserts); + } catch(DatabaseException $e) { + OC_Template::printExceptionErrorPage( $e ); } if((int)$result->numRows() === 0) { @@ -674,16 +707,12 @@ class OC_DB { } try { - $result = self::prepare($query); + $result = self::executeAudited($query, $inserts); } catch(PDOException $e) { - $entry = 'DB Error: "'.$e->getMessage() . '"<br />'; - $entry .= 'Offending command was: ' . $query.'<br />'; - OC_Log::write('core', $entry, OC_Log::FATAL); - error_log('DB error: ' . $entry); - OC_Template::printErrorPage( $entry ); + OC_Template::printExceptionErrorPage( $e ); } - return $result->execute($inserts); + return $result; } /** @@ -891,7 +920,32 @@ class OC_DB { return false; } } + /** + * check if a result is an error, writes a log entry and throws an exception, works with MDB2 and PDOException + * @param mixed $result + * @param string message + * @return void + * @throws DatabaseException + */ + public static function raiseExceptionOnError($result, $message = null) { + if(self::isError($result)) { + if ($message === null) { + $message = self::getErrorMessage($result); + } else { + $message .= ', Root cause:' . self::getErrorMessage($result); + } + throw new DatabaseException($message, getErrorCode($result)); + } + } + public static function getErrorCode($error) { + if ( self::$backend==self::BACKEND_MDB2 and PEAR::isError($error) ) { + $code = $error->getCode(); + } elseif ( self::$backend==self::BACKEND_PDO and self::$PDO ) { + $code = self::$PDO->errorCode(); + } + return $code; + } /** * returns the error code and message as a string for logging * works with MDB2 and PDOException @@ -901,9 +955,7 @@ class OC_DB { public static function getErrorMessage($error) { if ( self::$backend==self::BACKEND_MDB2 and PEAR::isError($error) ) { $msg = $error->getCode() . ': ' . $error->getMessage(); - if (defined('DEBUG') && DEBUG) { - $msg .= '(' . $error->getDebugInfo() . ')'; - } + $msg .= ' (' . $error->getDebugInfo() . ')'; } elseif (self::$backend==self::BACKEND_PDO and self::$PDO) { $msg = self::$PDO->errorCode() . ': '; $errorInfo = self::$PDO->errorInfo(); diff --git a/lib/files/cache/backgroundwatcher.php b/lib/files/cache/backgroundwatcher.php index 8933101577d..8e68f41cf44 100644 --- a/lib/files/cache/backgroundwatcher.php +++ b/lib/files/cache/backgroundwatcher.php @@ -59,9 +59,9 @@ class BackgroundWatcher { */ static private function getNextFileId($previous, $folder) { if ($folder) { - $query = \OC_DB::prepare('SELECT `fileid` FROM `*PREFIX*filecache` WHERE `fileid` > ? AND mimetype = ' . self::getFolderMimetype() . ' ORDER BY `fileid` ASC', 1); + $query = \OC_DB::prepare('SELECT `fileid` FROM `*PREFIX*filecache` WHERE `fileid` > ? AND `mimetype` = ' . self::getFolderMimetype() . ' ORDER BY `fileid` ASC', 1); } else { - $query = \OC_DB::prepare('SELECT `fileid` FROM `*PREFIX*filecache` WHERE `fileid` > ? AND mimetype != ' . self::getFolderMimetype() . ' ORDER BY `fileid` ASC', 1); + $query = \OC_DB::prepare('SELECT `fileid` FROM `*PREFIX*filecache` WHERE `fileid` > ? AND `mimetype` != ' . self::getFolderMimetype() . ' ORDER BY `fileid` ASC', 1); } $result = $query->execute(array($previous)); if ($row = $result->fetchRow()) { diff --git a/lib/files/cache/cache.php b/lib/files/cache/cache.php index 0210d5a73f1..5b2fcfaadf9 100644 --- a/lib/files/cache/cache.php +++ b/lib/files/cache/cache.php @@ -96,10 +96,13 @@ class Cache { * get the stored metadata of a file or folder * * @param string/int $file - * @return array + * @return array | false */ public function get($file) { if (is_string($file) or $file == '') { + // normalize file + $file = $this->normalize($file); + $where = 'WHERE `storage` = ? AND `path_hash` = ?'; $params = array($this->getNumericStorageId(), md5($file)); } else { //file id @@ -112,6 +115,12 @@ class Cache { $result = $query->execute($params); $data = $result->fetchRow(); + //FIXME hide this HACK in the next database layer, or just use doctrine and get rid of MDB2 and PDO + //PDO returns false, MDB2 returns null, oracle always uses MDB2, so convert null to false + if ($data === null) { + $data = false; + } + //merge partial data if (!$data and is_string($file)) { if (isset($this->partial[$file])) { @@ -179,6 +188,9 @@ class Cache { $this->update($id, $data); return $id; } else { + // normalize file + $file = $this->normalize($file); + if (isset($this->partial[$file])) { //add any saved partial data $data = array_merge($this->partial[$file], $data); unset($this->partial[$file]); @@ -220,11 +232,22 @@ class Cache { * @param array $data */ public function update($id, array $data) { + + if(isset($data['path'])) { + // normalize path + $data['path'] = $this->normalize($data['path']); + } + + if(isset($data['name'])) { + // normalize path + $data['name'] = $this->normalize($data['name']); + } + list($queryParts, $params) = $this->buildParts($data); $params[] = $id; $query = \OC_DB::prepare('UPDATE `*PREFIX*filecache` SET ' . implode(' = ?, ', $queryParts) . '=?' - . ' WHERE fileid = ?'); + . ' WHERE `fileid` = ?'); $query->execute($params); } @@ -267,6 +290,9 @@ class Cache { * @return int */ public function getId($file) { + // normalize file + $file = $this->normalize($file); + $pathHash = md5($file); $query = \OC_DB::prepare('SELECT `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path_hash` = ?'); @@ -334,6 +360,10 @@ class Cache { * @param string $target */ public function move($source, $target) { + // normalize source and target + $source = $this->normalize($source); + $target = $this->normalize($target); + $sourceData = $this->get($source); $sourceId = $sourceData['fileid']; $newParentId = $this->getParentId($target); @@ -361,10 +391,10 @@ class Cache { * remove all entries for files that are stored on the storage from the cache */ public function clear() { - $query = \OC_DB::prepare('DELETE FROM `*PREFIX*filecache` WHERE storage = ?'); + $query = \OC_DB::prepare('DELETE FROM `*PREFIX*filecache` WHERE `storage` = ?'); $query->execute(array($this->getNumericStorageId())); - $query = \OC_DB::prepare('DELETE FROM `*PREFIX*storages` WHERE id = ?'); + $query = \OC_DB::prepare('DELETE FROM `*PREFIX*storages` WHERE `id` = ?'); $query->execute(array($this->storageId)); } @@ -374,6 +404,9 @@ class Cache { * @return int, Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE */ public function getStatus($file) { + // normalize file + $file = $this->normalize($file); + $pathHash = md5($file); $query = \OC_DB::prepare('SELECT `size` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path_hash` = ?'); $result = $query->execute(array($this->getNumericStorageId(), $pathHash)); @@ -402,6 +435,10 @@ class Cache { * @return array of file data */ public function search($pattern) { + + // normalize pattern + $pattern = $this->normalize($pattern); + $query = \OC_DB::prepare(' SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`, `encrypted`, `unencrypted_size`, `etag` FROM `*PREFIX*filecache` WHERE `name` LIKE ? AND `storage` = ?' @@ -551,4 +588,14 @@ class Cache { return null; } } + + /** + * normalize the given path + * @param $path + * @return string + */ + public function normalize($path) { + + return \OC_Util::normalizeUnicode($path); + } } diff --git a/lib/files/cache/legacy.php b/lib/files/cache/legacy.php index b8e2548639b..ab8ae6dfadd 100644 --- a/lib/files/cache/legacy.php +++ b/lib/files/cache/legacy.php @@ -45,7 +45,7 @@ class Legacy { return $this->cacheHasItems; } try { - $query = \OC_DB::prepare('SELECT `id` FROM `*PREFIX*fscache` WHERE `user` = ? LIMIT 1'); + $query = \OC_DB::prepare('SELECT `id` FROM `*PREFIX*fscache` WHERE `user` = ?',1); } catch (\Exception $e) { $this->cacheHasItems = false; return false; diff --git a/lib/files/filesystem.php b/lib/files/filesystem.php index b10625e20de..d3fddf8c421 100644 --- a/lib/files/filesystem.php +++ b/lib/files/filesystem.php @@ -152,6 +152,9 @@ class Filesystem { * @return string */ static public function getMountPoint($path) { + if (!self::$mounts) { + \OC_Util::setupFS(); + } $mount = self::$mounts->find($path); if ($mount) { return $mount->getMountPoint(); @@ -167,6 +170,9 @@ class Filesystem { * @return string[] */ static public function getMountPoints($path) { + if (!self::$mounts) { + \OC_Util::setupFS(); + } $result = array(); $mounts = self::$mounts->findIn($path); foreach ($mounts as $mount) { @@ -182,6 +188,9 @@ class Filesystem { * @return \OC\Files\Storage\Storage */ public static function getStorage($mountPoint) { + if (!self::$mounts) { + \OC_Util::setupFS(); + } $mount = self::$mounts->find($mountPoint); return $mount->getStorage(); } @@ -191,6 +200,9 @@ class Filesystem { * @return Mount\Mount[] */ public static function getMountByStorageId($id) { + if (!self::$mounts) { + \OC_Util::setupFS(); + } return self::$mounts->findByStorageId($id); } @@ -199,6 +211,9 @@ class Filesystem { * @return Mount\Mount[] */ public static function getMountByNumericId($id) { + if (!self::$mounts) { + \OC_Util::setupFS(); + } return self::$mounts->findByNumericId($id); } @@ -209,6 +224,9 @@ class Filesystem { * @return array consisting of the storage and the internal path */ static public function resolvePath($path) { + if (!self::$mounts) { + \OC_Util::setupFS(); + } $mount = self::$mounts->find($path); if ($mount) { return array($mount->getStorage(), $mount->getInternalPath($path)); @@ -223,7 +241,7 @@ class Filesystem { } self::$defaultInstance = new View($root); - if(!self::$mounts) { + if (!self::$mounts) { self::$mounts = new Mount\Manager(); } @@ -235,8 +253,8 @@ class Filesystem { return true; } - static public function initMounts(){ - if(!self::$mounts) { + static public function initMounts() { + if (!self::$mounts) { self::$mounts = new Mount\Manager(); } } @@ -359,7 +377,9 @@ class Filesystem { * clear all mounts and storage backends */ public static function clearMounts() { - self::$mounts->clear(); + if (self::$mounts) { + self::$mounts->clear(); + } } /** @@ -370,6 +390,9 @@ class Filesystem { * @param string $mountpoint */ static public function mount($class, $arguments, $mountpoint) { + if (!self::$mounts) { + \OC_Util::setupFS(); + } $mount = new Mount\Mount($class, $mountpoint, $arguments); self::$mounts->addMount($mount); } @@ -631,9 +654,8 @@ class Filesystem { $path = substr($path, 0, -1); } //normalize unicode if possible - if (class_exists('Normalizer')) { - $path = \Normalizer::normalize($path); - } + $path = \OC_Util::normalizeUnicode($path); + return $path; } diff --git a/lib/files/view.php b/lib/files/view.php index ecb0f30400a..e2fc8d965b8 100644 --- a/lib/files/view.php +++ b/lib/files/view.php @@ -300,7 +300,7 @@ class View { list ($count, $result) = \OC_Helper::streamCopy($data, $target); fclose($target); fclose($data); - if ($this->fakeRoot == Filesystem::getRoot() && !Cache\Scanner::isPartialFile($path)) { + if ($this->fakeRoot == Filesystem::getRoot() && !Cache\Scanner::isPartialFile($path) && $result !== false) { if (!$exists) { \OC_Hook::emit( Filesystem::CLASSNAME, @@ -386,11 +386,13 @@ class View { $source = $this->fopen($path1 . $postFix1, 'r'); $target = $this->fopen($path2 . $postFix2, 'w'); list($count, $result) = \OC_Helper::streamCopy($source, $target); - list($storage1, $internalPath1) = Filesystem::resolvePath($absolutePath1 . $postFix1); - $storage1->unlink($internalPath1); + if ($result !== false) { + list($storage1, $internalPath1) = Filesystem::resolvePath($absolutePath1 . $postFix1); + $storage1->unlink($internalPath1); + } } } - if ($this->fakeRoot == Filesystem::getRoot() && !Cache\Scanner::isPartialFile($path1)) { + if ($this->fakeRoot == Filesystem::getRoot() && !Cache\Scanner::isPartialFile($path1) && $result !== false) { \OC_Hook::emit( Filesystem::CLASSNAME, Filesystem::signal_post_rename, @@ -484,7 +486,7 @@ class View { list($count, $result) = \OC_Helper::streamCopy($source, $target); } } - if ($this->fakeRoot == Filesystem::getRoot()) { + if ($this->fakeRoot == Filesystem::getRoot() && $result !== false) { \OC_Hook::emit( Filesystem::CLASSNAME, Filesystem::signal_post_copy, @@ -648,7 +650,7 @@ class View { $result = $storage->$operation($internalPath); } $result = \OC_FileProxy::runPostProxies($operation, $this->getAbsolutePath($path), $result); - if (Filesystem::$loaded and $this->fakeRoot == Filesystem::getRoot()) { + if (Filesystem::$loaded and $this->fakeRoot == Filesystem::getRoot() && $result !== false) { if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open $this->runHooks($hooks, $path, true); } diff --git a/lib/l10n/bg_BG.php b/lib/l10n/bg_BG.php index 2de4c0a6e68..8412ac9548f 100644 --- a/lib/l10n/bg_BG.php +++ b/lib/l10n/bg_BG.php @@ -21,16 +21,21 @@ "%s enter the database username." => "%s въведете потребителско име за базата с данни.", "%s enter the database name." => "%s въведете име на базата с данни.", "%s you may not use dots in the database name" => "%s, не можете да ползвате точки в името на базата от данни", +"%s set the database host." => "%s задай хост на базата данни.", "PostgreSQL username and/or password not valid" => "Невалидно PostgreSQL потребителско име и/или парола", "You need to enter either an existing account or the administrator." => "Необходимо е да влезете в всъществуващ акаунт или като администратора", +"Oracle connection could not be established" => "Oracle връзка не можа да се осъществи", "MySQL username and/or password not valid" => "Невалидно MySQL потребителско име и/или парола", "DB Error: \"%s\"" => "Грешка в базата от данни: \"%s\"", +"Offending command was: \"%s\"" => "Проблемната команда беше: \"%s\"", "MySQL user '%s'@'localhost' exists already." => "MySQL потребителят '%s'@'localhost' вече съществува", "Drop this user from MySQL" => "Изтриване на потребителя от MySQL", "MySQL user '%s'@'%%' already exists" => "MySQL потребителят '%s'@'%%' вече съществува.", "Drop this user from MySQL." => "Изтриване на потребителя от MySQL.", "Oracle username and/or password not valid" => "Невалидно Oracle потребителско име и/или парола", +"Offending command was: \"%s\", name: %s, password: %s" => "Проблемната команда беше: \"%s\", име: %s, парола: %s", "MS SQL username and/or password not valid: %s" => "Невалидно MS SQL потребителско име и/или парола: %s", +"Your web server is not yet properly setup to allow files synchronization because the WebDAV interface seems to be broken." => "Вашият web сървър все още не е удачно настроен да позволява синхронизация на файлове, защото WebDAV интерфейсът изглежда не работи.", "Please double check the <a href='%s'>installation guides</a>." => "Моля направете повторна справка с <a href='%s'>ръководството за инсталиране</a>.", "seconds ago" => "преди секунди", "1 minute ago" => "преди 1 минута", diff --git a/lib/l10n/cs_CZ.php b/lib/l10n/cs_CZ.php index 36469507d40..b74b9a7184c 100644 --- a/lib/l10n/cs_CZ.php +++ b/lib/l10n/cs_CZ.php @@ -24,6 +24,7 @@ "%s set the database host." => "Zadejte název počítače s databází %s.", "PostgreSQL username and/or password not valid" => "Uživatelské jméno, či heslo PostgreSQL není platné", "You need to enter either an existing account or the administrator." => "Musíte zadat existující účet, či správce.", +"Oracle connection could not be established" => "Spojení s Oracle nemohlo být navázáno", "MySQL username and/or password not valid" => "Uživatelské jméno, či heslo MySQL není platné", "DB Error: \"%s\"" => "Chyba DB: \"%s\"", "Offending command was: \"%s\"" => "Podezřelý příkaz byl: \"%s\"", diff --git a/lib/l10n/de.php b/lib/l10n/de.php index 74715bc66eb..4869689ba78 100644 --- a/lib/l10n/de.php +++ b/lib/l10n/de.php @@ -24,6 +24,7 @@ "%s set the database host." => "%s setze den Datenbank-Host", "PostgreSQL username and/or password not valid" => "PostgreSQL Benutzername und/oder Passwort ungültig", "You need to enter either an existing account or the administrator." => "Du musst entweder ein existierendes Benutzerkonto oder das Administratoren-Konto angeben.", +"Oracle connection could not be established" => "Es konnte keine Verbindung zur Oracle-Datenbank hergestellt werden", "MySQL username and/or password not valid" => "MySQL Benutzername und/oder Passwort ungültig", "DB Error: \"%s\"" => "DB Fehler: \"%s\"", "Offending command was: \"%s\"" => "Fehlerhafter Befehl war: \"%s\"", diff --git a/lib/l10n/he.php b/lib/l10n/he.php index dcd0545adba..0069d77eee4 100644 --- a/lib/l10n/he.php +++ b/lib/l10n/he.php @@ -15,6 +15,8 @@ "Files" => "קבצים", "Text" => "טקסט", "Images" => "תמונות", +"Your web server is not yet properly setup to allow files synchronization because the WebDAV interface seems to be broken." => "שרת האינטרנט שלך אינו מוגדר לצורכי סנכרון קבצים עדיין כיוון שמנשק ה־WebDAV כנראה אינו תקין.", +"Please double check the <a href='%s'>installation guides</a>." => "נא לעיין שוב ב<a href='%s'>מדריכי ההתקנה</a>.", "seconds ago" => "שניות", "1 minute ago" => "לפני דקה אחת", "%d minutes ago" => "לפני %d דקות", diff --git a/lib/l10n/lt_LT.php b/lib/l10n/lt_LT.php index cebaa6937d8..b8268ed4376 100644 --- a/lib/l10n/lt_LT.php +++ b/lib/l10n/lt_LT.php @@ -14,13 +14,17 @@ "Token expired. Please reload page." => "Sesija baigėsi. Prašome perkrauti puslapį.", "Files" => "Failai", "Text" => "Žinučių", +"Images" => "Paveikslėliai", "seconds ago" => "prieš sekundę", "1 minute ago" => "Prieš 1 minutę", "%d minutes ago" => "prieš %d minučių", +"1 hour ago" => "prieš 1 valandą", +"%d hours ago" => "prieš %d valandų", "today" => "šiandien", "yesterday" => "vakar", "%d days ago" => "prieš %d dienų", "last month" => "praeitą mėnesį", +"%d months ago" => "prieš %d mėnesių", "last year" => "praeitais metais", "years ago" => "prieš metus" ); diff --git a/lib/l10n/ru.php b/lib/l10n/ru.php index e077b688c09..e3e3aee5a92 100644 --- a/lib/l10n/ru.php +++ b/lib/l10n/ru.php @@ -24,6 +24,7 @@ "%s set the database host." => "%s задайте хост базы данных.", "PostgreSQL username and/or password not valid" => "Неверное имя пользователя и/или пароль PostgreSQL", "You need to enter either an existing account or the administrator." => "Вы должны войти или в существующий аккаунт или под администратором.", +"Oracle connection could not be established" => "соединение с Oracle не может быть установлено", "MySQL username and/or password not valid" => "Неверное имя пользователя и/или пароль MySQL", "DB Error: \"%s\"" => "Ошибка БД: \"%s\"", "Offending command was: \"%s\"" => "Вызываемая команда была: \"%s\"", diff --git a/lib/l10n/sv.php b/lib/l10n/sv.php index 3dcb26d5d8d..f2b7c892058 100644 --- a/lib/l10n/sv.php +++ b/lib/l10n/sv.php @@ -16,6 +16,25 @@ "Files" => "Filer", "Text" => "Text", "Images" => "Bilder", +"Set an admin username." => "Ange ett användarnamn för administratören.", +"Set an admin password." => "Ange ett administratörslösenord.", +"%s enter the database username." => "%s ange databasanvändare.", +"%s enter the database name." => "%s ange databasnamn", +"%s you may not use dots in the database name" => "%s du får inte använda punkter i databasnamnet", +"%s set the database host." => "%s ange databasserver/host.", +"PostgreSQL username and/or password not valid" => "PostgreSQL-användarnamnet och/eller lösenordet är felaktigt", +"You need to enter either an existing account or the administrator." => "Du måste antingen ange ett befintligt konto eller administratör.", +"Oracle connection could not be established" => "Oracle-anslutning kunde inte etableras", +"MySQL username and/or password not valid" => "MySQL-användarnamnet och/eller lösenordet är felaktigt", +"DB Error: \"%s\"" => "DB error: \"%s\"", +"Offending command was: \"%s\"" => "Det felaktiga kommandot var: \"%s\"", +"MySQL user '%s'@'localhost' exists already." => "MySQL-användaren '%s'@'localhost' existerar redan.", +"Drop this user from MySQL" => "Radera denna användare från MySQL", +"MySQL user '%s'@'%%' already exists" => "MySQl-användare '%s'@'%%' existerar redan", +"Drop this user from MySQL." => "Radera denna användare från MySQL.", +"Oracle username and/or password not valid" => "Oracle-användarnamnet och/eller lösenordet är felaktigt", +"Offending command was: \"%s\", name: %s, password: %s" => "Det felande kommandot var: \"%s\", name: %s, password: %s", +"MS SQL username and/or password not valid: %s" => "MS SQL-användaren och/eller lösenordet var inte giltigt: %s", "Your web server is not yet properly setup to allow files synchronization because the WebDAV interface seems to be broken." => "Din webbserver är inte korrekt konfigurerad för att tillåta filsynkronisering eftersom WebDAV inte verkar fungera.", "Please double check the <a href='%s'>installation guides</a>." => "Var god kontrollera <a href='%s'>installationsguiden</a>.", "seconds ago" => "sekunder sedan", diff --git a/lib/l10n/tr.php b/lib/l10n/tr.php index 7996447b95d..2662d61649d 100644 --- a/lib/l10n/tr.php +++ b/lib/l10n/tr.php @@ -24,6 +24,7 @@ "%s set the database host." => "%s veritabanı sunucu adını tanımla", "PostgreSQL username and/or password not valid" => "PostgreSQL adi kullanici ve/veya parola yasal degildir. ", "You need to enter either an existing account or the administrator." => "Bir konto veya kullanici birlemek ihtiyacin. ", +"Oracle connection could not be established" => "Oracle bağlantısı kurulamadı", "MySQL username and/or password not valid" => "MySQL kullanıcı adı ve/veya parolası geçerli değil", "DB Error: \"%s\"" => "DB Hata: ''%s''", "Offending command was: \"%s\"" => "Komut rahasiz ''%s''. ", diff --git a/lib/l10n/zh_CN.php b/lib/l10n/zh_CN.php index 61e405d8058..edb0f81ee9d 100644 --- a/lib/l10n/zh_CN.php +++ b/lib/l10n/zh_CN.php @@ -24,6 +24,7 @@ "%s set the database host." => "%s 设置数据库所在主机。", "PostgreSQL username and/or password not valid" => "PostgreSQL 数据库用户名和/或密码无效", "You need to enter either an existing account or the administrator." => "你需要输入一个数据库中已有的账户或管理员账户。", +"Oracle connection could not be established" => "不能建立甲骨文连接", "MySQL username and/or password not valid" => "MySQL 数据库用户名和/或密码无效", "DB Error: \"%s\"" => "数据库错误:\"%s\"", "Offending command was: \"%s\"" => "冲突命令为:\"%s\"", diff --git a/lib/public/backgroundjob.php b/lib/public/backgroundjob.php index 601046fe691..cc076a3a845 100644 --- a/lib/public/backgroundjob.php +++ b/lib/public/backgroundjob.php @@ -1,49 +1,46 @@ <?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/>. -* -*/ + * 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. + * Public interface of ownCloud for background 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; +use \OC\BackgroundJob\JobList; + /** - * This class provides functions to manage backgroundjobs in ownCloud - * - * There are two kind of background jobs in ownCloud: regular tasks and - * queued tasks. + * This class provides functions to register backgroundjobs in ownCloud * - * 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. + * To create a new backgroundjob create a new class that inharits from either \OC\BackgroundJob\Job, + * \OC\BackgroundJob\QueuedJob or \OC\BackgroundJob\TimedJob and register it using + * \OCP\BackgroundJob->registerJob($job, $argument), $argument will be passed to the run() function + * of the job when the job is executed. * - * 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. + * A regular Job will be executed every time cron.php is run, a QueuedJob will only run once and a TimedJob + * will only run at a specific interval which is to be specified in the constructor of the job by calling + * $this->setInterval($interval) with $interval in seconds. */ class BackgroundJob { /** @@ -59,82 +56,136 @@ class BackgroundJob { /** * @brief sets the background jobs execution type - * @param $type execution type + * @param string $type execution type * @return boolean * * This method sets the execution type of the background jobs. Possible types * are "none", "ajax", "webcron", "cron" */ - public static function setExecutionType( $type ) { - return \OC_BackgroundJob::setExecutionType( $type ); + public static function setExecutionType($type) { + return \OC_BackgroundJob::setExecutionType($type); + } + + /** + * @param \OC\BackgroundJob\Job|string $job + * @param mixed $argument + */ + public static function registerJob($job, $argument = null) { + $jobList = new JobList(); + $jobList->add($job, $argument); } /** + * @deprecated * @brief creates a regular task - * @param $klass class name - * @param $method method name + * @param string $klass class name + * @param string $method method name * @return true */ - public static function addRegularTask( $klass, $method ) { - return \OC_BackgroundJob_RegularTask::register( $klass, $method ); + public static function addRegularTask($klass, $method) { + self::registerJob('OC\BackgroundJob\Legacy\RegularJob', array($klass, $method)); + return true; } /** + * @deprecated * @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(); + $jobList = new JobList(); + $allJobs = $jobList->getAll(); + $regularJobs = array(); + foreach ($allJobs as $job) { + if ($job instanceof RegularLegacyJob) { + $key = implode('-', $job->getArgument()); + $regularJobs[$key] = $job->getArgument(); + } + } + return $regularJobs; } /** + * @deprecated * @brief Gets one queued task - * @param $id ID of the task + * @param int $id ID of the task * @return associative array */ - public static function findQueuedTask( $id ) { - return \OC_BackgroundJob_QueuedTask::find( $id ); + public static function findQueuedTask($id) { + $jobList = new JobList(); + return $jobList->getById($id); } /** + * @deprecated * @brief Gets all queued tasks * @return array with associative arrays */ public static function allQueuedTasks() { - return \OC_BackgroundJob_QueuedTask::all(); + $jobList = new JobList(); + $allJobs = $jobList->getAll(); + $queuedJobs = array(); + foreach ($allJobs as $job) { + if ($job instanceof QueuedLegacyJob) { + $queuedJob = $job->getArgument(); + $queuedJob['id'] = $job->getId(); + $queuedJobs[] = $queuedJob; + } + } + return $queuedJobs; } /** + * @deprecated * @brief Gets all queued tasks of a specific app - * @param $app app name + * @param string $app app name * @return array with associative arrays */ - public static function queuedTaskWhereAppIs( $app ) { - return \OC_BackgroundJob_QueuedTask::whereAppIs( $app ); + public static function queuedTaskWhereAppIs($app) { + $jobList = new JobList(); + $allJobs = $jobList->getAll(); + $queuedJobs = array(); + foreach ($allJobs as $job) { + if ($job instanceof QueuedLegacyJob) { + $queuedJob = $job->getArgument(); + $queuedJob['id'] = $job->getId(); + if ($queuedJob['app'] === $app) { + $queuedJobs[] = $queuedJob; + } + } + } + return $queuedJobs; } /** + * @deprecated * @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 + * @param string $app app name + * @param string $class class name + * @param string $method method name + * @param string $parameters all useful data as text + * @return int id of task */ - public static function addQueuedTask( $app, $klass, $method, $parameters ) { - return \OC_BackgroundJob_QueuedTask::add( $app, $klass, $method, $parameters ); + public static function addQueuedTask($app, $class, $method, $parameters) { + self::registerJob('OC\BackgroundJob\Legacy\QueuedJob', array('app' => $app, 'klass' => $class, 'method' => $method, 'parameters' => $parameters)); + return true; } /** + * @deprecated * @brief deletes a queued task - * @param $id id of task - * @return true/false + * @param int $id id of task + * @return bool * * Deletes a report */ - public static function deleteQueuedTask( $id ) { - return \OC_BackgroundJob_QueuedTask::delete( $id ); + public static function deleteQueuedTask($id) { + $jobList = new JobList(); + $job = $jobList->getById($id); + if ($job) { + $jobList->remove($job); + } } } diff --git a/lib/public/share.php b/lib/public/share.php index 6c93139b107..6a26101a1ce 100644 --- a/lib/public/share.php +++ b/lib/public/share.php @@ -152,11 +152,11 @@ class Share { // Fetch all shares of this file path from DB $query = \OC_DB::prepare( - 'SELECT share_with + 'SELECT `share_with` FROM `*PREFIX*share` WHERE - item_source = ? AND share_type = ?' + `item_source` = ? AND `share_type` = ?' ); $result = $query->execute(array($source, self::SHARE_TYPE_USER)); @@ -171,11 +171,11 @@ class Share { // We also need to take group shares into account $query = \OC_DB::prepare( - 'SELECT share_with + 'SELECT `share_with` FROM `*PREFIX*share` WHERE - item_source = ? AND share_type = ?' + `item_source` = ? AND `share_type` = ?' ); $result = $query->execute(array($source, self::SHARE_TYPE_GROUP)); @@ -192,11 +192,11 @@ class Share { //check for public link shares if (!$publicShare) { $query = \OC_DB::prepare( - 'SELECT share_with + 'SELECT `share_with` FROM `*PREFIX*share` WHERE - item_source = ? AND share_type = ?' + `item_source` = ? AND `share_type` = ?' ); $result = $query->execute(array($source, self::SHARE_TYPE_LINK)); @@ -1009,7 +1009,7 @@ class Share { if (!isset($mounts[$row['storage']])) { $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']); if (is_array($mountPoints)) { - $mounts[$row['storage']] = $mountPoints[key($mountPoints)]; + $mounts[$row['storage']] = current($mountPoints); } } if ($mounts[$row['storage']]) { diff --git a/lib/response.php b/lib/response.php index 49d79fda709..674176d078b 100644 --- a/lib/response.php +++ b/lib/response.php @@ -11,6 +11,7 @@ class OC_Response { const STATUS_NOT_MODIFIED = 304; const STATUS_TEMPORARY_REDIRECT = 307; const STATUS_NOT_FOUND = 404; + const STATUS_INTERNAL_SERVER_ERROR = 500; /** * @brief Enable response caching by sending correct HTTP headers @@ -70,6 +71,9 @@ class OC_Response { case self::STATUS_NOT_FOUND; $status = $status . ' Not Found'; break; + case self::STATUS_INTERNAL_SERVER_ERROR; + $status = $status . ' Internal Server Error'; + break; } header($protocol.' '.$status); } diff --git a/lib/setup.php b/lib/setup.php index a63cc664dbc..71a2d13937e 100644 --- a/lib/setup.php +++ b/lib/setup.php @@ -106,12 +106,6 @@ class OC_Setup { 'hint' => $e->getHint() ); return($error); - } catch (Exception $e) { - $error[] = array( - 'error' => $e->getMessage(), - 'hint' => '' - ); - return($error); } } elseif($dbtype == 'pgsql') { @@ -127,7 +121,7 @@ class OC_Setup { try { self::setupPostgreSQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix, $username); - } catch (Exception $e) { + } catch (DatabaseSetupException $e) { $error[] = array( 'error' => $l->t('PostgreSQL username and/or password not valid'), 'hint' => $l->t('You need to enter either an existing account or the administrator.') @@ -150,7 +144,7 @@ class OC_Setup { try { self::setupOCIDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix, $dbtablespace, $username); - } catch (Exception $e) { + } catch (DatabaseSetupException $e) { $error[] = array( 'error' => $l->t('Oracle connection could not be established'), 'hint' => $e->getMessage().' Check environment: ORACLE_HOME='.getenv('ORACLE_HOME') @@ -177,7 +171,7 @@ class OC_Setup { try { self::setupMSSQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix); - } catch (Exception $e) { + } catch (DatabaseSetupException $e) { $error[] = array( 'error' => 'MS SQL username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.' @@ -326,7 +320,7 @@ class OC_Setup { $connection_string = "host='$e_host' dbname=postgres user='$e_user' password='$e_password'"; $connection = @pg_connect($connection_string); if(!$connection) { - throw new Exception($l->t('PostgreSQL username and/or password not valid')); + throw new DatabaseSetupException($l->t('PostgreSQL username and/or password not valid')); } $e_user = pg_escape_string($dbuser); //check for roles creation rights in postgresql @@ -371,7 +365,7 @@ class OC_Setup { $connection_string = "host='$e_host' dbname='$e_dbname' user='$e_user' password='$e_password'"; $connection = @pg_connect($connection_string); if(!$connection) { - throw new Exception($l->t('PostgreSQL username and/or password not valid')); + throw new DatabaseSetupException($l->t('PostgreSQL username and/or password not valid')); } $query = "select count(*) FROM pg_class WHERE relname='{$dbtableprefix}users' limit 1"; $result = pg_query($connection, $query); @@ -461,9 +455,9 @@ class OC_Setup { if(!$connection) { $e = oci_error(); if (is_array ($e) && isset ($e['message'])) { - throw new Exception($e['message']); + throw new DatabaseSetupException($e['message']); } - throw new Exception($l->t('Oracle username and/or password not valid')); + throw new DatabaseSetupException($l->t('Oracle username and/or password not valid')); } //check for roles creation rights in oracle @@ -530,7 +524,7 @@ class OC_Setup { } $connection = @oci_connect($dbuser, $dbpass, $easy_connect_string); if(!$connection) { - throw new Exception($l->t('Oracle username and/or password not valid')); + throw new DatabaseSetupException($l->t('Oracle username and/or password not valid')); } $query = "SELECT count(*) FROM user_tables WHERE table_name = :un"; $stmt = oci_parse($connection, $query); @@ -641,7 +635,7 @@ class OC_Setup { } else { $entry = ''; } - throw new Exception($l->t('MS SQL username and/or password not valid: %s', array($entry))); + throw new DatabaseSetupException($l->t('MS SQL username and/or password not valid: %s', array($entry))); } OC_Config::setValue('dbuser', $dbuser); diff --git a/lib/template.php b/lib/template.php index 9467dedb62a..01f0fc28b60 100644 --- a/lib/template.php +++ b/lib/template.php @@ -535,4 +535,25 @@ class OC_Template{ $content->printPage(); die(); } + + /** + * print error page using Exception details + * @param Exception $exception + */ + + public static function printExceptionErrorPage(Exception $exception) { + $error_msg = $exception->getMessage(); + if ($exception->getCode()) { + $error_msg = '['.$exception->getCode().'] '.$error_msg; + } + $hint = $exception->getTraceAsString(); + while ($exception = $exception->previous()) { + $error_msg .= '<br/>Caused by: '; + if ($exception->getCode()) { + $error_msg .= '['.$exception->getCode().'] '; + } + $error_msg .= $exception->getMessage(); + }; + self::printErrorPage($error_msg, $hint); + } } diff --git a/lib/user.php b/lib/user.php index 1dde87a1339..06ea8e791dd 100644 --- a/lib/user.php +++ b/lib/user.php @@ -30,35 +30,85 @@ * post_createUser(uid, password) * pre_deleteUser(&run, uid) * post_deleteUser(uid) - * pre_setPassword(&run, uid, password) - * post_setPassword(uid, password) + * pre_setPassword(&run, uid, password, recoveryPassword) + * post_setPassword(uid, password, recoveryPassword) * pre_login(&run, uid, password) * post_login(uid) * logout() */ class OC_User { - // The backend used for user management - private static $_usedBackends = array(); + public static $userSession = null; + + private static function getUserSession() { + if (!self::$userSession) { + $manager = new \OC\User\Manager(); + self::$userSession = new \OC\User\Session($manager, \OC::$session); + self::$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) { + \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password)); + }); + self::$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) { + /** @var $user \OC\User\User */ + \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password)); + }); + self::$userSession->listen('\OC\User', 'preDelete', function ($user) { + /** @var $user \OC\User\User */ + \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID())); + }); + self::$userSession->listen('\OC\User', 'postDelete', function ($user) { + /** @var $user \OC\User\User */ + \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID())); + }); + self::$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) { + /** @var $user \OC\User\User */ + OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword)); + }); + self::$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) { + /** @var $user \OC\User\User */ + OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword)); + }); + self::$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) { + \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password)); + }); + self::$userSession->listen('\OC\User', 'postLogin', function ($user, $password) { + /** @var $user \OC\User\User */ + \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password)); + }); + self::$userSession->listen('\OC\User', 'logout', function () { + \OC_Hook::emit('OC_User', 'logout', array()); + }); + } + return self::$userSession; + } - private static $_setupedBackends = array(); + /** + * @return \OC\User\Manager + */ + private static function getManager() { + return self::getUserSession()->getManager(); + } - // Backends available (except database) private static $_backends = array(); + private static $_usedBackends = array(); + + private static $_setupedBackends = array(); + /** * @brief registers backend - * @param $name name of the backend - * @returns true/false + * @param string $backend name of the backend + * @deprecated Add classes by calling useBackend with a class instance instead + * @return bool * * 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; } /** * @brief gets available backends + * @deprecated * @returns array of backends * * Returns the names of all backends. @@ -69,6 +119,7 @@ class OC_User { /** * @brief gets used backends + * @deprecated * @returns array of backends * * Returns the names of all used backends. @@ -79,33 +130,36 @@ class OC_User { /** * @brief Adds the backend to the list of used backends - * @param $backend default: database The backend to use for user managment - * @returns true/false + * @param string | OC_User_Backend $backend default: database The backend to use for user management + * @return bool * * Set the User Authentication Module */ - public static function useBackend( $backend = 'database' ) { - if($backend instanceof OC_User_Interface) { - OC_Log::write('core', 'Adding user backend instance of '.get_class($backend).'.', OC_Log::DEBUG); - self::$_usedBackends[get_class($backend)]=$backend; + public static function useBackend($backend = 'database') { + if ($backend instanceof OC_User_Interface) { + OC_Log::write('core', 'Adding user backend instance of ' . get_class($backend) . '.', OC_Log::DEBUG); + self::$_usedBackends[get_class($backend)] = $backend; + self::getManager()->registerBackend($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': - OC_Log::write('core', 'Adding user backend '.$backend.'.', OC_Log::DEBUG); + OC_Log::write('core', 'Adding user backend ' . $backend . '.', OC_Log::DEBUG); self::$_usedBackends[$backend] = new OC_User_Database(); + self::getManager()->registerBackend(self::$_usedBackends[$backend]); break; default: - OC_Log::write('core', 'Adding default user backend '.$backend.'.', OC_Log::DEBUG); + OC_Log::write('core', 'Adding default user backend ' . $backend . '.', OC_Log::DEBUG); $className = 'OC_USER_' . strToUpper($backend); self::$_usedBackends[$backend] = new $className(); + self::getManager()->registerBackend(self::$_usedBackends[$backend]); break; } } @@ -116,121 +170,73 @@ class OC_User { * remove all used backends */ public static function clearBackends() { - self::$_usedBackends=array(); + self::$_usedBackends = array(); + self::getManager()->clearBackends(); } /** * 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)) { - if(array_search($i, self::$_setupedBackends)===false) { + $backends = OC_Config::getValue('user_backends', array()); + foreach ($backends as $i => $config) { + $class = $config['class']; + $arguments = $config['arguments']; + if (class_exists($class)) { + if (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; + $_setupedBackends[] = $i; } else { - OC_Log::write('core', 'User backend '.$class.' already initialized.', OC_Log::DEBUG); + OC_Log::write('core', 'User backend ' . $class . ' already initialized.', OC_Log::DEBUG); } } else { - OC_Log::write('core', 'User backend '.$class.' not found.', OC_Log::ERROR); + 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 - * @returns true/false + * @param string $uid The username of the user to create + * @param string $password The password of the new user + * @throws Exception + * @return bool true/false * * Creates a new user. Basic checking of username is done in OC_User * itself, not in its subclasses. * * Allowed characters in the username are: "a-z", "A-Z", "0-9" and "_.@-" */ - 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 )) { - 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) == '') { - throw new Exception('A valid username must be provided'); - } - // No empty password - if(trim($password) == '') { - throw new Exception('A valid password must be provided'); - } - - // Check if user already exists - if( self::userExistsForCreation($uid) ) { - throw new Exception('The username is already being used'); - } - - - $run = true; - OC_Hook::emit( "OC_User", "pre_createUser", array( "run" => &$run, "uid" => $uid, "password" => $password )); - - if( $run ) { - //create the user in the first backend that supports creating users - foreach(self::$_usedBackends as $backend) { - if(!$backend->implementsActions(OC_USER_BACKEND_CREATE_USER)) - continue; - - $backend->createUser($uid, $password); - OC_Hook::emit( "OC_User", "post_createUser", array( "uid" => $uid, "password" => $password )); - - return self::userExists($uid); - } - } - return false; + public static function createUser($uid, $password) { + return self::getManager()->createUser($uid, $password); } /** * @brief delete a user - * @param $uid The username of the user to delete - * @returns true/false + * @param string $uid The username of the user to delete + * @return bool * * Deletes a user */ - public static function deleteUser( $uid ) { - $run = true; - OC_Hook::emit( "OC_User", "pre_deleteUser", array( "run" => &$run, "uid" => $uid )); - - if( $run ) { - //delete the user from all backends - foreach(self::$_usedBackends as $backend) { - $backend->deleteUser($uid); - } - if (self::userExists($uid)) { - return false; - } + public static function deleteUser($uid) { + $user = self::getManager()->get($uid); + if ($user) { + $user->delete(); + // We have to delete the user from all groups - foreach( OC_Group::getUserGroups( $uid ) as $i ) { - OC_Group::removeFromGroup( $uid, $i ); + foreach (OC_Group::getUserGroups($uid) as $i) { + OC_Group::removeFromGroup($uid, $i); } // Delete the user's keys in preferences OC_Preferences::deleteUser($uid); // Delete user files in /data/ - OC_Helper::rmdirr(OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ) . '/'.$uid.'/'); - - // Emit and exit - OC_Hook::emit( "OC_User", "post_deleteUser", array( "uid" => $uid )); - return true; - } - else{ - return false; + OC_Helper::rmdirr(OC_Config::getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid . '/'); } } @@ -238,75 +244,34 @@ class OC_User { * @brief Try to login a user * @param $uid The username of the user to log in * @param $password The password of the user - * @returns true/false + * @return bool * * Log in a user and regenerate a new session - if the password is ok */ - public static function login( $uid, $password ) { - $run = true; - OC_Hook::emit( "OC_User", "pre_login", array( "run" => &$run, "uid" => $uid, "password" => $password)); - - if( $run ) { - $uid = self::checkPassword( $uid, $password ); - $enabled = self::isEnabled($uid); - if($uid && $enabled) { - session_regenerate_id(true); - self::setUserId($uid); - self::setDisplayName($uid); - OC_Hook::emit( "OC_User", "post_login", array( "uid" => $uid, 'password'=>$password )); - return true; - } - } - return false; + public static function login($uid, $password) { + return self::getUserSession()->login($uid, $password); } /** * @brief Sets user id for session and triggers emit */ public static function setUserId($uid) { - \OC::$session->set('user_id', $uid); + OC::$session->set('user_id', $uid); } /** * @brief Sets user display name for session */ public static function setDisplayName($uid, $displayName = null) { - $result = false; - if ($displayName ) { - foreach(self::$_usedBackends as $backend) { - if($backend->implementsActions(OC_USER_BACKEND_SET_DISPLAYNAME)) { - if($backend->userExists($uid)) { - $result |= $backend->setDisplayName($uid, $displayName); - } - } - } - } else { - $displayName = self::determineDisplayName($uid); - $result = true; - } - if (OC_User::getUser() === $uid) { - \OC::$session->set('display_name', $displayName); + if (is_null($displayName)) { + $displayName = $uid; } - return $result; - } - - - /** - * @brief get display name - * @param $uid The username - * @returns string display name or uid if no display name is defined - * - */ - private static function determineDisplayName( $uid ) { - foreach(self::$_usedBackends as $backend) { - if($backend->implementsActions(OC_USER_BACKEND_GET_DISPLAYNAME)) { - $result=$backend->getDisplayName( $uid ); - if($result) { - return $result; - } - } + $user = self::getManager()->get($uid); + if ($user) { + return $user->setDisplayName($displayName); + } else { + return false; } - return $uid; } /** @@ -315,36 +280,31 @@ class OC_User { * Logout, destroys session */ public static function logout() { - OC_Hook::emit( "OC_User", "logout", array()); - session_unset(); - session_destroy(); - OC_User::unsetMagicInCookie(); + self::getUserSession()->logout(); } /** * @brief Check if the user is logged in - * @returns true/false + * @returns bool * * Checks if the user is logged in */ public static function isLoggedIn() { - if( \OC::$session->get('user_id')) { + if (\OC::$session->get('user_id')) { OC_App::loadApps(array('authentication')); self::setupBackends(); - if (self::userExists(\OC::$session->get('user_id')) ) { - return true; - } + return self::userExists(\OC::$session->get('user_id')); } return false; } /** * @brief Check if the user is an admin user - * @param $uid uid of the admin - * @returns bool + * @param string $uid uid of the admin + * @return bool */ public static function isAdminUser($uid) { - if(OC_Group::inGroup($uid, 'admin' )) { + if (OC_Group::inGroup($uid, 'admin')) { return true; } return false; @@ -356,32 +316,40 @@ class OC_User { * @return string uid or false */ public static function getUser() { - if( \OC::$session->get('user_id') ) { - return \OC::$session->get('user_id'); - } - else{ + $uid = OC::$session->get('user_id'); + if (!is_null($uid)) { + return $uid; + } else { return false; } } /** * @brief get the display name of the user currently logged in. + * @param string $uid * @return string uid or false */ - public static function getDisplayName($user=null) { - if ( $user ) { - return self::determineDisplayName($user); - } else if( \OC::$session->get('display_name') ) { - return \OC::$session->get('display_name'); - } - else{ - return false; + public static function getDisplayName($uid = null) { + if ($uid) { + $user = self::getManager()->get($uid); + if ($user) { + return $user->getDisplayName(); + } else { + return $uid; + } + } else { + $user = self::getUserSession()->getUser(); + if ($user) { + return $user->getDisplayName(); + } else { + return false; + } } } /** * @brief Autogenerate a password - * @returns string + * @return string * * generates a password */ @@ -391,112 +359,89 @@ class OC_User { /** * @brief Set password - * @param $uid The username - * @param $password The new password - * @param $recoveryPassword for the encryption app to reset encryption keys - * @returns true/false + * @param string $uid The username + * @param string $password The new password + * @param string $recoveryPassword for the encryption app to reset encryption keys + * @return bool * * Change the password of a user */ - public static function setPassword( $uid, $password, $recoveryPassword = null ) { - $run = true; - OC_Hook::emit( "OC_User", "pre_setPassword", array( "run" => &$run, "uid" => $uid, "password" => $password, "recoveryPassword" => $recoveryPassword )); - - if( $run ) { - $success = false; - foreach(self::$_usedBackends as $backend) { - if($backend->implementsActions(OC_USER_BACKEND_SET_PASSWORD)) { - if($backend->userExists($uid)) { - $success |= $backend->setPassword($uid, $password); - } - } - } - // invalidate all login cookies - OC_Preferences::deleteApp($uid, 'login_token'); - OC_Hook::emit( "OC_User", "post_setPassword", array( "uid" => $uid, "password" => $password, "recoveryPassword" => $recoveryPassword )); - return $success; - } - else{ + public static function setPassword($uid, $password, $recoveryPassword = null) { + $user = self::getManager()->get($uid); + if ($user) { + return $user->setPassword($password, $recoveryPassword); + } else { return false; } } /** * @brief Check whether user can change his password - * @param $uid The username - * @returns true/false + * @param string $uid The username + * @return bool * * Check whether a specified user can change his password */ public static function canUserChangePassword($uid) { - foreach(self::$_usedBackends as $backend) { - if($backend->implementsActions(OC_USER_BACKEND_SET_PASSWORD)) { - if($backend->userExists($uid)) { - return true; - } - } + $user = self::getManager()->get($uid); + if ($user) { + return $user->canChangePassword(); + } else { + return false; } - return false; } /** * @brief Check whether user can change his display name - * @param $uid The username - * @returns true/false + * @param string $uid The username + * @return bool * * Check whether a specified user can change his display name */ public static function canUserChangeDisplayName($uid) { - if (OC_Config::getValue('allow_user_to_change_display_name', true)) { - foreach(self::$_usedBackends as $backend) { - if($backend->implementsActions(OC_USER_BACKEND_SET_DISPLAYNAME)) { - if($backend->userExists($uid)) { - return true; - } - } - } + $user = self::getManager()->get($uid); + if ($user) { + return $user->canChangeDisplayName(); + } else { + return false; } - return false; } /** * @brief Check if the password is correct - * @param $uid The username - * @param $password The password - * @returns string + * @param string $uid The username + * @param string $password The password + * @return bool * * 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)) { - $result=$backend->checkPassword( $uid, $password ); - if($result) { - return $result; - } + public static function checkPassword($uid, $password) { + $user = self::getManager()->get($uid); + if ($user) { + if ($user->checkPassword($password)) { + return $user->getUID(); + } else { + return false; } + } else { + return false; } } /** - * @brief Check if the password is correct * @param string $uid The username - * @param string $password The password - * @returns string + * @return string * * returns the path to the users home directory */ public static function getHome($uid) { - foreach(self::$_usedBackends as $backend) { - if($backend->implementsActions(OC_USER_BACKEND_GET_HOME) && $backend->userExists($uid)) { - $result=$backend->getHome($uid); - if($result) { - return $result; - } - } + $user = self::getManager()->get($uid); + if ($user) { + return $user->getHome(); + } else { + return OC_Config::getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid; } - return OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ) . '/' . $uid; } /** @@ -506,152 +451,93 @@ class OC_User { * Get a list of all users. */ public static function getUsers($search = '', $limit = null, $offset = null) { - $users = array(); - foreach (self::$_usedBackends as $backend) { - $backendUsers = $backend->getUsers($search, $limit, $offset); - if (is_array($backendUsers)) { - $users = array_merge($users, $backendUsers); - } + $users = self::getManager()->search($search, $limit, $offset); + $uids = array(); + foreach ($users as $user) { + $uids[] = $user->getUID(); } - asort($users); - return $users; + return $uids; } /** * @brief Get a list of all users display name - * @returns associative array with all display names (value) and corresponding uids (key) + * @param string $search + * @param int $limit + * @param int $offset + * @return array associative array with all display names (value) and corresponding uids (key) * * Get a list of all display names and user ids. */ public static function getDisplayNames($search = '', $limit = null, $offset = null) { $displayNames = array(); - foreach (self::$_usedBackends as $backend) { - $backendDisplayNames = $backend->getDisplayNames($search, $limit, $offset); - if (is_array($backendDisplayNames)) { - $displayNames = $displayNames + $backendDisplayNames; - } + $users = self::getManager()->searchDisplayName($search, $limit, $offset); + foreach ($users as $user) { + $displayNames[$user->getUID()] = $user->getDisplayName(); } - asort($displayNames); return $displayNames; } /** * @brief check if a user exists * @param string $uid the username - * @param string $excludingBackend (default none) * @return boolean */ - public static function userExists($uid, $excludingBackend=null) { - foreach(self::$_usedBackends as $backend) { - if (!is_null($excludingBackend) && !strcmp(get_class($backend), $excludingBackend)) { - OC_Log::write('OC_User', $excludingBackend . 'excluded from user existance check.', OC_Log::DEBUG); - continue; - } - $result=$backend->userExists($uid); - if($result===true) { - return true; - } - } - return false; + public static function userExists($uid) { + return self::getManager()->userExists($uid); } - public static function userExistsForCreation($uid) { - foreach(self::$_usedBackends as $backend) { - if(!$backend->hasUserListings()) - continue; - - $result=$backend->userExists($uid); - if($result===true) { - return true; - } - } - return false; - } - /** * disables a user - * @param string $userid the user to disable + * + * @param string $uid the user to disable */ - public static function disableUser($userid) { - $sql = "INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, `configkey`, `configvalue`) VALUES(?, ?, ?, ?)"; - $stmt = OC_DB::prepare($sql); - if ( ! OC_DB::isError($stmt) ) { - $result = $stmt->execute(array($userid, 'core', 'enabled', 'false')); - if ( OC_DB::isError($result) ) { - OC_Log::write('OC_User', 'could not enable user: '. OC_DB::getErrorMessage($result), OC_Log::ERROR); - } - } else { - OC_Log::write('OC_User', 'could not disable user: '. OC_DB::getErrorMessage($stmt), OC_Log::ERROR); + public static function disableUser($uid) { + $user = self::getManager()->get($uid); + if ($user) { + $user->setEnabled(false); } } /** * enable a user - * @param string $userid + * + * @param string $uid */ - public static function enableUser($userid) { - $sql = 'DELETE FROM `*PREFIX*preferences`' - ." WHERE `userid` = ? AND `appid` = ? AND `configkey` = ? AND `configvalue` = ?"; - $stmt = OC_DB::prepare($sql); - if ( ! OC_DB::isError($stmt) ) { - $result = $stmt->execute(array($userid, 'core', 'enabled', 'false')); - if ( OC_DB::isError($result) ) { - OC_Log::write('OC_User', 'could not enable user: '. OC_DB::getErrorMessage($result), OC_Log::ERROR); - } - } else { - OC_Log::write('OC_User', 'could not enable user: '. OC_DB::getErrorMessage($stmt), OC_Log::ERROR); + public static function enableUser($uid) { + $user = self::getManager()->get($uid); + if ($user) { + $user->setEnabled(true); } } /** * checks if a user is enabled - * @param string $userid + * + * @param string $uid * @return bool */ - public static function isEnabled($userid) { - $sql = 'SELECT `userid` FROM `*PREFIX*preferences`' - .' WHERE `userid` = ? AND `appid` = ? AND `configkey` = ? AND `configvalue` = ?'; - if (OC_Config::getValue( 'dbtype', 'sqlite' ) === 'oci') { //FIXME oracle hack - $sql = 'SELECT `userid` FROM `*PREFIX*preferences`' - .' WHERE `userid` = ? AND `appid` = ? AND `configkey` = ? AND to_char(`configvalue`) = ?'; - } - $stmt = OC_DB::prepare($sql); - if ( ! OC_DB::isError($stmt) ) { - $result = $stmt->execute(array($userid, 'core', 'enabled', 'false')); - if ( ! OC_DB::isError($result) ) { - return $result->numRows() ? false : true; - } else { - OC_Log::write('OC_User', - 'could not check if enabled: '. OC_DB::getErrorMessage($result), - OC_Log::ERROR); - } + public static function isEnabled($uid) { + $user = self::getManager()->get($uid); + if ($user) { + return $user->isEnabled(); } else { - OC_Log::write('OC_User', 'could not check if enabled: '. OC_DB::getErrorMessage($stmt), OC_Log::ERROR); + return false; } - return false; } /** * @brief Set cookie value to use in next page load * @param string $username username to be set + * @param string $token */ public static function setMagicInCookie($username, $token) { - $secure_cookie = OC_Config::getValue("forcessl", false); - $expires = time() + OC_Config::getValue('remember_login_cookie_lifetime', 60*60*24*15); - setcookie("oc_username", $username, $expires, OC::$WEBROOT, '', $secure_cookie); - setcookie("oc_token", $token, $expires, OC::$WEBROOT, '', $secure_cookie, true); - setcookie("oc_remember_login", true, $expires, OC::$WEBROOT, '', $secure_cookie); + self::getUserSession()->setMagicInCookie($username, $token); } /** * @brief Remove cookie for "remember username" */ public static function unsetMagicInCookie() { - unset($_COOKIE["oc_username"]); - unset($_COOKIE["oc_token"]); - unset($_COOKIE["oc_remember_login"]); - setcookie("oc_username", null, -1); - setcookie("oc_token", null, -1); - setcookie("oc_remember_login", null, -1); + self::getUserSession()->unsetMagicInCookie(); } } diff --git a/lib/user/backend.php b/lib/user/backend.php index 93e8f17ca98..e9be08e429c 100644 --- a/lib/user/backend.php +++ b/lib/user/backend.php @@ -58,7 +58,7 @@ abstract class OC_User_Backend implements OC_User_Interface { /** * @brief Get all supported actions - * @returns bitwise-or'ed actions + * @return int bitwise-or'ed actions * * Returns the supported actions as int to be * compared with OC_USER_BACKEND_CREATE_USER etc. @@ -76,8 +76,8 @@ abstract class OC_User_Backend implements OC_User_Interface { /** * @brief Check if backend implements actions - * @param $actions bitwise-or'ed actions - * @returns boolean + * @param int $actions bitwise-or'ed actions + * @return boolean * * Returns the supported actions as int to be * compared with OC_USER_BACKEND_CREATE_USER etc. @@ -87,12 +87,12 @@ abstract class OC_User_Backend implements OC_User_Interface { } /** - * @brief delete a user - * @param $uid The username of the user to delete - * @returns true/false - * - * Deletes a user - */ + * @brief delete a user + * @param string $uid The username of the user to delete + * @return bool + * + * Deletes a user + */ public function deleteUser( $uid ) { return false; } @@ -127,8 +127,8 @@ abstract class OC_User_Backend implements OC_User_Interface { /** * @brief get display name of the user - * @param $uid user ID of the user - * @return display name + * @param string $uid user ID of the user + * @return string display name */ public function getDisplayName($uid) { return $uid; diff --git a/lib/user/dummy.php b/lib/user/dummy.php index d63f60efbeb..b5b7a6c3c7a 100644 --- a/lib/user/dummy.php +++ b/lib/user/dummy.php @@ -1,114 +1,118 @@ <?php /** -* ownCloud -* -* @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 -* 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/>. -* -*/ + * ownCloud + * + * @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 + * 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/>. + * + */ /** * dummy user backend, does not keep state, only for testing use */ class OC_User_Dummy extends OC_User_Backend { - private $users=array(); + private $users = array(); + /** - * @brief Create a new user - * @param $uid The username of the user to create - * @param $password The password of the new user - * @returns true/false - * - * Creates a new user. Basic checking of username is done in OC_User - * itself, not in its subclasses. - */ + * @brief Create a new user + * @param string $uid The username of the user to create + * @param string $password The password of the new user + * @return bool + * + * 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])) { + if (isset($this->users[$uid])) { return false; - }else{ - $this->users[$uid]=$password; + } else { + $this->users[$uid] = $password; return true; } } /** - * @brief delete a user - * @param $uid The username of the user to delete - * @returns true/false - * - * Deletes a user - */ - public function deleteUser( $uid ) { - if(isset($this->users[$uid])) { + * @brief delete a user + * @param string $uid The username of the user to delete + * @return bool + * + * Deletes a user + */ + public function deleteUser($uid) { + if (isset($this->users[$uid])) { unset($this->users[$uid]); return true; - }else{ + } else { return false; } } /** - * @brief Set password - * @param $uid The username - * @param $password The new password - * @returns true/false - * - * Change the password of a user - */ + * @brief Set password + * @param string $uid The username + * @param string $password The new password + * @return bool + * + * Change the password of a user + */ public function setPassword($uid, $password) { - if(isset($this->users[$uid])) { - $this->users[$uid]=$password; + if (isset($this->users[$uid])) { + $this->users[$uid] = $password; return true; - }else{ + } else { return false; } } /** - * @brief Check if the password is correct - * @param $uid The username - * @param $password The password - * @returns string - * - * Check if the password is correct without logging in the user - * returns the user id or false - */ + * @brief Check if the password is correct + * @param string $uid The username + * @param string $password The password + * @return string + * + * 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])) { - return ($this->users[$uid]==$password); - }else{ + if (isset($this->users[$uid])) { + return ($this->users[$uid] == $password); + } else { return false; } } /** - * @brief Get a list of all users - * @returns array with all uids - * - * Get a list of all users. - */ + * @brief Get a list of all users + * @param string $search + * @param int $limit + * @param int $offset + * @return array with all uids + * + * Get a list of all users. + */ public function getUsers($search = '', $limit = null, $offset = null) { return array_keys($this->users); } /** - * @brief check if a user exists - * @param string $uid the username - * @return boolean - */ + * @brief check if a user exists + * @param string $uid the username + * @return boolean + */ public function userExists($uid) { return isset($this->users[$uid]); } diff --git a/lib/user/manager.php b/lib/user/manager.php new file mode 100644 index 00000000000..d17cdf1a200 --- /dev/null +++ b/lib/user/manager.php @@ -0,0 +1,228 @@ +<?php + +/** + * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OC\User; + +use OC\Hooks\PublicEmitter; + +/** + * Class Manager + * + * Hooks available in scope \OC\User: + * - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword) + * - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword) + * - preDelete(\OC\User\User $user) + * - postDelete(\OC\User\User $user) + * - preCreateUser(string $uid, string $password) + * - postCreateUser(\OC\User\User $user, string $password) + * + * @package OC\User + */ +class Manager extends PublicEmitter { + /** + * @var \OC_User_Backend[] $backends + */ + private $backends = array(); + + private $cachedUsers = array(); + + public function __construct() { + $cachedUsers = $this->cachedUsers; + $this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) { + $i = array_search($user, $cachedUsers); + if ($i !== false) { + unset($cachedUsers[$i]); + } + }); + } + + /** + * register a user backend + * + * @param \OC_User_Backend $backend + */ + public function registerBackend($backend) { + $this->backends[] = $backend; + } + + /** + * remove a user backend + * + * @param \OC_User_Backend $backend + */ + public function removeBackend($backend) { + $this->cachedUsers = array(); + if (($i = array_search($backend, $this->backends)) !== false) { + unset($this->backends[$i]); + } + } + + /** + * remove all user backends + */ + public function clearBackends() { + $this->cachedUsers = array(); + $this->backends = array(); + } + + /** + * get a user by user id + * + * @param string $uid + * @return \OC\User\User + */ + public function get($uid) { + if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends + return $this->cachedUsers[$uid]; + } + foreach ($this->backends as $backend) { + if ($backend->userExists($uid)) { + return $this->getUserObject($uid, $backend); + } + } + return null; + } + + /** + * get or construct the user object + * + * @param string $uid + * @param \OC_User_Backend $backend + * @return \OC\User\User + */ + protected function getUserObject($uid, $backend) { + if (isset($this->cachedUsers[$uid])) { + return $this->cachedUsers[$uid]; + } + $this->cachedUsers[$uid] = new User($uid, $backend, $this); + return $this->cachedUsers[$uid]; + } + + /** + * check if a user exists + * + * @param string $uid + * @return bool + */ + public function userExists($uid) { + $user = $this->get($uid); + return ($user !== null); + } + + /** + * search by user id + * + * @param string $pattern + * @param int $limit + * @param int $offset + * @return \OC\User\User[] + */ + public function search($pattern, $limit = null, $offset = null) { + $users = array(); + foreach ($this->backends as $backend) { + $backendUsers = $backend->getUsers($pattern, $limit, $offset); + if (is_array($backendUsers)) { + foreach ($backendUsers as $uid) { + $users[] = $this->getUserObject($uid, $backend); + if (!is_null($limit)) { + $limit--; + } + if (!is_null($offset) and $offset > 0) { + $offset--; + } + + } + } + } + + usort($users, function ($a, $b) { + /** + * @var \OC\User\User $a + * @var \OC\User\User $b + */ + return strcmp($a->getUID(), $b->getUID()); + }); + return $users; + } + + /** + * search by displayName + * + * @param string $pattern + * @param int $limit + * @param int $offset + * @return \OC\User\User[] + */ + public function searchDisplayName($pattern, $limit = null, $offset = null) { + $users = array(); + foreach ($this->backends as $backend) { + $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset); + if (is_array($backendUsers)) { + foreach ($backendUsers as $uid => $displayName) { + $users[] = $this->getUserObject($uid, $backend); + if (!is_null($limit)) { + $limit--; + } + if (!is_null($offset) and $offset > 0) { + $offset--; + } + + } + } + } + + usort($users, function ($a, $b) { + /** + * @var \OC\User\User $a + * @var \OC\User\User $b + */ + return strcmp($a->getDisplayName(), $b->getDisplayName()); + }); + return $users; + } + + /** + * @param string $uid + * @param string $password + * @throws \Exception + * @return bool | \OC\User\User the created user of false + */ + public 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)) { + 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) == '') { + throw new \Exception('A valid username must be provided'); + } + // No empty password + if (trim($password) == '') { + throw new \Exception('A valid password must be provided'); + } + + // Check if user already exists + if ($this->userExists($uid)) { + throw new \Exception('The username is already being used'); + } + + $this->emit('\OC\User', 'preCreateUser', array($uid, $password)); + foreach ($this->backends as $backend) { + if ($backend->implementsActions(\OC_USER_BACKEND_CREATE_USER)) { + $backend->createUser($uid, $password); + $user = $this->getUserObject($uid, $backend); + $this->emit('\OC\User', 'postCreateUser', array($user, $password)); + return $user; + } + } + return false; + } +} diff --git a/lib/user/session.php b/lib/user/session.php new file mode 100644 index 00000000000..cf93d9593af --- /dev/null +++ b/lib/user/session.php @@ -0,0 +1,173 @@ +<?php + +/** + * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OC\User; + +use OC\Hooks\Emitter; + +/** + * Class Session + * + * Hooks available in scope \OC\User: + * - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword) + * - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword) + * - preDelete(\OC\User\User $user) + * - postDelete(\OC\User\User $user) + * - preCreateUser(string $uid, string $password) + * - postCreateUser(\OC\User\User $user) + * - preLogin(string $user, string $password) + * - postLogin(\OC\User\User $user) + * - logout() + * + * @package OC\User + */ +class Session implements Emitter { + /** + * @var \OC\User\Manager $manager + */ + private $manager; + + /** + * @var \OC\Session\Session $session + */ + private $session; + + /** + * @var \OC\User\User $activeUser + */ + protected $activeUser; + + /** + * @param \OC\User\Manager $manager + * @param \OC\Session\Session $session + */ + public function __construct($manager, $session) { + $this->manager = $manager; + $this->session = $session; + } + + /** + * @param string $scope + * @param string $method + * @param callable $callback + */ + public function listen($scope, $method, $callback) { + $this->manager->listen($scope, $method, $callback); + } + + /** + * @param string $scope optional + * @param string $method optional + * @param callable $callback optional + */ + public function removeListener($scope = null, $method = null, $callback = null) { + $this->manager->removeListener($scope, $method, $callback); + } + + /** + * get the manager object + * + * @return \OC\User\Manager + */ + public function getManager() { + return $this->manager; + } + + /** + * set the currently active user + * + * @param \OC\User\User $user + */ + public function setUser($user) { + if (is_null($user)) { + $this->session->remove('user_id'); + } else { + $this->session->set('user_id', $user->getUID()); + } + $this->activeUser = $user; + } + + /** + * get the current active user + * + * @return \OC\User\User + */ + public function getUser() { + if ($this->activeUser) { + return $this->activeUser; + } else { + $uid = $this->session->get('user_id'); + if ($uid) { + $this->activeUser = $this->manager->get($uid); + return $this->activeUser; + } else { + return null; + } + } + } + + /** + * try to login with the provided credentials + * + * @param string $uid + * @param string $password + * @return bool + */ + public function login($uid, $password) { + $this->manager->emit('\OC\User', 'preLogin', array($uid, $password)); + $user = $this->manager->get($uid); + if ($user) { + $result = $user->checkPassword($password); + if ($result and $user->isEnabled()) { + $this->setUser($user); + $this->manager->emit('\OC\User', 'postLogin', array($user, $password)); + return true; + } else { + return false; + } + } else { + return false; + } + } + + /** + * logout the user from the session + */ + public function logout() { + $this->manager->emit('\OC\User', 'logout'); + $this->setUser(null); + $this->unsetMagicInCookie(); + } + + /** + * Set cookie value to use in next page load + * + * @param string $username username to be set + * @param string $token + */ + public function setMagicInCookie($username, $token) { + $secure_cookie = \OC_Config::getValue("forcessl", false); //TODO: DI for cookies and OC_Config + $expires = time() + \OC_Config::getValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15); + setcookie("oc_username", $username, $expires, \OC::$WEBROOT, '', $secure_cookie); + setcookie("oc_token", $token, $expires, \OC::$WEBROOT, '', $secure_cookie, true); + setcookie("oc_remember_login", true, $expires, \OC::$WEBROOT, '', $secure_cookie); + } + + /** + * Remove cookie for "remember username" + */ + public function unsetMagicInCookie() { + unset($_COOKIE["oc_username"]); //TODO: DI + unset($_COOKIE["oc_token"]); + unset($_COOKIE["oc_remember_login"]); + setcookie("oc_username", null, -1); + setcookie("oc_token", null, -1); + setcookie("oc_remember_login", null, -1); + } +} diff --git a/lib/user/user.php b/lib/user/user.php new file mode 100644 index 00000000000..55d7848a979 --- /dev/null +++ b/lib/user/user.php @@ -0,0 +1,197 @@ +<?php + +/** + * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OC\User; + +use OC\Hooks\Emitter; + +class User { + /** + * @var string $uid + */ + private $uid; + + /** + * @var string $displayName + */ + private $displayName; + + /** + * @var \OC_User_Backend $backend + */ + private $backend; + + /** + * @var bool $enabled + */ + private $enabled; + + /** + * @var Emitter | Manager $emitter + */ + private $emitter; + + /** + * @param string $uid + * @param \OC_User_Backend $backend + * @param Emitter $emitter + */ + public function __construct($uid, $backend, $emitter = null) { + $this->uid = $uid; + if ($backend->implementsActions(OC_USER_BACKEND_GET_DISPLAYNAME)) { + $this->displayName = $backend->getDisplayName($uid); + } else { + $this->displayName = $uid; + } + $this->backend = $backend; + $this->emitter = $emitter; + $enabled = \OC_Preferences::getValue($uid, 'core', 'enabled', 'true'); //TODO: DI for OC_Preferences + $this->enabled = ($enabled === 'true'); + } + + /** + * get the user id + * + * @return string + */ + public function getUID() { + return $this->uid; + } + + /** + * get the displayname for the user, if no specific displayname is set it will fallback to the user id + * + * @return string + */ + public function getDisplayName() { + return $this->displayName; + } + + /** + * set the displayname for the user + * + * @param string $displayName + * @return bool + */ + public function setDisplayName($displayName) { + if ($this->canChangeDisplayName()) { + $this->displayName = $displayName; + $result = $this->backend->setDisplayName($this->uid, $displayName); + return $result !== false; + } else { + return false; + } + } + + /** + * Delete the user + * + * @return bool + */ + public function delete() { + if ($this->emitter) { + $this->emitter->emit('\OC\User', 'preDelete', array($this)); + } + $result = $this->backend->deleteUser($this->uid); + if ($this->emitter) { + $this->emitter->emit('\OC\User', 'postDelete', array($this)); + } + return !($result === false); + } + + /** + * Check if the password is valid for the user + * + * @param $password + * @return bool + */ + public function checkPassword($password) { + if ($this->backend->implementsActions(\OC_USER_BACKEND_CHECK_PASSWORD)) { + $result = $this->backend->checkPassword($this->uid, $password); + if ($result !== false) { + $this->uid = $result; + } + return !($result === false); + } else { + return false; + } + } + + /** + * Set the password of the user + * + * @param string $password + * @param string $recoveryPassword for the encryption app to reset encryption keys + * @return bool + */ + public function setPassword($password, $recoveryPassword) { + if ($this->emitter) { + $this->emitter->emit('\OC\User', 'preSetPassword', array($this, $password, $recoveryPassword)); + } + if ($this->backend->implementsActions(\OC_USER_BACKEND_SET_PASSWORD)) { + $result = $this->backend->setPassword($this->uid, $password); + if ($this->emitter) { + $this->emitter->emit('\OC\User', 'postSetPassword', array($this, $password, $recoveryPassword)); + } + return !($result === false); + } else { + return false; + } + } + + /** + * get the users home folder to mount + * + * @return string + */ + public function getHome() { + if ($this->backend->implementsActions(\OC_USER_BACKEND_GET_HOME) and $home = $this->backend->getHome($this->uid)) { + return $home; + } + return \OC_Config::getValue("datadirectory", \OC::$SERVERROOT . "/data") . '/' . $this->uid; //TODO switch to Config object once implemented + } + + /** + * check if the backend supports changing passwords + * + * @return bool + */ + public function canChangePassword() { + return $this->backend->implementsActions(\OC_USER_BACKEND_SET_PASSWORD); + } + + /** + * check if the backend supports changing display names + * + * @return bool + */ + public function canChangeDisplayName() { + return $this->backend->implementsActions(\OC_USER_BACKEND_SET_DISPLAYNAME); + } + + /** + * check if the user is enabled + * + * @return bool + */ + public function isEnabled() { + return $this->enabled; + } + + /** + * set the enabled status for the user + * + * @param bool $enabled + */ + public function setEnabled($enabled) { + $this->enabled = $enabled; + $enabled = ($enabled) ? 'true' : 'false'; + \OC_Preferences::setValue($this->uid, 'core', 'enabled', $enabled); + } +} diff --git a/lib/util.php b/lib/util.php index 581f35bc0ac..95af22ed0ee 100755 --- a/lib/util.php +++ b/lib/util.php @@ -1,4 +1,7 @@ <?php + +require_once 'Patchwork/PHP/Shim/Normalizer.php'; + /** * Class for utility functions * @@ -77,7 +80,7 @@ class OC_Util { public static function getVersion() { // hint: We only can count up. Reset minor/patchlevel when // updating major/minor version number. - return array(5, 80, 04); + return array(5, 80, 05); } /** @@ -641,11 +644,10 @@ class OC_Util { /** * Check if the ownCloud server can connect to the internet */ - public static function isinternetconnectionworking() { - - // in case there is no internet connection on purpose there is no need to display a warning - if (!\OC_Config::getValue("has_internet_connection", true)) { - return true; + public static function isInternetConnectionWorking() { + // in case there is no internet connection on purpose return false + if (self::isInternetConnectionEnabled() === false) { + return false; } // try to connect to owncloud.org to see if http connections to the internet are possible. @@ -667,6 +669,13 @@ class OC_Util { } } + + /** + * Check if the connection to the internet is disabled on purpose + */ + public static function isInternetConnectionEnabled(){ + return \OC_Config::getValue("has_internet_connection", true); + } /** * clear all levels of output buffering @@ -823,5 +832,21 @@ class OC_Util { return $theme; } + /** + * Normalize a unicode string + * @param string $value a not normalized string + * @return bool|string + */ + public static function normalizeUnicode($value) { + if(class_exists('Patchwork\PHP\Shim\Normalizer')) { + $normalizedValue = \Patchwork\PHP\Shim\Normalizer::normalize($value); + if($normalizedValue === false) { + \OC_Log::write( 'core', 'normalizing failed for "' . $value . '"', \OC_Log::WARN); + } else { + $value = $normalizedValue; + } + } + return $value; + } } |