From 6f4ecd32b37cc668ee0d59721c2451f349bb9290 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Fri, 21 Feb 2014 22:52:48 +0100 Subject: Add more caching in the group manager --- lib/private/group/manager.php | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) (limited to 'lib/private') diff --git a/lib/private/group/manager.php b/lib/private/group/manager.php index 9b433b64fd4..451de0c0539 100644 --- a/lib/private/group/manager.php +++ b/lib/private/group/manager.php @@ -40,7 +40,12 @@ class Manager extends PublicEmitter { /** * @var \OC\Group\Group[] */ - private $cachedGroups; + private $cachedGroups = array(); + + /** + * @var \OC\Group\Group[] + */ + private $cachedUserGroups = array(); /** * @param \OC\User\Manager $userManager @@ -141,7 +146,7 @@ class Manager extends PublicEmitter { $offset -= count($groupIds); } foreach ($groupIds as $groupId) { - $groups[$groupId] = $this->getGroupObject($groupId); + $groups[$groupId] = $this->get($groupId); } if (!is_null($limit) and $limit <= 0) { return array_values($groups); @@ -155,13 +160,18 @@ class Manager extends PublicEmitter { * @return \OC\Group\Group[] */ public function getUserGroups($user) { + $uid = $user->getUID(); + if (isset($this->cachedUserGroups[$uid])) { + return $this->cachedUserGroups[$uid]; + } $groups = array(); foreach ($this->backends as $backend) { - $groupIds = $backend->getUserGroups($user->getUID()); + $groupIds = $backend->getUserGroups($uid); foreach ($groupIds as $groupId) { - $groups[$groupId] = $this->getGroupObject($groupId); + $groups[$groupId] = $this->get($groupId); } } - return array_values($groups); + $this->cachedUserGroups[$uid] = array_values($groups); + return $this->cachedUserGroups[$uid]; } } -- cgit v1.2.3 From f4f72e77d8bf312b6fc693d43ef5fc831130db3b Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Fri, 21 Feb 2014 22:53:31 +0100 Subject: Delay fetching the display name until it is requested --- lib/private/user/user.php | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'lib/private') diff --git a/lib/private/user/user.php b/lib/private/user/user.php index ef5364cbf7b..710f9061b53 100644 --- a/lib/private/user/user.php +++ b/lib/private/user/user.php @@ -55,11 +55,6 @@ class User { */ public function __construct($uid, $backend, $emitter = null, $config = null) { $this->uid = $uid; - if ($backend and $backend->implementsActions(OC_USER_BACKEND_GET_DISPLAYNAME)) { - $this->displayName = $backend->getDisplayName($uid); - } else { - $this->displayName = $uid; - } $this->backend = $backend; $this->emitter = $emitter; $this->config = $config; @@ -86,6 +81,13 @@ class User { * @return string */ public function getDisplayName() { + if (!isset($this->displayName)) { + if ($this->backend and $this->backend->implementsActions(OC_USER_BACKEND_GET_DISPLAYNAME)) { + $this->displayName = $this->backend->getDisplayName($this->uid); + } else { + $this->displayName = $this->uid; + } + } return $this->displayName; } -- cgit v1.2.3 From 00e27d5343dab36380129dd8d30e2699e5121079 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 27 Feb 2014 19:12:03 +0100 Subject: Clear the cached user groups when a group is deleted --- lib/private/group/manager.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'lib/private') diff --git a/lib/private/group/manager.php b/lib/private/group/manager.php index 451de0c0539..deceb8bb929 100644 --- a/lib/private/group/manager.php +++ b/lib/private/group/manager.php @@ -52,12 +52,14 @@ class Manager extends PublicEmitter { */ public function __construct($userManager) { $this->userManager = $userManager; - $cache = & $this->cachedGroups; - $this->listen('\OC\Group', 'postDelete', function ($group) use (&$cache) { + $cachedGroups = & $this->cachedGroups; + $cachedUserGroups = & $this->cachedUserGroups; + $this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) { /** * @var \OC\Group\Group $group */ - unset($cache[$group->getGID()]); + unset($cachedGroups[$group->getGID()]); + $cachedUserGroups = array(); }); } -- cgit v1.2.3 From cb37a2716a75013dd79f8830a6d074e5afebb767 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 27 Feb 2014 20:09:07 +0100 Subject: Also clear cached UserGroup when a user is added/removed --- lib/private/group/manager.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'lib/private') diff --git a/lib/private/group/manager.php b/lib/private/group/manager.php index deceb8bb929..151b185dbf7 100644 --- a/lib/private/group/manager.php +++ b/lib/private/group/manager.php @@ -61,6 +61,18 @@ class Manager extends PublicEmitter { unset($cachedGroups[$group->getGID()]); $cachedUserGroups = array(); }); + $this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) { + /** + * @var \OC\Group\Group $group + */ + $cachedUserGroups = array(); + }); + $this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) { + /** + * @var \OC\Group\Group $group + */ + $cachedUserGroups = array(); + }); } /** -- cgit v1.2.3 From b54b0b2153742d0d5376045287e5874929437298 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Wed, 5 Mar 2014 00:26:06 +0100 Subject: Yet another cleanup --- lib/private/tags.php | 53 +++++++++++++++++++++++++++++++--------------------- tests/lib/tags.php | 2 +- 2 files changed, 33 insertions(+), 22 deletions(-) (limited to 'lib/private') diff --git a/lib/private/tags.php b/lib/private/tags.php index 06550068f76..2e786e3fd7b 100644 --- a/lib/private/tags.php +++ b/lib/private/tags.php @@ -121,21 +121,7 @@ class Tags implements \OCP\ITags { * @return boolean. */ public function isEmpty() { - $sql = 'SELECT COUNT(*) FROM `' . self::TAG_TABLE . '` ' - . 'WHERE `uid` = ? AND `type` = ?'; - try { - $stmt = \OCP\DB::prepare($sql); - $result = $stmt->execute(array($this->user, $this->type)); - if (\OCP\DB::isError($result)) { - \OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR); - return false; - } - return ((int)$result->fetchOne() === 0); - } catch(\Exception $e) { - \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(), - \OCP\Util::ERROR); - return false; - } + return count($this->tags) === 0; } /** @@ -184,6 +170,10 @@ class Tags implements \OCP\ITags { $tagId = $tag; } elseif(is_string($tag)) { $tag = trim($tag); + if($tag === '') { + \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG); + return false; + } $tagId = $this->array_searchi($tag, $this->tags); } @@ -234,11 +224,15 @@ class Tags implements \OCP\ITags { * Add a new tag. * * @param string $name A string with a name of the tag - * @return false|string the id of the added tag or false if it already exists. + * @return false|string the id of the added tag or false on error. */ public function add($name) { $name = trim($name); + if($name === '') { + \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG); + return false; + } if($this->hasTag($name)) { \OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', \OCP\Util::DEBUG); return false; @@ -280,6 +274,12 @@ class Tags implements \OCP\ITags { public function rename($from, $to) { $from = trim($from); $to = trim($to); + + if($to === '' || $from === '') { + \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG); + return false; + } + $id = $this->array_searchi($from, $this->tags); if($id === false) { \OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', \OCP\Util::DEBUG); @@ -318,6 +318,8 @@ class Tags implements \OCP\ITags { $names = array($names); } $names = array_map('trim', $names); + array_filter($names); + $newones = array(); foreach($names as $name) { if(($this->in_arrayi( @@ -492,9 +494,9 @@ class Tags implements \OCP\ITags { */ public function addToFavorites($objid) { if(!$this->hasTag(self::TAG_FAVORITE)) { - $this->add(self::TAG_FAVORITE, true); + $this->add(self::TAG_FAVORITE); } - return $this->tagAs($objid, self::TAG_FAVORITE, $this->type); + return $this->tagAs($objid, self::TAG_FAVORITE); } /** @@ -504,7 +506,7 @@ class Tags implements \OCP\ITags { * @return boolean */ public function removeFromFavorites($objid) { - return $this->unTag($objid, self::TAG_FAVORITE, $this->type); + return $this->unTag($objid, self::TAG_FAVORITE); } /** @@ -512,13 +514,17 @@ class Tags implements \OCP\ITags { * * @param int $objid The id of the object * @param string $tag The id or name of the tag - * @return boolean Returns false on database error. + * @return boolean Returns false on error. */ public function tagAs($objid, $tag) { if(is_string($tag) && !is_numeric($tag)) { $tag = trim($tag); + if($tag === '') { + \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG); + return false; + } if(!$this->hasTag($tag)) { - $this->add($tag, true); + $this->add($tag); } $tagId = $this->array_searchi($tag, $this->tags); } else { @@ -549,6 +555,10 @@ class Tags implements \OCP\ITags { public function unTag($objid, $tag) { if(is_string($tag) && !is_numeric($tag)) { $tag = trim($tag); + if($tag === '') { + \OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', \OCP\Util::DEBUG); + return false; + } $tagId = $this->array_searchi($tag, $this->tags); } else { $tagId = $tag; @@ -579,6 +589,7 @@ class Tags implements \OCP\ITags { } $names = array_map('trim', $names); + array_filter($names); \OCP\Util::writeLog('core', __METHOD__ . ', before: ' . print_r($this->tags, true), \OCP\Util::DEBUG); diff --git a/tests/lib/tags.php b/tests/lib/tags.php index 97e3734cfda..976b4b4fdc8 100644 --- a/tests/lib/tags.php +++ b/tests/lib/tags.php @@ -130,7 +130,7 @@ class Test_Tags extends PHPUnit_Framework_TestCase { $tagger = $this->tagMgr->load($this->objectType); foreach($objids as $id) { - $tagger->tagAs($id, 'Family'); + $this->assertTrue($tagger->tagAs($id, 'Family')); } $this->assertEquals(1, count($tagger->getTags())); -- cgit v1.2.3 From f9853b253c6ecb9a77a9d1c9006c5f548cdfd04e Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Mon, 31 Mar 2014 20:00:44 +0200 Subject: Deduplicate connection handling code into \OC\DB\ConnectionFactory --- core/command/db/converttype.php | 45 ++++-------- core/register_command.php | 2 +- lib/private/db.php | 139 +++++++++++------------------------ lib/private/db/connectionfactory.php | 117 +++++++++++++++++++++++++++++ 4 files changed, 173 insertions(+), 130 deletions(-) create mode 100644 lib/private/db/connectionfactory.php (limited to 'lib/private') diff --git a/core/command/db/converttype.php b/core/command/db/converttype.php index 387f873adb6..2a4e6747e65 100644 --- a/core/command/db/converttype.php +++ b/core/command/db/converttype.php @@ -21,11 +21,18 @@ class ConvertType extends Command { */ protected $config; + /** + * @var \OC\DB\ConnectionFactory + */ + protected $connectionFactory; + /** * @param \OC\Config $config + * @param \OC\DB\ConnectionFactory $connectionFactory */ - public function __construct($config) { + public function __construct($config, $connectionFactory) { $this->config = $config; + $this->connectionFactory = $connectionFactory; parent::__construct(); } @@ -87,12 +94,6 @@ class ConvertType extends Command { ; } - private static $type2driver = array( - 'mysql' => 'pdo_mysql', - 'pgsql' => 'pdo_pgsql', - 'oci' => 'oci8', - 'mssql' => 'pdo_sqlsrv', - ); protected function execute(InputInterface $input, OutputInterface $output) { $fromDB = \OC_DB::getConnection(); $toDB = $this->getToDBConnection($input, $output); @@ -140,35 +141,17 @@ class ConvertType extends Command { private function getToDBConnection($input, $output) { $type = $input->getArgument('type'); - $username = $input->getArgument('username'); - $hostname = $input->getArgument('hostname'); - $dbname = $input->getArgument('database'); - $password = $input->getOption('password'); - - if (!isset(self::$type2driver[$type])) { - throw new \InvalidArgumentException('Unknown type: '.$type); - } $connectionParams = array( - 'driver' => self::$type2driver[$type], - 'user' => $username, - 'password' => $password, - 'host' => $hostname, - 'dbname' => $dbname, + 'host' => $input->getArgument('hostname'), + 'user' => $input->getArgument('username'), + 'password' => $input->getOption('password'), + 'dbname' => $input->getArgument('database'), + 'tablePrefix' => $this->config->getValue('dbtableprefix', 'oc_'), ); if ($input->getOption('port')) { $connectionParams['port'] = $input->getOption('port'); } - switch ($type) { - case 'mysql': - case 'mssql': - $connectionParams['charset'] = 'UTF8'; - break; - case 'oci': - $connectionParams['charset'] = 'AL32UTF8'; - break; - } - - return \Doctrine\DBAL\DriverManager::getConnection($connectionParams); + return $this->connectionFactory->getConnection($type, $connectionParams); } private function getTables($db) { diff --git a/core/register_command.php b/core/register_command.php index a3833214c21..f1361c859fc 100644 --- a/core/register_command.php +++ b/core/register_command.php @@ -9,7 +9,7 @@ /** @var $application Symfony\Component\Console\Application */ $application->add(new OC\Core\Command\Status); $application->add(new OC\Core\Command\Db\GenerateChangeScript()); -$application->add(new OC\Core\Command\Db\ConvertType(OC_Config::getObject())); +$application->add(new OC\Core\Command\Db\ConvertType(OC_Config::getObject(), new \OC\DB\ConnectionFactory())); $application->add(new OC\Core\Command\Upgrade()); $application->add(new OC\Core\Command\Maintenance\SingleUser()); $application->add(new OC\Core\Command\App\Disable()); diff --git a/lib/private/db.php b/lib/private/db.php index cfdac766bff..11532d9fa54 100644 --- a/lib/private/db.php +++ b/lib/private/db.php @@ -72,102 +72,45 @@ class OC_DB { $port=false; } - // do nothing if the connection already has been established - if (!self::$connection) { - $config = new \Doctrine\DBAL\Configuration(); - $eventManager = new \Doctrine\Common\EventManager(); - switch($type) { - case 'sqlite': - case 'sqlite3': - $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT.'/data' ); - $connectionParams = array( - 'user' => $user, - 'password' => $pass, - 'path' => $datadir.'/'.$name.'.db', - 'driver' => 'pdo_sqlite', - ); - $connectionParams['adapter'] = '\OC\DB\AdapterSqlite'; - $connectionParams['wrapperClass'] = 'OC\DB\Connection'; - break; - case 'mysql': - $connectionParams = array( - 'user' => $user, - 'password' => $pass, - 'host' => $host, - 'port' => $port, - 'dbname' => $name, - 'charset' => 'UTF8', - 'driver' => 'pdo_mysql', - ); - $connectionParams['adapter'] = '\OC\DB\Adapter'; - $connectionParams['wrapperClass'] = 'OC\DB\Connection'; - // Send "SET NAMES utf8". Only required on PHP 5.3 below 5.3.6. - // See http://stackoverflow.com/questions/4361459/php-pdo-charset-set-names#4361485 - $eventManager->addEventSubscriber(new \Doctrine\DBAL\Event\Listeners\MysqlSessionInit); - break; - case 'pgsql': - $connectionParams = array( - 'user' => $user, - 'password' => $pass, - 'host' => $host, - 'port' => $port, - 'dbname' => $name, - 'driver' => 'pdo_pgsql', - ); - $connectionParams['adapter'] = '\OC\DB\AdapterPgSql'; - $connectionParams['wrapperClass'] = 'OC\DB\Connection'; - break; - case 'oci': - $connectionParams = array( - 'user' => $user, - 'password' => $pass, - 'host' => $host, - 'dbname' => $name, - 'charset' => 'AL32UTF8', - 'driver' => 'oci8', - ); - if (!empty($port)) { - $connectionParams['port'] = $port; - } - $connectionParams['adapter'] = '\OC\DB\AdapterOCI8'; - $connectionParams['wrapperClass'] = 'OC\DB\OracleConnection'; - $eventManager->addEventSubscriber(new \Doctrine\DBAL\Event\Listeners\OracleSessionInit); - break; - case 'mssql': - $connectionParams = array( - 'user' => $user, - 'password' => $pass, - 'host' => $host, - 'port' => $port, - 'dbname' => $name, - 'charset' => 'UTF8', - 'driver' => 'pdo_sqlsrv', - ); - $connectionParams['adapter'] = '\OC\DB\AdapterSQLSrv'; - $connectionParams['wrapperClass'] = 'OC\DB\Connection'; - break; - default: - return false; - } - $connectionParams['tablePrefix'] = OC_Config::getValue('dbtableprefix', 'oc_' ); - try { - self::$connection = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config, $eventManager); - if ($type === 'sqlite' || $type === 'sqlite3') { - // Sqlite doesn't handle query caching and schema changes - // TODO: find a better way to handle this - self::$connection->disableQueryStatementCaching(); - } - } catch(\Doctrine\DBAL\DBALException $e) { - OC_Log::write('core', $e->getMessage(), OC_Log::FATAL); - OC_User::setUserId(null); - - // send http status 503 - header('HTTP/1.1 503 Service Temporarily Unavailable'); - header('Status: 503 Service Temporarily Unavailable'); - OC_Template::printErrorPage('Failed to connect to database'); - die(); + $factory = new \OC\DB\ConnectionFactory(); + if (!$factory->isValidType($type)) { + return false; + } + + if ($factory->normalizeType($type) === 'sqlite3') { + $datadir = OC_Config::getValue("datadirectory", OC::$SERVERROOT.'/data'); + $connectionParams = array( + 'user' => $user, + 'password' => $pass, + 'path' => $datadir.'/'.$name.'.db', + ); + } else { + $connectionParams = array( + 'user' => $user, + 'password' => $pass, + 'host' => $host, + 'dbname' => $name, + ); + if (!empty($port)) { + $connectionParams['port'] = $port; } } + + $connectionParams['tablePrefix'] = OC_Config::getValue('dbtableprefix', 'oc_'); + + try { + self::$connection = $factory->getConnection($type, $connectionParams); + } catch(\Doctrine\DBAL\DBALException $e) { + OC_Log::write('core', $e->getMessage(), OC_Log::FATAL); + OC_User::setUserId(null); + + // send http status 503 + header('HTTP/1.1 503 Service Temporarily Unavailable'); + header('Status: 503 Service Temporarily Unavailable'); + OC_Template::printErrorPage('Failed to connect to database'); + die(); + } + return true; } @@ -202,12 +145,12 @@ class OC_DB { */ static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) { self::connect(); - + if ($isManipulation === null) { //try to guess, so we return the number of rows on manipulations $isManipulation = self::isManipulation($query); } - + // return the result try { $result = self::$connection->prepare($query, $limit, $offset); @@ -222,7 +165,7 @@ class OC_DB { /** * tries to guess the type of statement based on the first 10 characters * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements - * + * * @param string $sql * @return bool */ @@ -245,7 +188,7 @@ class OC_DB { } return false; } - + /** * @brief execute a prepared statement, on error write log and throw exception * @param mixed $stmt OC_DB_StatementWrapper, diff --git a/lib/private/db/connectionfactory.php b/lib/private/db/connectionfactory.php new file mode 100644 index 00000000000..14ffe1a4a56 --- /dev/null +++ b/lib/private/db/connectionfactory.php @@ -0,0 +1,117 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OC\DB; + +/** +* Takes care of creating and configurating Doctrine connections. +*/ +class ConnectionFactory { + /** + * @var array + * + * Array mapping DBMS type to default connection parameters passed to + * \Doctrine\DBAL\DriverManager::getConnection(). + */ + protected $defaultConnectionParams = array( + 'mssql' => array( + 'adapter' => '\OC\DB\AdapterSQLSrv', + 'charset' => 'UTF8', + 'driver' => 'pdo_sqlsrv', + 'wrapperClass' => 'OC\DB\Connection', + ), + 'mysql' => array( + 'adapter' => '\OC\DB\Adapter', + 'charset' => 'UTF8', + 'driver' => 'pdo_mysql', + 'wrapperClass' => 'OC\DB\Connection', + ), + 'oci' => array( + 'adapter' => '\OC\DB\AdapterOCI8', + 'charset' => 'AL32UTF8', + 'driver' => 'oci8', + 'wrapperClass' => 'OC\DB\OracleConnection', + ), + 'pgsql' => array( + 'adapter' => '\OC\DB\AdapterPgSql', + 'driver' => 'pdo_pgsql', + 'wrapperClass' => 'OC\DB\Connection', + ), + 'sqlite3' => array( + 'adapter' => '\OC\DB\AdapterSqlite', + 'driver' => 'pdo_sqlite', + 'wrapperClass' => 'OC\DB\Connection', + ), + ); + + /** + * @brief Get default connection parameters for a given DBMS. + * @param string $type DBMS type + * @throws \InvalidArgumentException If $type is invalid + * @return array Default connection parameters. + */ + public function getDefaultConnectionParams($type) { + $normalizedType = $this->normalizeType($type); + if (!isset($this->defaultConnectionParams[$normalizedType])) { + throw new \InvalidArgumentException("Unsupported type: $type"); + } + return $this->defaultConnectionParams[$normalizedType]; + } + + /** + * @brief Get default connection parameters for a given DBMS. + * @param string $type DBMS type + * @param array $additionalConnectionParams Additional connection parameters + * @return \OC\DB\Connection + */ + public function getConnection($type, $additionalConnectionParams) { + $normalizedType = $this->normalizeType($type); + $eventManager = new \Doctrine\Common\EventManager(); + switch ($normalizedType) { + case 'mysql': + // Send "SET NAMES utf8". Only required on PHP 5.3 below 5.3.6. + // See http://stackoverflow.com/questions/4361459/php-pdo-charset-set-names#4361485 + $eventManager->addEventSubscriber(new \Doctrine\DBAL\Event\Listeners\MysqlSessionInit); + break; + case 'oci': + $eventManager->addEventSubscriber(new \Doctrine\DBAL\Event\Listeners\OracleSessionInit); + break; + } + $connection = \Doctrine\DBAL\DriverManager::getConnection( + array_merge($this->getDefaultConnectionParams($type), $additionalConnectionParams), + new \Doctrine\DBAL\Configuration(), + $eventManager + ); + switch ($normalizedType) { + case 'sqlite3': + // Sqlite doesn't handle query caching and schema changes + // TODO: find a better way to handle this + $connection->disableQueryStatementCaching(); + break; + } + return $connection; + } + + /** + * @brief Normalize DBMS type + * @param string $type DBMS type + * @return string Normalized DBMS type + */ + public function normalizeType($type) { + return $type === 'sqlite' ? 'sqlite3' : $type; + } + + /** + * @brief Checks whether the specififed DBMS type is valid. + * @return bool + */ + public function isValidType($type) { + $normalizedType = $this->normalizeType($type); + return isset($this->defaultConnectionParams[$normalizedType]); + } +} -- cgit v1.2.3 From 9b4643f3865f5f14483b2e4618967f6cc91b0a22 Mon Sep 17 00:00:00 2001 From: josh4trunks Date: Thu, 3 Apr 2014 20:46:54 -0700 Subject: Send URI instead of filepath to NGINX for X-Accel --- lib/private/files.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/files.php b/lib/private/files.php index bfe6d3c02da..a377c196cdc 100644 --- a/lib/private/files.php +++ b/lib/private/files.php @@ -152,7 +152,7 @@ class OC_Files { /** @var $storage \OC\Files\Storage\Storage */ list($storage) = $view->resolvePath($filename); if ($storage->isLocal()) { - self::addSendfileHeader(\OC\Files\Filesystem::getLocalFile($filename)); + self::addSendfileHeader($filename); } else { \OC\Files\Filesystem::readfile($filename); } @@ -167,9 +167,11 @@ class OC_Files { */ private static function addSendfileHeader($filename) { if (isset($_SERVER['MOD_X_SENDFILE_ENABLED'])) { + $filename = \OC\Files\Filesystem::getLocalFile($filename); header("X-Sendfile: " . $filename); } if (isset($_SERVER['MOD_X_SENDFILE2_ENABLED'])) { + $filename = \OC\Files\Filesystem::getLocalFile($filename); if (isset($_SERVER['HTTP_RANGE']) && preg_match("/^bytes=([0-9]+)-([0-9]*)$/", $_SERVER['HTTP_RANGE'], $range)) { $filelength = filesize($filename); @@ -185,6 +187,7 @@ class OC_Files { } if (isset($_SERVER['MOD_X_ACCEL_REDIRECT_ENABLED'])) { + $filename = \OC::$WEBROOT . '/data' . \OC\Files\Filesystem::getRoot() . $filename; header("X-Accel-Redirect: " . $filename); } } -- cgit v1.2.3 From 511816b878d2574cdb1ee638ab731dbf635ff035 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Wed, 9 Apr 2014 21:53:06 +0200 Subject: Implement the register function of OC\ContactsManager --- lib/private/contactsmanager.php | 60 ++++++++++++++++++++++++++++++++--------- 1 file changed, 48 insertions(+), 12 deletions(-) (limited to 'lib/private') diff --git a/lib/private/contactsmanager.php b/lib/private/contactsmanager.php index 1cb3da7098f..fb0f938db36 100644 --- a/lib/private/contactsmanager.php +++ b/lib/private/contactsmanager.php @@ -34,6 +34,7 @@ namespace OC { * @return array of contacts which are arrays of key-value-pairs */ public function search($pattern, $searchProperties = array(), $options = array()) { + $this->loadAddressBooks(); $result = array(); foreach($this->address_books as $address_book) { $r = $address_book->search($pattern, $searchProperties, $options); @@ -51,12 +52,14 @@ namespace OC { * @return bool successful or not */ public function delete($id, $address_book_key) { - if (!array_key_exists($address_book_key, $this->address_books)) + $address_book = $this->getAddressBook($address_book_key); + if (!$address_book) { return null; + } - $address_book = $this->address_books[$address_book_key]; - if ($address_book->getPermissions() & \OCP\PERMISSION_DELETE) + if ($address_book->getPermissions() & \OCP\PERMISSION_DELETE) { return null; + } return $address_book->delete($id); } @@ -70,13 +73,14 @@ namespace OC { * @return array representing the contact just created or updated */ public function createOrUpdate($properties, $address_book_key) { - - if (!array_key_exists($address_book_key, $this->address_books)) + $address_book = $this->getAddressBook($address_book_key); + if (!$address_book) { return null; + } - $address_book = $this->address_books[$address_book_key]; - if ($address_book->getPermissions() & \OCP\PERMISSION_CREATE) + if ($address_book->getPermissions() & \OCP\PERMISSION_CREATE) { return null; + } return $address_book->createOrUpdate($properties); } @@ -87,7 +91,7 @@ namespace OC { * @return bool true if enabled, false if not */ public function isEnabled() { - return !empty($this->address_books); + return !empty($this->address_books) || !empty($this->address_book_loaders); } /** @@ -108,6 +112,7 @@ namespace OC { * @return array */ public function getAddressBooks() { + $this->loadAddressBooks(); $result = array(); foreach($this->address_books as $address_book) { $result[$address_book->getKey()] = $address_book->getDisplayName(); @@ -121,6 +126,7 @@ namespace OC { */ public function clear() { $this->address_books = array(); + $this->address_book_loaders = array(); } /** @@ -128,6 +134,11 @@ namespace OC { */ private $address_books = array(); + /** + * @var \Closure[] to call to load/register address books + */ + private $address_book_loaders = array(); + /** * In order to improve lazy loading a closure can be registered which will be called in case * address books are actually requested @@ -135,11 +146,36 @@ namespace OC { * @param string $key * @param \Closure $callable */ - function register($key, \Closure $callable) + public function register($key, \Closure $callable) { - // - //TODO: implement me - // + $this->address_book_loaders[$key] = $callable; + } + + /** + * Get (and load when needed) the address book for $key + * + * @param string $address_book_key + * @return \OCP\IAddressBook + */ + protected function getAddressBook($address_book_key) + { + $this->loadAddressBooks(); + if (!array_key_exists($address_book_key, $this->address_books)) { + return null; + } + + return $this->address_books[$address_book_key]; + } + + /** + * Load all address books registered with 'register' + */ + protected function loadAddressBooks() + { + foreach($this->address_book_loaders as $callable) { + $callable(); + } + $this->address_book_loaders = array(); } } } -- cgit v1.2.3 From 5c412f480cb885516a3bdd22f9b9e5f49394eec4 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 10 Apr 2014 18:06:31 +0200 Subject: $key is not needed for registering contactsmanager callbacks --- lib/private/contactsmanager.php | 5 ++--- lib/public/contacts/imanager.php | 3 +-- 2 files changed, 3 insertions(+), 5 deletions(-) (limited to 'lib/private') diff --git a/lib/private/contactsmanager.php b/lib/private/contactsmanager.php index fb0f938db36..02338453bec 100644 --- a/lib/private/contactsmanager.php +++ b/lib/private/contactsmanager.php @@ -143,12 +143,11 @@ namespace OC { * In order to improve lazy loading a closure can be registered which will be called in case * address books are actually requested * - * @param string $key * @param \Closure $callable */ - public function register($key, \Closure $callable) + public function register(\Closure $callable) { - $this->address_book_loaders[$key] = $callable; + $this->address_book_loaders[] = $callable; } /** diff --git a/lib/public/contacts/imanager.php b/lib/public/contacts/imanager.php index 005b71f298b..1387836573b 100644 --- a/lib/public/contacts/imanager.php +++ b/lib/public/contacts/imanager.php @@ -138,11 +138,10 @@ namespace OCP\Contacts { * In order to improve lazy loading a closure can be registered which will be called in case * address books are actually requested * - * @param string $key * @param \Closure $callable * @return void */ - function register($key, \Closure $callable); + function register(\Closure $callable); /** * @return array -- cgit v1.2.3 From 694244f2e0ea138049869072de496e5f1210a3a7 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 10 Apr 2014 18:07:15 +0200 Subject: Supply the contactsmanager object to the callbacks --- lib/private/contactsmanager.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/contactsmanager.php b/lib/private/contactsmanager.php index 02338453bec..fb2981f8e31 100644 --- a/lib/private/contactsmanager.php +++ b/lib/private/contactsmanager.php @@ -172,7 +172,7 @@ namespace OC { protected function loadAddressBooks() { foreach($this->address_book_loaders as $callable) { - $callable(); + $callable($this); } $this->address_book_loaders = array(); } -- cgit v1.2.3 From 9cc41a24603b250b9c657edfc7007bf10e795899 Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Mon, 14 Apr 2014 18:33:21 +0200 Subject: Move PostgreSQL sequence resynchronisation out into PgSqlTools class. --- core/command/db/converttype.php | 17 ++++------------- lib/private/db/pgsqltools.php | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 13 deletions(-) create mode 100644 lib/private/db/pgsqltools.php (limited to 'lib/private') diff --git a/core/command/db/converttype.php b/core/command/db/converttype.php index 64178d1ef7f..3b405764e7f 100644 --- a/core/command/db/converttype.php +++ b/core/command/db/converttype.php @@ -1,6 +1,7 @@ + * Copyright (c) 2014 Andreas Fischer * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. @@ -230,25 +231,15 @@ class ConvertType extends Command { protected function convertDB(Connection $fromDB, Connection $toDB, array $tables, InputInterface $input, OutputInterface $output) { $this->config->setValue('maintenance', true); - $type = $input->getArgument('type'); try { // copy table rows foreach($tables as $table) { $output->writeln($table); $this->copyTable($fromDB, $toDB, $table, $input, $output); } - if ($type == 'pgsql') { - $sequences = $toDB->getSchemaManager()->listSequences(); - $dbname = $input->getArgument('database'); - foreach($sequences as $sequence) { - $info = $toDB->fetchAssoc('SELECT table_schema, table_name, column_name ' - .'FROM information_schema.columns ' - .'WHERE column_default = ? AND table_catalog = ?', - array("nextval('".$sequence->getName()."'::regclass)", $dbname)); - $table_name = $info['table_name']; - $column_name = $info['column_name']; - $toDB->executeQuery("SELECT setval('" . $sequence->getName() . "', (SELECT MAX(" . $column_name . ") FROM " . $table_name . "))"); - } + if ($input->getArgument('type') === 'pgsql') { + $tools = new \OC\DB\PgSqlTools; + $tools->resynchronizeDatabaseSequences($toDB); } // save new database config $this->saveDBInfo($input); diff --git a/lib/private/db/pgsqltools.php b/lib/private/db/pgsqltools.php new file mode 100644 index 00000000000..01e76148a2c --- /dev/null +++ b/lib/private/db/pgsqltools.php @@ -0,0 +1,39 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OC\DB; + +/** +* Various PostgreSQL specific helper functions. +*/ +class PgSqlTools { + /** + * @brief Resynchronizes all sequences of a database after using INSERTs + * without leaving out the auto-incremented column. + * @param \OC\DB\Connection $conn + * @return null + */ + public function resynchronizeDatabaseSequences(Connection $conn) { + $databaseName = $conn->getDatabase(); + foreach ($conn->getSchemaManager()->listSequences() as $sequence) { + $sequenceName = $sequence->getName(); + $sqlInfo = 'SELECT table_schema, table_name, column_name + FROM information_schema.columns + WHERE column_default = ? AND table_catalog = ?'; + $sequenceInfo = $conn->fetchAssoc($sqlInfo, array( + "nextval('$sequenceName'::regclass)", + $databaseName + )); + $tableName = $sequenceInfo['table_name']; + $columnName = $sequenceInfo['column_name']; + $sqlMaxId = "SELECT MAX($columnName) FROM $tableName"; + $sqlSetval = "SELECT setval('$sequenceName', ($sqlMaxId))"; + $conn->executeQuery($sqlSetval); + } + } +} -- cgit v1.2.3 From 714343cd74af55c37c7eccb2f076013dc94db898 Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Tue, 15 Apr 2014 16:29:43 +0200 Subject: Add Bart to PgSqlTools copyright. --- lib/private/db/pgsqltools.php | 1 + 1 file changed, 1 insertion(+) (limited to 'lib/private') diff --git a/lib/private/db/pgsqltools.php b/lib/private/db/pgsqltools.php index 01e76148a2c..c3ac140594d 100644 --- a/lib/private/db/pgsqltools.php +++ b/lib/private/db/pgsqltools.php @@ -1,5 +1,6 @@ * Copyright (c) 2014 Andreas Fischer * This file is licensed under the Affero General Public License version 3 or * later. -- cgit v1.2.3 From a9bf3df82d0c3d0f54c9fe45dbb911756f37b166 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Tue, 15 Apr 2014 17:46:11 +0200 Subject: Fix PHPdoc in OC\Share\Share and OCP\Share --- lib/private/share/share.php | 175 ++++++++++++++++++++++---------------------- lib/public/share.php | 138 +++++++++++++++++----------------- 2 files changed, 158 insertions(+), 155 deletions(-) (limited to 'lib/private') diff --git a/lib/private/share/share.php b/lib/private/share/share.php index d4f08e8e016..d9425b793c9 100644 --- a/lib/private/share/share.php +++ b/lib/private/share/share.php @@ -48,11 +48,11 @@ class Share extends \OC\Share\Constants { /** * Register a sharing backend class that implements OCP\Share_Backend for an item type - * @param string Item type - * @param string Backend class - * @param string (optional) Depends on item type - * @param array (optional) List of supported file extensions if this item type depends on files - * @return Returns true if backend is registered or false if error + * @param string $itemType Item type + * @param string $class Backend class + * @param string $collectionOf (optional) Depends on item type + * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files + * @return boolean true if backend is registered or false if error */ public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) { if (self::isEnabled()) { @@ -78,7 +78,7 @@ class Share extends \OC\Share\Constants { /** * Check if the Share API is enabled - * @return Returns true if enabled or false + * @return boolean true if enabled or false * * The Share API is enabled by default if not configured */ @@ -91,9 +91,9 @@ class Share extends \OC\Share\Constants { /** * Find which users can access a shared item - * @param $path to the file - * @param $user owner of the file - * @param include owner to the list of users with access to the file + * @param string $path to the file + * @param string $user owner of the file + * @param bool $includeOwner include owner to the list of users with access to the file * @return array * @note $path needs to be relative to user data dir, e.g. 'file.txt' * not '/admin/data/file.txt' @@ -198,12 +198,12 @@ class Share extends \OC\Share\Constants { /** * Get the items of item type shared with the current user - * @param string Item type - * @param int Format (optional) Format type must be defined by the backend - * @param mixed Parameters (optional) - * @param int Number of items to return (optional) Returns all by default - * @param bool include collections (optional) - * @return Return depends on format + * @param string $itemType + * @param int $format (optional) Format type must be defined by the backend + * @param mixed $parameters (optional) + * @param int $limit Number of items to return (optional) Returns all by default + * @param bool $includeCollections (optional) + * @return mixed Return depends on format */ public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE, $parameters = null, $limit = -1, $includeCollections = false) { @@ -216,9 +216,9 @@ class Share extends \OC\Share\Constants { * @param string $itemType * @param string $itemTarget * @param int $format (optional) Format type must be defined by the backend - * @param mixed Parameters (optional) - * @param bool include collections (optional) - * @return Return depends on format + * @param mixed $parameters (optional) + * @param bool $includeCollections (optional) + * @return mixed Return depends on format */ public static function getItemSharedWith($itemType, $itemTarget, $format = self::FORMAT_NONE, $parameters = null, $includeCollections = false) { @@ -277,12 +277,12 @@ class Share extends \OC\Share\Constants { /** * Get the item of item type shared with the current user by source - * @param string Item type - * @param string Item source - * @param int Format (optional) Format type must be defined by the backend - * @param mixed Parameters - * @param bool include collections - * @return Return depends on format + * @param string $itemType + * @param string $itemSource + * @param int $format (optional) Format type must be defined by the backend + * @param mixed $parameters + * @param bool $includeCollections + * @return mixed Return depends on format */ public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE, $parameters = null, $includeCollections = false) { @@ -292,9 +292,9 @@ class Share extends \OC\Share\Constants { /** * Get the item of item type shared by a link - * @param string Item type - * @param string Item source - * @param string Owner of link + * @param string $itemType + * @param string $itemSource + * @param string $uidOwner Owner of link * @return Item */ public static function getItemSharedWithByLink($itemType, $itemSource, $uidOwner) { @@ -354,12 +354,12 @@ class Share extends \OC\Share\Constants { /** * Get the shared items of item type owned by the current user - * @param string Item type - * @param int Format (optional) Format type must be defined by the backend - * @param mixed Parameters - * @param int Number of items to return (optional) Returns all by default - * @param bool include collections - * @return Return depends on format + * @param string $itemType + * @param int $format (optional) Format type must be defined by the backend + * @param mixed $parameters + * @param int $limit Number of items to return (optional) Returns all by default + * @param bool $includeCollections + * @return mixed Return depends on format */ public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null, $limit = -1, $includeCollections = false) { @@ -369,12 +369,12 @@ class Share extends \OC\Share\Constants { /** * Get the shared item of item type owned by the current user - * @param string Item type - * @param string Item source - * @param int Format (optional) Format type must be defined by the backend - * @param mixed Parameters - * @param bool include collections - * @return Return depends on format + * @param string $itemType + * @param string $itemSource + * @param int $format (optional) Format type must be defined by the backend + * @param mixed $parameters + * @param bool $includeCollections + * @return mixed Return depends on format */ public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE, $parameters = null, $includeCollections = false) { @@ -384,11 +384,11 @@ class Share extends \OC\Share\Constants { /** * Get all users an item is shared with - * @param string Item type - * @param string Item source - * @param string Owner - * @param bool Include collections - * @praram bool check expire date + * @param string $itemType + * @param string $itemSource + * @param string $uidOwner + * @param bool $includeCollections + * @param bool $checkExpireDate * @return Return array of users */ public static function getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections = false, $checkExpireDate = true) { @@ -559,11 +559,11 @@ class Share extends \OC\Share\Constants { /** * Unshare an item from a user, group, or delete a private link - * @param string Item type - * @param string Item source - * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK - * @param string User or group the item is being shared with - * @return Returns true on success or false on failure + * @param string $itemType + * @param string $itemSource + * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK + * @param string $shareWith User or group the item is being shared with + * @return boolean true on success or false on failure */ public static function unshare($itemType, $itemSource, $shareType, $shareWith) { $item = self::getItems($itemType, $itemSource, $shareType, $shareWith, \OC_User::getUser(),self::FORMAT_NONE, null, 1); @@ -576,9 +576,9 @@ class Share extends \OC\Share\Constants { /** * Unshare an item from all users, groups, and remove all links - * @param string Item type - * @param string Item source - * @return Returns true on success or false on failure + * @param string $itemType + * @param string $itemSource + * @return boolean true on success or false on failure */ public static function unshareAll($itemType, $itemSource) { // Get all of the owners of shares of this item. @@ -608,9 +608,9 @@ class Share extends \OC\Share\Constants { /** * Unshare an item shared with the current user - * @param string Item type - * @param string Item target - * @return Returns true on success or false on failure + * @param string $itemType + * @param string $itemTarget + * @return boolean true on success or false on failure * * Unsharing from self is not allowed for items inside collections */ @@ -643,6 +643,7 @@ class Share extends \OC\Share\Constants { } return false; } + /** * sent status if users got informed by mail about share * @param string $itemType @@ -667,12 +668,12 @@ class Share extends \OC\Share\Constants { /** * Set the permissions of an item for a specific user or group - * @param string Item type - * @param string Item source - * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK - * @param string User or group the item is being shared with - * @param int CRUDS permissions - * @return Returns true on success or false on failure + * @param string $itemType + * @param string $itemSource + * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK + * @param string $shareWith User or group the item is being shared with + * @param int $permissions CRUDS permissions + * @return boolean true on success or false on failure */ public static function setPermissions($itemType, $itemSource, $shareType, $shareWith, $permissions) { if ($item = self::getItems($itemType, $itemSource, $shareType, $shareWith, @@ -754,7 +755,7 @@ class Share extends \OC\Share\Constants { * @param string $itemType * @param string $itemSource * @param string $date expiration date - * @return \OCP\Share_Backend + * @return boolean */ public static function setExpirationDate($itemType, $itemSource, $date) { $user = \OC_User::getUser(); @@ -853,7 +854,7 @@ class Share extends \OC\Share\Constants { /** * Check if resharing is allowed - * @return Returns true if allowed or false + * @return boolean true if allowed or false * * Resharing is allowed by default if not configured */ @@ -870,7 +871,7 @@ class Share extends \OC\Share\Constants { /** * Get a list of collection item types for the specified item type - * @param string Item type + * @param string $itemType * @return array */ private static function getCollectionItemTypes($itemType) { @@ -894,17 +895,17 @@ class Share extends \OC\Share\Constants { /** * Get shared items from the database - * @param string Item type + * @param string $itemType * @param string Item source or target (optional) - * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique - * @param string User or group the item is being shared with - * @param string User that is the owner of shared items (optional) - * @param int Format to convert items to with formatItems() - * @param mixed Parameters to pass to formatItems() - * @param int Number of items to return, -1 to return all matches (optional) - * @param bool Include collection item types (optional) - * @param bool TODO (optional) - * @prams bool check expire date + * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique + * @param string $shareWith User or group the item is being shared with + * @param string uidOwner User that is the owner of shared items (optional) + * @param int $format Format to convert items to with formatItems() + * @param mixed $parameters to pass to formatItems() + * @param int $limit Number of items to return, -1 to return all matches (optional) + * @param bool $includeCollections Include collection item types (optional) + * @param bool $itemShareWithBySource (optional) + * @param bool $checkExpireDate * @return array * * See public functions getItem(s)... for parameter usage @@ -1242,15 +1243,15 @@ class Share extends \OC\Share\Constants { /** * Put shared item into the database - * @param string Item type - * @param string Item source - * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK - * @param string User or group the item is being shared with - * @param string User that is the owner of shared item - * @param int CRUDS permissions - * @param bool|array Parent folder target (optional) - * @param string token (optional) - * @param string name of the source item (optional) + * @param string $itemType Item type + * @param string $itemSource Item source + * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK + * @param string $shareWith User or group the item is being shared with + * @param string $uidOwner User that is the owner of shared item + * @param int $permissions CRUDS permissions + * @param bool|array $parentFolder Parent folder target (optional) + * @param string $token (optional) + * @param string $itemSourceName name of the source item (optional) * @return bool Returns true on success or false on failure */ private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, @@ -1600,11 +1601,11 @@ class Share extends \OC\Share\Constants { /** * @brief format result * @param array $items result - * @prams string $column is it a file share or a general share ('file_target' or 'item_target') - * @params \OCP\Share_Backend $backend sharing backend + * @param string $column is it a file share or a general share ('file_target' or 'item_target') + * @param \OCP\Share_Backend $backend sharing backend * @param int $format - * @param array additional format parameters - * @return array formate result + * @param array $parameters additional format parameters + * @return array format result */ private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) { if ($format === self::FORMAT_NONE) { diff --git a/lib/public/share.php b/lib/public/share.php index 564839e86b6..4306c1b038f 100644 --- a/lib/public/share.php +++ b/lib/public/share.php @@ -41,11 +41,11 @@ class Share extends \OC\Share\Constants { /** * Register a sharing backend class that implements OCP\Share_Backend for an item type - * @param string Item type - * @param string Backend class - * @param string (optional) Depends on item type - * @param array (optional) List of supported file extensions if this item type depends on files - * @return Returns true if backend is registered or false if error + * @param string $itemType Item type + * @param string $class Backend class + * @param string $collectionOf (optional) Depends on item type + * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files + * @return boolean true if backend is registered or false if error */ public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) { return \OC\Share\Share::registerBackend($itemType, $class, $collectionOf, $supportedFileExtensions); @@ -53,7 +53,7 @@ class Share extends \OC\Share\Constants { /** * Check if the Share API is enabled - * @return Returns true if enabled or false + * @return boolean true if enabled or false * * The Share API is enabled by default if not configured */ @@ -76,12 +76,12 @@ class Share extends \OC\Share\Constants { /** * Get the items of item type shared with the current user - * @param string Item type - * @param int Format (optional) Format type must be defined by the backend - * @param mixed Parameters (optional) - * @param int Number of items to return (optional) Returns all by default - * @param bool include collections (optional) - * @return Return depends on format + * @param string $itemType + * @param int $format (optional) Format type must be defined by the backend + * @param mixed $parameters (optional) + * @param int $limit Number of items to return (optional) Returns all by default + * @param bool $includeCollections (optional) + * @return mixed Return depends on format */ public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE, $parameters = null, $limit = -1, $includeCollections = false) { @@ -96,7 +96,7 @@ class Share extends \OC\Share\Constants { * @param int $format (optional) Format type must be defined by the backend * @param mixed Parameters (optional) * @param bool include collections (optional) - * @return Return depends on format + * @return mixed Return depends on format */ public static function getItemSharedWith($itemType, $itemTarget, $format = self::FORMAT_NONE, $parameters = null, $includeCollections = false) { @@ -117,12 +117,12 @@ class Share extends \OC\Share\Constants { /** * Get the item of item type shared with the current user by source - * @param string Item type - * @param string Item source - * @param int Format (optional) Format type must be defined by the backend - * @param mixed Parameters - * @param bool include collections - * @return Return depends on format + * @param string $itemType + * @param string $itemSource + * @param int $format (optional) Format type must be defined by the backend + * @param mixed $parameters + * @param bool $includeCollections + * @return mixed Return depends on format */ public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE, $parameters = null, $includeCollections = false) { @@ -131,9 +131,9 @@ class Share extends \OC\Share\Constants { /** * Get the item of item type shared by a link - * @param string Item type - * @param string Item source - * @param string Owner of link + * @param string $itemType + * @param string $itemSource + * @param string $uidOwner Owner of link * @return Item */ public static function getItemSharedWithByLink($itemType, $itemSource, $uidOwner) { @@ -161,12 +161,12 @@ class Share extends \OC\Share\Constants { /** * Get the shared items of item type owned by the current user - * @param string Item type - * @param int Format (optional) Format type must be defined by the backend - * @param mixed Parameters - * @param int Number of items to return (optional) Returns all by default - * @param bool include collections - * @return Return depends on format + * @param string $itemType + * @param int $format (optional) Format type must be defined by the backend + * @param mixed $parameters + * @param int $limit Number of items to return (optional) Returns all by default + * @param bool $includeCollections + * @return mixed Return depends on format */ public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null, $limit = -1, $includeCollections = false) { @@ -176,12 +176,12 @@ class Share extends \OC\Share\Constants { /** * Get the shared item of item type owned by the current user - * @param string Item type - * @param string Item source - * @param int Format (optional) Format type must be defined by the backend - * @param mixed Parameters - * @param bool include collections - * @return Return depends on format + * @param string $itemType + * @param string $itemSource + * @param int $format (optional) Format type must be defined by the backend + * @param mixed $parameters + * @param bool $includeCollections + * @return mixed Return depends on format */ public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE, $parameters = null, $includeCollections = false) { @@ -191,11 +191,11 @@ class Share extends \OC\Share\Constants { /** * Get all users an item is shared with - * @param string Item type - * @param string Item source - * @param string Owner - * @param bool Include collections - * @praram bool check expire date + * @param string $itemType + * @param string $itemSource + * @param string $uidOwner + * @param bool $includeCollections + * @param bool $checkExpireDate * @return Return array of users */ public static function getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections = false, $checkExpireDate = true) { @@ -224,11 +224,11 @@ class Share extends \OC\Share\Constants { /** * Unshare an item from a user, group, or delete a private link - * @param string Item type - * @param string Item source - * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK - * @param string User or group the item is being shared with - * @return Returns true on success or false on failure + * @param string $itemType + * @param string $itemSource + * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK + * @param string $shareWith User or group the item is being shared with + * @return boolean true on success or false on failure */ public static function unshare($itemType, $itemSource, $shareType, $shareWith) { return \OC\Share\Share::unshare($itemType, $itemSource, $shareType, $shareWith); @@ -236,9 +236,9 @@ class Share extends \OC\Share\Constants { /** * Unshare an item from all users, groups, and remove all links - * @param string Item type - * @param string Item source - * @return Returns true on success or false on failure + * @param string $itemType + * @param string $itemSource + * @return boolean true on success or false on failure */ public static function unshareAll($itemType, $itemSource) { return \OC\Share\Share::unshareAll($itemType, $itemSource); @@ -246,15 +246,16 @@ class Share extends \OC\Share\Constants { /** * Unshare an item shared with the current user - * @param string Item type - * @param string Item target - * @return Returns true on success or false on failure + * @param string $itemType + * @param string $itemTarget + * @return boolean true on success or false on failure * * Unsharing from self is not allowed for items inside collections */ public static function unshareFromSelf($itemType, $itemTarget) { return \OC\Share\Share::unshareFromSelf($itemType, $itemTarget); } + /** * sent status if users got informed by mail about share * @param string $itemType @@ -268,12 +269,12 @@ class Share extends \OC\Share\Constants { /** * Set the permissions of an item for a specific user or group - * @param string Item type - * @param string Item source - * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK - * @param string User or group the item is being shared with - * @param int CRUDS permissions - * @return Returns true on success or false on failure + * @param string $itemType + * @param string $itemSource + * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK + * @param string $shareWith User or group the item is being shared with + * @param int $permissions CRUDS permissions + * @return boolean true on success or false on failure */ public static function setPermissions($itemType, $itemSource, $shareType, $shareWith, $permissions) { return \OC\Share\Share::setPermissions($itemType, $itemSource, $shareType, $shareWith, $permissions); @@ -284,7 +285,7 @@ class Share extends \OC\Share\Constants { * @param string $itemType * @param string $itemSource * @param string $date expiration date - * @return Share_Backend + * @return boolean */ public static function setExpirationDate($itemType, $itemSource, $date) { return \OC\Share\Share::setExpirationDate($itemType, $itemSource, $date); @@ -324,9 +325,9 @@ interface Share_Backend { /** * Get the source of the item to be stored in the database - * @param string Item source - * @param string Owner of the item - * @return mixed|array|false Source + * @param string $itemSource + * @param string $uidOwner Owner of the item + * @return boolean|null Source * * Return an array if the item is file dependent, the array needs two keys: 'item' and 'file' * Return false if the item does not exist for the user @@ -337,9 +338,9 @@ interface Share_Backend { /** * Get a unique name of the item for the specified user - * @param string Item source - * @param string|false User the item is being shared with - * @param array|null List of similar item names already existing as shared items + * @param string $itemSource + * @param string|false $shareWith User the item is being shared with + * @param array|null $exclude List of similar item names already existing as shared items * @return string Target name * * This function needs to verify that the user does not already have an item with this name. @@ -349,8 +350,8 @@ interface Share_Backend { /** * Converts the shared item sources back into the item in the specified format - * @param array Shared items - * @param int Format + * @param array $items Shared items + * @param int $format * @return TODO * * The items array is a 3-dimensional array with the item_source as the @@ -380,8 +381,9 @@ interface Share_Backend_File_Dependent extends Share_Backend { /** * Get the file path of the item - * @param string Item source - * @param string User that is the owner of shared item + * @param string $itemSource + * @param string $uidOwner User that is the owner of shared item + * @return boolean */ public function getFilePath($itemSource, $uidOwner); @@ -395,7 +397,7 @@ interface Share_Backend_Collection extends Share_Backend { /** * Get the sources of the children of the item - * @param string Item source + * @param string $itemSource * @return array Returns an array of children each inside an array with the keys: source, target, and file_path if applicable */ public function getChildren($itemSource); -- cgit v1.2.3 From 6fe3fd4a0be3a309f6337f72c6cc6a2774934864 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Tue, 15 Apr 2014 23:04:35 +0200 Subject: Fix linkToPublic. Refs #8218 --- lib/private/helper.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/helper.php b/lib/private/helper.php index da3d3cd1c6e..5ce0c2e59ac 100644 --- a/lib/private/helper.php +++ b/lib/private/helper.php @@ -125,8 +125,12 @@ class OC_Helper { * Returns a absolute url to the given service. */ public static function linkToPublic($service, $add_slash = false) { - return self::linkToAbsolute('', 'public.php') . '?service=' . $service - . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : ''); + return OC::$server->getURLGenerator()->getAbsoluteURL( + self::linkTo( + '', 'public.php') . '?service=' . $service + . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '' + ) + ); } /** -- cgit v1.2.3 From da99e403bca23e63cfa4e8becb432f95efdba606 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Wed, 16 Apr 2014 14:30:24 +0200 Subject: Also fix linkToAbsolute --- lib/private/helper.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'lib/private') diff --git a/lib/private/helper.php b/lib/private/helper.php index 5ce0c2e59ac..738c4944b3d 100644 --- a/lib/private/helper.php +++ b/lib/private/helper.php @@ -78,7 +78,9 @@ class OC_Helper { * Returns a absolute url to the given app and file. */ public static function linkToAbsolute($app, $file, $args = array()) { - return self::linkTo($app, $file, $args); + return OC::$server->getURLGenerator()->getAbsoluteURL( + self::linkTo($app, $file, $args) + ); } /** @@ -112,8 +114,10 @@ class OC_Helper { * Returns a absolute url to the given service. */ public static function linkToRemote($service, $add_slash = true) { - return self::makeURLAbsolute(self::linkToRemoteBase($service)) - . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : ''); + return OC::$server->getURLGenerator()->getAbsoluteURL( + self::linkToRemoteBase($service) + . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '') + ); } /** -- cgit v1.2.3 From 9583549556c91b109c3965ea40f708a0f46c8f51 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 17 Apr 2014 17:56:23 +0200 Subject: camelCase vars in OC\ContactsManager --- lib/private/contactsmanager.php | 68 ++++++++++++++++++++--------------------- 1 file changed, 34 insertions(+), 34 deletions(-) (limited to 'lib/private') diff --git a/lib/private/contactsmanager.php b/lib/private/contactsmanager.php index fb2981f8e31..c08f739bf33 100644 --- a/lib/private/contactsmanager.php +++ b/lib/private/contactsmanager.php @@ -36,8 +36,8 @@ namespace OC { public function search($pattern, $searchProperties = array(), $options = array()) { $this->loadAddressBooks(); $result = array(); - foreach($this->address_books as $address_book) { - $r = $address_book->search($pattern, $searchProperties, $options); + foreach($this->addressBooks as $addressBook) { + $r = $addressBook->search($pattern, $searchProperties, $options); $result = array_merge($result, $r); } @@ -48,20 +48,20 @@ namespace OC { * This function can be used to delete the contact identified by the given id * * @param object $id the unique identifier to a contact - * @param string $address_book_key identifier of the address book in which the contact shall be deleted + * @param string $addressBookKey identifier of the address book in which the contact shall be deleted * @return bool successful or not */ - public function delete($id, $address_book_key) { - $address_book = $this->getAddressBook($address_book_key); - if (!$address_book) { + public function delete($id, $addressBookKey) { + $addressBook = $this->getAddressBook($addressBookKey); + if (!$addressBook) { return null; } - if ($address_book->getPermissions() & \OCP\PERMISSION_DELETE) { + if ($addressBook->getPermissions() & \OCP\PERMISSION_DELETE) { return null; } - return $address_book->delete($id); + return $addressBook->delete($id); } /** @@ -69,20 +69,20 @@ namespace OC { * Otherwise the contact will be updated by replacing the entire data set. * * @param array $properties this array if key-value-pairs defines a contact - * @param string $address_book_key identifier of the address book in which the contact shall be created or updated + * @param string $addressBookKey identifier of the address book in which the contact shall be created or updated * @return array representing the contact just created or updated */ - public function createOrUpdate($properties, $address_book_key) { - $address_book = $this->getAddressBook($address_book_key); - if (!$address_book) { + public function createOrUpdate($properties, $addressBookKey) { + $addressBook = $this->getAddressBook($addressBookKey); + if (!$addressBook) { return null; } - if ($address_book->getPermissions() & \OCP\PERMISSION_CREATE) { + if ($addressBook->getPermissions() & \OCP\PERMISSION_CREATE) { return null; } - return $address_book->createOrUpdate($properties); + return $addressBook->createOrUpdate($properties); } /** @@ -91,21 +91,21 @@ namespace OC { * @return bool true if enabled, false if not */ public function isEnabled() { - return !empty($this->address_books) || !empty($this->address_book_loaders); + return !empty($this->addressBooks) || !empty($this->addressBookLoaders); } /** - * @param \OCP\IAddressBook $address_book + * @param \OCP\IAddressBook $addressBook */ - public function registerAddressBook(\OCP\IAddressBook $address_book) { - $this->address_books[$address_book->getKey()] = $address_book; + public function registerAddressBook(\OCP\IAddressBook $addressBook) { + $this->addressBooks[$addressBook->getKey()] = $addressBook; } /** - * @param \OCP\IAddressBook $address_book + * @param \OCP\IAddressBook $addressBook */ - public function unregisterAddressBook(\OCP\IAddressBook $address_book) { - unset($this->address_books[$address_book->getKey()]); + public function unregisterAddressBook(\OCP\IAddressBook $addressBook) { + unset($this->addressBooks[$addressBook->getKey()]); } /** @@ -114,8 +114,8 @@ namespace OC { public function getAddressBooks() { $this->loadAddressBooks(); $result = array(); - foreach($this->address_books as $address_book) { - $result[$address_book->getKey()] = $address_book->getDisplayName(); + foreach($this->addressBooks as $addressBook) { + $result[$addressBook->getKey()] = $addressBook->getDisplayName(); } return $result; @@ -125,19 +125,19 @@ namespace OC { * removes all registered address book instances */ public function clear() { - $this->address_books = array(); - $this->address_book_loaders = array(); + $this->addressBooks = array(); + $this->addressBookLoaders = array(); } /** * @var \OCP\IAddressBook[] which holds all registered address books */ - private $address_books = array(); + private $addressBooks = array(); /** * @var \Closure[] to call to load/register address books */ - private $address_book_loaders = array(); + private $addressBookLoaders = array(); /** * In order to improve lazy loading a closure can be registered which will be called in case @@ -147,23 +147,23 @@ namespace OC { */ public function register(\Closure $callable) { - $this->address_book_loaders[] = $callable; + $this->addressBookLoaders[] = $callable; } /** * Get (and load when needed) the address book for $key * - * @param string $address_book_key + * @param string $addressBookKey * @return \OCP\IAddressBook */ - protected function getAddressBook($address_book_key) + protected function getAddressBook($addressBookKey) { $this->loadAddressBooks(); - if (!array_key_exists($address_book_key, $this->address_books)) { + if (!array_key_exists($addressBookKey, $this->addressBooks)) { return null; } - return $this->address_books[$address_book_key]; + return $this->addressBooks[$addressBookKey]; } /** @@ -171,10 +171,10 @@ namespace OC { */ protected function loadAddressBooks() { - foreach($this->address_book_loaders as $callable) { + foreach($this->addressBookLoaders as $callable) { $callable($this); } - $this->address_book_loaders = array(); + $this->addressBookLoaders = array(); } } } -- cgit v1.2.3 From f260951825aae63c4295a7e39ea06d823f75bddd Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Sat, 19 Apr 2014 14:56:16 +0200 Subject: port database layer from appframework to core --- lib/private/appframework/db/db.php | 57 +++++ .../dependencyinjection/dicontainer.php | 8 + .../appframework/db/doesnotexistexception.php | 42 +++ lib/public/appframework/db/entity.php | 229 +++++++++++++++++ lib/public/appframework/db/idb.php | 51 ++++ lib/public/appframework/db/mapper.php | 284 +++++++++++++++++++++ .../db/multipleobjectsreturnedexception.php | 42 +++ tests/lib/appframework/db/EntityTest.php | 204 +++++++++++++++ tests/lib/appframework/db/MapperTest.php | 264 +++++++++++++++++++ tests/lib/appframework/db/MapperTestUtility.php | 179 +++++++++++++ 10 files changed, 1360 insertions(+) create mode 100644 lib/private/appframework/db/db.php create mode 100644 lib/public/appframework/db/doesnotexistexception.php create mode 100644 lib/public/appframework/db/entity.php create mode 100644 lib/public/appframework/db/idb.php create mode 100644 lib/public/appframework/db/mapper.php create mode 100644 lib/public/appframework/db/multipleobjectsreturnedexception.php create mode 100644 tests/lib/appframework/db/EntityTest.php create mode 100644 tests/lib/appframework/db/MapperTest.php create mode 100644 tests/lib/appframework/db/MapperTestUtility.php (limited to 'lib/private') diff --git a/lib/private/appframework/db/db.php b/lib/private/appframework/db/db.php new file mode 100644 index 00000000000..c12e9d45ef2 --- /dev/null +++ b/lib/private/appframework/db/db.php @@ -0,0 +1,57 @@ +. + * + */ + +namespace OC\AppFramework\Db; + +use \OCP\AppFramework\Db\IDb; + + +/** + * Small Facade for being able to inject the database connection for tests + */ +class Db implements IDb { + + + /** + * Used to abstract the owncloud database access away + * @param string $sql the sql query with ? placeholder for params + * @param int $limit the maximum number of rows + * @param int $offset from which row we want to start + * @return \OCP\DB a query object + */ + public function prepareQuery($sql, $limit=null, $offset=null){ + return \OCP\DB::prepare($sql, $limit, $offset); + } + + + /** + * Used to get the id of the just inserted element + * @param string $tableName the name of the table where we inserted the item + * @return int the id of the inserted element + */ + public function getInsertId($tableName){ + return \OCP\DB::insertid($tableName); + } + + +} diff --git a/lib/private/appframework/dependencyinjection/dicontainer.php b/lib/private/appframework/dependencyinjection/dicontainer.php index e478225a53d..0faa507c76e 100644 --- a/lib/private/appframework/dependencyinjection/dicontainer.php +++ b/lib/private/appframework/dependencyinjection/dicontainer.php @@ -32,6 +32,7 @@ use OC\AppFramework\Middleware\MiddlewareDispatcher; use OC\AppFramework\Middleware\Security\SecurityMiddleware; use OC\AppFramework\Utility\SimpleContainer; use OC\AppFramework\Utility\TimeFactory; +use OC\AppFramework\Db\Db; use OCP\AppFramework\IApi; use OCP\AppFramework\IAppContainer; use OCP\AppFramework\Middleware; @@ -60,6 +61,13 @@ class DIContainer extends SimpleContainer implements IAppContainer{ return new API($c['AppName']); }); + /** + * Database + */ + $this['Db'] = $this->share(function($c){ + return new Db(); + }); + /** * Http */ diff --git a/lib/public/appframework/db/doesnotexistexception.php b/lib/public/appframework/db/doesnotexistexception.php new file mode 100644 index 00000000000..5861e74f6c8 --- /dev/null +++ b/lib/public/appframework/db/doesnotexistexception.php @@ -0,0 +1,42 @@ +. + * + */ + + +namespace OCP\AppFramework\Db; + + +/** + * This is returned or should be returned when a find request does not find an + * entry in the database + */ +class DoesNotExistException extends \Exception { + + /** + * Constructor + * @param string $msg the error message + */ + public function __construct($msg){ + parent::__construct($msg); + } + +} \ No newline at end of file diff --git a/lib/public/appframework/db/entity.php b/lib/public/appframework/db/entity.php new file mode 100644 index 00000000000..6042cb98288 --- /dev/null +++ b/lib/public/appframework/db/entity.php @@ -0,0 +1,229 @@ +. +* +*/ + +namespace OCP\AppFramework\Db; + + +abstract class Entity { + + public $id; + + private $_updatedFields = array(); + private $_fieldTypes = array('id' => 'integer'); + + + /** + * Simple alternative constructor for building entities from a request + * @param array $params the array which was obtained via $this->params('key') + * in the controller + * @return Entity + */ + public static function fromParams(array $params) { + $instance = new static(); + + foreach($params as $key => $value) { + $method = 'set' . ucfirst($key); + $instance->$method($value); + } + + return $instance; + } + + + /** + * Maps the keys of the row array to the attributes + * @param array $row the row to map onto the entity + */ + public static function fromRow(array $row){ + $instance = new static(); + + foreach($row as $key => $value){ + $prop = ucfirst($instance->columnToProperty($key)); + $setter = 'set' . $prop; + $instance->$setter($value); + } + + $instance->resetUpdatedFields(); + + return $instance; + } + + + /** + * @return an array with attribute and type + */ + public function getFieldTypes() { + return $this->_fieldTypes; + } + + + /** + * Marks the entity as clean needed for setting the id after the insertion + */ + public function resetUpdatedFields(){ + $this->_updatedFields = array(); + } + + + protected function setter($name, $args) { + // setters should only work for existing attributes + if(property_exists($this, $name)){ + $this->markFieldUpdated($name); + + // if type definition exists, cast to correct type + if($args[0] !== null && array_key_exists($name, $this->_fieldTypes)) { + settype($args[0], $this->_fieldTypes[$name]); + } + $this->$name = $args[0]; + + } else { + throw new \BadFunctionCallException($name . + ' is not a valid attribute'); + } + } + + + protected function getter($name) { + // getters should only work for existing attributes + if(property_exists($this, $name)){ + return $this->$name; + } else { + throw new \BadFunctionCallException($name . + ' is not a valid attribute'); + } + } + + + /** + * Each time a setter is called, push the part after set + * into an array: for instance setId will save Id in the + * updated fields array so it can be easily used to create the + * getter method + */ + public function __call($methodName, $args){ + $attr = lcfirst( substr($methodName, 3) ); + + if(strpos($methodName, 'set') === 0){ + $this->setter($attr, $args); + } elseif(strpos($methodName, 'get') === 0) { + return $this->getter($attr); + } else { + throw new \BadFunctionCallException($methodName . + ' does not exist'); + } + + } + + + /** + * Mark am attribute as updated + * @param string $attribute the name of the attribute + */ + protected function markFieldUpdated($attribute){ + $this->_updatedFields[$attribute] = true; + } + + + /** + * Transform a database columnname to a property + * @param string $columnName the name of the column + * @return string the property name + */ + public function columnToProperty($columnName){ + $parts = explode('_', $columnName); + $property = null; + + foreach($parts as $part){ + if($property === null){ + $property = $part; + } else { + $property .= ucfirst($part); + } + } + + return $property; + } + + + /** + * Transform a property to a database column name + * @param string $property the name of the property + * @return string the column name + */ + public function propertyToColumn($property){ + $parts = preg_split('/(?=[A-Z])/', $property); + $column = null; + + foreach($parts as $part){ + if($column === null){ + $column = $part; + } else { + $column .= '_' . lcfirst($part); + } + } + + return $column; + } + + + /** + * @return array array of updated fields for update query + */ + public function getUpdatedFields(){ + return $this->_updatedFields; + } + + + /** + * Adds type information for a field so that its automatically casted to + * that value once its being returned from the database + * @param string $fieldName the name of the attribute + * @param string $type the type which will be used to call settype() + */ + protected function addType($fieldName, $type){ + $this->_fieldTypes[$fieldName] = $type; + } + + + /** + * Slugify the value of a given attribute + * Warning: This doesn't result in a unique value + * @param string $attributeName the name of the attribute, which value should be slugified + * @return string slugified value + */ + public function slugify($attributeName){ + // toSlug should only work for existing attributes + if(property_exists($this, $attributeName)){ + $value = $this->$attributeName; + // replace everything except alphanumeric with a single '-' + $value = preg_replace('/[^A-Za-z0-9]+/', '-', $value); + $value = strtolower($value); + // trim '-' + return trim($value, '-'); + } else { + throw new \BadFunctionCallException($attributeName . + ' is not a valid attribute'); + } + } + +} diff --git a/lib/public/appframework/db/idb.php b/lib/public/appframework/db/idb.php new file mode 100644 index 00000000000..e2edff4f615 --- /dev/null +++ b/lib/public/appframework/db/idb.php @@ -0,0 +1,51 @@ +. + * + */ + +namespace OCP\AppFramework\Db; + + +/** + * Small Facade for being able to inject the database connection for tests + */ +interface IDb { + + + /** + * Used to abstract the owncloud database access away + * @param string $sql the sql query with ? placeholder for params + * @param int $limit the maximum number of rows + * @param int $offset from which row we want to start + * @return \OCP\DB a query object + */ + public function prepareQuery($sql, $limit=null, $offset=null); + + + /** + * Used to get the id of the just inserted element + * @param string $tableName the name of the table where we inserted the item + * @return int the id of the inserted element + */ + public function getInsertId($tableName); + + +} diff --git a/lib/public/appframework/db/mapper.php b/lib/public/appframework/db/mapper.php new file mode 100644 index 00000000000..3e9778dbc61 --- /dev/null +++ b/lib/public/appframework/db/mapper.php @@ -0,0 +1,284 @@ +. + * + */ + + +namespace OCP\AppFramework\Db; + + +/** + * Simple parent class for inheriting your data access layer from. This class + * may be subject to change in the future + */ +abstract class Mapper { + + protected $tableName; + protected $entityClass; + private $db; + + /** + * @param Db $db Instance of the Db abstraction layer + * @param string $tableName the name of the table. set this to allow entity + * @param string $entityClass the name of the entity that the sql should be + * mapped to queries without using sql + */ + public function __construct(IDb $db, $tableName, $entityClass=null){ + $this->db = $db; + $this->tableName = '*PREFIX*' . $tableName; + + // if not given set the entity name to the class without the mapper part + // cache it here for later use since reflection is slow + if($entityClass === null) { + $this->entityClass = str_replace('Mapper', '', get_class($this)); + } else { + $this->entityClass = $entityClass; + } + } + + + /** + * @return string the table name + */ + public function getTableName(){ + return $this->tableName; + } + + + /** + * Deletes an entity from the table + * @param Entity $entity the entity that should be deleted + */ + public function delete(Entity $entity){ + $sql = 'DELETE FROM `' . $this->tableName . '` WHERE `id` = ?'; + $this->execute($sql, array($entity->getId())); + } + + + /** + * Creates a new entry in the db from an entity + * @param Entity $enttiy the entity that should be created + * @return the saved entity with the set id + */ + public function insert(Entity $entity){ + // get updated fields to save, fields have to be set using a setter to + // be saved + $properties = $entity->getUpdatedFields(); + $values = ''; + $columns = ''; + $params = array(); + + // build the fields + $i = 0; + foreach($properties as $property => $updated) { + $column = $entity->propertyToColumn($property); + $getter = 'get' . ucfirst($property); + + $columns .= '`' . $column . '`'; + $values .= '?'; + + // only append colon if there are more entries + if($i < count($properties)-1){ + $columns .= ','; + $values .= ','; + } + + array_push($params, $entity->$getter()); + $i++; + + } + + $sql = 'INSERT INTO `' . $this->tableName . '`(' . + $columns . ') VALUES(' . $values . ')'; + + $this->execute($sql, $params); + + $entity->setId((int) $this->db->getInsertId($this->tableName)); + return $entity; + } + + + + /** + * Updates an entry in the db from an entity + * @throws \InvalidArgumentException if entity has no id + * @param Entity $enttiy the entity that should be created + */ + public function update(Entity $entity){ + // entity needs an id + $id = $entity->getId(); + if($id === null){ + throw new \InvalidArgumentException( + 'Entity which should be updated has no id'); + } + + // get updated fields to save, fields have to be set using a setter to + // be saved + $properties = $entity->getUpdatedFields(); + // dont update the id field + unset($properties['id']); + + $columns = ''; + $params = array(); + + // build the fields + $i = 0; + foreach($properties as $property => $updated) { + + $column = $entity->propertyToColumn($property); + $getter = 'get' . ucfirst($property); + + $columns .= '`' . $column . '` = ?'; + + // only append colon if there are more entries + if($i < count($properties)-1){ + $columns .= ','; + } + + array_push($params, $entity->$getter()); + $i++; + } + + $sql = 'UPDATE `' . $this->tableName . '` SET ' . + $columns . ' WHERE `id` = ?'; + array_push($params, $id); + + $this->execute($sql, $params); + } + + + /** + * Runs an sql query + * @param string $sql the prepare string + * @param array $params the params which should replace the ? in the sql query + * @param int $limit the maximum number of rows + * @param int $offset from which row we want to start + * @return \PDOStatement the database query result + */ + protected function execute($sql, array $params=array(), $limit=null, $offset=null){ + $query = $this->db->prepareQuery($sql, $limit, $offset); + + $index = 1; // bindParam is 1 indexed + foreach($params as $param) { + + switch (gettype($param)) { + case 'integer': + $pdoConstant = \PDO::PARAM_INT; + break; + + case 'boolean': + $pdoConstant = \PDO::PARAM_BOOL; + break; + + default: + $pdoConstant = \PDO::PARAM_STR; + break; + } + + $query->bindValue($index, $param, $pdoConstant); + + $index++; + } + + return $query->execute(); + } + + + /** + * Returns an db result and throws exceptions when there are more or less + * results + * @see findEntity + * @param string $sql the sql query + * @param array $params the parameters of the sql query + * @param int $limit the maximum number of rows + * @param int $offset from which row we want to start + * @throws DoesNotExistException if the item does not exist + * @throws MultipleObjectsReturnedException if more than one item exist + * @return array the result as row + */ + protected function findOneQuery($sql, array $params=array(), $limit=null, $offset=null){ + $result = $this->execute($sql, $params, $limit, $offset); + $row = $result->fetchRow(); + + if($row === false || $row === null){ + throw new DoesNotExistException('No matching entry found'); + } + $row2 = $result->fetchRow(); + //MDB2 returns null, PDO and doctrine false when no row is available + if( ! ($row2 === false || $row2 === null )) { + throw new MultipleObjectsReturnedException('More than one result'); + } else { + return $row; + } + } + + + /** + * Creates an entity from a row. Automatically determines the entity class + * from the current mapper name (MyEntityMapper -> MyEntity) + * @param array $row the row which should be converted to an entity + * @return Entity the entity + */ + protected function mapRowToEntity($row) { + return call_user_func($this->entityClass .'::fromRow', $row); + } + + + /** + * Runs a sql query and returns an array of entities + * @param string $sql the prepare string + * @param array $params the params which should replace the ? in the sql query + * @param int $limit the maximum number of rows + * @param int $offset from which row we want to start + * @return array all fetched entities + */ + protected function findEntities($sql, array $params=array(), $limit=null, $offset=null) { + $result = $this->execute($sql, $params, $limit, $offset); + + $entities = array(); + + while($row = $result->fetchRow()){ + $entities[] = $this->mapRowToEntity($row); + } + + return $entities; + } + + + /** + * Returns an db result and throws exceptions when there are more or less + * results + * @param string $sql the sql query + * @param array $params the parameters of the sql query + * @param int $limit the maximum number of rows + * @param int $offset from which row we want to start + * @throws DoesNotExistException if the item does not exist + * @throws MultipleObjectsReturnedException if more than one item exist + * @return Entity the entity + */ + protected function findEntity($sql, array $params=array(), $limit=null, $offset=null){ + return $this->mapRowToEntity($this->findOneQuery($sql, $params, $limit, $offset)); + } + + +} diff --git a/lib/public/appframework/db/multipleobjectsreturnedexception.php b/lib/public/appframework/db/multipleobjectsreturnedexception.php new file mode 100644 index 00000000000..51d8d6bc7e1 --- /dev/null +++ b/lib/public/appframework/db/multipleobjectsreturnedexception.php @@ -0,0 +1,42 @@ +. + * + */ + + +namespace OCP\AppFramework\Db; + + +/** + * This is returned or should be returned when a find request finds more than one + * row + */ +class MultipleObjectsReturnedException extends \Exception { + + /** + * Constructor + * @param string $msg the error message + */ + public function __construct($msg){ + parent::__construct($msg); + } + +} \ No newline at end of file diff --git a/tests/lib/appframework/db/EntityTest.php b/tests/lib/appframework/db/EntityTest.php new file mode 100644 index 00000000000..170bd04b7b9 --- /dev/null +++ b/tests/lib/appframework/db/EntityTest.php @@ -0,0 +1,204 @@ +. +* +*/ + +namespace OCP\AppFramework\Db; + + + +class TestEntity extends Entity { + public $name; + public $email; + public $testId; + public $preName; + + public function __construct(){ + $this->addType('testId', 'integer'); + } +}; + + +class EntityTest extends \PHPUnit_Framework_TestCase { + + private $entity; + + protected function setUp(){ + $this->entity = new TestEntity(); + } + + + public function testResetUpdatedFields(){ + $entity = new TestEntity(); + $entity->setId(3); + $entity->resetUpdatedFields(); + + $this->assertEquals(array(), $entity->getUpdatedFields()); + } + + + public function testFromRow(){ + $row = array( + 'pre_name' => 'john', + 'email' => 'john@something.com' + ); + $this->entity = TestEntity::fromRow($row); + + $this->assertEquals($row['pre_name'], $this->entity->getPreName()); + $this->assertEquals($row['email'], $this->entity->getEmail()); + } + + + public function testGetSetId(){ + $id = 3; + $this->entity->setId(3); + + $this->assertEquals($id, $this->entity->getId()); + } + + + public function testColumnToPropertyNoReplacement(){ + $column = 'my'; + $this->assertEquals('my', + $this->entity->columnToProperty($column)); + } + + + public function testColumnToProperty(){ + $column = 'my_attribute'; + $this->assertEquals('myAttribute', + $this->entity->columnToProperty($column)); + } + + + public function testPropertyToColumnNoReplacement(){ + $property = 'my'; + $this->assertEquals('my', + $this->entity->propertyToColumn($property)); + } + + + public function testSetterMarksFieldUpdated(){ + $id = 3; + $this->entity->setId(3); + + $this->assertContains('id', $this->entity->getUpdatedFields()); + } + + + public function testCallShouldOnlyWorkForGetterSetter(){ + $this->setExpectedException('\BadFunctionCallException'); + + $this->entity->something(); + } + + + public function testGetterShouldFailIfAttributeNotDefined(){ + $this->setExpectedException('\BadFunctionCallException'); + + $this->entity->getTest(); + } + + + public function testSetterShouldFailIfAttributeNotDefined(){ + $this->setExpectedException('\BadFunctionCallException'); + + $this->entity->setTest(); + } + + + public function testFromRowShouldNotAssignEmptyArray(){ + $row = array(); + $entity2 = new TestEntity(); + + $this->entity = TestEntity::fromRow($row); + $this->assertEquals($entity2, $this->entity); + } + + + public function testIdGetsConvertedToInt(){ + $row = array('id' => '4'); + + $this->entity = TestEntity::fromRow($row); + $this->assertSame(4, $this->entity->getId()); + } + + + public function testSetType(){ + $row = array('testId' => '4'); + + $this->entity = TestEntity::fromRow($row); + $this->assertSame(4, $this->entity->getTestId()); + } + + + public function testFromParams(){ + $params = array( + 'testId' => 4, + 'email' => 'john@doe' + ); + + $entity = TestEntity::fromParams($params); + + $this->assertEquals($params['testId'], $entity->getTestId()); + $this->assertEquals($params['email'], $entity->getEmail()); + $this->assertTrue($entity instanceof TestEntity); + } + + public function testSlugify(){ + $entity = new TestEntity(); + $entity->setName('Slugify this!'); + $this->assertEquals('slugify-this', $entity->slugify('name')); + $entity->setName('°!"§$%&/()=?`´ß\}][{³²#\'+~*-_.:,;<>|äöüÄÖÜSlugify this!'); + $this->assertEquals('slugify-this', $entity->slugify('name')); + } + + + public function testSetterCasts() { + $entity = new TestEntity(); + $entity->setId('3'); + $this->assertSame(3, $entity->getId()); + } + + + public function testSetterDoesNotCastOnNull() { + $entity = new TestEntity(); + $entity->setId(null); + $this->assertSame(null, $entity->getId()); + } + + + public function testGetFieldTypes() { + $entity = new TestEntity(); + $this->assertEquals(array( + 'id' => 'integer', + 'testId' => 'integer' + ), $entity->getFieldTypes()); + } + + + public function testGetItInt() { + $entity = new TestEntity(); + $entity->setId(3); + $this->assertEquals('integer', gettype($entity->getId())); + } + +} \ No newline at end of file diff --git a/tests/lib/appframework/db/MapperTest.php b/tests/lib/appframework/db/MapperTest.php new file mode 100644 index 00000000000..2a7a3700dab --- /dev/null +++ b/tests/lib/appframework/db/MapperTest.php @@ -0,0 +1,264 @@ +. + * + */ + + +namespace OCP\AppFramework\Db; + + +require_once __DIR__ . '/MapperTestUtility.php'; + + +class Example extends Entity { + public $preName; + public $email; +}; + + +class ExampleMapper extends Mapper { + public function __construct(IDb $db){ parent::__construct($db, 'table'); } + public function find($table, $id){ return $this->findOneQuery($table, $id); } + public function findOneEntity($table, $id){ return $this->findEntity($table, $id); } + public function findAll($table){ return $this->findAllQuery($table); } + public function findAllEntities($table){ return $this->findEntities($table); } + public function mapRow($row){ return $this->mapRowToEntity($row); } + public function pDeleteQuery($table, $id){ $this->deleteQuery($table, $id); } +} + + +class MapperTest extends MapperTestUtility { + + private $mapper; + + public function setUp(){ + parent::setUp(); + $this->mapper = new ExampleMapper($this->db); + } + + + public function testMapperShouldSetTableName(){ + $this->assertEquals('*PREFIX*table', $this->mapper->getTableName()); + } + + + public function testFindQuery(){ + $sql = 'hi'; + $params = array('jo'); + $rows = array( + array('hi') + ); + $row = $this->setMapperResult($sql, $params, $rows); + $this->mapper->find($sql, $params); + } + + public function testFindEntity(){ + $sql = 'hi'; + $params = array('jo'); + $rows = array( + array('pre_name' => 'hi') + ); + $row = $this->setMapperResult($sql, $params, $rows); + $this->mapper->findOneEntity($sql, $params); + } + + public function testFindNotFound(){ + $sql = 'hi'; + $params = array('jo'); + $rows = array(); + $row = $this->setMapperResult($sql, $params, $rows); + $this->setExpectedException( + '\OCP\AppFramework\Db\DoesNotExistException'); + $this->mapper->find($sql, $params); + } + + public function testFindEntityNotFound(){ + $sql = 'hi'; + $params = array('jo'); + $rows = array(); + $row = $this->setMapperResult($sql, $params, $rows); + $this->setExpectedException( + '\OCP\AppFramework\Db\DoesNotExistException'); + $this->mapper->findOneEntity($sql, $params); + } + + public function testFindMultiple(){ + $sql = 'hi'; + $params = array('jo'); + $rows = array( + array('jo'), array('ho') + ); + $row = $this->setMapperResult($sql, $params, $rows); + $this->setExpectedException( + '\OCP\AppFramework\Db\MultipleObjectsReturnedException'); + $this->mapper->find($sql, $params); + } + + public function testFindEntityMultiple(){ + $sql = 'hi'; + $params = array('jo'); + $rows = array( + array('jo'), array('ho') + ); + $row = $this->setMapperResult($sql, $params, $rows); + $this->setExpectedException( + '\OCP\AppFramework\Db\MultipleObjectsReturnedException'); + $this->mapper->findOneEntity($sql, $params); + } + + + public function testDelete(){ + $sql = 'DELETE FROM `*PREFIX*table` WHERE `id` = ?'; + $params = array(2); + + $this->setMapperResult($sql, $params); + $entity = new Example(); + $entity->setId($params[0]); + + $this->mapper->delete($entity); + } + + + public function testCreate(){ + $this->db->expects($this->once()) + ->method('getInsertId') + ->with($this->equalTo('*PREFIX*table')) + ->will($this->returnValue(3)); + $this->mapper = new ExampleMapper($this->db); + + $sql = 'INSERT INTO `*PREFIX*table`(`pre_name`,`email`) ' . + 'VALUES(?,?)'; + $params = array('john', 'my@email'); + $entity = new Example(); + $entity->setPreName($params[0]); + $entity->setEmail($params[1]); + + $this->setMapperResult($sql, $params); + + $this->mapper->insert($entity); + } + + + public function testCreateShouldReturnItemWithCorrectInsertId(){ + $this->db->expects($this->once()) + ->method('getInsertId') + ->with($this->equalTo('*PREFIX*table')) + ->will($this->returnValue(3)); + $this->mapper = new ExampleMapper($this->db); + + $sql = 'INSERT INTO `*PREFIX*table`(`pre_name`,`email`) ' . + 'VALUES(?,?)'; + $params = array('john', 'my@email'); + $entity = new Example(); + $entity->setPreName($params[0]); + $entity->setEmail($params[1]); + + $this->setMapperResult($sql, $params); + + $result = $this->mapper->insert($entity); + + $this->assertEquals(3, $result->getId()); + } + + + public function testUpdate(){ + $sql = 'UPDATE `*PREFIX*table` ' . + 'SET ' . + '`pre_name` = ?,'. + '`email` = ? ' . + 'WHERE `id` = ?'; + + $params = array('john', 'my@email', 1); + $entity = new Example(); + $entity->setPreName($params[0]); + $entity->setEmail($params[1]); + $entity->setId($params[2]); + + $this->setMapperResult($sql, $params); + + $this->mapper->update($entity); + } + + + public function testUpdateNoId(){ + $sql = 'UPDATE `*PREFIX*table` ' . + 'SET ' . + '`pre_name` = ?,'. + '`email` = ? ' . + 'WHERE `id` = ?'; + + $params = array('john', 'my@email'); + $entity = new Example(); + $entity->setPreName($params[0]); + $entity->setEmail($params[1]); + + $this->setExpectedException('InvalidArgumentException'); + + $this->mapper->update($entity); + } + + + public function testMapRowToEntity(){ + $entity1 = $this->mapper->mapRow(array('pre_name' => 'test1', 'email' => 'test2')); + $entity2 = new Example(); + $entity2->setPreName('test1'); + $entity2->setEmail('test2'); + $entity2->resetUpdatedFields(); + $this->assertEquals($entity2, $entity1); + } + + public function testFindEntities(){ + $sql = 'hi'; + $rows = array( + array('pre_name' => 'hi') + ); + $entity = new Example(); + $entity->setPreName('hi'); + $entity->resetUpdatedFields(); + $row = $this->setMapperResult($sql, array(), $rows); + $result = $this->mapper->findAllEntities($sql); + $this->assertEquals(array($entity), $result); + } + + public function testFindEntitiesNotFound(){ + $sql = 'hi'; + $rows = array(); + $row = $this->setMapperResult($sql, array(), $rows); + $result = $this->mapper->findAllEntities($sql); + $this->assertEquals(array(), $result); + } + + public function testFindEntitiesMultiple(){ + $sql = 'hi'; + $rows = array( + array('pre_name' => 'jo'), array('email' => 'ho') + ); + $entity1 = new Example(); + $entity1->setPreName('jo'); + $entity1->resetUpdatedFields(); + $entity2 = new Example(); + $entity2->setEmail('ho'); + $entity2->resetUpdatedFields(); + $row = $this->setMapperResult($sql, array(), $rows); + $result = $this->mapper->findAllEntities($sql); + $this->assertEquals(array($entity1, $entity2), $result); + } +} \ No newline at end of file diff --git a/tests/lib/appframework/db/MapperTestUtility.php b/tests/lib/appframework/db/MapperTestUtility.php new file mode 100644 index 00000000000..ecd79fef263 --- /dev/null +++ b/tests/lib/appframework/db/MapperTestUtility.php @@ -0,0 +1,179 @@ +. + * + */ + + +namespace OCP\AppFramework\Db; + + +/** + * Simple utility class for testing mappers + */ +abstract class MapperTestUtility extends \PHPUnit_Framework_TestCase { + + + protected $db; + private $query; + private $pdoResult; + private $queryAt; + private $prepareAt; + private $fetchAt; + private $iterators; + + + /** + * Run this function before the actual test to either set or initialize the + * db. After this the db can be accessed by using $this->db + */ + protected function setUp(){ + $this->db = $this->getMockBuilder( + '\OCP\AppFramework\Db\IDb') + ->disableOriginalConstructor() + ->getMock(); + + $this->query = $this->getMock('Query', array('execute', 'bindValue')); + $this->pdoResult = $this->getMock('Result', array('fetchRow')); + $this->queryAt = 0; + $this->prepareAt = 0; + $this->iterators = array(); + $this->fetchAt = 0; + } + + + /** + * Create mocks and set expected results for database queries + * @param string $sql the sql query that you expect to receive + * @param array $arguments the expected arguments for the prepare query + * method + * @param array $returnRows the rows that should be returned for the result + * of the database query. If not provided, it wont be assumed that fetchRow + * will be called on the result + */ + protected function setMapperResult($sql, $arguments=array(), $returnRows=array(), + $limit=null, $offset=null){ + + $this->iterators[] = new ArgumentIterator($returnRows); + + $iterators = $this->iterators; + $fetchAt = $this->fetchAt; + + $this->pdoResult->expects($this->any()) + ->method('fetchRow') + ->will($this->returnCallback( + function() use ($iterators, $fetchAt){ + $iterator = $iterators[$fetchAt]; + $result = $iterator->next(); + + if($result === false) { + $fetchAt++; + } + + return $result; + } + )); + + $index = 1; + foreach($arguments as $argument) { + switch (gettype($argument)) { + case 'integer': + $pdoConstant = \PDO::PARAM_INT; + break; + + case 'NULL': + $pdoConstant = \PDO::PARAM_NULL; + break; + + case 'boolean': + $pdoConstant = \PDO::PARAM_BOOL; + break; + + default: + $pdoConstant = \PDO::PARAM_STR; + break; + } + $this->query->expects($this->at($this->queryAt)) + ->method('bindValue') + ->with($this->equalTo($index), + $this->equalTo($argument), + $this->equalTo($pdoConstant)); + $index++; + $this->queryAt++; + } + + $this->query->expects($this->at($this->queryAt)) + ->method('execute') + ->with() + ->will($this->returnValue($this->pdoResult)); + $this->queryAt++; + + if($limit === null && $offset === null) { + $this->db->expects($this->at($this->prepareAt)) + ->method('prepareQuery') + ->with($this->equalTo($sql)) + ->will(($this->returnValue($this->query))); + } elseif($limit !== null && $offset === null) { + $this->db->expects($this->at($this->prepareAt)) + ->method('prepareQuery') + ->with($this->equalTo($sql), $this->equalTo($limit)) + ->will(($this->returnValue($this->query))); + } elseif($limit === null && $offset !== null) { + $this->db->expects($this->at($this->prepareAt)) + ->method('prepareQuery') + ->with($this->equalTo($sql), + $this->equalTo(null), + $this->equalTo($offset)) + ->will(($this->returnValue($this->query))); + } else { + $this->db->expects($this->at($this->prepareAt)) + ->method('prepareQuery') + ->with($this->equalTo($sql), + $this->equalTo($limit), + $this->equalTo($offset)) + ->will(($this->returnValue($this->query))); + } + $this->prepareAt++; + $this->fetchAt++; + + } + + +} + + +class ArgumentIterator { + + private $arguments; + + public function __construct($arguments){ + $this->arguments = $arguments; + } + + public function next(){ + $result = array_shift($this->arguments); + if($result === null){ + return false; + } else { + return $result; + } + } +} + -- cgit v1.2.3 From 95a83233a9194d3d5cd0f060b0d7678379401b2a Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Sat, 19 Apr 2014 15:32:17 +0200 Subject: fix doc strings for db facade --- lib/private/appframework/db/db.php | 2 +- lib/public/appframework/db/idb.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/appframework/db/db.php b/lib/private/appframework/db/db.php index c12e9d45ef2..713b39175c6 100644 --- a/lib/private/appframework/db/db.php +++ b/lib/private/appframework/db/db.php @@ -37,7 +37,7 @@ class Db implements IDb { * @param string $sql the sql query with ? placeholder for params * @param int $limit the maximum number of rows * @param int $offset from which row we want to start - * @return \OCP\DB a query object + * @return \OC_DB_StatementWrapper prepared SQL query */ public function prepareQuery($sql, $limit=null, $offset=null){ return \OCP\DB::prepare($sql, $limit, $offset); diff --git a/lib/public/appframework/db/idb.php b/lib/public/appframework/db/idb.php index e2edff4f615..e5313476f40 100644 --- a/lib/public/appframework/db/idb.php +++ b/lib/public/appframework/db/idb.php @@ -35,7 +35,7 @@ interface IDb { * @param string $sql the sql query with ? placeholder for params * @param int $limit the maximum number of rows * @param int $offset from which row we want to start - * @return \OCP\DB a query object + * @return \OC_DB_StatementWrapper prepared SQL query */ public function prepareQuery($sql, $limit=null, $offset=null); -- cgit v1.2.3 From 4a7e0561caebd470fbaaf88655619930260a573e Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Sat, 19 Apr 2014 19:30:12 +0200 Subject: move db into iservercontainer --- lib/private/appframework/db/db.php | 2 +- .../dependencyinjection/dicontainer.php | 7 --- lib/private/server.php | 13 ++++++ lib/public/appframework/db/idb.php | 51 ---------------------- lib/public/appframework/db/mapper.php | 2 + lib/public/idb.php | 51 ++++++++++++++++++++++ lib/public/iservercontainer.php | 8 ++++ tests/lib/appframework/db/MapperTest.php | 2 + tests/lib/appframework/db/MapperTestUtility.php | 2 +- 9 files changed, 78 insertions(+), 60 deletions(-) delete mode 100644 lib/public/appframework/db/idb.php create mode 100644 lib/public/idb.php (limited to 'lib/private') diff --git a/lib/private/appframework/db/db.php b/lib/private/appframework/db/db.php index 713b39175c6..fc77a38f814 100644 --- a/lib/private/appframework/db/db.php +++ b/lib/private/appframework/db/db.php @@ -23,7 +23,7 @@ namespace OC\AppFramework\Db; -use \OCP\AppFramework\Db\IDb; +use \OCP\IDb; /** diff --git a/lib/private/appframework/dependencyinjection/dicontainer.php b/lib/private/appframework/dependencyinjection/dicontainer.php index 0faa507c76e..73d356e9852 100644 --- a/lib/private/appframework/dependencyinjection/dicontainer.php +++ b/lib/private/appframework/dependencyinjection/dicontainer.php @@ -61,13 +61,6 @@ class DIContainer extends SimpleContainer implements IAppContainer{ return new API($c['AppName']); }); - /** - * Database - */ - $this['Db'] = $this->share(function($c){ - return new Db(); - }); - /** * Http */ diff --git a/lib/private/server.php b/lib/private/server.php index 5d90a0b19fc..e977c643832 100644 --- a/lib/private/server.php +++ b/lib/private/server.php @@ -3,6 +3,7 @@ namespace OC; use OC\AppFramework\Http\Request; +use OC\AppFramework\Db\Db; use OC\AppFramework\Utility\SimpleContainer; use OC\Cache\UserCache; use OC\DB\ConnectionWrapper; @@ -177,6 +178,9 @@ class Server extends SimpleContainer implements IServerContainer { } return $router; }); + $this['Db'] = $this->share(function($c){ + return new Db(); + }); } /** @@ -392,4 +396,13 @@ class Server extends SimpleContainer implements IServerContainer { function getRouter(){ return $this->query('Router'); } + + + /** + * Returns an instance of the db facade + * @return \OCP\IDb + */ + function getDb() { + return $this->query('Db'); + } } diff --git a/lib/public/appframework/db/idb.php b/lib/public/appframework/db/idb.php deleted file mode 100644 index e5313476f40..00000000000 --- a/lib/public/appframework/db/idb.php +++ /dev/null @@ -1,51 +0,0 @@ -. - * - */ - -namespace OCP\AppFramework\Db; - - -/** - * Small Facade for being able to inject the database connection for tests - */ -interface IDb { - - - /** - * Used to abstract the owncloud database access away - * @param string $sql the sql query with ? placeholder for params - * @param int $limit the maximum number of rows - * @param int $offset from which row we want to start - * @return \OC_DB_StatementWrapper prepared SQL query - */ - public function prepareQuery($sql, $limit=null, $offset=null); - - - /** - * Used to get the id of the just inserted element - * @param string $tableName the name of the table where we inserted the item - * @return int the id of the inserted element - */ - public function getInsertId($tableName); - - -} diff --git a/lib/public/appframework/db/mapper.php b/lib/public/appframework/db/mapper.php index 3e9778dbc61..46240649c77 100644 --- a/lib/public/appframework/db/mapper.php +++ b/lib/public/appframework/db/mapper.php @@ -26,6 +26,8 @@ namespace OCP\AppFramework\Db; +use \OCP\IDb; + /** * Simple parent class for inheriting your data access layer from. This class diff --git a/lib/public/idb.php b/lib/public/idb.php new file mode 100644 index 00000000000..82a8a681500 --- /dev/null +++ b/lib/public/idb.php @@ -0,0 +1,51 @@ +. + * + */ + +namespace OCP; + + +/** + * Small Facade for being able to inject the database connection for tests + */ +interface IDb { + + + /** + * Used to abstract the owncloud database access away + * @param string $sql the sql query with ? placeholder for params + * @param int $limit the maximum number of rows + * @param int $offset from which row we want to start + * @return \OC_DB_StatementWrapper prepared SQL query + */ + public function prepareQuery($sql, $limit=null, $offset=null); + + + /** + * Used to get the id of the just inserted element + * @param string $tableName the name of the table where we inserted the item + * @return int the id of the inserted element + */ + public function getInsertId($tableName); + + +} diff --git a/lib/public/iservercontainer.php b/lib/public/iservercontainer.php index 600d81d83af..22176c36b8a 100644 --- a/lib/public/iservercontainer.php +++ b/lib/public/iservercontainer.php @@ -113,6 +113,14 @@ interface IServerContainer { */ function getConfig(); + + /** + * Returns an instance of the db facade + * @return \OCP\IDb + */ + function getDb(); + + /** * Returns the app config manager * diff --git a/tests/lib/appframework/db/MapperTest.php b/tests/lib/appframework/db/MapperTest.php index c4eb35a068e..114081beb21 100644 --- a/tests/lib/appframework/db/MapperTest.php +++ b/tests/lib/appframework/db/MapperTest.php @@ -24,6 +24,8 @@ namespace OCP\AppFramework\Db; +use \OCP\IDb; + require_once __DIR__ . '/MapperTestUtility.php'; diff --git a/tests/lib/appframework/db/MapperTestUtility.php b/tests/lib/appframework/db/MapperTestUtility.php index ecd79fef263..4c81d4cd27b 100644 --- a/tests/lib/appframework/db/MapperTestUtility.php +++ b/tests/lib/appframework/db/MapperTestUtility.php @@ -46,7 +46,7 @@ abstract class MapperTestUtility extends \PHPUnit_Framework_TestCase { */ protected function setUp(){ $this->db = $this->getMockBuilder( - '\OCP\AppFramework\Db\IDb') + '\OCP\IDb') ->disableOriginalConstructor() ->getMock(); -- cgit v1.2.3 From 0c736feaba9ffec4d9fae2f812ba7499a14b1c45 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Sat, 19 Apr 2014 19:31:49 +0200 Subject: remove useless import --- lib/private/appframework/dependencyinjection/dicontainer.php | 1 - 1 file changed, 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/appframework/dependencyinjection/dicontainer.php b/lib/private/appframework/dependencyinjection/dicontainer.php index 73d356e9852..e478225a53d 100644 --- a/lib/private/appframework/dependencyinjection/dicontainer.php +++ b/lib/private/appframework/dependencyinjection/dicontainer.php @@ -32,7 +32,6 @@ use OC\AppFramework\Middleware\MiddlewareDispatcher; use OC\AppFramework\Middleware\Security\SecurityMiddleware; use OC\AppFramework\Utility\SimpleContainer; use OC\AppFramework\Utility\TimeFactory; -use OC\AppFramework\Db\Db; use OCP\AppFramework\IApi; use OCP\AppFramework\IAppContainer; use OCP\AppFramework\Middleware; -- cgit v1.2.3 From 7c0370105af504e31fa2d6be088273a3bba7262f Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Sat, 26 Apr 2014 11:15:09 +0200 Subject: Fix wrong var name --- lib/private/contactsmanager.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/contactsmanager.php b/lib/private/contactsmanager.php index a7cbba6c639..8cfbb3da9f6 100644 --- a/lib/private/contactsmanager.php +++ b/lib/private/contactsmanager.php @@ -40,7 +40,7 @@ namespace OC { $r = $addressBook->search($pattern, $searchProperties, $options); $contacts = array(); foreach($r as $c){ - $c['addressbook-key'] = $address_book->getKey(); + $c['addressbook-key'] = $addressBook->getKey(); $contacts[] = $c; } $result = array_merge($result, $contacts); -- cgit v1.2.3 From 50f49c57b5d51951dae87c0a9d57ad2b5dbefef7 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 1 May 2014 18:11:30 +0200 Subject: Some more params are optional --- lib/private/share/share.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'lib/private') diff --git a/lib/private/share/share.php b/lib/private/share/share.php index 21876bba831..9956ac99d57 100644 --- a/lib/private/share/share.php +++ b/lib/private/share/share.php @@ -1004,9 +1004,9 @@ class Share extends \OC\Share\Constants { * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique * @param string $shareWith User or group the item is being shared with * @param string uidOwner User that is the owner of shared items (optional) - * @param int $format Format to convert items to with formatItems() - * @param mixed $parameters to pass to formatItems() - * @param int $limit Number of items to return, -1 to return all matches (optional) + * @param int $format Format to convert items to with formatItems() (optional) + * @param mixed $parameters to pass to formatItems() (optional) + * @param int $limit Number of items to retur/n, -1 to return all matches (optional) * @param bool $includeCollections Include collection item types (optional) * @param bool $itemShareWithBySource (optional) * @param bool $checkExpireDate -- cgit v1.2.3 From c92c577b5e05ea1d932c6739b87fea8beea21e1b Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Fri, 2 May 2014 17:37:16 +0200 Subject: - Introduce isShared() and isMounted() on FileInfo class - Reuse these methods on determineIcon() - Generate permission string for the desktop client - expose {http://owncloud.org/ns}permissions as additional WebDAV property containing the permission string --- apps/files/lib/helper.php | 17 ++++------------- lib/private/connector/sabre/filesplugin.php | 18 ++++++++++++++---- lib/private/connector/sabre/node.php | 29 +++++++++++++++++++++++++++++ lib/private/files/fileinfo.php | 24 ++++++++++++++++++++++++ lib/public/files/fileinfo.php | 14 ++++++++++++++ 5 files changed, 85 insertions(+), 17 deletions(-) (limited to 'lib/private') diff --git a/apps/files/lib/helper.php b/apps/files/lib/helper.php index 0ae87d12fbf..3d395081411 100644 --- a/apps/files/lib/helper.php +++ b/apps/files/lib/helper.php @@ -27,20 +27,11 @@ class Helper */ public static function determineIcon($file) { if($file['type'] === 'dir') { - $dir = $file['directory']; $icon = \OC_Helper::mimetypeIcon('dir'); - $absPath = $file->getPath(); - $mount = \OC\Files\Filesystem::getMountManager()->find($absPath); - if (!is_null($mount)) { - $sid = $mount->getStorageId(); - if (!is_null($sid)) { - $sid = explode(':', $sid); - if ($sid[0] === 'shared') { - $icon = \OC_Helper::mimetypeIcon('dir-shared'); - } elseif ($sid[0] !== 'local' and $sid[0] !== 'home') { - $icon = \OC_Helper::mimetypeIcon('dir-external'); - } - } + if ($file->isShared()) { + $icon = \OC_Helper::mimetypeIcon('dir-shared'); + } elseif ($file->isMounted()) { + $icon = \OC_Helper::mimetypeIcon('dir-external'); } }else{ $icon = \OC_Helper::mimetypeIcon($file->getMimetype()); diff --git a/lib/private/connector/sabre/filesplugin.php b/lib/private/connector/sabre/filesplugin.php index 65231040fb5..e2ff574c455 100644 --- a/lib/private/connector/sabre/filesplugin.php +++ b/lib/private/connector/sabre/filesplugin.php @@ -37,6 +37,7 @@ class OC_Connector_Sabre_FilesPlugin extends Sabre_DAV_ServerPlugin $server->xmlNamespaces[self::NS_OWNCLOUD] = 'oc'; $server->protectedProperties[] = '{' . self::NS_OWNCLOUD . '}id'; + $server->protectedProperties[] = '{' . self::NS_OWNCLOUD . '}permissions'; $this->server = $server; $this->server->subscribeEvent('beforeGetProperties', array($this, 'beforeGetProperties')); @@ -57,15 +58,24 @@ class OC_Connector_Sabre_FilesPlugin extends Sabre_DAV_ServerPlugin if ($node instanceof OC_Connector_Sabre_Node) { - $fileid_propertyname = '{' . self::NS_OWNCLOUD . '}id'; - if (array_search($fileid_propertyname, $requestedProperties)) { - unset($requestedProperties[array_search($fileid_propertyname, $requestedProperties)]); + $fileIdPropertyName = '{' . self::NS_OWNCLOUD . '}id'; + $permissionsPropertyName = '{' . self::NS_OWNCLOUD . '}permissions'; + if (array_search($fileIdPropertyName, $requestedProperties)) { + unset($requestedProperties[array_search($fileIdPropertyName, $requestedProperties)]); + } + if (array_search($permissionsPropertyName, $requestedProperties)) { + unset($requestedProperties[array_search($permissionsPropertyName, $requestedProperties)]); } /** @var $node OC_Connector_Sabre_Node */ $fileId = $node->getFileId(); if (!is_null($fileId)) { - $returnedProperties[200][$fileid_propertyname] = $fileId; + $returnedProperties[200][$fileIdPropertyName] = $fileId; + } + + $permissions = $node->getDavPermissions(); + if (!is_null($fileId)) { + $returnedProperties[200][$permissionsPropertyName] = $permissions; } } diff --git a/lib/private/connector/sabre/node.php b/lib/private/connector/sabre/node.php index eede39cba8b..ca8dcce9e86 100644 --- a/lib/private/connector/sabre/node.php +++ b/lib/private/connector/sabre/node.php @@ -237,4 +237,33 @@ abstract class OC_Connector_Sabre_Node implements Sabre_DAV_INode, Sabre_DAV_IPr return null; } + + /** + * @return string|null + */ + public function getDavPermissions() { + $p =''; + if ($this->info->isShared()) { + $p .= 'S'; + } + if ($this->info->isShareable()) { + $p .= 'R'; + } + if ($this->info->isMounted()) { + $p .= 'M'; + } + if ($this->info->getType() === \OCP\Files\FileInfo::TYPE_FILE) { + if ($this->info->isUpdateable()) { + $p .= 'W'; + } + } else { + if ($this->info->isDeletable()) { + $p .= 'D'; + } + if ($this->info->isUpdateable()) { + $p .= 'CK'; + } + } + return $p; + } } diff --git a/lib/private/files/fileinfo.php b/lib/private/files/fileinfo.php index d6940f50bf1..357364415fb 100644 --- a/lib/private/files/fileinfo.php +++ b/lib/private/files/fileinfo.php @@ -196,4 +196,28 @@ class FileInfo implements \OCP\Files\FileInfo, \ArrayAccess { public function isShareable() { return $this->checkPermissions(\OCP\PERMISSION_SHARE); } + + /** + * Check if a file or folder is shared + * @return bool + */ + public function isShared() { + $sid = $this->getStorage()->getId(); + if (!is_null($sid)) { + $sid = explode(':', $sid); + return ($sid[0] === 'shared'); + } + + return false; + } + + public function isMounted() { + $sid = $this->getStorage()->getId(); + if (!is_null($sid)) { + $sid = explode(':', $sid); + return ($sid[0] !== 'local' and $sid[0] !== 'home'); + } + + return false; + } } diff --git a/lib/public/files/fileinfo.php b/lib/public/files/fileinfo.php index 37162e09336..f934637156e 100644 --- a/lib/public/files/fileinfo.php +++ b/lib/public/files/fileinfo.php @@ -135,4 +135,18 @@ interface FileInfo { * @return bool */ public function isShareable(); + + /** + * Check if a file or folder is shared + * + * @return bool + */ + public function isShared(); + + /** + * Check if a file or folder is mounted + * + * @return bool + */ + public function isMounted(); } -- cgit v1.2.3 From 0b7d9e2668e3a2e2049eb84f9c49fac41d71d35e Mon Sep 17 00:00:00 2001 From: Lukas Reschke Date: Sun, 4 May 2014 15:51:08 +0200 Subject: Cleanup code a little bit - Use OCP\Response constants instead of the HTTP error code - Use checkAppEnabled() instead of OC_App::isEnabled with an if statement - Remove uneeded variable $baseURL - Rename $isvalid to $isValid --- apps/files_sharing/ajax/list.php | 16 ++++------------ apps/files_sharing/ajax/publicpreview.php | 21 ++++++++++----------- lib/private/response.php | 1 + 3 files changed, 15 insertions(+), 23 deletions(-) (limited to 'lib/private') diff --git a/apps/files_sharing/ajax/list.php b/apps/files_sharing/ajax/list.php index 4b645496253..76926d84b22 100644 --- a/apps/files_sharing/ajax/list.php +++ b/apps/files_sharing/ajax/list.php @@ -20,17 +20,10 @@ * */ -// only need filesystem apps -$RUNTIME_APPTYPES=array('filesystem'); - -// Init owncloud - -if(!\OC_App::isEnabled('files_sharing')){ - exit; -} +OCP\JSON::checkAppEnabled('files_sharing'); if(!isset($_GET['t'])){ - \OC_Response::setStatus(400); //400 Bad Request + \OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST); \OC_Log::write('core-preview', 'No token parameter was passed', \OC_Log::DEBUG); exit; } @@ -55,13 +48,12 @@ $dir = $data['realPath']; $dir = \OC\Files\Filesystem::normalizePath($dir); if (!\OC\Files\Filesystem::is_dir($dir . '/')) { - \OC_Response::setStatus(404); + \OC_Response::setStatus(OC_Response::STATUS_NOT_FOUND); \OCP\JSON::error(array('success' => false)); exit(); } $data = array(); -$baseUrl = OCP\Util::linkTo('files_sharing', 'index.php') . '?t=' . urlencode($token) . '&dir='; // make filelist $files = \OCA\Files\Helper::getFiles($dir); @@ -88,4 +80,4 @@ if (OC_Appconfig::getValue('core', 'shareapi_allow_public_upload', 'yes') === 'n $data['permissions'] = $permissions; -OCP\JSON::success(array('data' => $data)); +OCP\JSON::success(array('data' => $data)); \ No newline at end of file diff --git a/apps/files_sharing/ajax/publicpreview.php b/apps/files_sharing/ajax/publicpreview.php index d12d212a2e6..6ba47e5b3a6 100644 --- a/apps/files_sharing/ajax/publicpreview.php +++ b/apps/files_sharing/ajax/publicpreview.php @@ -5,9 +5,8 @@ * later. * See the COPYING-README file. */ -if(!\OC_App::isEnabled('files_sharing')){ - exit; -} + +OCP\JSON::checkAppEnabled('files_sharing'); \OC_User::setIncognitoMode(true); @@ -18,20 +17,20 @@ $scalingUp = array_key_exists('scalingup', $_GET) ? (bool) $_GET['scalingup'] : $token = array_key_exists('t', $_GET) ? (string) $_GET['t'] : ''; if($token === ''){ - \OC_Response::setStatus(400); //400 Bad Request + \OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST); \OC_Log::write('core-preview', 'No token parameter was passed', \OC_Log::DEBUG); exit; } $linkedItem = \OCP\Share::getShareByToken($token); if($linkedItem === false || ($linkedItem['item_type'] !== 'file' && $linkedItem['item_type'] !== 'folder')) { - \OC_Response::setStatus(404); + \OC_Response::setStatus(\OC_Response::STATUS_NOT_FOUND); \OC_Log::write('core-preview', 'Passed token parameter is not valid', \OC_Log::DEBUG); exit; } if(!isset($linkedItem['uid_owner']) || !isset($linkedItem['file_source'])) { - \OC_Response::setStatus(500); + \OC_Response::setStatus(\OC_Response::STATUS_INTERNAL_SERVER_ERROR); \OC_Log::write('core-preview', 'Passed token seems to be valid, but it does not contain all necessary information . ("' . $token . '")', \OC_Log::WARN); exit; } @@ -50,9 +49,9 @@ $pathInfo = $view->getFileInfo($path); $sharedFile = null; if($linkedItem['item_type'] === 'folder') { - $isvalid = \OC\Files\Filesystem::isValidPath($file); - if(!$isvalid) { - \OC_Response::setStatus(400); //400 Bad Request + $isValid = \OC\Files\Filesystem::isValidPath($file); + if(!$isValid) { + \OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST); \OC_Log::write('core-preview', 'Passed filename is not valid, might be malicious (file:"' . $file . '";ip:"' . $_SERVER['REMOTE_ADDR'] . '")', \OC_Log::WARN); exit; } @@ -71,7 +70,7 @@ if(substr($path, 0, 1) === '/') { } if($maxX === 0 || $maxY === 0) { - \OC_Response::setStatus(400); //400 Bad Request + \OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST); \OC_Log::write('core-preview', 'x and/or y set to 0', \OC_Log::DEBUG); exit; } @@ -87,6 +86,6 @@ try{ $preview->show(); } catch (\Exception $e) { - \OC_Response::setStatus(500); + \OC_Response::setStatus(\OC_Response::STATUS_INTERNAL_SERVER_ERROR); \OC_Log::write('core', $e->getmessage(), \OC_Log::DEBUG); } diff --git a/lib/private/response.php b/lib/private/response.php index 1aa5e629b8b..19df9719dee 100644 --- a/lib/private/response.php +++ b/lib/private/response.php @@ -10,6 +10,7 @@ class OC_Response { const STATUS_FOUND = 304; const STATUS_NOT_MODIFIED = 304; const STATUS_TEMPORARY_REDIRECT = 307; + const STATUS_BAD_REQUEST = 400; const STATUS_NOT_FOUND = 404; const STATUS_INTERNAL_SERVER_ERROR = 500; const STATUS_SERVICE_UNAVAILABLE = 503; -- cgit v1.2.3 From 72864d1c5314ecbf912555f24e94b41f4218c11d Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Tue, 6 May 2014 18:05:06 +0200 Subject: Typo --- lib/private/share/share.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/share/share.php b/lib/private/share/share.php index 9956ac99d57..942ae96dc4f 100644 --- a/lib/private/share/share.php +++ b/lib/private/share/share.php @@ -1006,7 +1006,7 @@ class Share extends \OC\Share\Constants { * @param string uidOwner User that is the owner of shared items (optional) * @param int $format Format to convert items to with formatItems() (optional) * @param mixed $parameters to pass to formatItems() (optional) - * @param int $limit Number of items to retur/n, -1 to return all matches (optional) + * @param int $limit Number of items to return, -1 to return all matches (optional) * @param bool $includeCollections Include collection item types (optional) * @param bool $itemShareWithBySource (optional) * @param bool $checkExpireDate -- cgit v1.2.3 From 4a493c8835b606e9c2b74f275cb8c471adb5fa06 Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Mon, 5 May 2014 11:31:25 +0200 Subject: Some expected Sabre exceptions are now logged with DEBUG level --- lib/private/connector/sabre/exceptionloggerplugin.php | 17 +++++++++++++++-- lib/public/util.php | 9 +++++---- 2 files changed, 20 insertions(+), 6 deletions(-) (limited to 'lib/private') diff --git a/lib/private/connector/sabre/exceptionloggerplugin.php b/lib/private/connector/sabre/exceptionloggerplugin.php index 8e77afaf207..5eaf1e87621 100644 --- a/lib/private/connector/sabre/exceptionloggerplugin.php +++ b/lib/private/connector/sabre/exceptionloggerplugin.php @@ -11,6 +11,17 @@ class OC_Connector_Sabre_ExceptionLoggerPlugin extends Sabre_DAV_ServerPlugin { + private $nonFatalExceptions = array( + 'Sabre_DAV_Exception_NotAuthenticated' => true, + // the sync client uses this to find out whether files exist, + // so it is not always an error, log it as debug + 'Sabre_DAV_Exception_NotFound' => true, + // this one mostly happens when the same file is uploaded at + // exactly the same time from two clients, only one client + // wins, the second one gets "Precondition failed" + 'Sabre_DAV_Exception_PreconditionFailed' => true, + ); + private $appName; /** @@ -43,8 +54,10 @@ class OC_Connector_Sabre_ExceptionLoggerPlugin extends Sabre_DAV_ServerPlugin */ public function logException($e) { $exceptionClass = get_class($e); - if ($exceptionClass !== 'Sabre_DAV_Exception_NotAuthenticated') { - \OCP\Util::logException($this->appName, $e); + $level = \OCP\Util::FATAL; + if (isset($this->nonFatalExceptions[$exceptionClass])) { + $level = \OCP\Util::DEBUG; } + \OCP\Util::logException($this->appName, $e, $level); } } diff --git a/lib/public/util.php b/lib/public/util.php index f06ddd66641..3b0fc09f7e5 100644 --- a/lib/public/util.php +++ b/lib/public/util.php @@ -86,21 +86,22 @@ class Util { * if DEBUG mode is enabled * @param string $app app name * @param \Exception $ex exception to log + * @param string $level log level, defaults to \OCP\Util::FATAL */ - public static function logException( $app, \Exception $ex ) { + public static function logException( $app, \Exception $ex, $level = \OCP\Util::FATAL ) { $class = get_class($ex); $message = $class . ': ' . $ex->getMessage(); if ($ex->getCode()) { $message .= ' [' . $ex->getCode() . ']'; } - \OCP\Util::writeLog($app, $message, \OCP\Util::FATAL); + \OCP\Util::writeLog($app, $message, $level); if (defined('DEBUG') and DEBUG) { // also log stack trace $stack = explode("\n", $ex->getTraceAsString()); // first element is empty array_shift($stack); foreach ($stack as $s) { - \OCP\Util::writeLog($app, 'Exception: ' . $s, \OCP\Util::FATAL); + \OCP\Util::writeLog($app, 'Exception: ' . $s, $level); } // include cause @@ -110,7 +111,7 @@ class Util { if ($ex->getCode()) { $message .= '[' . $ex->getCode() . '] '; } - \OCP\Util::writeLog($app, 'Exception: ' . $message, \OCP\Util::FATAL); + \OCP\Util::writeLog($app, 'Exception: ' . $message, $level); } } } -- cgit v1.2.3 From c4109d9aefdde9e0d88dfaf96c9cec97cd3694a1 Mon Sep 17 00:00:00 2001 From: Lukas Reschke Date: Wed, 7 May 2014 15:11:42 +0200 Subject: Use strict type comparison We certainly don't want to have type juggling on that. --- lib/private/user/database.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/user/database.php b/lib/private/user/database.php index 681f03981f5..dec38464f98 100644 --- a/lib/private/user/database.php +++ b/lib/private/user/database.php @@ -183,14 +183,14 @@ class OC_User_Database extends OC_User_Backend { $row = $result->fetchRow(); if ($row) { $storedHash = $row['password']; - if ($storedHash[0] == '$') { //the new phpass based hashing + if ($storedHash[0] === '$') { //the new phpass based hashing $hasher = $this->getHasher(); if ($hasher->CheckPassword($password . OC_Config::getValue('passwordsalt', ''), $storedHash)) { return $row['uid']; } //old sha1 based hashing - } elseif (sha1($password) == $storedHash) { + } elseif (sha1($password) === $storedHash) { //upgrade to new hashing $this->setPassword($row['uid'], $password); return $row['uid']; -- cgit v1.2.3 From 9f88141bcd52517b676de7603499bbb606180438 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Wed, 7 May 2014 20:46:08 +0200 Subject: Use 'boolean' as type instead of 'bool' --- lib/private/share/share.php | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) (limited to 'lib/private') diff --git a/lib/private/share/share.php b/lib/private/share/share.php index 942ae96dc4f..e0c14c23bd4 100644 --- a/lib/private/share/share.php +++ b/lib/private/share/share.php @@ -93,8 +93,8 @@ class Share extends \OC\Share\Constants { * Find which users can access a shared item * @param string $path to the file * @param string $ownerUser owner of the file - * @param bool $includeOwner include owner to the list of users with access to the file - * @param bool $returnUserPaths Return an array with the user => path map + * @param boolean $includeOwner include owner to the list of users with access to the file + * @param boolean $returnUserPaths Return an array with the user => path map * @return array * @note $path needs to be relative to user data dir, e.g. 'file.txt' * not '/admin/data/file.txt' @@ -243,7 +243,7 @@ class Share extends \OC\Share\Constants { * @param int $format (optional) Format type must be defined by the backend * @param mixed $parameters (optional) * @param int $limit Number of items to return (optional) Returns all by default - * @param bool $includeCollections (optional) + * @param boolean $includeCollections (optional) * @return mixed Return depends on format */ public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE, @@ -259,7 +259,7 @@ class Share extends \OC\Share\Constants { * @param int Format (optional) Format type must be defined by the backend * @param mixed Parameters (optional) * @param int Number of items to return (optional) Returns all by default - * @param bool include collections (optional) + * @param boolean include collections (optional) * @return Return depends on format */ public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE, @@ -274,7 +274,7 @@ class Share extends \OC\Share\Constants { * @param string $itemTarget * @param int $format (optional) Format type must be defined by the backend * @param mixed $parameters (optional) - * @param bool $includeCollections (optional) + * @param boolean $includeCollections (optional) * @return mixed Return depends on format */ public static function getItemSharedWith($itemType, $itemTarget, $format = self::FORMAT_NONE, @@ -338,7 +338,7 @@ class Share extends \OC\Share\Constants { * @param string $itemSource * @param int $format (optional) Format type must be defined by the backend * @param mixed $parameters - * @param bool $includeCollections + * @param boolean $includeCollections * @return mixed Return depends on format */ public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE, @@ -362,7 +362,7 @@ class Share extends \OC\Share\Constants { /** * Based on the given token the share information will be returned - password protected shares will be verified * @param string $token - * @return array | bool false will be returned in case the token is unknown or unauthorized + * @return array | boolean false will be returned in case the token is unknown or unauthorized */ public static function getShareByToken($token, $checkPasswordProtection = true) { $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1); @@ -415,7 +415,7 @@ class Share extends \OC\Share\Constants { * @param int $format (optional) Format type must be defined by the backend * @param mixed $parameters * @param int $limit Number of items to return (optional) Returns all by default - * @param bool $includeCollections + * @param boolean $includeCollections * @return mixed Return depends on format */ public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null, @@ -430,7 +430,7 @@ class Share extends \OC\Share\Constants { * @param string $itemSource * @param int $format (optional) Format type must be defined by the backend * @param mixed $parameters - * @param bool $includeCollections + * @param boolean $includeCollections * @return mixed Return depends on format */ public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE, @@ -444,8 +444,8 @@ class Share extends \OC\Share\Constants { * @param string $itemType * @param string $itemSource * @param string $uidOwner - * @param bool $includeCollections - * @param bool $checkExpireDate + * @param boolean $includeCollections + * @param boolean $checkExpireDate * @return Return array of users */ public static function getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections = false, $checkExpireDate = true) { @@ -478,7 +478,7 @@ class Share extends \OC\Share\Constants { * @internal param \OCP\SHARE_TYPE_USER $int , SHARE_TYPE_GROUP, or SHARE_TYPE_LINK * @internal param \OCP\User $string or group the item is being shared with * @internal param \OCP\CRUDS $int permissions - * @return bool|string Returns true on success or false on failure, Returns token on success for links + * @return boolean|string Returns true on success or false on failure, Returns token on success for links */ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null) { $uidOwner = \OC_User::getUser(); @@ -733,7 +733,7 @@ class Share extends \OC\Share\Constants { * @param string $itemType * @param string $itemSource * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK - * @param bool $status + * @param boolean $status */ public static function setSendMailStatus($itemType, $itemSource, $shareType, $status) { $status = $status ? 1 : 0; @@ -874,7 +874,7 @@ class Share extends \OC\Share\Constants { /** * Checks whether a share has expired, calls unshareItem() if yes. * @param array $item Share data (usually database row) - * @return bool True if item was expired, false otherwise. + * @return boolean True if item was expired, false otherwise. */ protected static function expireItem(array $item) { @@ -1007,9 +1007,9 @@ class Share extends \OC\Share\Constants { * @param int $format Format to convert items to with formatItems() (optional) * @param mixed $parameters to pass to formatItems() (optional) * @param int $limit Number of items to return, -1 to return all matches (optional) - * @param bool $includeCollections Include collection item types (optional) - * @param bool $itemShareWithBySource (optional) - * @param bool $checkExpireDate + * @param boolean $includeCollections Include collection item types (optional) + * @param boolean $itemShareWithBySource (optional) + * @param boolean $checkExpireDate * @return array * * See public functions getItem(s)... for parameter usage @@ -1350,10 +1350,10 @@ class Share extends \OC\Share\Constants { * @param string $shareWith User or group the item is being shared with * @param string $uidOwner User that is the owner of shared item * @param int $permissions CRUDS permissions - * @param bool|array $parentFolder Parent folder target (optional) + * @param boolean|array $parentFolder Parent folder target (optional) * @param string $token (optional) * @param string $itemSourceName name of the source item (optional) - * @return bool Returns true on success or false on failure + * @return boolean Returns true on success or false on failure */ private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $parentFolder = null, $token = null, $itemSourceName = null) { @@ -1615,7 +1615,7 @@ class Share extends \OC\Share\Constants { * In case a password protected link is not yet authenticated this function will return false * * @param array $linkItem - * @return bool + * @return boolean */ public static function checkPasswordProtectedShare(array $linkItem) { if (!isset($linkItem['share_with'])) { @@ -1643,7 +1643,7 @@ class Share extends \OC\Share\Constants { /** * @breif construct select statement * @param int $format - * @param bool $fileDependent ist it a file/folder share or a generla share + * @param boolean $fileDependent ist it a file/folder share or a generla share * @param string $uidOwner * @return string select statement */ -- cgit v1.2.3 From 05dc694c5c113079306a351f16a422e514d4a1e8 Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Thu, 8 May 2014 13:33:55 +0200 Subject: Fix getPathById for Oracle Added extra code to handle the case of Oracle which saves empty strings as null values. --- lib/private/files/cache/cache.php | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'lib/private') diff --git a/lib/private/files/cache/cache.php b/lib/private/files/cache/cache.php index 1c9de56f8c5..c4f03b4d9ef 100644 --- a/lib/private/files/cache/cache.php +++ b/lib/private/files/cache/cache.php @@ -603,6 +603,10 @@ class Cache { $sql = 'SELECT `path` FROM `*PREFIX*filecache` WHERE `fileid` = ? AND `storage` = ?'; $result = \OC_DB::executeAudited($sql, array($id, $this->getNumericStorageId())); if ($row = $result->fetchRow()) { + // Oracle stores empty strings as null... + if ($row['path'] === null) { + return ''; + } return $row['path']; } else { return null; -- cgit v1.2.3 From 88225db4af499a7e13fc62ceb8cd9de461878202 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 8 May 2014 18:11:29 +0200 Subject: Memcached hasKey should test for success, the get can fail for other reasons. One of the other failures is no running server. --- lib/private/memcache/memcached.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/memcache/memcached.php b/lib/private/memcache/memcached.php index 075828eebad..cd8e2e8d0b6 100644 --- a/lib/private/memcache/memcached.php +++ b/lib/private/memcache/memcached.php @@ -57,7 +57,7 @@ class Memcached extends Cache { public function hasKey($key) { self::$cache->get($this->getNamespace() . $key); - return self::$cache->getResultCode() !== \Memcached::RES_NOTFOUND; + return self::$cache->getResultCode() === \Memcached::RES_SUCCESS; } public function remove($key) { -- cgit v1.2.3 From e5ee84ca9b7c2b95275fa7ea1100fe8c34a4d695 Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Fri, 9 May 2014 17:18:43 +0200 Subject: - update permissions - change xml tag to perm --- lib/private/connector/sabre/filesplugin.php | 2 +- lib/private/connector/sabre/node.php | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) (limited to 'lib/private') diff --git a/lib/private/connector/sabre/filesplugin.php b/lib/private/connector/sabre/filesplugin.php index e2ff574c455..1d8f28008b3 100644 --- a/lib/private/connector/sabre/filesplugin.php +++ b/lib/private/connector/sabre/filesplugin.php @@ -37,7 +37,7 @@ class OC_Connector_Sabre_FilesPlugin extends Sabre_DAV_ServerPlugin $server->xmlNamespaces[self::NS_OWNCLOUD] = 'oc'; $server->protectedProperties[] = '{' . self::NS_OWNCLOUD . '}id'; - $server->protectedProperties[] = '{' . self::NS_OWNCLOUD . '}permissions'; + $server->protectedProperties[] = '{' . self::NS_OWNCLOUD . '}perm'; $this->server = $server; $this->server->subscribeEvent('beforeGetProperties', array($this, 'beforeGetProperties')); diff --git a/lib/private/connector/sabre/node.php b/lib/private/connector/sabre/node.php index ca8dcce9e86..ee38dfc8642 100644 --- a/lib/private/connector/sabre/node.php +++ b/lib/private/connector/sabre/node.php @@ -252,14 +252,17 @@ abstract class OC_Connector_Sabre_Node implements Sabre_DAV_INode, Sabre_DAV_IPr if ($this->info->isMounted()) { $p .= 'M'; } + if ($this->info->isDeletable()) { + $p .= 'D'; + } + if ($this->info->isDeletable()) { + $p .= 'N'; + } if ($this->info->getType() === \OCP\Files\FileInfo::TYPE_FILE) { if ($this->info->isUpdateable()) { $p .= 'W'; } } else { - if ($this->info->isDeletable()) { - $p .= 'D'; - } if ($this->info->isUpdateable()) { $p .= 'CK'; } -- cgit v1.2.3 From 287c8981bce2027bcda24c30c79704e2ebe6f779 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 7 Mar 2014 02:53:33 +0100 Subject: Check if ReflectionMethod::getDocComment is working --- lib/private/util.php | 12 ++++++++++++ settings/admin.php | 1 + settings/templates/admin.php | 15 +++++++++++++++ 3 files changed, 28 insertions(+) (limited to 'lib/private') diff --git a/lib/private/util.php b/lib/private/util.php index e2005d31c38..5d747c36574 100755 --- a/lib/private/util.php +++ b/lib/private/util.php @@ -938,6 +938,18 @@ class OC_Util { return true; } + /** + * Check if it's possible to get the inline annotations + * + * @return bool + */ + public static function isAnnotationsWorking() { + $reflection = new \ReflectionMethod(__METHOD__); + $docs = $reflection->getDocComment(); + + return (is_string($docs) && strlen($docs) > 50); + } + /** * @brief Check if the PHP module fileinfo is loaded. * @return bool diff --git a/settings/admin.php b/settings/admin.php index 49dde59ce2a..bd135435f16 100755 --- a/settings/admin.php +++ b/settings/admin.php @@ -38,6 +38,7 @@ $tmpl->assign('entriesremain', $entriesremain); $tmpl->assign('htaccessworking', $htaccessworking); $tmpl->assign('internetconnectionworking', OC_Util::isInternetConnectionEnabled() ? OC_Util::isInternetConnectionWorking() : false); $tmpl->assign('isLocaleWorking', OC_Util::isSetLocaleWorking()); +$tmpl->assign('isAnnotationsWorking', OC_Util::isAnnotationsWorking()); $tmpl->assign('isWebDavWorking', OC_Util::isWebDAVWorking()); $tmpl->assign('has_fileinfo', OC_Util::fileInfoLoaded()); $tmpl->assign('old_php', OC_Util::isPHPoutdated()); diff --git a/settings/templates/admin.php b/settings/templates/admin.php index d8a800ca202..d6aa867d469 100644 --- a/settings/templates/admin.php +++ b/settings/templates/admin.php @@ -83,6 +83,21 @@ if (!$_['isWebDavWorking']) { +
+

t('Setup Warning'));?>

+ + + t('PHP is apparently setup to strip inline doc blocks. This will make several core apps inaccessible.')); ?> + t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')); ?> + + +
+ -- cgit v1.2.3 From b4298c68ca3b79abb7413452311daf074206c31c Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Wed, 7 May 2014 01:55:06 +0200 Subject: - make logger available in the container - inject logger class into log - adding PHPDoc comments and fixing typos --- lib/private/log.php | 30 +++++++++++---- lib/private/server.php | 27 ++++++++++--- lib/public/ilogger.php | 101 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 145 insertions(+), 13 deletions(-) create mode 100644 lib/public/ilogger.php (limited to 'lib/private') diff --git a/lib/private/log.php b/lib/private/log.php index e0b9fe3c696..c7a3b99a5e0 100644 --- a/lib/private/log.php +++ b/lib/private/log.php @@ -8,6 +8,8 @@ namespace OC; +use \OCP\ILogger; + /** * logging utilities * @@ -18,8 +20,24 @@ namespace OC; * MonoLog is an example implementing this interface. */ -class Log { - private $logClass; +class Log implements ILogger { + + private $logger; + + /** + * @param string $logger The logger that should be used + */ + public function __construct($logger=null) { + // FIXME: Add this for backwards compatibility, should be fixed at some point probably + if($logger === null) { + $this->logger = 'OC_Log_'.ucfirst(\OC_Config::getValue('log_type', 'owncloud')); + call_user_func(array($this->logger, 'init')); + } else { + $this->logger = $logger; + } + + } + /** * System is unusable. @@ -112,10 +130,6 @@ class Log { $this->log(\OC_Log::DEBUG, $message, $context); } - public function __construct() { - $this->logClass = 'OC_Log_'.ucfirst(\OC_Config::getValue('log_type', 'owncloud')); - call_user_func(array($this->logClass, 'init')); - } /** * Logs with an arbitrary level. @@ -130,7 +144,7 @@ class Log { } else { $app = 'no app in context'; } - $logClass=$this->logClass; - $logClass::write($app, $message, $level); + $logger=$this->logger; + $logger::write($app, $message, $level); } } diff --git a/lib/private/server.php b/lib/private/server.php index 4c29092cf44..52dd56e291e 100644 --- a/lib/private/server.php +++ b/lib/private/server.php @@ -30,9 +30,9 @@ class Server extends SimpleContainer implements IServerContainer { } if (\OC::$session->exists('requesttoken')) { - $requesttoken = \OC::$session->get('requesttoken'); + $requestToken = \OC::$session->get('requesttoken'); } else { - $requesttoken = false; + $requestToken = false; } if (defined('PHPUNIT_RUN') && PHPUNIT_RUN @@ -54,7 +54,7 @@ class Server extends SimpleContainer implements IServerContainer { ? $_SERVER['REQUEST_METHOD'] : null, 'urlParams' => $urlParams, - 'requesttoken' => $requesttoken, + 'requesttoken' => $requestToken, ), $stream ); }); @@ -158,6 +158,14 @@ class Server extends SimpleContainer implements IServerContainer { $this->registerService('AvatarManager', function($c) { return new AvatarManager(); }); + $this->registerService('Logger', function($c) { + /** @var $c SimpleContainer */ + $logClass = $c->query('AllConfig')->getSystemValue('log_type', 'owncloud'); + $logger = 'OC_Log_' . ucfirst($logClass); + call_user_func(array($logger, 'init')); + + return new Log($logger); + }); $this->registerService('JobList', function ($c) { /** * @var Server $c @@ -325,14 +333,14 @@ class Server extends SimpleContainer implements IServerContainer { } /** - * @return \OC\URLGenerator + * @return \OCP\IURLGenerator */ function getURLGenerator() { return $this->query('URLGenerator'); } /** - * @return \OC\Helper + * @return \OCP\IHelper */ function getHelper() { return $this->query('AppHelper'); @@ -392,6 +400,15 @@ class Server extends SimpleContainer implements IServerContainer { return $this->query('JobList'); } + /** + * Returns a logger instance + * + * @return \OCP\ILogger + */ + function getLogger(){ + return $this->query('Logger'); + } + /** * Returns a router for generating and matching urls * diff --git a/lib/public/ilogger.php b/lib/public/ilogger.php new file mode 100644 index 00000000000..ad0fcd05a1d --- /dev/null +++ b/lib/public/ilogger.php @@ -0,0 +1,101 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OCP; + +/** + * Interface ILogger + * @package OCP + * + * This logger interface follows the design guidelines of PSR-3 + * https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md#3-psrlogloggerinterface + */ +interface ILogger { + /** + * System is unusable. + * + * @param string $message + * @param array $context + * @return null + */ + function emergency($message, array $context = array()); + + /** + * Action must be taken immediately. + * + * @param string $message + * @param array $context + * @return null + */ + function alert($message, array $context = array()); + + /** + * Critical conditions. + * + * @param string $message + * @param array $context + * @return null + */ + function critical($message, array $context = array()); + + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + * + * @param string $message + * @param array $context + * @return null + */ + function error($message, array $context = array()); + + /** + * Exceptional occurrences that are not errors. + * + * @param string $message + * @param array $context + * @return null + */ + function warning($message, array $context = array()); + + /** + * Normal but significant events. + * + * @param string $message + * @param array $context + * @return null + */ + function notice($message, array $context = array()); + + /** + * Interesting events. + * + * @param string $message + * @param array $context + * @return null + */ + function info($message, array $context = array()); + + /** + * Detailed debug information. + * + * @param string $message + * @param array $context + * @return null + */ + function debug($message, array $context = array()); + + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string $message + * @param array $context + * @return mixed + */ + function log($level, $message, array $context = array()); +} -- cgit v1.2.3 From 9a4d204b55da063631f01a780d32b3fd88c729cd Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Thu, 8 May 2014 11:47:18 +0200 Subject: add cors middleware remove methodannotationreader namespace fix namespace for server container fix tests fail if with cors credentials header is set to true, implement a reusable preflighted cors method in the controller baseclass, make corsmiddleware private and register it for every request remove uneeded local in cors middleware registratio dont uppercase cors to easily use it from routes fix indention comment fixes explicitely set allow credentials header to false dont depend on better controllers PR, fix that stuff later split cors methods to be in a seperate controller for exposing apis remove protected definitions from apicontroller since controller has it --- .../dependencyinjection/dicontainer.php | 6 ++ .../middleware/security/corsmiddleware.php | 73 +++++++++++++++++ lib/public/appframework/apicontroller.php | 93 ++++++++++++++++++++++ lib/public/appframework/controller.php | 13 ++- lib/public/appframework/http/response.php | 4 + .../appframework/controller/ApiControllerTest.php | 55 +++++++++++++ .../lib/appframework/controller/ControllerTest.php | 4 +- tests/lib/appframework/http/ResponseTest.php | 2 +- .../middleware/security/CORSMiddlewareTest.php | 77 ++++++++++++++++++ 9 files changed, 322 insertions(+), 5 deletions(-) create mode 100644 lib/private/appframework/middleware/security/corsmiddleware.php create mode 100644 lib/public/appframework/apicontroller.php create mode 100644 tests/lib/appframework/controller/ApiControllerTest.php create mode 100644 tests/lib/appframework/middleware/security/CORSMiddlewareTest.php (limited to 'lib/private') diff --git a/lib/private/appframework/dependencyinjection/dicontainer.php b/lib/private/appframework/dependencyinjection/dicontainer.php index e478225a53d..becd755bda7 100644 --- a/lib/private/appframework/dependencyinjection/dicontainer.php +++ b/lib/private/appframework/dependencyinjection/dicontainer.php @@ -30,6 +30,7 @@ use OC\AppFramework\Http\Dispatcher; use OC\AppFramework\Core\API; use OC\AppFramework\Middleware\MiddlewareDispatcher; use OC\AppFramework\Middleware\Security\SecurityMiddleware; +use OC\AppFramework\Middleware\Security\CORSMiddleware; use OC\AppFramework\Utility\SimpleContainer; use OC\AppFramework\Utility\TimeFactory; use OCP\AppFramework\IApi; @@ -92,10 +93,15 @@ class DIContainer extends SimpleContainer implements IAppContainer{ return new SecurityMiddleware($app, $c['Request']); }); + $this['CORSMiddleware'] = $this->share(function($c) { + return new CORSMiddleware($c['Request']); + }); + $middleWares = &$this->middleWares; $this['MiddlewareDispatcher'] = $this->share(function($c) use (&$middleWares) { $dispatcher = new MiddlewareDispatcher(); $dispatcher->registerMiddleware($c['SecurityMiddleware']); + $dispatcher->registerMiddleware($c['CORSMiddleware']); foreach($middleWares as $middleWare) { $dispatcher->registerMiddleware($c[$middleWare]); diff --git a/lib/private/appframework/middleware/security/corsmiddleware.php b/lib/private/appframework/middleware/security/corsmiddleware.php new file mode 100644 index 00000000000..1049b3ed473 --- /dev/null +++ b/lib/private/appframework/middleware/security/corsmiddleware.php @@ -0,0 +1,73 @@ + + * @copyright Bernhard Posselt 2014 + */ + +namespace OC\AppFramework\Middleware\Security; + +use OC\AppFramework\Utility\MethodAnnotationReader; +use OCP\IRequest; +use OCP\AppFramework\Http\Response; +use OCP\AppFramework\Middleware; + +/** + * This middleware sets the correct CORS headers on a response if the + * controller has the @CORS annotation. This is needed for webapps that want + * to access an API and dont run on the same domain, see + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS + */ +class CORSMiddleware extends Middleware { + + private $request; + + /** + * @param string $request the name of the method that will be called on + * the controller + */ + public function __construct(IRequest $request) { + $this->request = $request; + } + + + /** + * This is being run after a successful controllermethod call and allows + * the manipulation of a Response object. The middleware is run in reverse order + * + * @param Controller $controller the controller that is being called + * @param string $methodName the name of the method that will be called on + * the controller + * @param Response $response the generated response from the controller + * @return Response a Response object + */ + public function afterController($controller, $methodName, Response $response){ + // only react if its a CORS request and if the request sends origin and + $reflector = new MethodAnnotationReader($controller, $methodName); + + if(isset($this->request->server['HTTP_ORIGIN']) && + $reflector->hasAnnotation('CORS')) { + + // allow credentials headers must not be true or CSRF is possible + // otherwise + foreach($response->getHeaders() as $header => $value ) { + if(strtolower($header) === 'access-control-allow-credentials' && + strtolower(trim($value)) === 'true') { + $msg = 'Access-Control-Allow-Credentials must not be '. + 'set to true in order to prevent CSRF'; + throw new SecurityException($msg); + } + } + + $origin = $this->request->server['HTTP_ORIGIN']; + $response->addHeader('Access-Control-Allow-Origin', $origin); + } + return $response; + } + + +} diff --git a/lib/public/appframework/apicontroller.php b/lib/public/appframework/apicontroller.php new file mode 100644 index 00000000000..5272f3ed529 --- /dev/null +++ b/lib/public/appframework/apicontroller.php @@ -0,0 +1,93 @@ +. + * + */ + +/** + * Public interface of ownCloud for apps to use. + * AppFramework\Controller class + */ + +namespace OCP\AppFramework; + +use OCP\AppFramework\Http\Response; +use OCP\IRequest; + + +/** + * Base class to inherit your controllers from that are used for RESTful APIs + */ +abstract class ApiController extends Controller { + + private $corsMethods; + private $corsAllowedHeaders; + private $corsMaxAge; + + /** + * constructor of the controller + * @param string $appName the name of the app + * @param IRequest $request an instance of the request + * @param string $corsMethods: comma seperated string of HTTP verbs which + * should be allowed for websites or webapps when calling your API, defaults to + * 'PUT, POST, GET, DELETE, PATCH' + * @param string $corsAllowedHeaders: comma seperated string of HTTP headers + * which should be allowed for websites or webapps when calling your API, + * defaults to 'Authorization, Content-Type, Accept' + * @param int $corsMaxAge number in seconds how long a preflighted OPTIONS + * request should be cached, defaults to 1728000 seconds + */ + public function __construct($appName, + IRequest $request, + $corsMethods='PUT, POST, GET, DELETE, PATCH', + $corsAllowedHeaders='Authorization, Content-Type, Accept', + $corsMaxAge=1728000){ + parent::__construct($appName, $request); + $this->corsMethods = $corsMethods; + $this->corsAllowedHeaders = $corsAllowedHeaders; + $this->corsMaxAge = $corsMaxAge; + } + + + /** + * This method implements a preflighted cors response for you that you can + * link to for the options request + * + * @NoAdminRequired + * @NoCSRFRequired + * @PublicPage + */ + public function preflightedCors() { + if(isset($this->request->server['HTTP_ORIGIN'])) { + $origin = $this->request->server['HTTP_ORIGIN']; + } else { + $origin = '*'; + } + + $response = new Response(); + $response->addHeader('Access-Control-Allow-Origin', $origin); + $response->addHeader('Access-Control-Allow-Methods', $this->corsMethods); + $response->addHeader('Access-Control-Max-Age', $this->corsMaxAge); + $response->addHeader('Access-Control-Allow-Headers', $this->corsAllowedHeaders); + $response->addHeader('Access-Control-Allow-Credentials', 'false'); + return $response; + } + + +} diff --git a/lib/public/appframework/controller.php b/lib/public/appframework/controller.php index 758f0a80083..f42eba172c7 100644 --- a/lib/public/appframework/controller.php +++ b/lib/public/appframework/controller.php @@ -28,7 +28,6 @@ namespace OCP\AppFramework; use OCP\AppFramework\Http\TemplateResponse; -use OCP\AppFramework\IAppContainer; use OCP\IRequest; @@ -49,12 +48,22 @@ abstract class Controller { */ protected $request; + /** * constructor of the controller * @param string $appName the name of the app * @param IRequest $request an instance of the request + * @param string $corsMethods: comma seperated string of HTTP verbs which + * should be allowed for websites or webapps when calling your API, defaults to + * 'PUT, POST, GET, DELETE, PATCH' + * @param string $corsAllowedHeaders: comma seperated string of HTTP headers + * which should be allowed for websites or webapps when calling your API, + * defaults to 'Authorization, Content-Type, Accept' + * @param int $corsMaxAge number in seconds how long a preflighted OPTIONS + * request should be cached, defaults to 1728000 seconds */ - public function __construct($appName, IRequest $request){ + public function __construct($appName, + IRequest $request){ $this->appName = $appName; $this->request = $request; } diff --git a/lib/public/appframework/http/response.php b/lib/public/appframework/http/response.php index 45402d9b3b3..559d14dd7e7 100644 --- a/lib/public/appframework/http/response.php +++ b/lib/public/appframework/http/response.php @@ -92,6 +92,10 @@ class Response { * @return Response Reference to this object */ public function addHeader($name, $value) { + $name = trim($name); // always remove leading and trailing whitespace + // to be able to reliably check for security + // headers + if(is_null($value)) { unset($this->headers[$name]); } else { diff --git a/tests/lib/appframework/controller/ApiControllerTest.php b/tests/lib/appframework/controller/ApiControllerTest.php new file mode 100644 index 00000000000..b772f540ce8 --- /dev/null +++ b/tests/lib/appframework/controller/ApiControllerTest.php @@ -0,0 +1,55 @@ +. + * + */ + + +namespace OCP\AppFramework; + +use OC\AppFramework\Http\Request; +use OCP\AppFramework\Http\TemplateResponse; + + +class ChildApiController extends ApiController {}; + + +class ApiControllerTest extends \PHPUnit_Framework_TestCase { + + + public function testCors() { + $request = new Request( + array('server' => array('HTTP_ORIGIN' => 'test')) + ); + $this->controller = new ChildApiController('app', $request, 'verbs', + 'headers', 100); + + $response = $this->controller->preflightedCors(); + + $headers = $response->getHeaders(); + + $this->assertEquals('test', $headers['Access-Control-Allow-Origin']); + $this->assertEquals('verbs', $headers['Access-Control-Allow-Methods']); + $this->assertEquals('headers', $headers['Access-Control-Allow-Headers']); + $this->assertEquals('false', $headers['Access-Control-Allow-Credentials']); + $this->assertEquals(100, $headers['Access-Control-Max-Age']); + } + +} diff --git a/tests/lib/appframework/controller/ControllerTest.php b/tests/lib/appframework/controller/ControllerTest.php index f17d5f24aa5..b6c83125da1 100644 --- a/tests/lib/appframework/controller/ControllerTest.php +++ b/tests/lib/appframework/controller/ControllerTest.php @@ -22,10 +22,9 @@ */ -namespace Test\AppFramework\Controller; +namespace OCP\AppFramework; use OC\AppFramework\Http\Request; -use OCP\AppFramework\Controller; use OCP\AppFramework\Http\TemplateResponse; @@ -129,4 +128,5 @@ class ControllerTest extends \PHPUnit_Framework_TestCase { $this->assertEquals('daheim', $this->controller->env('PATH')); } + } diff --git a/tests/lib/appframework/http/ResponseTest.php b/tests/lib/appframework/http/ResponseTest.php index 27350725d79..4b8d3ae50ef 100644 --- a/tests/lib/appframework/http/ResponseTest.php +++ b/tests/lib/appframework/http/ResponseTest.php @@ -42,7 +42,7 @@ class ResponseTest extends \PHPUnit_Framework_TestCase { public function testAddHeader(){ - $this->childResponse->addHeader('hello', 'world'); + $this->childResponse->addHeader(' hello ', 'world'); $headers = $this->childResponse->getHeaders(); $this->assertEquals('world', $headers['hello']); } diff --git a/tests/lib/appframework/middleware/security/CORSMiddlewareTest.php b/tests/lib/appframework/middleware/security/CORSMiddlewareTest.php new file mode 100644 index 00000000000..8224e9b4aa6 --- /dev/null +++ b/tests/lib/appframework/middleware/security/CORSMiddlewareTest.php @@ -0,0 +1,77 @@ + + * @copyright Bernhard Posselt 2014 + */ + + +namespace OC\AppFramework\Middleware\Security; + +use OC\AppFramework\Http\Request; +use OCP\AppFramework\Http\Response; + + +class CORSMiddlewareTest extends \PHPUnit_Framework_TestCase { + + /** + * @CORS + */ + public function testSetCORSAPIHeader() { + $request = new Request( + array('server' => array('HTTP_ORIGIN' => 'test')) + ); + + $middleware = new CORSMiddleware($request); + $response = $middleware->afterController($this, __FUNCTION__, new Response()); + $headers = $response->getHeaders(); + + $this->assertEquals('test', $headers['Access-Control-Allow-Origin']); + } + + + public function testNoAnnotationNoCORSHEADER() { + $request = new Request( + array('server' => array('HTTP_ORIGIN' => 'test')) + ); + $middleware = new CORSMiddleware($request); + + $response = $middleware->afterController($this, __FUNCTION__, new Response()); + $headers = $response->getHeaders(); + $this->assertFalse(array_key_exists('Access-Control-Allow-Origin', $headers)); + } + + + /** + * @CORS + */ + public function testNoOriginHeaderNoCORSHEADER() { + $request = new Request(); + + $middleware = new CORSMiddleware($request); + $response = $middleware->afterController($this, __FUNCTION__, new Response()); + $headers = $response->getHeaders(); + $this->assertFalse(array_key_exists('Access-Control-Allow-Origin', $headers)); + } + + + /** + * @CORS + * @expectedException \OC\AppFramework\Middleware\Security\SecurityException + */ + public function testCorsIgnoredIfWithCredentialsHeaderPresent() { + $request = new Request( + array('server' => array('HTTP_ORIGIN' => 'test')) + ); + $middleware = new CORSMiddleware($request); + + $response = new Response(); + $response->addHeader('AcCess-control-Allow-Credentials ', 'TRUE'); + $response = $middleware->afterController($this, __FUNCTION__, $response); + } + +} -- cgit v1.2.3 From e05192a23d11867a9860ac6e38e372e21919a861 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Sun, 11 May 2014 14:03:58 +0200 Subject: Fix method signature --- lib/private/appframework/middleware/security/corsmiddleware.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/appframework/middleware/security/corsmiddleware.php b/lib/private/appframework/middleware/security/corsmiddleware.php index 1049b3ed473..e32c5d42875 100644 --- a/lib/private/appframework/middleware/security/corsmiddleware.php +++ b/lib/private/appframework/middleware/security/corsmiddleware.php @@ -27,8 +27,7 @@ class CORSMiddleware extends Middleware { private $request; /** - * @param string $request the name of the method that will be called on - * the controller + * @param IRequest $request */ public function __construct(IRequest $request) { $this->request = $request; -- cgit v1.2.3 From cd3ed01483ce9989491cfe9019b6c373275bc949 Mon Sep 17 00:00:00 2001 From: Lukas Reschke Date: Sun, 11 May 2014 15:24:42 +0200 Subject: Fix Typo I guess that should be `default` and not `defautl`, wondering how this ever worked. --- apps/user_ldap/tests/user_ldap.php | 2 +- lib/private/appframework/core/api.php | 2 +- lib/private/hook.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'lib/private') diff --git a/apps/user_ldap/tests/user_ldap.php b/apps/user_ldap/tests/user_ldap.php index 8c8d85b3c33..cb4c3b316dc 100644 --- a/apps/user_ldap/tests/user_ldap.php +++ b/apps/user_ldap/tests/user_ldap.php @@ -71,7 +71,7 @@ class Test_User_Ldap_Direct extends \PHPUnit_Framework_TestCase { case 'ladyofshadows': return 'dnOfLadyOfShadows'; break; - defautl: + default: return false; } })); diff --git a/lib/private/appframework/core/api.php b/lib/private/appframework/core/api.php index e7269373bb0..8f289a0a047 100644 --- a/lib/private/appframework/core/api.php +++ b/lib/private/appframework/core/api.php @@ -136,7 +136,7 @@ class API implements IApi{ * @brief Emits a signal. To get data from the slot use references! * @param string $signalClass class name of emitter * @param string $signalName name of signal - * @param array $params defautl: array() array with additional data + * @param array $params default: array() array with additional data * @return bool, true if slots exists or false if not */ public function emitHook($signalClass, $signalName, $params = array()) { diff --git a/lib/private/hook.php b/lib/private/hook.php index b63b442c31b..7ae6496f91d 100644 --- a/lib/private/hook.php +++ b/lib/private/hook.php @@ -45,7 +45,7 @@ class OC_Hook{ * @brief emits a signal * @param string $signalclass class name of emitter * @param string $signalname name of signal - * @param array $params defautl: array() array with additional data + * @param array $params default: array() array with additional data * @return bool, true if slots exists or false if not * * Emits a signal. To get data from the slot use references! -- cgit v1.2.3 From a40e49cae5983d8158562e142919cd3108bd2fd8 Mon Sep 17 00:00:00 2001 From: Lukas Reschke Date: Sun, 11 May 2014 15:49:19 +0200 Subject: Harden issubdirectory() realpath() may return false in case the directory does not exist since we can not be sure how different PHP versions may behave here we do an additional check whether realpath returned false --- lib/private/helper.php | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/helper.php b/lib/private/helper.php index 64da1f6fb12..1883ae2a8f2 100644 --- a/lib/private/helper.php +++ b/lib/private/helper.php @@ -733,9 +733,21 @@ class OC_Helper { * @return bool */ public static function issubdirectory($sub, $parent) { - if (strpos(realpath($sub), realpath($parent)) === 0) { + $realpathSub = realpath($sub); + $realpathParent = realpath($parent); + + // realpath() may return false in case the directory does not exist + // since we can not be sure how different PHP versions may behave here + // we do an additional check whether realpath returned false + if($realpathSub === false || $realpathParent === false) { + return false; + } + + // Check whether $sub is a subdirectory of $parent + if (strpos($realpathSub, $realpathParent) === 0) { return true; } + return false; } -- cgit v1.2.3 From fd5b2d11d6a174f46df563917060e350f6df079a Mon Sep 17 00:00:00 2001 From: Lukas Reschke Date: Sun, 11 May 2014 15:50:59 +0200 Subject: Rename issubdirectory to isSubDirectory --- lib/base.php | 2 +- lib/private/helper.php | 2 +- lib/private/l10n.php | 10 +++++----- tests/lib/helper.php | 8 ++++---- 4 files changed, 11 insertions(+), 11 deletions(-) (limited to 'lib/private') diff --git a/lib/base.php b/lib/base.php index 1f7d0c0da65..f8266ac649f 100644 --- a/lib/base.php +++ b/lib/base.php @@ -613,7 +613,7 @@ class OC { if (!is_null(self::$REQUESTEDFILE)) { $subdir = OC_App::getAppPath(OC::$REQUESTEDAPP) . '/' . self::$REQUESTEDFILE; $parent = OC_App::getAppPath(OC::$REQUESTEDAPP); - if (!OC_Helper::issubdirectory($subdir, $parent)) { + if (!OC_Helper::isSubDirectory($subdir, $parent)) { self::$REQUESTEDFILE = null; header('HTTP/1.0 404 Not Found'); exit; diff --git a/lib/private/helper.php b/lib/private/helper.php index 1883ae2a8f2..6bc054bce86 100644 --- a/lib/private/helper.php +++ b/lib/private/helper.php @@ -732,7 +732,7 @@ class OC_Helper { * @param string $parent * @return bool */ - public static function issubdirectory($sub, $parent) { + public static function isSubDirectory($sub, $parent) { $realpathSub = realpath($sub); $realpathParent = realpath($parent); diff --git a/lib/private/l10n.php b/lib/private/l10n.php index d6680d63445..c1596a64163 100644 --- a/lib/private/l10n.php +++ b/lib/private/l10n.php @@ -134,10 +134,10 @@ class OC_L10N implements \OCP\IL10N { $i18ndir = self::findI18nDir($app); // Localization is in /l10n, Texts are in $i18ndir // (Just no need to define date/time format etc. twice) - if((OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/core/l10n/') - || OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/lib/l10n/') - || OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/settings') - || OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC_App::getAppPath($app).'/l10n/') + if((OC_Helper::isSubDirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/core/l10n/') + || OC_Helper::isSubDirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/lib/l10n/') + || OC_Helper::isSubDirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/settings') + || OC_Helper::isSubDirectory($i18ndir.$lang.'.php', OC_App::getAppPath($app).'/l10n/') ) && file_exists($i18ndir.$lang.'.php')) { // Include the file, save the data from $CONFIG @@ -162,7 +162,7 @@ class OC_L10N implements \OCP\IL10N { } } - if(file_exists(OC::$SERVERROOT.'/core/l10n/l10n-'.$lang.'.php') && OC_Helper::issubdirectory(OC::$SERVERROOT.'/core/l10n/l10n-'.$lang.'.php', OC::$SERVERROOT.'/core/l10n/')) { + if(file_exists(OC::$SERVERROOT.'/core/l10n/l10n-'.$lang.'.php') && OC_Helper::isSubDirectory(OC::$SERVERROOT.'/core/l10n/l10n-'.$lang.'.php', OC::$SERVERROOT.'/core/l10n/')) { // Include the file, save the data from $CONFIG include OC::$SERVERROOT.'/core/l10n/l10n-'.$lang.'.php'; if(isset($LOCALIZATIONS) && is_array($LOCALIZATIONS)) { diff --git a/tests/lib/helper.php b/tests/lib/helper.php index 5663df7c9ae..59db30a73f6 100644 --- a/tests/lib/helper.php +++ b/tests/lib/helper.php @@ -120,15 +120,15 @@ class Test_Helper extends PHPUnit_Framework_TestCase { $this->assertEquals($result, $expected); } - function testIssubdirectory() { - $result = OC_Helper::issubdirectory("./data/", "/anotherDirectory/"); + function testIsSubDirectory() { + $result = OC_Helper::isSubDirectory("./data/", "/anotherDirectory/"); $this->assertFalse($result); - $result = OC_Helper::issubdirectory("./data/", "./data/"); + $result = OC_Helper::isSubDirectory("./data/", "./data/"); $this->assertTrue($result); mkdir("data/TestSubdirectory", 0777); - $result = OC_Helper::issubdirectory("data/TestSubdirectory/", "data"); + $result = OC_Helper::isSubDirectory("data/TestSubdirectory/", "data"); rmdir("data/TestSubdirectory"); $this->assertTrue($result); } -- cgit v1.2.3 From 80648da43197c91ed52f36cee8bc818038b88eb6 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Tue, 6 May 2014 16:29:19 +0200 Subject: implement most of the basic stuff that was suggested in #8290 --- .../dependencyinjection/dicontainer.php | 16 +- lib/private/appframework/http/dispatcher.php | 88 ++++++++++- .../middleware/security/securitymiddleware.php | 16 +- .../utility/controllermethodreflector.php | 97 ++++++++++++ .../utility/methodannotationreader.php | 61 -------- lib/public/appframework/controller.php | 65 ++++++++ .../appframework/http/iresponseserializer.php | 27 ++++ lib/public/appframework/http/templateresponse.php | 10 +- .../lib/appframework/controller/ControllerTest.php | 55 ++++++- tests/lib/appframework/http/DispatcherTest.php | 164 +++++++++++++++++++-- .../lib/appframework/http/TemplateResponseTest.php | 46 ++---- .../middleware/security/SecurityMiddlewareTest.php | 33 +++-- .../utility/ControllerMethodReflectorTest.php | 115 +++++++++++++++ .../utility/MethodAnnotationReaderTest.php | 55 ------- 14 files changed, 664 insertions(+), 184 deletions(-) create mode 100644 lib/private/appframework/utility/controllermethodreflector.php delete mode 100644 lib/private/appframework/utility/methodannotationreader.php create mode 100644 lib/public/appframework/http/iresponseserializer.php create mode 100644 tests/lib/appframework/utility/ControllerMethodReflectorTest.php delete mode 100644 tests/lib/appframework/utility/MethodAnnotationReaderTest.php (limited to 'lib/private') diff --git a/lib/private/appframework/dependencyinjection/dicontainer.php b/lib/private/appframework/dependencyinjection/dicontainer.php index becd755bda7..c6139df2382 100644 --- a/lib/private/appframework/dependencyinjection/dicontainer.php +++ b/lib/private/appframework/dependencyinjection/dicontainer.php @@ -33,6 +33,7 @@ use OC\AppFramework\Middleware\Security\SecurityMiddleware; use OC\AppFramework\Middleware\Security\CORSMiddleware; use OC\AppFramework\Utility\SimpleContainer; use OC\AppFramework\Utility\TimeFactory; +use OC\AppFramework\Utility\ControllerMethodReflector; use OCP\AppFramework\IApi; use OCP\AppFramework\IAppContainer; use OCP\AppFramework\Middleware; @@ -81,7 +82,11 @@ class DIContainer extends SimpleContainer implements IAppContainer{ }); $this['Dispatcher'] = $this->share(function($c) { - return new Dispatcher($c['Protocol'], $c['MiddlewareDispatcher']); + return new Dispatcher( + $c['Protocol'], + $c['MiddlewareDispatcher'], + $c['ControllerMethodReflector'] + ); }); @@ -90,7 +95,11 @@ class DIContainer extends SimpleContainer implements IAppContainer{ */ $app = $this; $this['SecurityMiddleware'] = $this->share(function($c) use ($app){ - return new SecurityMiddleware($app, $c['Request']); + return new SecurityMiddleware( + $app, + $c['Request'], + $c['ControllerMethodReflector'] + ); }); $this['CORSMiddleware'] = $this->share(function($c) { @@ -118,6 +127,9 @@ class DIContainer extends SimpleContainer implements IAppContainer{ return new TimeFactory(); }); + $this['ControllerMethodReflector'] = $this->share(function($c) { + return new ControllerMethodReflector(); + }); } diff --git a/lib/private/appframework/http/dispatcher.php b/lib/private/appframework/http/dispatcher.php index a2afb53f0fa..532e49540b1 100644 --- a/lib/private/appframework/http/dispatcher.php +++ b/lib/private/appframework/http/dispatcher.php @@ -26,7 +26,11 @@ namespace OC\AppFramework\Http; use \OC\AppFramework\Middleware\MiddlewareDispatcher; use \OC\AppFramework\Http; +use \OC\AppFramework\Utility\ControllerMethodReflector; + use OCP\AppFramework\Controller; +use OCP\AppFramework\Http\Response; +use OCP\IRequest; /** @@ -36,17 +40,25 @@ class Dispatcher { private $middlewareDispatcher; private $protocol; - + private $reflector; + private $request; /** * @param Http $protocol the http protocol with contains all status headers * @param MiddlewareDispatcher $middlewareDispatcher the dispatcher which * runs the middleware + * @param ControllerMethodReflector the reflector that is used to inject + * the arguments for the controller + * @param IRequest $request the incoming request */ public function __construct(Http $protocol, - MiddlewareDispatcher $middlewareDispatcher) { + MiddlewareDispatcher $middlewareDispatcher, + ControllerMethodReflector $reflector, + IRequest $request) { $this->protocol = $protocol; $this->middlewareDispatcher = $middlewareDispatcher; + $this->reflector = $reflector; + $this->request = $request; } @@ -63,10 +75,13 @@ class Dispatcher { $out = array(null, array(), null); try { + // prefill reflector with everything thats needed for the + // middlewares + $this->reflector->reflect($controller, $methodName); $this->middlewareDispatcher->beforeController($controller, $methodName); - $response = $controller->$methodName(); + $response = $this->executeController($controller, $methodName); // if an exception appears, the middleware checks if it can handle the // exception and creates a response. If no response is created, it is @@ -98,4 +113,71 @@ class Dispatcher { } + /** + * Uses the reflected parameters, types and request parameters to execute + * the controller + * @return Response + */ + private function executeController($controller, $methodName) { + $arguments = array(); + + // valid types that will be casted + $types = array('int', 'integer', 'bool', 'boolean', 'float'); + + foreach($this->reflector->getParameters() as $param) { + + // try to get the parameter from the request object and cast + // it to the type annotated in the @param annotation + $value = $this->request->getParam($param); + $type = $this->reflector->getType($param); + + // if this is submitted using GET or a POST form, 'false' should be + // converted to false + if(($type === 'bool' || $type === 'boolean') && + $value === 'false' && + ( + $this->request->method === 'GET' || + ( + $this->request->method === 'POST' && + strpos($this->request->getHeader('Content-Type'), + 'application/x-www-form-urlencoded') !== false + ) + ) + ) { + $value = false; + + } elseif(in_array($type, $types)) { + settype($value, $type); + } + + $arguments[] = $value; + } + + $response = call_user_func_array(array($controller, $methodName), $arguments); + + // format response if not of type response + if(!($response instanceof Response)) { + + // get format from the url format or request format parameter + $format = $this->request->getParam('format'); + + // if none is given try the first Accept header + if($format === null) { + $header = $this->request->getHeader('Accept'); + $formats = explode(',', $header); + + if($header !== null && count($formats) > 0) { + $accept = strtolower(trim($formats[0])); + $format = str_replace('application/', '', $accept); + } else { + $format = 'json'; + } + } + + $response = $controller->formatResponse($response, $format); + } + + return $response; + } + } diff --git a/lib/private/appframework/middleware/security/securitymiddleware.php b/lib/private/appframework/middleware/security/securitymiddleware.php index 0f160d224ad..b4ace5d0e90 100644 --- a/lib/private/appframework/middleware/security/securitymiddleware.php +++ b/lib/private/appframework/middleware/security/securitymiddleware.php @@ -25,7 +25,7 @@ namespace OC\AppFramework\Middleware\Security; use OC\AppFramework\Http; -use OC\AppFramework\Utility\MethodAnnotationReader; +use OC\AppFramework\Utility\ControllerMethodReflector; use OCP\AppFramework\Http\RedirectResponse; use OCP\AppFramework\Middleware; use OCP\AppFramework\Http\Response; @@ -55,10 +55,13 @@ class SecurityMiddleware extends Middleware { /** * @param IAppContainer $app * @param IRequest $request + * @param ControllerMethodReflector $reflector */ - public function __construct(IAppContainer $app, IRequest $request){ + public function __construct(IAppContainer $app, IRequest $request, + ControllerMethodReflector $reflector){ $this->app = $app; $this->request = $request; + $this->reflector = $reflector; } @@ -72,28 +75,25 @@ class SecurityMiddleware extends Middleware { */ public function beforeController($controller, $methodName){ - // get annotations from comments - $annotationReader = new MethodAnnotationReader($controller, $methodName); - // this will set the current navigation entry of the app, use this only // for normal HTML requests and not for AJAX requests $this->app->getServer()->getNavigationManager()->setActiveEntry($this->app->getAppName()); // security checks - $isPublicPage = $annotationReader->hasAnnotation('PublicPage'); + $isPublicPage = $this->reflector->hasAnnotation('PublicPage'); if(!$isPublicPage) { if(!$this->app->isLoggedIn()) { throw new SecurityException('Current user is not logged in', Http::STATUS_UNAUTHORIZED); } - if(!$annotationReader->hasAnnotation('NoAdminRequired')) { + if(!$this->reflector->hasAnnotation('NoAdminRequired')) { if(!$this->app->isAdminUser()) { throw new SecurityException('Logged in user must be an admin', Http::STATUS_FORBIDDEN); } } } - if(!$annotationReader->hasAnnotation('NoCSRFRequired')) { + if(!$this->reflector->hasAnnotation('NoCSRFRequired')) { if(!$this->request->passesCSRFCheck()) { throw new SecurityException('CSRF check failed', Http::STATUS_PRECONDITION_FAILED); } diff --git a/lib/private/appframework/utility/controllermethodreflector.php b/lib/private/appframework/utility/controllermethodreflector.php new file mode 100644 index 00000000000..d6209cae2f2 --- /dev/null +++ b/lib/private/appframework/utility/controllermethodreflector.php @@ -0,0 +1,97 @@ +. + * + */ + + +namespace OC\AppFramework\Utility; + + +/** + * Reads and parses annotations from doc comments + */ +class ControllerMethodReflector { + + private $annotations; + private $types; + private $parameters; + + public function __construct() { + $this->types = array(); + $this->parameters = array(); + $this->annotations = array(); + } + + + /** + * @param object $object an object or classname + * @param string $method the method which we want to inspect + */ + public function reflect($object, $method){ + $reflection = new \ReflectionMethod($object, $method); + $docs = $reflection->getDocComment(); + + // extract everything prefixed by @ and first letter uppercase + preg_match_all('/@([A-Z]\w+)/', $docs, $matches); + $this->annotations = $matches[1]; + + // extract type parameter information + preg_match_all('/@param (?\w+) \$(?\w+)/', $docs, $matches); + $this->types = array_combine($matches['var'], $matches['type']); + + // get method parameters + foreach ($reflection->getParameters() as $param) { + $this->parameters[] = $param->name; + } + } + + + /** + * Inspects the PHPDoc parameters for types + * @param strint $parameter the parameter whose type comments should be + * parsed + * @return string type in the type parameters (@param int $something) would + * return int + */ + public function getType($parameter) { + return $this->types[$parameter]; + } + + + /** + * @return array the arguments of the method + */ + public function getParameters() { + return $this->parameters; + } + + + /** + * Check if a method contains an annotation + * @param string $name the name of the annotation + * @return bool true if the annotation is found + */ + public function hasAnnotation($name){ + return in_array($name, $this->annotations); + } + + +} diff --git a/lib/private/appframework/utility/methodannotationreader.php b/lib/private/appframework/utility/methodannotationreader.php deleted file mode 100644 index 42060a08529..00000000000 --- a/lib/private/appframework/utility/methodannotationreader.php +++ /dev/null @@ -1,61 +0,0 @@ -. - * - */ - - -namespace OC\AppFramework\Utility; - - -/** - * Reads and parses annotations from doc comments - */ -class MethodAnnotationReader { - - private $annotations; - - /** - * @param object $object an object or classname - * @param string $method the method which we want to inspect for annotations - */ - public function __construct($object, $method){ - $this->annotations = array(); - - $reflection = new \ReflectionMethod($object, $method); - $docs = $reflection->getDocComment(); - - // extract everything prefixed by @ and first letter uppercase - preg_match_all('/@([A-Z]\w+)/', $docs, $matches); - $this->annotations = $matches[1]; - } - - - /** - * Check if a method contains an annotation - * @param string $name the name of the annotation - * @return bool true if the annotation is found - */ - public function hasAnnotation($name){ - return in_array($name, $this->annotations); - } - - -} diff --git a/lib/public/appframework/controller.php b/lib/public/appframework/controller.php index f42eba172c7..f28a1d83a63 100644 --- a/lib/public/appframework/controller.php +++ b/lib/public/appframework/controller.php @@ -28,6 +28,8 @@ namespace OCP\AppFramework; use OCP\AppFramework\Http\TemplateResponse; +use OCP\AppFramework\Http\JSONResponse; +use OCP\AppFramework\Http\IResponseSerializer; use OCP\IRequest; @@ -48,6 +50,8 @@ abstract class Controller { */ protected $request; + private $serializer; + private $formatters; /** * constructor of the controller @@ -66,11 +70,66 @@ abstract class Controller { IRequest $request){ $this->appName = $appName; $this->request = $request; + + // default formatters + $this->formatters = array( + 'json' => function ($response) { + return new JSONResponse($response); + } + ); + } + + + /** + * Registers a serializer that is executed before a formatter is being + * called, useful for turning any data into PHP arrays that can be used + * by a JSONResponse for instance + * @param IResponseSerializer $serializer + */ + protected function registerSerializer(IResponseSerializer $serializer) { + $this->serializer = $serializer; + } + + + /** + * Registers a formatter for a type + * @param string $format + * @param \Closure $closure + */ + protected function registerFormatter($format, \Closure $formatter) { + $this->formatters[$format] = $formatter; + } + + + /** + * Serializes and formats a response + * @param mixed response the value that was returned from a controller and + * is not a Response instance + * @param string $format the format for which a formatter has been registered + * @throws \DomainException if format does not match a registered formatter + * @return Response + */ + public function formatResponse($response, $format='json') { + if(array_key_exists($format, $this->formatters)) { + + if ($this->serializer) { + $response = $this->serializer->serialize($response); + } + + $formatter = $this->formatters[$format]; + + return $formatter($response); + + } else { + throw new \DomainException('No formatter registered for format ' . + $format . '!'); + } } /** * Lets you access post and get parameters by the index + * @deprecated write your parameters as method arguments instead * @param string $key the key which you want to access in the URL Parameter * placeholder, $_POST or $_GET array. * The priority how they're returned is the following: @@ -88,6 +147,7 @@ abstract class Controller { /** * Returns all params that were received, be it from the request * (as GET or POST) or throuh the URL by the route + * @deprecated use $this->request instead * @return array the array with all parameters */ public function getParams() { @@ -97,6 +157,7 @@ abstract class Controller { /** * Returns the method of the request + * @deprecated use $this->request instead * @return string the method of the request (POST, GET, etc) */ public function method() { @@ -106,6 +167,7 @@ abstract class Controller { /** * Shortcut for accessing an uploaded file through the $_FILES array + * @deprecated use $this->request instead * @param string $key the key that will be taken from the $_FILES array * @return array the file in the $_FILES element */ @@ -116,6 +178,7 @@ abstract class Controller { /** * Shortcut for getting env variables + * @deprecated use $this->request instead * @param string $key the key that will be taken from the $_ENV array * @return array the value in the $_ENV element */ @@ -126,6 +189,7 @@ abstract class Controller { /** * Shortcut for getting cookie variables + * @deprecated use $this->request instead * @param string $key the key that will be taken from the $_COOKIE array * @return array the value in the $_COOKIE element */ @@ -136,6 +200,7 @@ abstract class Controller { /** * Shortcut for rendering a template + * @deprecated return a template response instead * @param string $templateName the name of the template * @param array $params the template parameters in key => value structure * @param string $renderAs user renders a full page, blank only your template diff --git a/lib/public/appframework/http/iresponseserializer.php b/lib/public/appframework/http/iresponseserializer.php new file mode 100644 index 00000000000..8ffdd451020 --- /dev/null +++ b/lib/public/appframework/http/iresponseserializer.php @@ -0,0 +1,27 @@ +. + * + */ + +namespace OCP\AppFramework\Http; + +interface IResponseSerializer { + function serialize($response); +} \ No newline at end of file diff --git a/lib/public/appframework/http/templateresponse.php b/lib/public/appframework/http/templateresponse.php index f5baf788ada..52355f93cdd 100644 --- a/lib/public/appframework/http/templateresponse.php +++ b/lib/public/appframework/http/templateresponse.php @@ -61,12 +61,16 @@ class TemplateResponse extends Response { * constructor of TemplateResponse * @param string $appName the name of the app to load the template from * @param string $templateName the name of the template + * @param array $params an array of parameters which should be passed to the + * template + * @param string $renderAs how the page should be rendered, defaults to user */ - public function __construct($appName, $templateName) { + public function __construct($appName, $templateName, array $params=array(), + $renderAs='user') { $this->templateName = $templateName; $this->appName = $appName; - $this->params = array(); - $this->renderAs = 'user'; + $this->params = $params; + $this->renderAs = $renderAs; } diff --git a/tests/lib/appframework/controller/ControllerTest.php b/tests/lib/appframework/controller/ControllerTest.php index b6c83125da1..4785c686f27 100644 --- a/tests/lib/appframework/controller/ControllerTest.php +++ b/tests/lib/appframework/controller/ControllerTest.php @@ -26,9 +26,31 @@ namespace OCP\AppFramework; use OC\AppFramework\Http\Request; use OCP\AppFramework\Http\TemplateResponse; +use OCP\AppFramework\Http\JSONResponse; +use OCP\AppFramework\Http\IResponseSerializer; -class ChildController extends Controller {}; +class ToUpperCaseSerializer implements IResponseSerializer { + public function serialize($response) { + return array(strtoupper($response)); + } +} + +class ChildController extends Controller { + public function custom($in) { + $this->registerFormatter('json', function ($response) { + return new JSONResponse(array(strlen($response))); + }); + + return $in; + } + + public function serializer($in) { + $this->registerSerializer(new ToUpperCaseSerializer()); + + return $in; + } +}; class ControllerTest extends \PHPUnit_Framework_TestCase { @@ -129,4 +151,35 @@ class ControllerTest extends \PHPUnit_Framework_TestCase { } + /** + * @expectedException \DomainException + */ + public function testFormatResonseInvalidFormat() { + $this->controller->formatResponse(null, 'test'); + } + + + public function testFormat() { + $response = $this->controller->formatResponse(array('hi'), 'json'); + + $this->assertEquals(array('hi'), $response->getData()); + } + + + public function testCustomFormatter() { + $response = $this->controller->custom('hi'); + $response = $this->controller->formatResponse($response, 'json'); + + $this->assertEquals(array(2), $response->getData()); + } + + + public function testCustomSerializer() { + $response = $this->controller->serializer('hi'); + $response = $this->controller->formatResponse($response, 'json'); + + $this->assertEquals(array('HI'), $response->getData()); + } + + } diff --git a/tests/lib/appframework/http/DispatcherTest.php b/tests/lib/appframework/http/DispatcherTest.php index 9841dcaa1f7..ba1e989cce9 100644 --- a/tests/lib/appframework/http/DispatcherTest.php +++ b/tests/lib/appframework/http/DispatcherTest.php @@ -25,8 +25,28 @@ namespace OC\AppFramework\Http; use OC\AppFramework\Middleware\MiddlewareDispatcher; +use OC\AppFramework\Utility\ControllerMethodReflector; use OCP\AppFramework\Http; -//require_once(__DIR__ . "/../classloader.php"); +use OCP\AppFramework\Http\JSONResponse; +use OCP\AppFramework\Controller; + + +class TestController extends Controller { + public function __construct($appName, $request) { + parent::__construct($appName, $request); + } + + /** + * @param int $int + * @param bool $bool + */ + public function exec($int, $bool) { + $this->registerFormatter('text', function($in) { + return new JSONResponse(array('text' => $in)); + }); + return array($int, $bool); + } +} class DispatcherTest extends \PHPUnit_Framework_TestCase { @@ -39,6 +59,7 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { private $lastModified; private $etag; private $http; + private $reflector; protected function setUp() { $this->controllerMethod = 'test'; @@ -64,8 +85,17 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { '\OCP\AppFramework\Controller', array($this->controllerMethod), array($app, $request)); + $this->request = $this->getMockBuilder( + '\OC\AppFramework\Http\Request') + ->disableOriginalConstructor() + ->getMock(); + + $this->reflector = new ControllerMethodReflector(); + $this->dispatcher = new Dispatcher( - $this->http, $this->middlewareDispatcher); + $this->http, $this->middlewareDispatcher, $this->reflector, + $this->request + ); $this->response = $this->getMockBuilder( '\OCP\AppFramework\Http\Response') @@ -81,7 +111,7 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { * @param string $out * @param string $httpHeaders */ - private function setMiddlewareExpections($out=null, + private function setMiddlewareExpectations($out=null, $httpHeaders=null, $responseHeaders=array(), $ex=false, $catchEx=true) { @@ -159,14 +189,12 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { ->with($this->equalTo($this->controller), $this->equalTo($this->controllerMethod), $this->equalTo($out)) - ->will($this->returnValue($out)); - - + ->will($this->returnValue($out)); } public function testDispatcherReturnsArrayWith2Entries() { - $this->setMiddlewareExpections(); + $this->setMiddlewareExpectations(); $response = $this->dispatcher->dispatch($this->controller, $this->controllerMethod); @@ -180,7 +208,7 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { $out = 'yo'; $httpHeaders = 'Http'; $responseHeaders = array('hell' => 'yeah'); - $this->setMiddlewareExpections($out, $httpHeaders, $responseHeaders); + $this->setMiddlewareExpectations($out, $httpHeaders, $responseHeaders); $response = $this->dispatcher->dispatch($this->controller, $this->controllerMethod); @@ -195,7 +223,7 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { $out = 'yo'; $httpHeaders = 'Http'; $responseHeaders = array('hell' => 'yeah'); - $this->setMiddlewareExpections($out, $httpHeaders, $responseHeaders, true); + $this->setMiddlewareExpectations($out, $httpHeaders, $responseHeaders, true); $response = $this->dispatcher->dispatch($this->controller, $this->controllerMethod); @@ -210,7 +238,7 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { $out = 'yo'; $httpHeaders = 'Http'; $responseHeaders = array('hell' => 'yeah'); - $this->setMiddlewareExpections($out, $httpHeaders, $responseHeaders, true, false); + $this->setMiddlewareExpectations($out, $httpHeaders, $responseHeaders, true, false); $this->setExpectedException('\Exception'); $response = $this->dispatcher->dispatch($this->controller, @@ -218,4 +246,120 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { } + + private function dispatcherPassthrough() { + $this->middlewareDispatcher->expects($this->once()) + ->method('beforeController'); + $this->middlewareDispatcher->expects($this->once()) + ->method('afterController') + ->will($this->returnCallback(function($a, $b, $in) { + return $in; + })); + $this->middlewareDispatcher->expects($this->once()) + ->method('beforeOutput') + ->will($this->returnCallback(function($a, $b, $in) { + return $in; + })); + } + + public function testControllerParametersInjected() { + $this->request = new Request(array( + 'post' => array( + 'int' => '3', + 'bool' => 'false' + ), + 'method' => 'POST' + )); + $this->dispatcher = new Dispatcher( + $this->http, $this->middlewareDispatcher, $this->reflector, + $this->request + ); + $controller = new TestController('app', $this->request); + + // reflector is supposed to be called once + $this->dispatcherPassthrough(); + $response = $this->dispatcher->dispatch($controller, 'exec'); + + $this->assertEquals('[3,true]', $response[2]); + } + + + public function testResponseTransformedByUrlFormat() { + $this->request = new Request(array( + 'post' => array( + 'int' => '3', + 'bool' => 'false' + ), + 'urlParams' => array( + 'format' => 'text' + ), + 'method' => 'GET' + )); + $this->dispatcher = new Dispatcher( + $this->http, $this->middlewareDispatcher, $this->reflector, + $this->request + ); + $controller = new TestController('app', $this->request); + + // reflector is supposed to be called once + $this->dispatcherPassthrough(); + $response = $this->dispatcher->dispatch($controller, 'exec'); + + $this->assertEquals('{"text":[3,false]}', $response[2]); + } + + + public function testResponseTransformedByAcceptHeader() { + $this->request = new Request(array( + 'post' => array( + 'int' => '3', + 'bool' => 'false' + ), + 'server' => array( + 'HTTP_ACCEPT' => 'application/text, test', + 'HTTP_CONTENT_TYPE' => 'application/x-www-form-urlencoded' + ), + 'method' => 'POST' + )); + $this->dispatcher = new Dispatcher( + $this->http, $this->middlewareDispatcher, $this->reflector, + $this->request + ); + $controller = new TestController('app', $this->request); + + // reflector is supposed to be called once + $this->dispatcherPassthrough(); + $response = $this->dispatcher->dispatch($controller, 'exec'); + + $this->assertEquals('{"text":[3,false]}', $response[2]); + } + + + public function testResponsePrimarilyTransformedByParameterFormat() { + $this->request = new Request(array( + 'post' => array( + 'int' => '3', + 'bool' => 'false' + ), + 'get' => array( + 'format' => 'text' + ), + 'server' => array( + 'HTTP_ACCEPT' => 'application/json, test' + ), + 'method' => 'POST' + )); + $this->dispatcher = new Dispatcher( + $this->http, $this->middlewareDispatcher, $this->reflector, + $this->request + ); + $controller = new TestController('app', $this->request); + + // reflector is supposed to be called once + $this->dispatcherPassthrough(); + $response = $this->dispatcher->dispatch($controller, 'exec'); + + $this->assertEquals('{"text":[3,true]}', $response[2]); + } + } diff --git a/tests/lib/appframework/http/TemplateResponseTest.php b/tests/lib/appframework/http/TemplateResponseTest.php index 0b158edff6f..29ce8cf224a 100644 --- a/tests/lib/appframework/http/TemplateResponseTest.php +++ b/tests/lib/appframework/http/TemplateResponseTest.php @@ -51,6 +51,22 @@ class TemplateResponseTest extends \PHPUnit_Framework_TestCase { } + public function testSetParamsConstructor(){ + $params = array('hi' => 'yo'); + $this->tpl = new TemplateResponse($this->api, 'home', $params); + + $this->assertEquals(array('hi' => 'yo'), $this->tpl->getParams()); + } + + + public function testSetRenderAsConstructor(){ + $renderAs = 'myrender'; + $this->tpl = new TemplateResponse($this->api, 'home', array(), $renderAs); + + $this->assertEquals($renderAs, $this->tpl->getRenderAs()); + } + + public function testSetParams(){ $params = array('hi' => 'yo'); $this->tpl->setParams($params); @@ -63,36 +79,6 @@ class TemplateResponseTest extends \PHPUnit_Framework_TestCase { $this->assertEquals('home', $this->tpl->getTemplateName()); } - -// public function testRender(){ -// $ocTpl = $this->getMock('Template', array('fetchPage')); -// $ocTpl->expects($this->once()) -// ->method('fetchPage'); -// -// $tpl = new TemplateResponse('core', 'error'); -// -// $tpl->render(); -// } -// -// -// public function testRenderAssignsParams(){ -// $params = array('john' => 'doe'); -// -// $tpl = new TemplateResponse('app', 'home'); -// $tpl->setParams($params); -// -// $tpl->render(); -// } -// -// -// public function testRenderDifferentApp(){ -// -// $tpl = new TemplateResponse('app', 'home', 'app2'); -// -// $tpl->render(); -// } - - public function testGetRenderAs(){ $render = 'myrender'; $this->tpl->renderAs($render); diff --git a/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php b/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php index 19e8a68c388..e91aaca25a0 100644 --- a/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php +++ b/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php @@ -26,6 +26,7 @@ namespace OC\AppFramework\Middleware\Security; use OC\AppFramework\Http; use OC\AppFramework\Http\Request; +use OC\AppFramework\Utility\ControllerMethodReflector; use OCP\AppFramework\Http\RedirectResponse; use OCP\AppFramework\Http\JSONResponse; @@ -37,14 +38,16 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { private $secException; private $secAjaxException; private $request; + private $reader; public function setUp() { $api = $this->getMock('OC\AppFramework\DependencyInjection\DIContainer', array(), array('test')); $this->controller = $this->getMock('OCP\AppFramework\Controller', array(), array($api, new Request())); + $this->reader = new ControllerMethodReflector(); $this->request = new Request(); - $this->middleware = new SecurityMiddleware($api, $this->request); + $this->middleware = new SecurityMiddleware($api, $this->request, $this->reader); $this->secException = new SecurityException('hey', false); $this->secAjaxException = new SecurityException('hey', true); } @@ -68,7 +71,8 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { $api->expects($this->any())->method('getServer') ->will($this->returnValue($serverMock)); - $sec = new SecurityMiddleware($api, $this->request); + $sec = new SecurityMiddleware($api, $this->request, $this->reader); + $this->reader->reflect('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', $method); $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', $method); } @@ -99,11 +103,12 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { ->will($this->returnValue(true)); } - $sec = new SecurityMiddleware($api, $this->request); + $sec = new SecurityMiddleware($api, $this->request, $this->reader); try { - $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', - $method); + $controller = '\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest'; + $this->reader->reflect($controller, $method); + $sec->beforeController($controller, $method); } catch (SecurityException $ex){ $this->assertEquals($status, $ex->getCode()); } @@ -184,7 +189,9 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { ->method('isLoggedIn') ->will($this->returnValue(true)); - $sec = new SecurityMiddleware($api, $this->request); + $sec = new SecurityMiddleware($api, $this->request, $this->reader); + $this->reader->reflect('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', + 'testNoChecks'); $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testNoChecks'); } @@ -207,7 +214,7 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { ->will($this->returnValue(true)); } - $sec = new SecurityMiddleware($api, $this->request); + $sec = new SecurityMiddleware($api, $this->request, $this->reader); if($shouldFail){ $this->setExpectedException('\OC\AppFramework\Middleware\Security\SecurityException'); @@ -215,6 +222,7 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { $this->setExpectedException(null); } + $this->reader->reflect('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', $method); $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', $method); } @@ -230,7 +238,8 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { ->method('passesCSRFCheck') ->will($this->returnValue(false)); - $sec = new SecurityMiddleware($api, $request); + $sec = new SecurityMiddleware($api, $request, $this->reader); + $this->reader->reflect('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testCsrfCheck'); $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testCsrfCheck'); } @@ -246,7 +255,8 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { ->method('passesCSRFCheck') ->will($this->returnValue(false)); - $sec = new SecurityMiddleware($api, $request); + $sec = new SecurityMiddleware($api, $request, $this->reader); + $this->reader->reflect('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testNoCsrfCheck'); $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testNoCsrfCheck'); } @@ -261,7 +271,8 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { ->method('passesCSRFCheck') ->will($this->returnValue(true)); - $sec = new SecurityMiddleware($api, $request); + $sec = new SecurityMiddleware($api, $request, $this->reader); + $this->reader->reflect('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testFailCsrfCheck'); $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testFailCsrfCheck'); } @@ -318,7 +329,7 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { $this->request = new Request( array('server' => array('HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'))); - $this->middleware = new SecurityMiddleware($api, $this->request); + $this->middleware = new SecurityMiddleware($api, $this->request, $this->reader); $response = $this->middleware->afterException($this->controller, 'test', $this->secException); diff --git a/tests/lib/appframework/utility/ControllerMethodReflectorTest.php b/tests/lib/appframework/utility/ControllerMethodReflectorTest.php new file mode 100644 index 00000000000..2a7c0031581 --- /dev/null +++ b/tests/lib/appframework/utility/ControllerMethodReflectorTest.php @@ -0,0 +1,115 @@ +. + * + */ + + +namespace OC\AppFramework\Utility; + + +class ControllerMethodReflectorTest extends \PHPUnit_Framework_TestCase { + + + /** + * @Annotation + */ + public function testReadAnnotation(){ + $reader = new ControllerMethodReflector(); + $reader->reflect( + '\OC\AppFramework\Utility\ControllerMethodReflectorTest', + 'testReadAnnotation' + ); + + $this->assertTrue($reader->hasAnnotation('Annotation')); + } + + + /** + * @Annotation + * @param test + */ + public function testReadAnnotationNoLowercase(){ + $reader = new ControllerMethodReflector(); + $reader->reflect( + '\OC\AppFramework\Utility\ControllerMethodReflectorTest', + 'testReadAnnotationNoLowercase' + ); + + $this->assertTrue($reader->hasAnnotation('Annotation')); + $this->assertFalse($reader->hasAnnotation('param')); + } + + + /** + * @Annotation + * @param int $test + */ + public function testReadTypeIntAnnotations(){ + $reader = new ControllerMethodReflector(); + $reader->reflect( + '\OC\AppFramework\Utility\ControllerMethodReflectorTest', + 'testReadTypeIntAnnotations' + ); + + $this->assertEquals('int', $reader->getType('test')); + } + + + /** + * @Annotation + * @param double $test + */ + public function testReadTypeDoubleAnnotations(){ + $reader = new ControllerMethodReflector(); + $reader->reflect( + '\OC\AppFramework\Utility\ControllerMethodReflectorTest', + 'testReadTypeDoubleAnnotations' + ); + + $this->assertEquals('double', $reader->getType('test')); + } + + + public function arguments($arg, $arg2) {} + public function testReflectParameters() { + $reader = new ControllerMethodReflector(); + $reader->reflect( + '\OC\AppFramework\Utility\ControllerMethodReflectorTest', + 'arguments' + ); + + $this->assertEquals(array('arg', 'arg2'), $reader->getParameters()); + } + + + public function arguments2($arg) {} + public function testReflectParameters2() { + $reader = new ControllerMethodReflector(); + $reader->reflect( + '\OC\AppFramework\Utility\ControllerMethodReflectorTest', + 'arguments2' + ); + + $this->assertEquals(array('arg',), $reader->getParameters()); + } + + +} diff --git a/tests/lib/appframework/utility/MethodAnnotationReaderTest.php b/tests/lib/appframework/utility/MethodAnnotationReaderTest.php deleted file mode 100644 index c68812aa5c7..00000000000 --- a/tests/lib/appframework/utility/MethodAnnotationReaderTest.php +++ /dev/null @@ -1,55 +0,0 @@ -. - * - */ - - -namespace OC\AppFramework\Utility; - - -class MethodAnnotationReaderTest extends \PHPUnit_Framework_TestCase { - - - /** - * @Annotation - */ - public function testReadAnnotation(){ - $reader = new MethodAnnotationReader('\OC\AppFramework\Utility\MethodAnnotationReaderTest', - 'testReadAnnotation'); - - $this->assertTrue($reader->hasAnnotation('Annotation')); - } - - - /** - * @Annotation - * @param test - */ - public function testReadAnnotationNoLowercase(){ - $reader = new MethodAnnotationReader('\OC\AppFramework\Utility\MethodAnnotationReaderTest', - 'testReadAnnotationNoLowercase'); - - $this->assertTrue($reader->hasAnnotation('Annotation')); - $this->assertFalse($reader->hasAnnotation('param')); - } - - -} -- cgit v1.2.3 From 4dca2038bf3dbc8f17f08e9479de886483ba1e4b Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Tue, 6 May 2014 16:31:08 +0200 Subject: add request to dispatcher class --- lib/private/appframework/dependencyinjection/dicontainer.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/appframework/dependencyinjection/dicontainer.php b/lib/private/appframework/dependencyinjection/dicontainer.php index c6139df2382..d4a1b97944d 100644 --- a/lib/private/appframework/dependencyinjection/dicontainer.php +++ b/lib/private/appframework/dependencyinjection/dicontainer.php @@ -85,7 +85,8 @@ class DIContainer extends SimpleContainer implements IAppContainer{ return new Dispatcher( $c['Protocol'], $c['MiddlewareDispatcher'], - $c['ControllerMethodReflector'] + $c['ControllerMethodReflector'], + $c['Request'] ); }); -- cgit v1.2.3 From d8da79cab0838ff9ffb3929a7bf854d8d5dc0797 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Tue, 6 May 2014 16:58:39 +0200 Subject: add test for not failing when adding more comments after type parameters, do not limit x-www-form-urlencoded to POST --- lib/private/appframework/http/dispatcher.php | 7 ++----- tests/lib/appframework/http/DispatcherTest.php | 2 +- tests/lib/appframework/utility/ControllerMethodReflectorTest.php | 2 +- 3 files changed, 4 insertions(+), 7 deletions(-) (limited to 'lib/private') diff --git a/lib/private/appframework/http/dispatcher.php b/lib/private/appframework/http/dispatcher.php index 532e49540b1..9015d650250 100644 --- a/lib/private/appframework/http/dispatcher.php +++ b/lib/private/appframework/http/dispatcher.php @@ -137,11 +137,8 @@ class Dispatcher { $value === 'false' && ( $this->request->method === 'GET' || - ( - $this->request->method === 'POST' && - strpos($this->request->getHeader('Content-Type'), - 'application/x-www-form-urlencoded') !== false - ) + strpos($this->request->getHeader('Content-Type'), + 'application/x-www-form-urlencoded') !== false) ) ) { $value = false; diff --git a/tests/lib/appframework/http/DispatcherTest.php b/tests/lib/appframework/http/DispatcherTest.php index ba1e989cce9..d1296f9cf0f 100644 --- a/tests/lib/appframework/http/DispatcherTest.php +++ b/tests/lib/appframework/http/DispatcherTest.php @@ -319,7 +319,7 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { 'HTTP_ACCEPT' => 'application/text, test', 'HTTP_CONTENT_TYPE' => 'application/x-www-form-urlencoded' ), - 'method' => 'POST' + 'method' => 'PUT' )); $this->dispatcher = new Dispatcher( $this->http, $this->middlewareDispatcher, $this->reflector, diff --git a/tests/lib/appframework/utility/ControllerMethodReflectorTest.php b/tests/lib/appframework/utility/ControllerMethodReflectorTest.php index 2a7c0031581..3659a6b206c 100644 --- a/tests/lib/appframework/utility/ControllerMethodReflectorTest.php +++ b/tests/lib/appframework/utility/ControllerMethodReflectorTest.php @@ -75,7 +75,7 @@ class ControllerMethodReflectorTest extends \PHPUnit_Framework_TestCase { /** * @Annotation - * @param double $test + * @param double $test something special */ public function testReadTypeDoubleAnnotations(){ $reader = new ControllerMethodReflector(); -- cgit v1.2.3 From ede732577227ec814577f638ebfa3b2b84595041 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Tue, 6 May 2014 19:09:03 +0200 Subject: fix broken if --- lib/private/appframework/http/dispatcher.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/appframework/http/dispatcher.php b/lib/private/appframework/http/dispatcher.php index 9015d650250..dcc0ff05f7d 100644 --- a/lib/private/appframework/http/dispatcher.php +++ b/lib/private/appframework/http/dispatcher.php @@ -138,7 +138,7 @@ class Dispatcher { ( $this->request->method === 'GET' || strpos($this->request->getHeader('Content-Type'), - 'application/x-www-form-urlencoded') !== false) + 'application/x-www-form-urlencoded') !== false ) ) { $value = false; -- cgit v1.2.3 From c590244fa1635906b1b3d82bf0c2f8289e562bd9 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Tue, 6 May 2014 19:13:59 +0200 Subject: add private property for reflector in security middleware --- lib/private/appframework/middleware/security/securitymiddleware.php | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'lib/private') diff --git a/lib/private/appframework/middleware/security/securitymiddleware.php b/lib/private/appframework/middleware/security/securitymiddleware.php index b4ace5d0e90..510bca28c42 100644 --- a/lib/private/appframework/middleware/security/securitymiddleware.php +++ b/lib/private/appframework/middleware/security/securitymiddleware.php @@ -52,6 +52,11 @@ class SecurityMiddleware extends Middleware { */ private $request; + /** + * @var OC\AppFramework\Utility\ControllerMethodReflector + */ + private $reflector; + /** * @param IAppContainer $app * @param IRequest $request -- cgit v1.2.3 From cb666c18d6dd6863495b1da5fe979fdc5fa42204 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Tue, 6 May 2014 20:25:41 +0200 Subject: rename formatter to responder, formatResponse to buildResponse --- lib/private/appframework/http/dispatcher.php | 2 +- lib/public/appframework/controller.php | 24 +++++++++++----------- .../lib/appframework/controller/ControllerTest.php | 10 ++++----- tests/lib/appframework/http/DispatcherTest.php | 2 +- 4 files changed, 19 insertions(+), 19 deletions(-) (limited to 'lib/private') diff --git a/lib/private/appframework/http/dispatcher.php b/lib/private/appframework/http/dispatcher.php index dcc0ff05f7d..d6c0aeb9940 100644 --- a/lib/private/appframework/http/dispatcher.php +++ b/lib/private/appframework/http/dispatcher.php @@ -171,7 +171,7 @@ class Dispatcher { } } - $response = $controller->formatResponse($response, $format); + $response = $controller->buildResponse($response, $format); } return $response; diff --git a/lib/public/appframework/controller.php b/lib/public/appframework/controller.php index f28a1d83a63..f96f346ac88 100644 --- a/lib/public/appframework/controller.php +++ b/lib/public/appframework/controller.php @@ -51,7 +51,7 @@ abstract class Controller { protected $request; private $serializer; - private $formatters; + private $responders; /** * constructor of the controller @@ -71,8 +71,8 @@ abstract class Controller { $this->appName = $appName; $this->request = $request; - // default formatters - $this->formatters = array( + // default responders + $this->responders = array( 'json' => function ($response) { return new JSONResponse($response); } @@ -94,34 +94,34 @@ abstract class Controller { /** * Registers a formatter for a type * @param string $format - * @param \Closure $closure + * @param \Closure $responder */ - protected function registerFormatter($format, \Closure $formatter) { - $this->formatters[$format] = $formatter; + protected function registerResponder($format, \Closure $responder) { + $this->responders[$format] = $responder; } /** * Serializes and formats a response - * @param mixed response the value that was returned from a controller and + * @param mixed $response the value that was returned from a controller and * is not a Response instance * @param string $format the format for which a formatter has been registered * @throws \DomainException if format does not match a registered formatter * @return Response */ - public function formatResponse($response, $format='json') { - if(array_key_exists($format, $this->formatters)) { + public function buildResponse($response, $format='json') { + if(array_key_exists($format, $this->responders)) { if ($this->serializer) { $response = $this->serializer->serialize($response); } - $formatter = $this->formatters[$format]; + $responder = $this->responders[$format]; - return $formatter($response); + return $responder($response); } else { - throw new \DomainException('No formatter registered for format ' . + throw new \DomainException('No responder registered for format ' . $format . '!'); } } diff --git a/tests/lib/appframework/controller/ControllerTest.php b/tests/lib/appframework/controller/ControllerTest.php index 4785c686f27..0696d00a425 100644 --- a/tests/lib/appframework/controller/ControllerTest.php +++ b/tests/lib/appframework/controller/ControllerTest.php @@ -38,7 +38,7 @@ class ToUpperCaseSerializer implements IResponseSerializer { class ChildController extends Controller { public function custom($in) { - $this->registerFormatter('json', function ($response) { + $this->registerResponder('json', function ($response) { return new JSONResponse(array(strlen($response))); }); @@ -155,12 +155,12 @@ class ControllerTest extends \PHPUnit_Framework_TestCase { * @expectedException \DomainException */ public function testFormatResonseInvalidFormat() { - $this->controller->formatResponse(null, 'test'); + $this->controller->buildResponse(null, 'test'); } public function testFormat() { - $response = $this->controller->formatResponse(array('hi'), 'json'); + $response = $this->controller->buildResponse(array('hi'), 'json'); $this->assertEquals(array('hi'), $response->getData()); } @@ -168,7 +168,7 @@ class ControllerTest extends \PHPUnit_Framework_TestCase { public function testCustomFormatter() { $response = $this->controller->custom('hi'); - $response = $this->controller->formatResponse($response, 'json'); + $response = $this->controller->buildResponse($response, 'json'); $this->assertEquals(array(2), $response->getData()); } @@ -176,7 +176,7 @@ class ControllerTest extends \PHPUnit_Framework_TestCase { public function testCustomSerializer() { $response = $this->controller->serializer('hi'); - $response = $this->controller->formatResponse($response, 'json'); + $response = $this->controller->buildResponse($response, 'json'); $this->assertEquals(array('HI'), $response->getData()); } diff --git a/tests/lib/appframework/http/DispatcherTest.php b/tests/lib/appframework/http/DispatcherTest.php index d1296f9cf0f..08fb374cfa9 100644 --- a/tests/lib/appframework/http/DispatcherTest.php +++ b/tests/lib/appframework/http/DispatcherTest.php @@ -41,7 +41,7 @@ class TestController extends Controller { * @param bool $bool */ public function exec($int, $bool) { - $this->registerFormatter('text', function($in) { + $this->registerResponder('text', function($in) { return new JSONResponse(array('text' => $in)); }); return array($int, $bool); -- cgit v1.2.3 From 1d45239c65e524e0d9b068cfc184bf79e3fd25c3 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Tue, 6 May 2014 22:25:05 +0200 Subject: adjust license headers to new mail address --- lib/private/appframework/app.php | 2 +- lib/private/appframework/core/api.php | 2 +- lib/private/appframework/dependencyinjection/dicontainer.php | 2 +- lib/private/appframework/http.php | 2 +- lib/private/appframework/http/dispatcher.php | 2 +- lib/private/appframework/http/request.php | 2 ++ lib/private/appframework/middleware/middlewaredispatcher.php | 2 +- lib/private/appframework/middleware/security/securityexception.php | 2 +- lib/private/appframework/middleware/security/securitymiddleware.php | 2 +- lib/private/appframework/utility/controllermethodreflector.php | 2 +- lib/private/appframework/utility/timefactory.php | 2 +- lib/public/appframework/controller.php | 2 +- lib/public/appframework/http.php | 2 +- lib/public/appframework/http/downloadresponse.php | 2 +- lib/public/appframework/http/iresponseserializer.php | 2 +- lib/public/appframework/http/jsonresponse.php | 2 +- lib/public/appframework/http/redirectresponse.php | 2 +- lib/public/appframework/http/response.php | 2 +- lib/public/appframework/http/templateresponse.php | 2 +- lib/public/appframework/iapi.php | 2 +- lib/public/appframework/middleware.php | 2 +- tests/lib/app.php | 2 +- tests/lib/appframework/AppTest.php | 2 +- tests/lib/appframework/controller/ControllerTest.php | 2 +- tests/lib/appframework/dependencyinjection/DIContainerTest.php | 4 ++-- tests/lib/appframework/http/DispatcherTest.php | 2 +- tests/lib/appframework/http/DownloadResponseTest.php | 2 +- tests/lib/appframework/http/HttpTest.php | 2 +- tests/lib/appframework/http/JSONResponseTest.php | 4 ++-- tests/lib/appframework/http/RedirectResponseTest.php | 2 +- tests/lib/appframework/http/ResponseTest.php | 2 +- tests/lib/appframework/http/TemplateResponseTest.php | 2 +- tests/lib/appframework/middleware/MiddlewareDispatcherTest.php | 2 +- tests/lib/appframework/middleware/MiddlewareTest.php | 2 +- tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php | 2 +- tests/lib/appframework/utility/ControllerMethodReflectorTest.php | 2 +- tests/lib/group.php | 4 ++-- tests/lib/template.php | 2 +- 38 files changed, 42 insertions(+), 40 deletions(-) (limited to 'lib/private') diff --git a/lib/private/appframework/app.php b/lib/private/appframework/app.php index 3b13194862d..baf52d02054 100644 --- a/lib/private/appframework/app.php +++ b/lib/private/appframework/app.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/private/appframework/core/api.php b/lib/private/appframework/core/api.php index e7269373bb0..c114d0be9ff 100644 --- a/lib/private/appframework/core/api.php +++ b/lib/private/appframework/core/api.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/private/appframework/dependencyinjection/dicontainer.php b/lib/private/appframework/dependencyinjection/dicontainer.php index d4a1b97944d..00181694135 100644 --- a/lib/private/appframework/dependencyinjection/dicontainer.php +++ b/lib/private/appframework/dependencyinjection/dicontainer.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/private/appframework/http.php b/lib/private/appframework/http.php index 65d926105f1..d09e1d3ce2e 100644 --- a/lib/private/appframework/http.php +++ b/lib/private/appframework/http.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt, Thomas Tanghus, Bart Visscher - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/private/appframework/http/dispatcher.php b/lib/private/appframework/http/dispatcher.php index d6c0aeb9940..4fe48355272 100644 --- a/lib/private/appframework/http/dispatcher.php +++ b/lib/private/appframework/http/dispatcher.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt, Thomas Tanghus, Bart Visscher - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/private/appframework/http/request.php b/lib/private/appframework/http/request.php index 643fa685adc..8b68ca486ff 100644 --- a/lib/private/appframework/http/request.php +++ b/lib/private/appframework/http/request.php @@ -3,7 +3,9 @@ * ownCloud - Request * * @author Thomas Tanghus + * @author Bernhard Posselt * @copyright 2013 Thomas Tanghus (thomas@tanghus.net) + * @copyright 2014 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/private/appframework/middleware/middlewaredispatcher.php b/lib/private/appframework/middleware/middlewaredispatcher.php index 598743e523f..dcb63a8e552 100644 --- a/lib/private/appframework/middleware/middlewaredispatcher.php +++ b/lib/private/appframework/middleware/middlewaredispatcher.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/private/appframework/middleware/security/securityexception.php b/lib/private/appframework/middleware/security/securityexception.php index e551675acdf..df37d5e3275 100644 --- a/lib/private/appframework/middleware/security/securityexception.php +++ b/lib/private/appframework/middleware/security/securityexception.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/private/appframework/middleware/security/securitymiddleware.php b/lib/private/appframework/middleware/security/securitymiddleware.php index 510bca28c42..d7e398fe445 100644 --- a/lib/private/appframework/middleware/security/securitymiddleware.php +++ b/lib/private/appframework/middleware/security/securitymiddleware.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/private/appframework/utility/controllermethodreflector.php b/lib/private/appframework/utility/controllermethodreflector.php index d6209cae2f2..1f0cc7165b8 100644 --- a/lib/private/appframework/utility/controllermethodreflector.php +++ b/lib/private/appframework/utility/controllermethodreflector.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2014 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/private/appframework/utility/timefactory.php b/lib/private/appframework/utility/timefactory.php index 2c3dd6cf5e3..a9b07a356e3 100644 --- a/lib/private/appframework/utility/timefactory.php +++ b/lib/private/appframework/utility/timefactory.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/public/appframework/controller.php b/lib/public/appframework/controller.php index f96f346ac88..50b5ed3a80d 100644 --- a/lib/public/appframework/controller.php +++ b/lib/public/appframework/controller.php @@ -3,7 +3,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012, 2014 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/public/appframework/http.php b/lib/public/appframework/http.php index 60f314202cc..c6e2ff8846f 100644 --- a/lib/public/appframework/http.php +++ b/lib/public/appframework/http.php @@ -3,7 +3,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt, Thomas Tanghus, Bart Visscher - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/public/appframework/http/downloadresponse.php b/lib/public/appframework/http/downloadresponse.php index d3c2818e828..6b61490341e 100644 --- a/lib/public/appframework/http/downloadresponse.php +++ b/lib/public/appframework/http/downloadresponse.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/public/appframework/http/iresponseserializer.php b/lib/public/appframework/http/iresponseserializer.php index 8ffdd451020..c16e106df34 100644 --- a/lib/public/appframework/http/iresponseserializer.php +++ b/lib/public/appframework/http/iresponseserializer.php @@ -3,7 +3,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/public/appframework/http/jsonresponse.php b/lib/public/appframework/http/jsonresponse.php index 6d029b7464a..c6360e0a0f5 100644 --- a/lib/public/appframework/http/jsonresponse.php +++ b/lib/public/appframework/http/jsonresponse.php @@ -3,7 +3,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/public/appframework/http/redirectresponse.php b/lib/public/appframework/http/redirectresponse.php index 416e1533635..a1b482c6b3b 100644 --- a/lib/public/appframework/http/redirectresponse.php +++ b/lib/public/appframework/http/redirectresponse.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/public/appframework/http/response.php b/lib/public/appframework/http/response.php index 559d14dd7e7..20e936bb860 100644 --- a/lib/public/appframework/http/response.php +++ b/lib/public/appframework/http/response.php @@ -3,7 +3,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt, Thomas Tanghus, Bart Visscher - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/public/appframework/http/templateresponse.php b/lib/public/appframework/http/templateresponse.php index 52355f93cdd..02589f4e2a4 100644 --- a/lib/public/appframework/http/templateresponse.php +++ b/lib/public/appframework/http/templateresponse.php @@ -3,7 +3,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/public/appframework/iapi.php b/lib/public/appframework/iapi.php index c4aeea2d4e5..9af251be850 100644 --- a/lib/public/appframework/iapi.php +++ b/lib/public/appframework/iapi.php @@ -3,7 +3,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/lib/public/appframework/middleware.php b/lib/public/appframework/middleware.php index 24f31939935..2e1111e9d5d 100644 --- a/lib/public/appframework/middleware.php +++ b/lib/public/appframework/middleware.php @@ -3,7 +3,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/app.php b/tests/lib/app.php index 49f40f089bb..683820cabb6 100644 --- a/tests/lib/app.php +++ b/tests/lib/app.php @@ -1,6 +1,6 @@ + * Copyright (c) 2012 Bernhard Posselt * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. diff --git a/tests/lib/appframework/AppTest.php b/tests/lib/appframework/AppTest.php index 3628e4ceab2..92fa4838341 100644 --- a/tests/lib/appframework/AppTest.php +++ b/tests/lib/appframework/AppTest.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/appframework/controller/ControllerTest.php b/tests/lib/appframework/controller/ControllerTest.php index 0696d00a425..3c1716a91d8 100644 --- a/tests/lib/appframework/controller/ControllerTest.php +++ b/tests/lib/appframework/controller/ControllerTest.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/appframework/dependencyinjection/DIContainerTest.php b/tests/lib/appframework/dependencyinjection/DIContainerTest.php index d1bc900fb28..acc5c2e66d8 100644 --- a/tests/lib/appframework/dependencyinjection/DIContainerTest.php +++ b/tests/lib/appframework/dependencyinjection/DIContainerTest.php @@ -5,8 +5,8 @@ * * @author Bernhard Posselt * @author Morris Jobke - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com - * @copyright 2013 Morris Jobke morris.jobke@gmail.com + * @copyright 2012 Bernhard Posselt + * @copyright 2013 Morris Jobke * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/appframework/http/DispatcherTest.php b/tests/lib/appframework/http/DispatcherTest.php index 08fb374cfa9..2aef2911e2c 100644 --- a/tests/lib/appframework/http/DispatcherTest.php +++ b/tests/lib/appframework/http/DispatcherTest.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/appframework/http/DownloadResponseTest.php b/tests/lib/appframework/http/DownloadResponseTest.php index b305c63ad4d..5be16ce3c49 100644 --- a/tests/lib/appframework/http/DownloadResponseTest.php +++ b/tests/lib/appframework/http/DownloadResponseTest.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/appframework/http/HttpTest.php b/tests/lib/appframework/http/HttpTest.php index 0bdcee24c99..c62fa43863a 100644 --- a/tests/lib/appframework/http/HttpTest.php +++ b/tests/lib/appframework/http/HttpTest.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/appframework/http/JSONResponseTest.php b/tests/lib/appframework/http/JSONResponseTest.php index fbaae1b9227..c0c58ebf761 100644 --- a/tests/lib/appframework/http/JSONResponseTest.php +++ b/tests/lib/appframework/http/JSONResponseTest.php @@ -5,8 +5,8 @@ * * @author Bernhard Posselt * @author Morris Jobke - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com - * @copyright 2013 Morris Jobke morris.jobke@gmail.com + * @copyright 2012 Bernhard Posselt + * @copyright 2013 Morris Jobke * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/appframework/http/RedirectResponseTest.php b/tests/lib/appframework/http/RedirectResponseTest.php index f62b420f4ee..dfd0d7ee7dc 100644 --- a/tests/lib/appframework/http/RedirectResponseTest.php +++ b/tests/lib/appframework/http/RedirectResponseTest.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/appframework/http/ResponseTest.php b/tests/lib/appframework/http/ResponseTest.php index 4b8d3ae50ef..e83fe9e2d84 100644 --- a/tests/lib/appframework/http/ResponseTest.php +++ b/tests/lib/appframework/http/ResponseTest.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/appframework/http/TemplateResponseTest.php b/tests/lib/appframework/http/TemplateResponseTest.php index 29ce8cf224a..afdcf322b85 100644 --- a/tests/lib/appframework/http/TemplateResponseTest.php +++ b/tests/lib/appframework/http/TemplateResponseTest.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php b/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php index 935f97d2a6f..b1a58e21289 100644 --- a/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php +++ b/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/appframework/middleware/MiddlewareTest.php b/tests/lib/appframework/middleware/MiddlewareTest.php index 7a93c0d4dda..814efdd8118 100644 --- a/tests/lib/appframework/middleware/MiddlewareTest.php +++ b/tests/lib/appframework/middleware/MiddlewareTest.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php b/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php index e91aaca25a0..6a1bbf72c13 100644 --- a/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php +++ b/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/appframework/utility/ControllerMethodReflectorTest.php b/tests/lib/appframework/utility/ControllerMethodReflectorTest.php index 3659a6b206c..cccc7688884 100644 --- a/tests/lib/appframework/utility/ControllerMethodReflectorTest.php +++ b/tests/lib/appframework/utility/ControllerMethodReflectorTest.php @@ -4,7 +4,7 @@ * ownCloud - App Framework * * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/group.php b/tests/lib/group.php index 26232187c36..724e723b187 100644 --- a/tests/lib/group.php +++ b/tests/lib/group.php @@ -4,8 +4,8 @@ * * @author Robin Appelman * @author Bernhard Posselt - * @copyright 2012 Robin Appelman icewind@owncloud.com - * @copyright 2012 Bernhard Posselt nukeawhale@gmail.com + * @copyright 2012 Robin Appelman + * @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE diff --git a/tests/lib/template.php b/tests/lib/template.php index eedf688721d..819d592aacf 100644 --- a/tests/lib/template.php +++ b/tests/lib/template.php @@ -3,7 +3,7 @@ * ownCloud * * @author Bernhard Posselt -* @copyright 2012 Bernhard Posselt nukeawhale@gmail.com +* @copyright 2012 Bernhard Posselt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE -- cgit v1.2.3 From fcb1aa36f0f66cbc3a11a6443ba0feab35402285 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Wed, 7 May 2014 20:07:52 +0200 Subject: default to null to not fail if type is not annotated via phpdoc --- lib/private/appframework/utility/controllermethodreflector.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'lib/private') diff --git a/lib/private/appframework/utility/controllermethodreflector.php b/lib/private/appframework/utility/controllermethodreflector.php index 1f0cc7165b8..372b8d184de 100644 --- a/lib/private/appframework/utility/controllermethodreflector.php +++ b/lib/private/appframework/utility/controllermethodreflector.php @@ -68,11 +68,15 @@ class ControllerMethodReflector { * Inspects the PHPDoc parameters for types * @param strint $parameter the parameter whose type comments should be * parsed - * @return string type in the type parameters (@param int $something) would - * return int + * @return string|null type in the type parameters (@param int $something) + * would return int or null if not existing */ public function getType($parameter) { - return $this->types[$parameter]; + if(array_key_exists($parameter, $this->types)) { + return $this->types[$parameter]; + } else { + return null; + } } -- cgit v1.2.3 From 3e58a767ad5c4beec258bdb06efa93b99bd77648 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Sun, 11 May 2014 13:59:48 +0200 Subject: Fix method signature --- lib/private/appframework/http/dispatcher.php | 2 ++ 1 file changed, 2 insertions(+) (limited to 'lib/private') diff --git a/lib/private/appframework/http/dispatcher.php b/lib/private/appframework/http/dispatcher.php index 4fe48355272..39ca3398c66 100644 --- a/lib/private/appframework/http/dispatcher.php +++ b/lib/private/appframework/http/dispatcher.php @@ -116,6 +116,8 @@ class Dispatcher { /** * Uses the reflected parameters, types and request parameters to execute * the controller + * @param Controller $controller the controller to be executed + * @param string $methodName the method on the controller that should be executed * @return Response */ private function executeController($controller, $methodName) { -- cgit v1.2.3 From 474b8f071d4451a61c2ef83bd09e4d9933998331 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Sun, 11 May 2014 14:00:10 +0200 Subject: Fix typo --- lib/private/appframework/utility/controllermethodreflector.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/appframework/utility/controllermethodreflector.php b/lib/private/appframework/utility/controllermethodreflector.php index 372b8d184de..c9cdadcca4a 100644 --- a/lib/private/appframework/utility/controllermethodreflector.php +++ b/lib/private/appframework/utility/controllermethodreflector.php @@ -66,7 +66,7 @@ class ControllerMethodReflector { /** * Inspects the PHPDoc parameters for types - * @param strint $parameter the parameter whose type comments should be + * @param string $parameter the parameter whose type comments should be * parsed * @return string|null type in the type parameters (@param int $something) * would return int or null if not existing -- cgit v1.2.3 From 63f2f16b852e126cbbf478f2d25232195c5a37e4 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Sun, 11 May 2014 17:55:59 +0200 Subject: use new controllermethodreflector for corsmiddleware --- .../appframework/dependencyinjection/dicontainer.php | 5 ++++- .../middleware/security/corsmiddleware.php | 13 ++++++++----- .../middleware/security/CORSMiddlewareTest.php | 20 +++++++++++++++----- 3 files changed, 27 insertions(+), 11 deletions(-) (limited to 'lib/private') diff --git a/lib/private/appframework/dependencyinjection/dicontainer.php b/lib/private/appframework/dependencyinjection/dicontainer.php index 00181694135..97a6569a0f6 100644 --- a/lib/private/appframework/dependencyinjection/dicontainer.php +++ b/lib/private/appframework/dependencyinjection/dicontainer.php @@ -104,7 +104,10 @@ class DIContainer extends SimpleContainer implements IAppContainer{ }); $this['CORSMiddleware'] = $this->share(function($c) { - return new CORSMiddleware($c['Request']); + return new CORSMiddleware( + $c['Request'], + $c['ControllerMethodReflector'] + ); }); $middleWares = &$this->middleWares; diff --git a/lib/private/appframework/middleware/security/corsmiddleware.php b/lib/private/appframework/middleware/security/corsmiddleware.php index e32c5d42875..dca3996ea2e 100644 --- a/lib/private/appframework/middleware/security/corsmiddleware.php +++ b/lib/private/appframework/middleware/security/corsmiddleware.php @@ -11,7 +11,7 @@ namespace OC\AppFramework\Middleware\Security; -use OC\AppFramework\Utility\MethodAnnotationReader; +use OC\AppFramework\Utility\ControllerMethodReflector; use OCP\IRequest; use OCP\AppFramework\Http\Response; use OCP\AppFramework\Middleware; @@ -25,12 +25,16 @@ use OCP\AppFramework\Middleware; class CORSMiddleware extends Middleware { private $request; + private $reflector; /** * @param IRequest $request + * @param ControllerMethodReflector $reflector */ - public function __construct(IRequest $request) { + public function __construct(IRequest $request, + ControllerMethodReflector $reflector) { $this->request = $request; + $this->reflector = $reflector; } @@ -46,10 +50,9 @@ class CORSMiddleware extends Middleware { */ public function afterController($controller, $methodName, Response $response){ // only react if its a CORS request and if the request sends origin and - $reflector = new MethodAnnotationReader($controller, $methodName); if(isset($this->request->server['HTTP_ORIGIN']) && - $reflector->hasAnnotation('CORS')) { + $this->reflector->hasAnnotation('CORS')) { // allow credentials headers must not be true or CSRF is possible // otherwise @@ -57,7 +60,7 @@ class CORSMiddleware extends Middleware { if(strtolower($header) === 'access-control-allow-credentials' && strtolower(trim($value)) === 'true') { $msg = 'Access-Control-Allow-Credentials must not be '. - 'set to true in order to prevent CSRF'; + 'set to true in order to prevent CSRF'; throw new SecurityException($msg); } } diff --git a/tests/lib/appframework/middleware/security/CORSMiddlewareTest.php b/tests/lib/appframework/middleware/security/CORSMiddlewareTest.php index 8224e9b4aa6..79cd3b278af 100644 --- a/tests/lib/appframework/middleware/security/CORSMiddlewareTest.php +++ b/tests/lib/appframework/middleware/security/CORSMiddlewareTest.php @@ -13,11 +13,19 @@ namespace OC\AppFramework\Middleware\Security; use OC\AppFramework\Http\Request; +use OC\AppFramework\Utility\ControllerMethodReflector; + use OCP\AppFramework\Http\Response; class CORSMiddlewareTest extends \PHPUnit_Framework_TestCase { + private $reflector; + + protected function setUp() { + $this->reflector = new ControllerMethodReflector(); + } + /** * @CORS */ @@ -25,11 +33,11 @@ class CORSMiddlewareTest extends \PHPUnit_Framework_TestCase { $request = new Request( array('server' => array('HTTP_ORIGIN' => 'test')) ); + $this->reflector->reflect($this, __FUNCTION__); + $middleware = new CORSMiddleware($request, $this->reflector); - $middleware = new CORSMiddleware($request); $response = $middleware->afterController($this, __FUNCTION__, new Response()); $headers = $response->getHeaders(); - $this->assertEquals('test', $headers['Access-Control-Allow-Origin']); } @@ -38,7 +46,7 @@ class CORSMiddlewareTest extends \PHPUnit_Framework_TestCase { $request = new Request( array('server' => array('HTTP_ORIGIN' => 'test')) ); - $middleware = new CORSMiddleware($request); + $middleware = new CORSMiddleware($request, $this->reflector); $response = $middleware->afterController($this, __FUNCTION__, new Response()); $headers = $response->getHeaders(); @@ -51,8 +59,9 @@ class CORSMiddlewareTest extends \PHPUnit_Framework_TestCase { */ public function testNoOriginHeaderNoCORSHEADER() { $request = new Request(); + $this->reflector->reflect($this, __FUNCTION__); + $middleware = new CORSMiddleware($request, $this->reflector); - $middleware = new CORSMiddleware($request); $response = $middleware->afterController($this, __FUNCTION__, new Response()); $headers = $response->getHeaders(); $this->assertFalse(array_key_exists('Access-Control-Allow-Origin', $headers)); @@ -67,7 +76,8 @@ class CORSMiddlewareTest extends \PHPUnit_Framework_TestCase { $request = new Request( array('server' => array('HTTP_ORIGIN' => 'test')) ); - $middleware = new CORSMiddleware($request); + $this->reflector->reflect($this, __FUNCTION__); + $middleware = new CORSMiddleware($request, $this->reflector); $response = new Response(); $response->addHeader('AcCess-control-Allow-Credentials ', 'TRUE'); -- cgit v1.2.3 From d853c60d7e4eba63c8cb402249b7b77b94c4c764 Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Mon, 12 May 2014 10:54:09 +0200 Subject: adding interpolation as requested by PSR-3 --- lib/private/log.php | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'lib/private') diff --git a/lib/private/log.php b/lib/private/log.php index c7a3b99a5e0..682f6321474 100644 --- a/lib/private/log.php +++ b/lib/private/log.php @@ -144,6 +144,15 @@ class Log implements ILogger { } else { $app = 'no app in context'; } + // interpolate $message as defined in PSR-3 + $replace = array(); + foreach ($context as $key => $val) { + $replace['{' . $key . '}'] = $val; + } + + // interpolate replacement values into the message and return + $message = strtr($message, $replace); + $logger=$this->logger; $logger::write($app, $message, $level); } -- cgit v1.2.3 From da0e37ef0372b29bd0780709e3cf9d3c715ee63f Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Mon, 12 May 2014 11:27:39 +0200 Subject: Rotate thumbnail when encryption is enabled When a picture is encrypted, save it to a temporary file first so that the PHP function for rotation can access it as file. --- lib/private/preview/image.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'lib/private') diff --git a/lib/private/preview/image.php b/lib/private/preview/image.php index 59aaa27ef34..cec5d7c0170 100644 --- a/lib/private/preview/image.php +++ b/lib/private/preview/image.php @@ -22,12 +22,13 @@ class Image extends Provider { } $image = new \OC_Image(); - //check if file is encrypted + if($fileInfo['encrypted'] === true) { - $image->loadFromData(stream_get_contents($fileview->fopen($path, 'r'))); - }else{ - $image->loadFromFile($fileview->getLocalFile($path)); + $fileName = $fileview->toTmpFile($path); + } else { + $fileName = $fileview->getLocalFile($path); } + $image->loadFromFile($fileName); return $image->valid() ? $image : false; } -- cgit v1.2.3 From 9d95fff427e5f09e5a31b9da7b85ca852688851d Mon Sep 17 00:00:00 2001 From: Morris Jobke Date: Mon, 12 May 2014 13:32:03 +0200 Subject: fix missing spaces --- lib/private/log.php | 4 ++-- lib/private/server.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'lib/private') diff --git a/lib/private/log.php b/lib/private/log.php index 682f6321474..98465ec40ea 100644 --- a/lib/private/log.php +++ b/lib/private/log.php @@ -21,7 +21,7 @@ use \OCP\ILogger; */ class Log implements ILogger { - + private $logger; /** @@ -153,7 +153,7 @@ class Log implements ILogger { // interpolate replacement values into the message and return $message = strtr($message, $replace); - $logger=$this->logger; + $logger = $this->logger; $logger::write($app, $message, $level); } } diff --git a/lib/private/server.php b/lib/private/server.php index 52dd56e291e..4ee0238a1e6 100644 --- a/lib/private/server.php +++ b/lib/private/server.php @@ -405,7 +405,7 @@ class Server extends SimpleContainer implements IServerContainer { * * @return \OCP\ILogger */ - function getLogger(){ + function getLogger() { return $this->query('Logger'); } -- cgit v1.2.3 From 3cd32dcb7c368e48a5a7bf510864c8ddd9be85e8 Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Mon, 12 May 2014 15:14:01 +0200 Subject: adding X-Robots-Tag to all responses of ownCloud + move addSecurityHeaders() to OC_Response, which seems to be a more reasonable place --- lib/base.php | 30 +----------------------------- lib/private/response.php | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 29 deletions(-) (limited to 'lib/private') diff --git a/lib/base.php b/lib/base.php index f8266ac649f..be613706e64 100644 --- a/lib/base.php +++ b/lib/base.php @@ -212,34 +212,6 @@ class OC { } } - /* - * This function adds some security related headers to all requests served via base.php - * The implementation of this function has to happen here to ensure that all third-party - * components (e.g. SabreDAV) also benefit from this headers. - */ - public static function addSecurityHeaders() { - header('X-XSS-Protection: 1; mode=block'); // Enforce browser based XSS filters - header('X-Content-Type-Options: nosniff'); // Disable sniffing the content type for IE - - // iFrame Restriction Policy - $xFramePolicy = OC_Config::getValue('xframe_restriction', true); - if($xFramePolicy) { - header('X-Frame-Options: Sameorigin'); // Disallow iFraming from other domains - } - - // Content Security Policy - // If you change the standard policy, please also change it in config.sample.php - $policy = OC_Config::getValue('custom_csp_policy', - 'default-src \'self\'; ' - .'script-src \'self\' \'unsafe-eval\'; ' - .'style-src \'self\' \'unsafe-inline\'; ' - .'frame-src *; ' - .'img-src *; ' - .'font-src \'self\' data:; ' - .'media-src *'); - header('Content-Security-Policy:'.$policy); - } - public static function checkSSL() { // redirect to https site if configured if (OC_Config::getValue("forcessl", false)) { @@ -545,7 +517,7 @@ class OC { self::checkConfig(); self::checkInstalled(); self::checkSSL(); - self::addSecurityHeaders(); + OC_Response::addSecurityHeaders(); $errors = OC_Util::checkServer(); if (count($errors) > 0) { diff --git a/lib/private/response.php b/lib/private/response.php index 1aa5e629b8b..4905c0a787b 100644 --- a/lib/private/response.php +++ b/lib/private/response.php @@ -186,4 +186,36 @@ class OC_Response { self::setStatus(self::STATUS_NOT_FOUND); } } + + /* + * This function adds some security related headers to all requests served via base.php + * The implementation of this function has to happen here to ensure that all third-party + * components (e.g. SabreDAV) also benefit from this headers. + */ + public static function addSecurityHeaders() { + header('X-XSS-Protection: 1; mode=block'); // Enforce browser based XSS filters + header('X-Content-Type-Options: nosniff'); // Disable sniffing the content type for IE + + // iFrame Restriction Policy + $xFramePolicy = OC_Config::getValue('xframe_restriction', true); + if ($xFramePolicy) { + header('X-Frame-Options: Sameorigin'); // Disallow iFraming from other domains + } + + // Content Security Policy + // If you change the standard policy, please also change it in config.sample.php + $policy = OC_Config::getValue('custom_csp_policy', + 'default-src \'self\'; ' + . 'script-src \'self\' \'unsafe-eval\'; ' + . 'style-src \'self\' \'unsafe-inline\'; ' + . 'frame-src *; ' + . 'img-src *; ' + . 'font-src \'self\' data:; ' + . 'media-src *'); + header('Content-Security-Policy:' . $policy); + + // https://developers.google.com/webmasters/control-crawl-index/docs/robots_meta_tag + header('X-Robots-Tag: none'); + } + } -- cgit v1.2.3 From 4dd1a49a686462bc846e10623e97611ef171a731 Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Mon, 12 May 2014 16:20:07 +0200 Subject: remove legacy aka deprecated code: OC_Filesystem --- apps/files_encryption/lib/helper.php | 2 +- apps/files_encryption/lib/proxy.php | 6 +- apps/files_encryption/lib/util.php | 2 +- apps/files_versions/lib/versions.php | 2 +- lib/private/legacy/filesystem.php | 415 ----------------------------------- 5 files changed, 6 insertions(+), 421 deletions(-) delete mode 100644 lib/private/legacy/filesystem.php (limited to 'lib/private') diff --git a/apps/files_encryption/lib/helper.php b/apps/files_encryption/lib/helper.php index 8cbbe8a45a6..82a323d5e12 100755 --- a/apps/files_encryption/lib/helper.php +++ b/apps/files_encryption/lib/helper.php @@ -332,7 +332,7 @@ class Helper { * @param \OC\Files\View $view */ public static function mkdirr($path, $view) { - $dirname = \OC_Filesystem::normalizePath(dirname($path)); + $dirname = \OC\Files\Filesystem::normalizePath(dirname($path)); $dirParts = explode('/', $dirname); $dir = ""; foreach ($dirParts as $part) { diff --git a/apps/files_encryption/lib/proxy.php b/apps/files_encryption/lib/proxy.php index 7be82c313e4..5dc407f796a 100644 --- a/apps/files_encryption/lib/proxy.php +++ b/apps/files_encryption/lib/proxy.php @@ -101,7 +101,7 @@ class Proxy extends \OC_FileProxy { // create random cache folder $cacheFolder = rand(); - $path_slices = explode('/', \OC_Filesystem::normalizePath($path)); + $path_slices = explode('/', \OC\Files\Filesystem::normalizePath($path)); $path_slices[2] = "cache/".$cacheFolder; $tmpPath = implode('/', $path_slices); @@ -125,7 +125,7 @@ class Proxy extends \OC_FileProxy { // in the post proxy $tmpFileInfo = $view->getFileInfo($tmpPath); if ( isset($tmpFileInfo['size']) ) { - self::$unencryptedSizes[\OC_Filesystem::normalizePath($path)] = $tmpFileInfo['size']; + self::$unencryptedSizes[\OC\Files\Filesystem::normalizePath($path)] = $tmpFileInfo['size']; } // remove our temp file @@ -150,7 +150,7 @@ class Proxy extends \OC_FileProxy { * @return mixed */ public function postFile_put_contents($path, $result) { - $normalizedPath = \OC_Filesystem::normalizePath($path); + $normalizedPath = \OC\Files\Filesystem::normalizePath($path); if ( isset(self::$unencryptedSizes[$normalizedPath]) ) { $view = new \OC_FilesystemView('/'); $view->putFileInfo($normalizedPath, diff --git a/apps/files_encryption/lib/util.php b/apps/files_encryption/lib/util.php index 6372ab31b6e..fb0067171ee 100644 --- a/apps/files_encryption/lib/util.php +++ b/apps/files_encryption/lib/util.php @@ -1361,7 +1361,7 @@ class Util { return array( $fileOwnerUid, - \OC_Filesystem::normalizePath($filename) + \OC\Files\Filesystem::normalizePath($filename) ); } } diff --git a/apps/files_versions/lib/versions.php b/apps/files_versions/lib/versions.php index 290264a90cc..67acd5369a4 100644 --- a/apps/files_versions/lib/versions.php +++ b/apps/files_versions/lib/versions.php @@ -579,7 +579,7 @@ class Storage { * @param \OC\Files\View $view view on data/user/ */ private static function createMissingDirectories($filename, $view) { - $dirname = \OC_Filesystem::normalizePath(dirname($filename)); + $dirname = \OC\Files\Filesystem::normalizePath(dirname($filename)); $dirParts = explode('/', $dirname); $dir = "/files_versions"; foreach ($dirParts as $part) { diff --git a/lib/private/legacy/filesystem.php b/lib/private/legacy/filesystem.php deleted file mode 100644 index 34f92b357ca..00000000000 --- a/lib/private/legacy/filesystem.php +++ /dev/null @@ -1,415 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -/** - * Class for abstraction of filesystem functions - * This class won't call any filesystem functions for itself but but will pass them to the correct OC_Filestorage object - * this class should also handle all the file permission related stuff - * - * Hooks provided: - * read(path) - * write(path, &run) - * post_write(path) - * create(path, &run) (when a file is created, both create and write will be emitted in that order) - * post_create(path) - * delete(path, &run) - * post_delete(path) - * rename(oldpath,newpath, &run) - * post_rename(oldpath,newpath) - * copy(oldpath,newpath, &run) (if the newpath doesn't exists yes, copy, create and write will be emitted in that order) - * post_rename(oldpath,newpath) - * - * the &run parameter can be set to false to prevent the operation from occurring - */ - -/** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ -class OC_Filesystem { - /** - * get the mountpoint of the storage object for a path - * ( note: because a storage is not always mounted inside the fakeroot, the - * returned mountpoint is relative to the absolute root of the filesystem - * and doesn't take the chroot into account ) - * - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - * @param string $path - * @return string - */ - static public function getMountPoint($path) { - return \OC\Files\Filesystem::getMountPoint($path); - } - - /** - * resolve a path to a storage and internal path - * - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - * @param string $path - * @return array consisting of the storage and the internal path - */ - static public function resolvePath($path) { - return \OC\Files\Filesystem::resolvePath($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function init($user, $root) { - return \OC\Files\Filesystem::init($user, $root); - } - - /** - * get the default filesystem view - * - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - * @return \OC\Files\View - */ - static public function getView() { - return \OC\Files\Filesystem::getView(); - } - - /** - * tear down the filesystem, removing all storage providers - * - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function tearDown() { - \OC\Files\Filesystem::tearDown(); - } - - /** - * @brief get the relative path of the root data directory for the current user - * @return string - * - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - * Returns path like /admin/files - */ - static public function getRoot() { - return \OC\Files\Filesystem::getRoot(); - } - - /** - * clear all mounts and storage backends - * - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - public static function clearMounts() { - \OC\Files\Filesystem::clearMounts(); - } - - /** - * mount an \OC\Files\Storage\Storage in our virtual filesystem - * - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - * @param \OC\Files\Storage\Storage $class - * @param array $arguments - * @param string $mountpoint - */ - static public function mount($class, $arguments, $mountpoint) { - \OC\Files\Filesystem::mount($class, $arguments, $mountpoint); - } - - /** - * return the path to a local version of the file - * we need this because we can't know if a file is stored local or not from - * outside the filestorage and for some purposes a local file is needed - * - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - * @param string $path - * @return string - */ - static public function getLocalFile($path) { - return \OC\Files\Filesystem::getLocalFile($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - * @param string $path - * @return string - */ - static public function getLocalFolder($path) { - return \OC\Files\Filesystem::getLocalFolder($path); - } - - /** - * return path to file which reflects one visible in browser - * - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - * @param string $path - * @return string - */ - static public function getLocalPath($path) { - return \OC\Files\Filesystem::getLocalPath($path); - } - - /** - * check if the requested path is valid - * - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - * @param string $path - * @return bool - */ - static public function isValidPath($path) { - return \OC\Files\Filesystem::isValidPath($path); - } - - /** - * checks if a file is blacklisted for storage in the filesystem - * Listens to write and rename hooks - * - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - * @param array $data from hook - */ - static public function isBlacklisted($data) { - \OC\Files\Filesystem::isBlacklisted($data); - } - - /** - * following functions are equivalent to their php builtin equivalents for arguments/return values. - * - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function mkdir($path) { - return \OC\Files\Filesystem::mkdir($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function rmdir($path) { - return \OC\Files\Filesystem::rmdir($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function opendir($path) { - return \OC\Files\Filesystem::opendir($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function readdir($path) { - return \OC\Files\Filesystem::readdir($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function is_dir($path) { - return \OC\Files\Filesystem::is_dir($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function is_file($path) { - return \OC\Files\Filesystem::is_file($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function stat($path) { - return \OC\Files\Filesystem::stat($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function filetype($path) { - return \OC\Files\Filesystem::filetype($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function filesize($path) { - return \OC\Files\Filesystem::filesize($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function readfile($path) { - return \OC\Files\Filesystem::readfile($path); - } - - /** - * @deprecated Replaced by isReadable() as part of CRUDS - */ - static public function is_readable($path) { - return \OC\Files\Filesystem::isReadable($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function isCreatable($path) { - return \OC\Files\Filesystem::isCreatable($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function isReadable($path) { - return \OC\Files\Filesystem::isReadable($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function isUpdatable($path) { - return \OC\Files\Filesystem::isUpdatable($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function isDeletable($path) { - return \OC\Files\Filesystem::isDeletable($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function isSharable($path) { - return \OC\Files\Filesystem::isSharable($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function file_exists($path) { - return \OC\Files\Filesystem::file_exists($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function filemtime($path) { - return \OC\Files\Filesystem::filemtime($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function touch($path, $mtime = null) { - return \OC\Files\Filesystem::touch($path, $mtime); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function file_get_contents($path) { - return \OC\Files\Filesystem::file_get_contents($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function file_put_contents($path, $data) { - return \OC\Files\Filesystem::file_put_contents($path, $data); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function unlink($path) { - return \OC\Files\Filesystem::unlink($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function rename($path1, $path2) { - return \OC\Files\Filesystem::rename($path1, $path2); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function copy($path1, $path2) { - return \OC\Files\Filesystem::copy($path1, $path2); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function fopen($path, $mode) { - return \OC\Files\Filesystem::fopen($path, $mode); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function toTmpFile($path) { - return \OC\Files\Filesystem::toTmpFile($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function fromTmpFile($tmpFile, $path) { - return \OC\Files\Filesystem::fromTmpFile($tmpFile, $path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function getMimeType($path) { - return \OC\Files\Filesystem::getMimeType($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function hash($type, $path, $raw = false) { - return \OC\Files\Filesystem::hash($type, $path, $raw); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function free_space($path = '/') { - return \OC\Files\Filesystem::free_space($path); - } - - /** - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - */ - static public function search($query) { - return \OC\Files\Filesystem::search($query); - } - - /** - * check if a file or folder has been updated since $time - * - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - * @param string $path - * @param int $time - * @return bool - */ - static public function hasUpdated($path, $time) { - return \OC\Files\Filesystem::hasUpdated($path, $time); - } - - /** - * normalize a path - * - * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem - * @param string $path - * @param bool $stripTrailingSlash - * @return string - */ - public static function normalizePath($path, $stripTrailingSlash = true) { - return \OC\Files\Filesystem::normalizePath($path, $stripTrailingSlash); - } -} -- cgit v1.2.3 From 33987eea8302e5b8f7889c934debdc2b9dd0296c Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Mon, 12 May 2014 16:23:33 +0200 Subject: remove legacy aka deprecated code: OC_Cache --- apps/user_ldap/lib/connection.php | 2 +- apps/user_ldap/lib/proxy.php | 2 +- core/avatar/controller.php | 8 ++++---- lib/private/legacy/cache.php | 10 ---------- lib/private/route/router.php | 2 +- 5 files changed, 7 insertions(+), 17 deletions(-) delete mode 100644 lib/private/legacy/cache.php (limited to 'lib/private') diff --git a/apps/user_ldap/lib/connection.php b/apps/user_ldap/lib/connection.php index 173c4ebcc23..1ac803d374d 100644 --- a/apps/user_ldap/lib/connection.php +++ b/apps/user_ldap/lib/connection.php @@ -56,7 +56,7 @@ class Connection extends LDAPUtility { if($memcache->isAvailable()) { $this->cache = $memcache->create(); } else { - $this->cache = \OC_Cache::getGlobalCache(); + $this->cache = \OC\Cache::getGlobalCache(); } $this->hasPagedResultSupport = $this->ldap->hasPagedResultSupport(); diff --git a/apps/user_ldap/lib/proxy.php b/apps/user_ldap/lib/proxy.php index 0eb294eb7a0..1e101648942 100644 --- a/apps/user_ldap/lib/proxy.php +++ b/apps/user_ldap/lib/proxy.php @@ -31,7 +31,7 @@ abstract class Proxy { public function __construct(ILDAPWrapper $ldap) { $this->ldap = $ldap; - $this->cache = \OC_Cache::getGlobalCache(); + $this->cache = \OC\Cache::getGlobalCache(); } private function addAccess($configPrefix) { diff --git a/core/avatar/controller.php b/core/avatar/controller.php index 22693824461..06efbec3f3c 100644 --- a/core/avatar/controller.php +++ b/core/avatar/controller.php @@ -71,7 +71,7 @@ class Controller { $image = new \OC_Image($newAvatar); if ($image->valid()) { - \OC_Cache::set('tmpavatar', $image->data(), 7200); + \OC\Cache::set('tmpavatar', $image->data(), 7200); \OC_JSON::error(array("data" => "notsquare")); } else { $l = new \OC_L10n('core'); @@ -109,7 +109,7 @@ class Controller { \OC_JSON::checkLoggedIn(); \OC_JSON::callCheck(); - $tmpavatar = \OC_Cache::get('tmpavatar'); + $tmpavatar = \OC\Cache::get('tmpavatar'); if (is_null($tmpavatar)) { $l = new \OC_L10n('core'); \OC_JSON::error(array("data" => array("message" => $l->t("No temporary profile picture available, try again")) )); @@ -136,7 +136,7 @@ class Controller { return; } - $tmpavatar = \OC_Cache::get('tmpavatar'); + $tmpavatar = \OC\Cache::get('tmpavatar'); if (is_null($tmpavatar)) { $l = new \OC_L10n('core'); \OC_JSON::error(array("data" => array("message" => $l->t("No temporary profile picture available, try again")) )); @@ -149,7 +149,7 @@ class Controller { $avatar = new \OC_Avatar($user); $avatar->set($image->data()); // Clean up - \OC_Cache::remove('tmpavatar'); + \OC\Cache::remove('tmpavatar'); \OC_JSON::success(); } catch (\Exception $e) { \OC_JSON::error(array("data" => array("message" => $e->getMessage()) )); diff --git a/lib/private/legacy/cache.php b/lib/private/legacy/cache.php deleted file mode 100644 index f915eb516b1..00000000000 --- a/lib/private/legacy/cache.php +++ /dev/null @@ -1,10 +0,0 @@ -cacheKey = \OC_Cache::generateCacheKeyFromFiles($files); + $this->cacheKey = \OC\Cache::generateCacheKeyFromFiles($files); } return $this->cacheKey; } -- cgit v1.2.3 From e0dd69e4e605b7f4a2af4cdc8a15a8dfc1c0902a Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Mon, 12 May 2014 16:30:39 +0200 Subject: remove legacy aka deprecated code: OC_FilesystemView --- .../ajax/changeRecoveryPassword.php | 2 +- apps/files_encryption/ajax/getMigrationStatus.php | 2 +- apps/files_encryption/ajax/userrecovery.php | 2 +- apps/files_encryption/appinfo/app.php | 2 +- apps/files_encryption/hooks/hooks.php | 20 +++++----- apps/files_encryption/lib/helper.php | 4 +- apps/files_encryption/lib/keymanager.php | 44 +++++++++++----------- apps/files_encryption/lib/proxy.php | 10 ++--- apps/files_encryption/lib/session.php | 2 +- apps/files_encryption/lib/stream.php | 2 +- apps/files_encryption/lib/util.php | 8 ++-- apps/files_encryption/settings-personal.php | 2 +- apps/files_encryption/tests/crypt.php | 8 ++-- apps/files_encryption/tests/hooks.php | 8 ++-- apps/files_encryption/tests/keymanager.php | 6 +-- apps/files_encryption/tests/proxy.php | 6 +-- apps/files_encryption/tests/share.php | 8 ++-- apps/files_encryption/tests/stream.php | 4 +- apps/files_encryption/tests/trashbin.php | 4 +- apps/files_encryption/tests/util.php | 12 +++--- apps/files_encryption/tests/webdav.php | 4 +- apps/files_sharing/tests/base.php | 4 +- apps/files_sharing/tests/cache.php | 2 +- apps/files_trashbin/lib/trashbin.php | 6 +-- lib/private/files/view.php | 2 +- lib/private/legacy/filesystemview.php | 9 ----- settings/ajax/decryptall.php | 2 +- settings/changepassword/controller.php | 2 +- 28 files changed, 89 insertions(+), 98 deletions(-) delete mode 100644 lib/private/legacy/filesystemview.php (limited to 'lib/private') diff --git a/apps/files_encryption/ajax/changeRecoveryPassword.php b/apps/files_encryption/ajax/changeRecoveryPassword.php index 945f054ea84..f020e52607d 100644 --- a/apps/files_encryption/ajax/changeRecoveryPassword.php +++ b/apps/files_encryption/ajax/changeRecoveryPassword.php @@ -23,7 +23,7 @@ $oldPassword = $_POST['oldPassword']; $newPassword = $_POST['newPassword']; $view = new \OC\Files\View('/'); -$util = new \OCA\Encryption\Util(new \OC_FilesystemView('/'), \OCP\User::getUser()); +$util = new \OCA\Encryption\Util(new \OC\Files\View('/'), \OCP\User::getUser()); $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; diff --git a/apps/files_encryption/ajax/getMigrationStatus.php b/apps/files_encryption/ajax/getMigrationStatus.php index 7c9e0dcc51c..a8828401934 100644 --- a/apps/files_encryption/ajax/getMigrationStatus.php +++ b/apps/files_encryption/ajax/getMigrationStatus.php @@ -18,7 +18,7 @@ $migrationStatus = Util::MIGRATION_COMPLETED; if ($loginname !== '' && $password !== '') { $username = \OCP\User::checkPassword($loginname, $password); if ($username) { - $util = new Util(new \OC_FilesystemView('/'), $username); + $util = new Util(new \OC\Files\View('/'), $username); $migrationStatus = $util->getMigrationStatus(); } } diff --git a/apps/files_encryption/ajax/userrecovery.php b/apps/files_encryption/ajax/userrecovery.php index d6c94bde81e..81ca1459a91 100644 --- a/apps/files_encryption/ajax/userrecovery.php +++ b/apps/files_encryption/ajax/userrecovery.php @@ -19,7 +19,7 @@ if ( ) { $userId = \OCP\USER::getUser(); - $view = new \OC_FilesystemView('/'); + $view = new \OC\Files\View('/'); $util = new \OCA\Encryption\Util($view, $userId); // Save recovery preference to DB diff --git a/apps/files_encryption/appinfo/app.php b/apps/files_encryption/appinfo/app.php index 21de421c195..104e8568caa 100644 --- a/apps/files_encryption/appinfo/app.php +++ b/apps/files_encryption/appinfo/app.php @@ -40,7 +40,7 @@ if (!OC_Config::getValue('maintenance', false)) { \OC_Util::setupFS(); } - $view = new OC_FilesystemView('/'); + $view = new OC\Files\View('/'); $sessionReady = OCA\Encryption\Helper::checkRequirements(); if($sessionReady) { diff --git a/apps/files_encryption/hooks/hooks.php b/apps/files_encryption/hooks/hooks.php index 5f0494e62ca..c9ffeb454a1 100644 --- a/apps/files_encryption/hooks/hooks.php +++ b/apps/files_encryption/hooks/hooks.php @@ -48,7 +48,7 @@ class Hooks { $l = new \OC_L10N('files_encryption'); - $view = new \OC_FilesystemView('/'); + $view = new \OC\Files\View('/'); // ensure filesystem is loaded if(!\OC\Files\Filesystem::$loaded) { @@ -93,7 +93,7 @@ class Hooks { // If migration not yet done if ($ready) { - $userView = new \OC_FilesystemView('/' . $params['uid']); + $userView = new \OC\Files\View('/' . $params['uid']); // Set legacy encryption key if it exists, to support // depreciated encryption system @@ -142,7 +142,7 @@ class Hooks { public static function postCreateUser($params) { if (\OCP\App::isEnabled('files_encryption')) { - $view = new \OC_FilesystemView('/'); + $view = new \OC\Files\View('/'); $util = new Util($view, $params['uid']); Helper::setupUser($util, $params['password']); } @@ -155,7 +155,7 @@ class Hooks { public static function postDeleteUser($params) { if (\OCP\App::isEnabled('files_encryption')) { - $view = new \OC_FilesystemView('/'); + $view = new \OC\Files\View('/'); // cleanup public key $publicKey = '/public-keys/' . $params['uid'] . '.public.key'; @@ -196,7 +196,7 @@ class Hooks { // the necessary keys) if (Crypt::mode() === 'server') { - $view = new \OC_FilesystemView('/'); + $view = new \OC\Files\View('/'); if ($params['uid'] === \OCP\User::getUser()) { @@ -308,7 +308,7 @@ class Hooks { if ($params['itemType'] === 'file' || $params['itemType'] === 'folder') { - $view = new \OC_FilesystemView('/'); + $view = new \OC\Files\View('/'); $session = new \OCA\Encryption\Session($view); $userId = \OCP\User::getUser(); $util = new Util($view, $userId); @@ -350,7 +350,7 @@ class Hooks { if ($params['itemType'] === 'file' || $params['itemType'] === 'folder') { - $view = new \OC_FilesystemView('/'); + $view = new \OC\Files\View('/'); $userId = \OCP\User::getUser(); $util = new Util($view, $userId); $path = \OC\Files\Filesystem::getPath($params['fileSource']); @@ -403,7 +403,7 @@ class Hooks { */ public static function preRename($params) { $user = \OCP\User::getUser(); - $view = new \OC_FilesystemView('/'); + $view = new \OC\Files\View('/'); $util = new Util($view, $user); list($ownerOld, $pathOld) = $util->getUidAndFilename($params['oldpath']); @@ -437,7 +437,7 @@ class Hooks { $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; - $view = new \OC_FilesystemView('/'); + $view = new \OC\Files\View('/'); $session = new \OCA\Encryption\Session($view); $userId = \OCP\User::getUser(); $util = new Util($view, $userId); @@ -610,7 +610,7 @@ class Hooks { return true; } - $util = new Util(new \OC_FilesystemView('/'), \OCP\USER::getUser()); + $util = new Util(new \OC\Files\View('/'), \OCP\USER::getUser()); list($owner, $ownerPath) = $util->getUidAndFilename($path); self::$deleteFiles[$params[\OC\Files\Filesystem::signal_param_path]] = array( diff --git a/apps/files_encryption/lib/helper.php b/apps/files_encryption/lib/helper.php index 82a323d5e12..c3a31ff9fbc 100755 --- a/apps/files_encryption/lib/helper.php +++ b/apps/files_encryption/lib/helper.php @@ -153,7 +153,7 @@ class Helper { $return = true; } else { // get recovery key and check the password - $util = new \OCA\Encryption\Util(new \OC_FilesystemView('/'), \OCP\User::getUser()); + $util = new \OCA\Encryption\Util(new \OC\Files\View('/'), \OCP\User::getUser()); $return = $util->checkRecoveryPassword($recoveryPassword); if ($return) { $appConfig->setValue('files_encryption', 'recoveryAdminEnabled', 1); @@ -214,7 +214,7 @@ class Helper { * @return bool */ public static function adminDisableRecovery($recoveryPassword) { - $util = new Util(new \OC_FilesystemView('/'), \OCP\User::getUser()); + $util = new Util(new \OC\Files\View('/'), \OCP\User::getUser()); $return = $util->checkRecoveryPassword($recoveryPassword); if ($return) { diff --git a/apps/files_encryption/lib/keymanager.php b/apps/files_encryption/lib/keymanager.php index cb9f5e64af3..5aa8a6ab06e 100755 --- a/apps/files_encryption/lib/keymanager.php +++ b/apps/files_encryption/lib/keymanager.php @@ -32,12 +32,12 @@ class Keymanager { /** * @brief retrieve the ENCRYPTED private key from a user * - * @param \OC_FilesystemView $view + * @param \OC\Files\View $view * @param string $user * @return string private key or false (hopefully) * @note the key returned by this method must be decrypted before use */ - public static function getPrivateKey(\OC_FilesystemView $view, $user) { + public static function getPrivateKey(\OC\Files\View $view, $user) { $path = '/' . $user . '/' . 'files_encryption' . '/' . $user . '.private.key'; $key = false; @@ -56,11 +56,11 @@ class Keymanager { /** * @brief retrieve public key for a specified user - * @param \OC_FilesystemView $view + * @param \OC\Files\View $view * @param $userId * @return string public key or false */ - public static function getPublicKey(\OC_FilesystemView $view, $userId) { + public static function getPublicKey(\OC\Files\View $view, $userId) { $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; @@ -75,11 +75,11 @@ class Keymanager { /** * @brief Retrieve a user's public and private key - * @param \OC_FilesystemView $view + * @param \OC\Files\View $view * @param $userId * @return array keys: privateKey, publicKey */ - public static function getUserKeys(\OC_FilesystemView $view, $userId) { + public static function getUserKeys(\OC\Files\View $view, $userId) { return array( 'publicKey' => self::getPublicKey($view, $userId), @@ -90,11 +90,11 @@ class Keymanager { /** * @brief Retrieve public keys for given users - * @param \OC_FilesystemView $view + * @param \OC\Files\View $view * @param array $userIds * @return array of public keys for the specified users */ - public static function getPublicKeys(\OC_FilesystemView $view, array $userIds) { + public static function getPublicKeys(\OC\Files\View $view, array $userIds) { $keys = array(); @@ -111,7 +111,7 @@ class Keymanager { /** * @brief store file encryption key * - * @param \OC_FilesystemView $view + * @param \OC\Files\View $view * @param \OCA\Encryption\Util $util * @param string $path relative path of the file, including filename * @param string $catfile keyfile content @@ -119,7 +119,7 @@ class Keymanager { * @note The keyfile is not encrypted here. Client code must * asymmetrically encrypt the keyfile before passing it to this method */ - public static function setFileKey(\OC_FilesystemView $view, $util, $path, $catfile) { + public static function setFileKey(\OC\Files\View $view, $util, $path, $catfile) { $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; @@ -168,7 +168,7 @@ class Keymanager { /** * @brief retrieve keyfile for an encrypted file - * @param \OC_FilesystemView $view + * @param \OC\Files\View $view * @param \OCA\Encryption\Util $util * @param string|false $filePath * @internal param \OCA\Encryption\file $string name @@ -212,7 +212,7 @@ class Keymanager { /** * @brief Delete a keyfile * - * @param \OC_FilesystemView $view + * @param \OC\Files\View $view * @param string $path path of the file the key belongs to * @param string $userId the user to whom the file belongs * @return bool Outcome of unlink operation @@ -276,7 +276,7 @@ class Keymanager { $user = \OCP\User::getUser(); - $view = new \OC_FilesystemView('/' . $user . '/files_encryption'); + $view = new \OC\Files\View('/' . $user . '/files_encryption'); $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; @@ -295,14 +295,14 @@ class Keymanager { /** * @brief store share key * - * @param \OC_FilesystemView $view + * @param \OC\Files\View $view * @param string $path where the share key is stored * @param $shareKey * @return bool true/false * @note The keyfile is not encrypted here. Client code must * asymmetrically encrypt the keyfile before passing it to this method */ - private static function setShareKey(\OC_FilesystemView $view, $path, $shareKey) { + private static function setShareKey(\OC\Files\View $view, $path, $shareKey) { $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; @@ -320,13 +320,13 @@ class Keymanager { /** * @brief store multiple share keys for a single file - * @param \OC_FilesystemView $view + * @param \OC\Files\View $view * @param \OCA\Encryption\Util $util * @param string $path * @param array $shareKeys * @return bool */ - public static function setShareKeys(\OC_FilesystemView $view, $util, $path, array $shareKeys) { + public static function setShareKeys(\OC\Files\View $view, $util, $path, array $shareKeys) { // $shareKeys must be an array with the following format: // [userId] => [encrypted key] @@ -366,7 +366,7 @@ class Keymanager { /** * @brief retrieve shareKey for an encrypted file - * @param \OC_FilesystemView $view + * @param \OC\Files\View $view * @param string $userId * @param \OCA\Encryption\Util $util * @param string $filePath @@ -374,7 +374,7 @@ class Keymanager { * @note The sharekey returned is encrypted. Decryption * of the keyfile must be performed by client code */ - public static function getShareKey(\OC_FilesystemView $view, $userId, $util, $filePath) { + public static function getShareKey(\OC\Files\View $view, $userId, $util, $filePath) { // try reusing key file if part file $proxyStatus = \OC_FileProxy::$enabled; @@ -407,7 +407,7 @@ class Keymanager { /** * @brief delete all share keys of a given file - * @param \OC_FilesystemView $view + * @param \OC\Files\View $view * @param string $userId owner of the file * @param string $filePath path to the file, relative to the owners file dir */ @@ -447,7 +447,7 @@ class Keymanager { /** * @brief Delete a single user's shareKey for a single file */ - public static function delShareKey(\OC_FilesystemView $view, $userIds, $filePath) { + public static function delShareKey(\OC\Files\View $view, $userIds, $filePath) { $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; @@ -516,7 +516,7 @@ class Keymanager { * @param string|boolean $path * @param string $basePath */ - public static function keySetPreparation(\OC_FilesystemView $view, $path, $basePath, $userId) { + public static function keySetPreparation(\OC\Files\View $view, $path, $basePath, $userId) { $targetPath = ltrim($path, '/'); diff --git a/apps/files_encryption/lib/proxy.php b/apps/files_encryption/lib/proxy.php index 5dc407f796a..919853107a8 100644 --- a/apps/files_encryption/lib/proxy.php +++ b/apps/files_encryption/lib/proxy.php @@ -65,7 +65,7 @@ class Proxy extends \OC_FileProxy { return false; } - $view = new \OC_FilesystemView(''); + $view = new \OC\Files\View(''); $util = new Util($view, $userId); // for write operation we always encrypt the files, for read operations @@ -90,7 +90,7 @@ class Proxy extends \OC_FileProxy { if (!is_resource($data)) { // get root view - $view = new \OC_FilesystemView('/'); + $view = new \OC\Files\View('/'); // get relative path $relativePath = \OCA\Encryption\Helper::stripUserFilesPath($path); @@ -152,7 +152,7 @@ class Proxy extends \OC_FileProxy { public function postFile_put_contents($path, $result) { $normalizedPath = \OC\Files\Filesystem::normalizePath($path); if ( isset(self::$unencryptedSizes[$normalizedPath]) ) { - $view = new \OC_FilesystemView('/'); + $view = new \OC\Files\View('/'); $view->putFileInfo($normalizedPath, array('encrypted' => true, 'unencrypted_size' => self::$unencryptedSizes[$normalizedPath])); unset(self::$unencryptedSizes[$normalizedPath]); @@ -168,7 +168,7 @@ class Proxy extends \OC_FileProxy { public function postFile_get_contents($path, $data) { $plainData = null; - $view = new \OC_FilesystemView('/'); + $view = new \OC\Files\View('/'); // init session $session = new \OCA\Encryption\Session($view); @@ -291,7 +291,7 @@ class Proxy extends \OC_FileProxy { */ public function postFileSize($path, $size) { - $view = new \OC_FilesystemView('/'); + $view = new \OC\Files\View('/'); $userId = Helper::getUser($path); $util = new Util($view, $userId); diff --git a/apps/files_encryption/lib/session.php b/apps/files_encryption/lib/session.php index 3daaa06425f..19b669a27ff 100644 --- a/apps/files_encryption/lib/session.php +++ b/apps/files_encryption/lib/session.php @@ -37,7 +37,7 @@ class Session { /** * @brief if session is started, check if ownCloud key pair is set up, if not create it - * @param \OC_FilesystemView $view + * @param \OC\Files\View $view * * @note The ownCloud key pair is used to allow public link sharing even if encryption is enabled */ diff --git a/apps/files_encryption/lib/stream.php b/apps/files_encryption/lib/stream.php index df5de558867..8b575174e2e 100644 --- a/apps/files_encryption/lib/stream.php +++ b/apps/files_encryption/lib/stream.php @@ -91,7 +91,7 @@ class Stream { $this->newFile = false; if (!isset($this->rootView)) { - $this->rootView = new \OC_FilesystemView('/'); + $this->rootView = new \OC\Files\View('/'); } $this->session = new \OCA\Encryption\Session($this->rootView); diff --git a/apps/files_encryption/lib/util.php b/apps/files_encryption/lib/util.php index fb0067171ee..37fdcaceaa5 100644 --- a/apps/files_encryption/lib/util.php +++ b/apps/files_encryption/lib/util.php @@ -26,7 +26,7 @@ namespace OCA\Encryption; /** * @brief Class for utilities relating to encrypted file storage system - * @param \OC_FilesystemView $view expected to have OC '/' as root path + * @param \OC\Files\View $view expected to have OC '/' as root path * @param string $userId ID of the logged in user * @param int $client indicating status of client side encryption. Currently * unused, likely to become obsolete shortly @@ -38,7 +38,7 @@ class Util { const MIGRATION_IN_PROGRESS = -1; // migration is running const MIGRATION_OPEN = 0; // user still needs to be migrated - private $view; // OC_FilesystemView object for filesystem operations + private $view; // OC\Files\View object for filesystem operations private $userId; // ID of the user we use to encrypt/decrypt files private $keyId; // ID of the key we want to manipulate private $client; // Client side encryption mode flag @@ -53,7 +53,7 @@ class Util { private $isPublic; /** - * @param \OC_FilesystemView $view + * @param \OC\Files\View $view * @param $userId * @param bool $client */ @@ -1522,7 +1522,7 @@ class Util { if ($item['type'] === 'dir') { $this->addRecoveryKeys($filePath . '/'); } else { - $session = new \OCA\Encryption\Session(new \OC_FilesystemView('/')); + $session = new \OCA\Encryption\Session(new \OC\Files\View('/')); $sharingEnabled = \OCP\Share::isEnabled(); // remove '.key' extension from path e.g. 'file.txt.key' to 'file.txt' $file = substr($filePath, 0, -4); diff --git a/apps/files_encryption/settings-personal.php b/apps/files_encryption/settings-personal.php index 09e9df05352..e9875518f67 100644 --- a/apps/files_encryption/settings-personal.php +++ b/apps/files_encryption/settings-personal.php @@ -12,7 +12,7 @@ $tmpl = new OCP\Template('files_encryption', 'settings-personal'); $user = \OCP\USER::getUser(); -$view = new \OC_FilesystemView('/'); +$view = new \OC\Files\View('/'); $util = new \OCA\Encryption\Util($view, $user); $session = new \OCA\Encryption\Session($view); diff --git a/apps/files_encryption/tests/crypt.php b/apps/files_encryption/tests/crypt.php index 123943ea26a..83c2ab30b8e 100755 --- a/apps/files_encryption/tests/crypt.php +++ b/apps/files_encryption/tests/crypt.php @@ -34,7 +34,7 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase { public $dataUrl; public $dataShort; /** - * @var OC_FilesystemView + * @var OC\Files\View */ public $view; public $legacyEncryptedData; @@ -79,7 +79,7 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase { $this->genPublicKey = $keypair['publicKey']; $this->genPrivateKey = $keypair['privateKey']; - $this->view = new \OC_FilesystemView('/'); + $this->view = new \OC\Files\View('/'); // remember files_trashbin state $this->stateFilesTrashbin = OC_App::isEnabled('files_trashbin'); @@ -157,7 +157,7 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase { $filename = 'tmp-' . uniqid() . '.test'; - $util = new Encryption\Util(new \OC_FilesystemView(), $this->userId); + $util = new Encryption\Util(new \OC\Files\View(), $this->userId); $cryptedFile = file_put_contents('crypt:///' . $this->userId . '/files/'. $filename, $this->dataShort); @@ -216,7 +216,7 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase { // Generate a a random filename $filename = 'tmp-' . uniqid() . '.test'; - $util = new Encryption\Util(new \OC_FilesystemView(), $this->userId); + $util = new Encryption\Util(new \OC\Files\View(), $this->userId); // Save long data as encrypted file using stream wrapper $cryptedFile = file_put_contents('crypt:///' . $this->userId . '/files/' . $filename, $this->dataLong . $this->dataLong); diff --git a/apps/files_encryption/tests/hooks.php b/apps/files_encryption/tests/hooks.php index 047084ca2c1..ee534f708c2 100644 --- a/apps/files_encryption/tests/hooks.php +++ b/apps/files_encryption/tests/hooks.php @@ -40,7 +40,7 @@ class Test_Encryption_Hooks extends \PHPUnit_Framework_TestCase { const TEST_ENCRYPTION_HOOKS_USER2 = "test-encryption-hooks-user2"; /** - * @var \OC_FilesystemView + * @var \OC\Files\View */ public $user1View; // view on /data/user1/files public $user2View; // view on /data/user2/files @@ -83,9 +83,9 @@ class Test_Encryption_Hooks extends \PHPUnit_Framework_TestCase { \OC_User::setUserId(\Test_Encryption_Hooks::TEST_ENCRYPTION_HOOKS_USER1); // init filesystem view - $this->user1View = new \OC_FilesystemView('/'. \Test_Encryption_Hooks::TEST_ENCRYPTION_HOOKS_USER1 . '/files'); - $this->user2View = new \OC_FilesystemView('/'. \Test_Encryption_Hooks::TEST_ENCRYPTION_HOOKS_USER2 . '/files'); - $this->rootView = new \OC_FilesystemView('/'); + $this->user1View = new \OC\Files\View('/'. \Test_Encryption_Hooks::TEST_ENCRYPTION_HOOKS_USER1 . '/files'); + $this->user2View = new \OC\Files\View('/'. \Test_Encryption_Hooks::TEST_ENCRYPTION_HOOKS_USER2 . '/files'); + $this->rootView = new \OC\Files\View('/'); // init short data $this->data = 'hats'; diff --git a/apps/files_encryption/tests/keymanager.php b/apps/files_encryption/tests/keymanager.php index 0caf12e91a3..2bd2ddc8e68 100644 --- a/apps/files_encryption/tests/keymanager.php +++ b/apps/files_encryption/tests/keymanager.php @@ -29,7 +29,7 @@ class Test_Encryption_Keymanager extends \PHPUnit_Framework_TestCase { public $pass; public $stateFilesTrashbin; /** - * @var OC_FilesystemView + * @var OC\Files\View */ public $view; public $randomKey; @@ -68,7 +68,7 @@ class Test_Encryption_Keymanager extends \PHPUnit_Framework_TestCase { $this->genPublicKey = $keypair['publicKey']; $this->genPrivateKey = $keypair['privateKey']; - $this->view = new \OC_FilesystemView('/'); + $this->view = new \OC\Files\View('/'); \OC_User::setUserId(\Test_Encryption_Keymanager::TEST_USER); $this->userId = \Test_Encryption_Keymanager::TEST_USER; @@ -257,4 +257,4 @@ class TestProtectedKeymanagerMethods extends \OCA\Encryption\Keymanager { public static function testGetFilenameFromShareKey($sharekey) { return self::getFilenameFromShareKey($sharekey); } -} \ No newline at end of file +} diff --git a/apps/files_encryption/tests/proxy.php b/apps/files_encryption/tests/proxy.php index 647ee955eb1..533aaa376b9 100644 --- a/apps/files_encryption/tests/proxy.php +++ b/apps/files_encryption/tests/proxy.php @@ -42,7 +42,7 @@ class Test_Encryption_Proxy extends \PHPUnit_Framework_TestCase { public $userId; public $pass; /** - * @var \OC_FilesystemView + * @var \OC\Files\View */ public $view; // view in /data/user/files public $rootView; // view on /data/user @@ -75,8 +75,8 @@ class Test_Encryption_Proxy extends \PHPUnit_Framework_TestCase { $this->pass = \Test_Encryption_Proxy::TEST_ENCRYPTION_PROXY_USER1; // init filesystem view - $this->view = new \OC_FilesystemView('/'. \Test_Encryption_Proxy::TEST_ENCRYPTION_PROXY_USER1 . '/files'); - $this->rootView = new \OC_FilesystemView('/'. \Test_Encryption_Proxy::TEST_ENCRYPTION_PROXY_USER1 ); + $this->view = new \OC\Files\View('/'. \Test_Encryption_Proxy::TEST_ENCRYPTION_PROXY_USER1 . '/files'); + $this->rootView = new \OC\Files\View('/'. \Test_Encryption_Proxy::TEST_ENCRYPTION_PROXY_USER1 ); // init short data $this->data = 'hats'; diff --git a/apps/files_encryption/tests/share.php b/apps/files_encryption/tests/share.php index 512671c5767..f75092f5436 100755 --- a/apps/files_encryption/tests/share.php +++ b/apps/files_encryption/tests/share.php @@ -48,7 +48,7 @@ class Test_Encryption_Share extends \PHPUnit_Framework_TestCase { public $filename; public $dataShort; /** - * @var OC_FilesystemView + * @var OC\Files\View */ public $view; public $folder1; @@ -92,7 +92,7 @@ class Test_Encryption_Share extends \PHPUnit_Framework_TestCase { function setUp() { $this->dataShort = 'hats'; - $this->view = new \OC_FilesystemView('/'); + $this->view = new \OC\Files\View('/'); $this->folder1 = '/folder1'; $this->subfolder = '/subfolder1'; @@ -669,7 +669,7 @@ class Test_Encryption_Share extends \PHPUnit_Framework_TestCase { // login as admin \Test_Encryption_Util::loginHelper(\Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER1); - $util = new \OCA\Encryption\Util(new \OC_FilesystemView('/'), \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER1); + $util = new \OCA\Encryption\Util(new \OC\Files\View('/'), \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER1); // check if recovery password match $this->assertTrue($util->checkRecoveryPassword('test123')); @@ -777,7 +777,7 @@ class Test_Encryption_Share extends \PHPUnit_Framework_TestCase { // login as user2 \Test_Encryption_Util::loginHelper(\Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER2); - $util = new \OCA\Encryption\Util(new \OC_FilesystemView('/'), \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER2); + $util = new \OCA\Encryption\Util(new \OC\Files\View('/'), \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER2); // enable recovery for admin $this->assertTrue($util->setRecoveryForUser(1)); diff --git a/apps/files_encryption/tests/stream.php b/apps/files_encryption/tests/stream.php index fed2e7d89d1..f742cd3f8e9 100644 --- a/apps/files_encryption/tests/stream.php +++ b/apps/files_encryption/tests/stream.php @@ -42,7 +42,7 @@ class Test_Encryption_Stream extends \PHPUnit_Framework_TestCase { public $userId; public $pass; /** - * @var \OC_FilesystemView + * @var \OC\Files\View */ public $view; public $dataShort; @@ -71,7 +71,7 @@ class Test_Encryption_Stream extends \PHPUnit_Framework_TestCase { $this->pass = \Test_Encryption_Stream::TEST_ENCRYPTION_STREAM_USER1; // init filesystem view - $this->view = new \OC_FilesystemView('/'); + $this->view = new \OC\Files\View('/'); // init short data $this->dataShort = 'hats'; diff --git a/apps/files_encryption/tests/trashbin.php b/apps/files_encryption/tests/trashbin.php index 2f9ecfd9d5d..e36293ba81e 100755 --- a/apps/files_encryption/tests/trashbin.php +++ b/apps/files_encryption/tests/trashbin.php @@ -43,7 +43,7 @@ class Test_Encryption_Trashbin extends \PHPUnit_Framework_TestCase { public $userId; public $pass; /** - * @var \OC_FilesystemView + * @var \OC\Files\View */ public $view; public $dataShort; @@ -81,7 +81,7 @@ class Test_Encryption_Trashbin extends \PHPUnit_Framework_TestCase { $this->pass = \Test_Encryption_Trashbin::TEST_ENCRYPTION_TRASHBIN_USER1; // init filesystem view - $this->view = new \OC_FilesystemView('/'); + $this->view = new \OC\Files\View('/'); // init short data $this->dataShort = 'hats'; diff --git a/apps/files_encryption/tests/util.php b/apps/files_encryption/tests/util.php index 88ded7ec40a..de83f6bca2b 100755 --- a/apps/files_encryption/tests/util.php +++ b/apps/files_encryption/tests/util.php @@ -29,7 +29,7 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase { public $publicKeyDir; public $pass; /** - * @var OC_FilesystemView + * @var OC\Files\View */ public $view; public $keyfilesPath; @@ -92,7 +92,7 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase { $this->privateKeyPath = $this->encryptionDir . '/' . $this->userId . '.private.key'; // e.g. data/admin/admin.private.key - $this->view = new \OC_FilesystemView('/'); + $this->view = new \OC\Files\View('/'); $this->util = new Encryption\Util($this->view, $this->userId); @@ -205,7 +205,7 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase { function testIsLegacyUser() { \Test_Encryption_Util::loginHelper(\Test_Encryption_Util::TEST_ENCRYPTION_UTIL_LEGACY_USER); - $userView = new \OC_FilesystemView('/' . \Test_Encryption_Util::TEST_ENCRYPTION_UTIL_LEGACY_USER); + $userView = new \OC\Files\View('/' . \Test_Encryption_Util::TEST_ENCRYPTION_UTIL_LEGACY_USER); // Disable encryption proxy to prevent recursive calls $proxyStatus = \OC_FileProxy::$enabled; @@ -384,7 +384,7 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase { $params = array('uid' => \OCP\User::getUser(), 'password' => \OCP\User::getUser()); - $view = new OC_FilesystemView('/'); + $view = new OC\Files\View('/'); $util = new \OCA\Encryption\Util($view, \OCP\User::getUser()); $result = $util->initEncryption($params); @@ -496,8 +496,8 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase { function testEncryptLegacyFiles() { \Test_Encryption_Util::loginHelper(\Test_Encryption_Util::TEST_ENCRYPTION_UTIL_LEGACY_USER); - $userView = new \OC_FilesystemView('/' . \Test_Encryption_Util::TEST_ENCRYPTION_UTIL_LEGACY_USER); - $view = new \OC_FilesystemView('/' . \Test_Encryption_Util::TEST_ENCRYPTION_UTIL_LEGACY_USER . '/files'); + $userView = new \OC\Files\View('/' . \Test_Encryption_Util::TEST_ENCRYPTION_UTIL_LEGACY_USER); + $view = new \OC\Files\View('/' . \Test_Encryption_Util::TEST_ENCRYPTION_UTIL_LEGACY_USER . '/files'); // Disable encryption proxy to prevent recursive calls $proxyStatus = \OC_FileProxy::$enabled; diff --git a/apps/files_encryption/tests/webdav.php b/apps/files_encryption/tests/webdav.php index 1fe4c13d59e..bdd3d51897b 100755 --- a/apps/files_encryption/tests/webdav.php +++ b/apps/files_encryption/tests/webdav.php @@ -43,7 +43,7 @@ class Test_Encryption_Webdav extends \PHPUnit_Framework_TestCase { public $userId; public $pass; /** - * @var \OC_FilesystemView + * @var \OC\Files\View */ public $view; public $dataShort; @@ -82,7 +82,7 @@ class Test_Encryption_Webdav extends \PHPUnit_Framework_TestCase { $this->pass = \Test_Encryption_Webdav::TEST_ENCRYPTION_WEBDAV_USER1; // init filesystem view - $this->view = new \OC_FilesystemView('/'); + $this->view = new \OC\Files\View('/'); // init short data $this->dataShort = 'hats'; diff --git a/apps/files_sharing/tests/base.php b/apps/files_sharing/tests/base.php index 495dca072c7..11bbcb133f5 100644 --- a/apps/files_sharing/tests/base.php +++ b/apps/files_sharing/tests/base.php @@ -39,7 +39,7 @@ abstract class Test_Files_Sharing_Base extends \PHPUnit_Framework_TestCase { public $filename; public $data; /** - * @var OC_FilesystemView + * @var OC\Files\View */ public $view; public $folder; @@ -68,7 +68,7 @@ abstract class Test_Files_Sharing_Base extends \PHPUnit_Framework_TestCase { self::loginHelper(self::TEST_FILES_SHARING_API_USER1); $this->data = 'foobar'; - $this->view = new \OC_FilesystemView('/' . self::TEST_FILES_SHARING_API_USER1 . '/files'); + $this->view = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER1 . '/files'); // remember files_encryption state $this->stateFilesEncryption = \OC_App::isEnabled('files_encryption'); diff --git a/apps/files_sharing/tests/cache.php b/apps/files_sharing/tests/cache.php index 1af73c558d5..4e63a1844c6 100644 --- a/apps/files_sharing/tests/cache.php +++ b/apps/files_sharing/tests/cache.php @@ -25,7 +25,7 @@ require_once __DIR__ . '/base.php'; class Test_Files_Sharing_Cache extends Test_Files_Sharing_Base { /** - * @var OC_FilesystemView + * @var OC\Files\View */ public $user2View; diff --git a/apps/files_trashbin/lib/trashbin.php b/apps/files_trashbin/lib/trashbin.php index 173eb2164cf..e2f220051c7 100644 --- a/apps/files_trashbin/lib/trashbin.php +++ b/apps/files_trashbin/lib/trashbin.php @@ -216,7 +216,7 @@ class Trashbin { list($owner, $ownerPath) = self::getUidAndFilename($file_path); - $util = new \OCA\Encryption\Util(new \OC_FilesystemView('/'), $user); + $util = new \OCA\Encryption\Util(new \OC\Files\View('/'), $user); // disable proxy to prevent recursive calls $proxyStatus = \OC_FileProxy::$enabled; @@ -441,7 +441,7 @@ class Trashbin { list($owner, $ownerPath) = self::getUidAndFilename($target); - $util = new \OCA\Encryption\Util(new \OC_FilesystemView('/'), $user); + $util = new \OCA\Encryption\Util(new \OC\Files\View('/'), $user); if ($util->isSystemWideMountPoint($ownerPath)) { $baseDir = '/files_encryption/'; @@ -498,7 +498,7 @@ class Trashbin { $rootView->rename($ownerShareKey, $baseDir . '/share-keys/' . $ownerPath . '.' . $user . '.shareKey'); // try to re-share if file is shared - $filesystemView = new \OC_FilesystemView('/'); + $filesystemView = new \OC\Files\View('/'); $session = new \OCA\Encryption\Session($filesystemView); $util = new \OCA\Encryption\Util($filesystemView, $user); diff --git a/lib/private/files/view.php b/lib/private/files/view.php index 47fc04c937d..407f5981957 100644 --- a/lib/private/files/view.php +++ b/lib/private/files/view.php @@ -11,7 +11,7 @@ * working with files within that view (e.g. read, write, delete, etc.). Each * view is restricted to a set of directories via a virtual root. The default view * uses the currently logged in user's data directory as root (parts of - * OC_Filesystem are merely a wrapper for OC_FilesystemView). + * OC_Filesystem are merely a wrapper for OC\Files\View). * * Apps that need to access files outside of the user data folders (to modify files * belonging to a user other than the one currently logged in, for example) should diff --git a/lib/private/legacy/filesystemview.php b/lib/private/legacy/filesystemview.php deleted file mode 100644 index d6bca62e06a..00000000000 --- a/lib/private/legacy/filesystemview.php +++ /dev/null @@ -1,9 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. */ - -class OC_FilesystemView extends \OC\Files\View {} diff --git a/settings/ajax/decryptall.php b/settings/ajax/decryptall.php index d12df230d41..55685f778d1 100644 --- a/settings/ajax/decryptall.php +++ b/settings/ajax/decryptall.php @@ -10,7 +10,7 @@ OC_App::loadApp('files_encryption'); $params = array('uid' => \OCP\User::getUser(), 'password' => $_POST['password']); -$view = new OC_FilesystemView('/'); +$view = new OC\Files\View('/'); $util = new \OCA\Encryption\Util($view, \OCP\User::getUser()); $l = \OC_L10N::get('settings'); diff --git a/settings/changepassword/controller.php b/settings/changepassword/controller.php index 9f1e7329964..052715555e5 100644 --- a/settings/changepassword/controller.php +++ b/settings/changepassword/controller.php @@ -52,7 +52,7 @@ class Controller { if (\OC_App::isEnabled('files_encryption')) { //handle the recovery case - $util = new \OCA\Encryption\Util(new \OC_FilesystemView('/'), $username); + $util = new \OCA\Encryption\Util(new \OC\Files\View('/'), $username); $recoveryAdminEnabled = \OC_Appconfig::getValue('files_encryption', 'recoveryAdminEnabled'); $validRecoveryPassword = false; -- cgit v1.2.3 From f5ed92bf31f98d6dbdd7bbc7903169c90d82e464 Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Mon, 12 May 2014 16:34:47 +0200 Subject: remove legacy aka deprecated code: OC_Cache_FileGlobalGC --- lib/private/legacy/cache/fileglobalgc.php | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 lib/private/legacy/cache/fileglobalgc.php (limited to 'lib/private') diff --git a/lib/private/legacy/cache/fileglobalgc.php b/lib/private/legacy/cache/fileglobalgc.php deleted file mode 100644 index 385f6406673..00000000000 --- a/lib/private/legacy/cache/fileglobalgc.php +++ /dev/null @@ -1,4 +0,0 @@ - Date: Mon, 12 May 2014 21:58:09 +0200 Subject: fixing typos and adding PHPDoc --- lib/private/db/connectionfactory.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/db/connectionfactory.php b/lib/private/db/connectionfactory.php index 14ffe1a4a56..8f852cf7127 100644 --- a/lib/private/db/connectionfactory.php +++ b/lib/private/db/connectionfactory.php @@ -9,7 +9,7 @@ namespace OC\DB; /** -* Takes care of creating and configurating Doctrine connections. +* Takes care of creating and configuring Doctrine connections. */ class ConnectionFactory { /** @@ -91,6 +91,7 @@ class ConnectionFactory { case 'sqlite3': // Sqlite doesn't handle query caching and schema changes // TODO: find a better way to handle this + /** @var $connection \OC\DB\Connection */ $connection->disableQueryStatementCaching(); break; } @@ -107,7 +108,7 @@ class ConnectionFactory { } /** - * @brief Checks whether the specififed DBMS type is valid. + * @brief Checks whether the specified DBMS type is valid. * @return bool */ public function isValidType($type) { -- cgit v1.2.3 From a152e320f6aa98774950eb088588cd16387226f8 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Tue, 13 May 2014 10:40:49 +0200 Subject: make it possible to omit parameters and use the default parameters from the controller method --- lib/private/appframework/http/dispatcher.php | 4 +-- .../utility/controllermethodreflector.php | 9 +++-- tests/lib/appframework/http/DispatcherTest.php | 40 ++++++++++++++++++---- .../utility/ControllerMethodReflectorTest.php | 6 ++-- 4 files changed, 46 insertions(+), 13 deletions(-) (limited to 'lib/private') diff --git a/lib/private/appframework/http/dispatcher.php b/lib/private/appframework/http/dispatcher.php index 39ca3398c66..442e33ee726 100644 --- a/lib/private/appframework/http/dispatcher.php +++ b/lib/private/appframework/http/dispatcher.php @@ -126,11 +126,11 @@ class Dispatcher { // valid types that will be casted $types = array('int', 'integer', 'bool', 'boolean', 'float'); - foreach($this->reflector->getParameters() as $param) { + foreach($this->reflector->getParameters() as $param => $default) { // try to get the parameter from the request object and cast // it to the type annotated in the @param annotation - $value = $this->request->getParam($param); + $value = $this->request->getParam($param, $default); $type = $this->reflector->getType($param); // if this is submitted using GET or a POST form, 'false' should be diff --git a/lib/private/appframework/utility/controllermethodreflector.php b/lib/private/appframework/utility/controllermethodreflector.php index c9cdadcca4a..a1519c72809 100644 --- a/lib/private/appframework/utility/controllermethodreflector.php +++ b/lib/private/appframework/utility/controllermethodreflector.php @@ -59,7 +59,12 @@ class ControllerMethodReflector { // get method parameters foreach ($reflection->getParameters() as $param) { - $this->parameters[] = $param->name; + if($param->isOptional()) { + $default = $param->getDefaultValue(); + } else { + $default = null; + } + $this->parameters[$param->name] = $default; } } @@ -81,7 +86,7 @@ class ControllerMethodReflector { /** - * @return array the arguments of the method + * @return array the arguments of the method with key => default value */ public function getParameters() { return $this->parameters; diff --git a/tests/lib/appframework/http/DispatcherTest.php b/tests/lib/appframework/http/DispatcherTest.php index 2aef2911e2c..8117eec2075 100644 --- a/tests/lib/appframework/http/DispatcherTest.php +++ b/tests/lib/appframework/http/DispatcherTest.php @@ -40,11 +40,11 @@ class TestController extends Controller { * @param int $int * @param bool $bool */ - public function exec($int, $bool) { + public function exec($int, $bool, $test=4, $test2=1) { $this->registerResponder('text', function($in) { return new JSONResponse(array('text' => $in)); }); - return array($int, $bool); + return array($int, $bool, $test, $test2); } } @@ -262,6 +262,7 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { })); } + public function testControllerParametersInjected() { $this->request = new Request(array( 'post' => array( @@ -280,10 +281,34 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { $this->dispatcherPassthrough(); $response = $this->dispatcher->dispatch($controller, 'exec'); - $this->assertEquals('[3,true]', $response[2]); + $this->assertEquals('[3,true,4,1]', $response[2]); + } + + + public function testControllerParametersInjectedDefaultOverwritten() { + $this->request = new Request(array( + 'post' => array( + 'int' => '3', + 'bool' => 'false', + 'test2' => 7 + ), + 'method' => 'POST' + )); + $this->dispatcher = new Dispatcher( + $this->http, $this->middlewareDispatcher, $this->reflector, + $this->request + ); + $controller = new TestController('app', $this->request); + + // reflector is supposed to be called once + $this->dispatcherPassthrough(); + $response = $this->dispatcher->dispatch($controller, 'exec'); + + $this->assertEquals('[3,true,4,7]', $response[2]); } + public function testResponseTransformedByUrlFormat() { $this->request = new Request(array( 'post' => array( @@ -305,7 +330,7 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { $this->dispatcherPassthrough(); $response = $this->dispatcher->dispatch($controller, 'exec'); - $this->assertEquals('{"text":[3,false]}', $response[2]); + $this->assertEquals('{"text":[3,false,4,1]}', $response[2]); } @@ -331,7 +356,7 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { $this->dispatcherPassthrough(); $response = $this->dispatcher->dispatch($controller, 'exec'); - $this->assertEquals('{"text":[3,false]}', $response[2]); + $this->assertEquals('{"text":[3,false,4,1]}', $response[2]); } @@ -359,7 +384,10 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { $this->dispatcherPassthrough(); $response = $this->dispatcher->dispatch($controller, 'exec'); - $this->assertEquals('{"text":[3,true]}', $response[2]); + $this->assertEquals('{"text":[3,true,4,1]}', $response[2]); } + + + } diff --git a/tests/lib/appframework/utility/ControllerMethodReflectorTest.php b/tests/lib/appframework/utility/ControllerMethodReflectorTest.php index cccc7688884..8939a203edb 100644 --- a/tests/lib/appframework/utility/ControllerMethodReflectorTest.php +++ b/tests/lib/appframework/utility/ControllerMethodReflectorTest.php @@ -88,7 +88,7 @@ class ControllerMethodReflectorTest extends \PHPUnit_Framework_TestCase { } - public function arguments($arg, $arg2) {} + public function arguments($arg, $arg2='hi') {} public function testReflectParameters() { $reader = new ControllerMethodReflector(); $reader->reflect( @@ -96,7 +96,7 @@ class ControllerMethodReflectorTest extends \PHPUnit_Framework_TestCase { 'arguments' ); - $this->assertEquals(array('arg', 'arg2'), $reader->getParameters()); + $this->assertEquals(array('arg' => null, 'arg2' => 'hi'), $reader->getParameters()); } @@ -108,7 +108,7 @@ class ControllerMethodReflectorTest extends \PHPUnit_Framework_TestCase { 'arguments2' ); - $this->assertEquals(array('arg',), $reader->getParameters()); + $this->assertEquals(array('arg' => null), $reader->getParameters()); } -- cgit v1.2.3 From a9ac11718e62017c70682f99eb35b43b1ef9c498 Mon Sep 17 00:00:00 2001 From: Bjoern Schiessle Date: Tue, 29 Apr 2014 15:00:57 +0200 Subject: backup the encryption key after the encryption was disabled so that the user can restore them if needed --- apps/files_encryption/lib/util.php | 4 +-- apps/files_encryption/tests/util.php | 11 +++++++ lib/private/util.php | 36 ++++++++++++++++----- settings/ajax/deletekeys.php | 17 ++++++++++ settings/ajax/restorekeys.php | 24 ++++++++++++++ settings/js/personal.js | 61 ++++++++++++++++++++++++++++++------ settings/personal.php | 6 +++- settings/routes.php | 4 +++ settings/templates/personal.php | 35 +++++++++++++++++++-- 9 files changed, 176 insertions(+), 22 deletions(-) create mode 100644 settings/ajax/deletekeys.php create mode 100644 settings/ajax/restorekeys.php (limited to 'lib/private') diff --git a/apps/files_encryption/lib/util.php b/apps/files_encryption/lib/util.php index 6372ab31b6e..27b4db9253a 100644 --- a/apps/files_encryption/lib/util.php +++ b/apps/files_encryption/lib/util.php @@ -788,8 +788,8 @@ class Util { } if ($successful) { - $this->view->deleteAll($this->keyfilesPath); - $this->view->deleteAll($this->shareKeysPath); + $this->view->rename($this->keyfilesPath, $this->keyfilesPath . '.backup'); + $this->view->rename($this->shareKeysPath, $this->shareKeysPath . '.backup'); } \OC_FileProxy::$enabled = true; diff --git a/apps/files_encryption/tests/util.php b/apps/files_encryption/tests/util.php index 88ded7ec40a..fa8e1d729dd 100755 --- a/apps/files_encryption/tests/util.php +++ b/apps/files_encryption/tests/util.php @@ -413,8 +413,16 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase { // file should no longer be encrypted $this->assertEquals(0, $fileInfoUnencrypted['encrypted']); + // check if the keys where moved to the backup location + $this->assertTrue($this->view->is_dir($this->userId . '/files_encryption/keyfiles.backup')); + $this->assertTrue($this->view->file_exists($this->userId . '/files_encryption/keyfiles.backup/' . $filename . '.key')); + $this->assertTrue($this->view->is_dir($this->userId . '/files_encryption/share-keys.backup')); + $this->assertTrue($this->view->file_exists($this->userId . '/files_encryption/share-keys.backup/' . $filename . '.' . $user . '.shareKey')); + // cleanup $this->view->unlink($this->userId . '/files/' . $filename); + $this->view->deleteAll($this->userId . '/files_encryption/keyfiles.backup'); + $this->view->deleteAll($this->userId . '/files_encryption/share-keys.backup'); OC_App::enable('files_encryption'); } @@ -485,8 +493,11 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase { $this->assertFalse($this->view->is_dir($this->userId . '/files_encryption/keyfiles/')); $this->assertFalse($this->view->is_dir($this->userId . '/files_encryption/share-keys/')); + //cleanup $this->view->unlink($this->userId . '/files/' . $file1); $this->view->unlink($this->userId . '/files/' . $file2); + $this->view->deleteAll($this->userId . '/files_encryption/keyfiles.backup'); + $this->view->deleteAll($this->userId . '/files_encryption/share-keys.backup'); } diff --git a/lib/private/util.php b/lib/private/util.php index e2005d31c38..96d80beb4d1 100755 --- a/lib/private/util.php +++ b/lib/private/util.php @@ -550,6 +550,27 @@ class OC_Util { return $encryptedFiles; } + /** + * @brief check if a backup from the encryption keys exists + * @return boolean + */ + public static function backupKeysExists() { + //check if encryption was enabled in the past + $backupExists = false; + if (OC_App::isEnabled('files_encryption') === false) { + $view = new OC\Files\View('/' . OCP\User::getUser()); + $backupPath = '/files_encryption/keyfiles.backup'; + if ($view->is_dir($backupPath)) { + $dircontent = $view->getDirectoryContent($backupPath); + if (!empty($dircontent)) { + $backupExists = true; + } + } + } + + return $backupExists; + } + /** * @brief Check for correct file permissions of data directory * @param string $dataDirectory @@ -837,7 +858,7 @@ class OC_Util { if (!\OC_Config::getValue("check_for_working_htaccess", true)) { return true; } - + // testdata $fileName = '/htaccesstest.txt'; $testContent = 'testcontent'; @@ -1082,7 +1103,7 @@ class OC_Util { curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($curl, CURLOPT_URL, $url); - + curl_setopt($curl, CURLOPT_USERAGENT, "ownCloud Server Crawler"); if(OC_Config::getValue('proxy', '') != '') { @@ -1091,17 +1112,16 @@ class OC_Util { if(OC_Config::getValue('proxyuserpwd', '') != '') { curl_setopt($curl, CURLOPT_PROXYUSERPWD, OC_Config::getValue('proxyuserpwd')); } - - if (ini_get('open_basedir') === '' && ini_get('safe_mode' === 'Off')) { + + if (ini_get('open_basedir') === '' && ini_get('safe_mode' === 'Off')) { curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_MAXREDIRS, $max_redirects); $data = curl_exec($curl); } else { curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false); $mr = $max_redirects; - if ($mr > 0) { + if ($mr > 0) { $newURL = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL); - $rcurl = curl_copy_handle($curl); curl_setopt($rcurl, CURLOPT_HEADER, true); curl_setopt($rcurl, CURLOPT_NOBODY, true); @@ -1125,9 +1145,9 @@ class OC_Util { curl_close($rcurl); if ($mr > 0) { curl_setopt($curl, CURLOPT_URL, $newURL); - } + } } - + if($mr == 0 && $max_redirects > 0) { $data = false; } else { diff --git a/settings/ajax/deletekeys.php b/settings/ajax/deletekeys.php new file mode 100644 index 00000000000..1f84452e117 --- /dev/null +++ b/settings/ajax/deletekeys.php @@ -0,0 +1,17 @@ +deleteAll('keyfiles.backup'); +$sharekeysDeleted = $view->deleteAll('share-keys.backup'); + +if ($keyfilesDeleted && $sharekeysDeleted) { + \OCP\JSON::success(array('data' => array('message' => $l->t('Encryption keys deleted permanently')))); +} else { + \OCP\JSON::error(array('data' => array('message' => $l->t('Couldn\'t permanently delete your encryption keys, please check your owncloud.log or ask your administrator')))); +} diff --git a/settings/ajax/restorekeys.php b/settings/ajax/restorekeys.php new file mode 100644 index 00000000000..68e19c90457 --- /dev/null +++ b/settings/ajax/restorekeys.php @@ -0,0 +1,24 @@ +rename('keyfiles.backup', 'keyfiles'); +$sharekeysRestored = $view->rename('share-keys.backup' , 'share-keys'); + +if ($keyfilesRestored && $sharekeysRestored) { + \OCP\JSON::success(array('data' => array('message' => $l->t('Backups restored successfully')))); +} else { + // if one of the move operation was succesful we remove the files back to have a consistent state + if($keyfilesRestored) { + $view->rename('keyfiles', 'keyfiles.backup'); + } + if($sharekeysRestored) { + $view->rename('share-keys' , 'share-keys.backup'); + } + \OCP\JSON::error(array('data' => array('message' => $l->t('Couldn\'t restore your encryption keys, please check your owncloud.log or ask your administrator')))); +} diff --git a/settings/js/personal.js b/settings/js/personal.js index c1f1ef7466b..f297e3c1b1a 100644 --- a/settings/js/personal.js +++ b/settings/js/personal.js @@ -212,17 +212,30 @@ $(document).ready(function(){ OC.Encryption.decryptAll(privateKeyPassword); }); + + $('button:button[name="submitRestoreKeys"]').click(function() { + $('#restoreBackupKeys button:button[name="submitDeleteKeys"]').prop("disabled", true); + $('#restoreBackupKeys button:button[name="submitRestoreKeys"]').prop("disabled", true); + OC.Encryption.restoreKeys(); + }); + + $('button:button[name="submitDeleteKeys"]').click(function() { + $('#restoreBackupKeys button:button[name="submitDeleteKeys"]').prop("disabled", true); + $('#restoreBackupKeys button:button[name="submitRestoreKeys"]').prop("disabled", true); + OC.Encryption.deleteKeys(); + }); + $('#decryptAll input:password[name="privateKeyPassword"]').keyup(function(event) { var privateKeyPassword = $('#decryptAll input:password[id="privateKeyPassword"]').val(); if (privateKeyPassword !== '' ) { - $('#decryptAll button:button[name="submitDecryptAll"]').removeAttr("disabled"); + $('#decryptAll button:button[name="submitDecryptAll"]').prop("disabled", false); if(event.which === 13) { $('#decryptAll button:button[name="submitDecryptAll"]').prop("disabled", true); $('#decryptAll input:password[name="privateKeyPassword"]').prop("disabled", true); OC.Encryption.decryptAll(privateKeyPassword); } } else { - $('#decryptAll button:button[name="submitDecryptAll"]').attr("disabled", "true"); + $('#decryptAll button:button[name="submitDecryptAll"]').prop("disabled", true); } }); @@ -294,29 +307,59 @@ $(document).ready(function(){ OC.Encryption = { decryptAll: function(password) { - OC.Encryption.msg.startDecrypting('#decryptAll .msg'); + var message = t('settings', 'Decrypting files... Please wait, this can take some time.'); + OC.Encryption.msg.start('#decryptAll .msg', message); $.post('ajax/decryptall.php', {password:password}, function(data) { if (data.status === "error") { - OC.Encryption.msg.finishedDecrypting('#decryptAll .msg', data); - $('#decryptAll input:password[name="privateKeyPassword"]').removeAttr("disabled"); + OC.Encryption.msg.finished('#decryptAll .msg', data); + $('#decryptAll input:password[name="privateKeyPassword"]').prop("disabled", false); + } else { + OC.Encryption.msg.finished('#decryptAll .msg', data); + } + $('#restoreBackupKeys').removeClass('hidden'); + }); + }, + + deleteKeys: function() { + var message = t('settings', 'Delete encryptin keys permanently.'); + OC.Encryption.msg.start('#restoreBackupKeys .msg', message); + $.post('ajax/deletekeys.php', null, function(data) { + if (data.status === "error") { + OC.Encryption.msg.finished('#restoreBackupKeys .msg', data); + $('#restoreBackupKeys button:button[name="submitDeleteKeys"]').prop("disabled", false); + $('#restoreBackupKeys button:button[name="submitRestoreKeys"]').prop("disabled", false); + } else { + OC.Encryption.msg.finished('#restoreBackupKeys .msg', data); + } + }); + }, + + restoreKeys: function() { + var message = t('settings', 'Restore encryptin keys.'); + OC.Encryption.msg.start('#restoreBackupKeys .msg', message); + $.post('ajax/restorekeys.php', {}, function(data) { + if (data.status === "error") { + OC.Encryption.msg.finished('#restoreBackupKeys .msg', data); + $('#restoreBackupKeys button:button[name="submitDeleteKeys"]').prop("disabled", false); + $('#restoreBackupKeys button:button[name="submitRestoreKeys"]').prop("disabled", false); } else { - OC.Encryption.msg.finishedDecrypting('#decryptAll .msg', data); + OC.Encryption.msg.finished('#restoreBackupKeys .msg', data); } }); } }; OC.Encryption.msg={ - startDecrypting:function(selector){ + start:function(selector, msg){ var spinner = ''; $(selector) - .html( t('settings', 'Decrypting files... Please wait, this can take some time.') + ' ' + spinner ) + .html( msg + ' ' + spinner ) .removeClass('success') .removeClass('error') .stop(true, true) .show(); }, - finishedDecrypting:function(selector, data){ + finished:function(selector, data){ if( data.status === "success" ){ $(selector).html( data.data.message ) .addClass('success') diff --git a/settings/personal.php b/settings/personal.php index 0da14a8c8c4..47b2dc1a46a 100644 --- a/settings/personal.php +++ b/settings/personal.php @@ -33,7 +33,9 @@ $userLang=OC_Preferences::getValue( OC_User::getUser(), 'core', 'lang', OC_L10N: $languageCodes=OC_L10N::findAvailableLanguages(); //check if encryption was enabled in the past -$enableDecryptAll = OC_Util::encryptedFiles(); +$filesStillEncrypted = OC_Util::encryptedFiles(); +$backupKeysExists = OC_Util::backupKeysExists(); +$enableDecryptAll = $filesStillEncrypted || $backupKeysExists; // array of common languages $commonlangcodes = array( @@ -92,6 +94,8 @@ $tmpl->assign('passwordChangeSupported', OC_User::canUserChangePassword(OC_User: $tmpl->assign('displayNameChangeSupported', OC_User::canUserChangeDisplayName(OC_User::getUser())); $tmpl->assign('displayName', OC_User::getDisplayName()); $tmpl->assign('enableDecryptAll' , $enableDecryptAll); +$tmpl->assign('backupKeysExists' , $backupKeysExists); +$tmpl->assign('filesStillEncrypted' , $filesStillEncrypted); $tmpl->assign('enableAvatars', \OC_Config::getValue('enable_avatars', true)); $tmpl->assign('avatarChangeSupported', OC_User::canUserChangeAvatar(OC_User::getUser())); diff --git a/settings/routes.php b/settings/routes.php index a8bb0d981e8..21d406beeca 100644 --- a/settings/routes.php +++ b/settings/routes.php @@ -54,6 +54,10 @@ $this->create('settings_ajax_setlanguage', '/settings/ajax/setlanguage.php') ->actionInclude('settings/ajax/setlanguage.php'); $this->create('settings_ajax_decryptall', '/settings/ajax/decryptall.php') ->actionInclude('settings/ajax/decryptall.php'); +$this->create('settings_ajax_restorekeys', '/settings/ajax/restorekeys.php') + ->actionInclude('settings/ajax/restorekeys.php'); +$this->create('settings_ajax_deletekeys', '/settings/ajax/deletekeys.php') + ->actionInclude('settings/ajax/deletekeys.php'); // apps $this->create('settings_ajax_apps_ocs', '/settings/ajax/apps/ocs.php') ->actionInclude('settings/ajax/apps/ocs.php'); diff --git a/settings/templates/personal.php b/settings/templates/personal.php index cc1fce88c9f..afa3f5d700a 100644 --- a/settings/templates/personal.php +++ b/settings/templates/personal.php @@ -144,10 +144,15 @@ if($_['passwordChangeSupported']) { };?> -
+
+

t( 'Encryption' ) ); ?>

+ + + +
t( "The encryption app is no longer enabled, please decrypt all your files" )); ?>


+
+ + + + + +
> + + t( "Your encryption keys are moved to a backup location. If something went wrong you can restore the keys. Only delete them permanently if you are sure that all files are decrypted correctly." )); ?> +

+ + + + +

+
+ +
+ +
- +

t('Version'));?>

-- cgit v1.2.3 From bab8c1f8e51a93443c29fdabfdc9951d0efde473 Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Tue, 13 May 2014 14:17:51 +0200 Subject: Fixed getAbsolutePath case when path is "0" Make sure to correctly check for string emptiness when the passed path is "0". --- lib/private/files/view.php | 2 +- tests/lib/files/view.php | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/files/view.php b/lib/private/files/view.php index 407f5981957..39c71cfc0b0 100644 --- a/lib/private/files/view.php +++ b/lib/private/files/view.php @@ -37,7 +37,7 @@ class View { } public function getAbsolutePath($path = '/') { - if (!$path) { + if ($path === '') { $path = '/'; } if ($path[0] !== '/') { diff --git a/tests/lib/files/view.php b/tests/lib/files/view.php index f80dd06e1cb..a51b15857d5 100644 --- a/tests/lib/files/view.php +++ b/tests/lib/files/view.php @@ -585,4 +585,22 @@ class View extends \PHPUnit_Framework_TestCase { $info2 = $view->getFileInfo('/test/test'); $this->assertSame($info['etag'], $info2['etag']); } + + /** + * @dataProvider absolutePathProvider + */ + public function testGetAbsolutePath($expectedPath, $relativePath) { + $view = new \OC\Files\View('/files'); + $this->assertEquals($expectedPath, $view->getAbsolutePath($relativePath)); + } + + function absolutePathProvider() { + return array( + array('/files/', ''), + array('/files/0', '0'), + array('/files/', '/'), + array('/files/test', 'test'), + array('/files/test', '/test'), + ); + } } -- cgit v1.2.3 From b653ad164b83afbc07d7a82d2e4461dace28ba6a Mon Sep 17 00:00:00 2001 From: Robin McCorkell Date: Sun, 11 May 2014 18:05:28 +0100 Subject: Replace @returns with @return, in /lib --- lib/private/group.php | 6 +++--- lib/private/group/dummy.php | 18 +++++++++--------- lib/private/group/example.php | 16 ++++++++-------- lib/private/helper.php | 2 +- lib/private/installer.php | 2 +- lib/private/l10n.php | 20 ++++++++++---------- lib/private/ocsclient.php | 12 ++++++------ lib/private/request.php | 10 +++++----- lib/private/template/functions.php | 2 +- lib/private/user.php | 8 ++++---- lib/private/user/backend.php | 4 ++-- lib/private/user/database.php | 16 ++++++++-------- lib/private/user/example.php | 8 ++++---- lib/private/user/http.php | 2 +- lib/private/user/interface.php | 8 ++++---- lib/private/vobject.php | 6 +++--- lib/public/itags.php | 2 +- lib/public/util.php | 2 +- 18 files changed, 72 insertions(+), 72 deletions(-) (limited to 'lib/private') diff --git a/lib/private/group.php b/lib/private/group.php index ea6384bae3e..3191de5310a 100644 --- a/lib/private/group.php +++ b/lib/private/group.php @@ -203,7 +203,7 @@ class OC_Group { * @param string $search * @param int|null $limit * @param int|null $offset - * @returns array with group names + * @return array with group names * * Returns a list with all groups */ @@ -232,7 +232,7 @@ class OC_Group { * @param string $search * @param int $limit * @param int $offset - * @returns array with user ids + * @return array with user ids */ public static function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { $group = self::getManager()->get($gid); @@ -271,7 +271,7 @@ class OC_Group { * @param string $search * @param int $limit * @param int $offset - * @returns array with display names (value) and user ids(key) + * @return array with display names (value) and user ids(key) */ public static function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) { return self::getManager()->displayNamesInGroup($gid, $search, $limit, $offset); diff --git a/lib/private/group/dummy.php b/lib/private/group/dummy.php index 94cbb607ad1..37987f20128 100644 --- a/lib/private/group/dummy.php +++ b/lib/private/group/dummy.php @@ -29,7 +29,7 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief Try to create a new group * @param string $gid The name of the group to create - * @returns true/false + * @return true/false * * Trys to create a new group. If the group name already exists, false will * be returned. @@ -46,7 +46,7 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief delete a group * @param $gid gid of the group to delete - * @returns true/false + * @return true/false * * Deletes a group and removes it from the group_user-table */ @@ -63,7 +63,7 @@ class OC_Group_Dummy extends OC_Group_Backend { * @brief is user in group? * @param $uid uid of the user * @param $gid gid of the group - * @returns true/false + * @return true/false * * Checks whether the user is member of a group or not. */ @@ -79,7 +79,7 @@ class OC_Group_Dummy extends OC_Group_Backend { * @brief Add a user to a group * @param $uid Name of the user to add to group * @param $gid Name of the group in which add the user - * @returns true/false + * @return true/false * * Adds a user to a group. */ @@ -100,7 +100,7 @@ class OC_Group_Dummy extends OC_Group_Backend { * @brief Removes a user from a group * @param $uid NameUSER of the user to remove from group * @param $gid Name of the group from which remove the user - * @returns true/false + * @return true/false * * removes the user from a group. */ @@ -119,7 +119,7 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief Get all groups a user belongs to * @param $uid Name of the user - * @returns array with group names + * @return array with group names * * This function fetches all groups a user belongs to. It does not check * if the user exists at all. @@ -137,7 +137,7 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief get a list of all groups - * @returns array with group names + * @return array with group names * * Returns a list with all groups */ @@ -147,7 +147,7 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief get a list of all users in a group - * @returns array with user ids + * @return array with user ids */ public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { if(isset($this->groups[$gid])) { @@ -159,7 +159,7 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief get the number of all users in a group - * @returns int | bool + * @return int | bool */ public function countUsersInGroup($gid, $search = '', $limit = -1, $offset = 0) { if(isset($this->groups[$gid])) { diff --git a/lib/private/group/example.php b/lib/private/group/example.php index 3519b9ed92f..bcd6f814356 100644 --- a/lib/private/group/example.php +++ b/lib/private/group/example.php @@ -29,7 +29,7 @@ abstract class OC_Group_Example { /** * @brief Try to create a new group * @param $gid The name of the group to create - * @returns true/false + * @return true/false * * Trys to create a new group. If the group name already exists, false will * be returned. @@ -39,7 +39,7 @@ abstract class OC_Group_Example { /** * @brief delete a group * @param $gid gid of the group to delete - * @returns true/false + * @return true/false * * Deletes a group and removes it from the group_user-table */ @@ -49,7 +49,7 @@ abstract class OC_Group_Example { * @brief is user in group? * @param $uid uid of the user * @param $gid gid of the group - * @returns true/false + * @return true/false * * Checks whether the user is member of a group or not. */ @@ -59,7 +59,7 @@ abstract class OC_Group_Example { * @brief Add a user to a group * @param $uid Name of the user to add to group * @param $gid Name of the group in which add the user - * @returns true/false + * @return true/false * * Adds a user to a group. */ @@ -69,7 +69,7 @@ abstract class OC_Group_Example { * @brief Removes a user from a group * @param $uid NameUSER of the user to remove from group * @param $gid Name of the group from which remove the user - * @returns true/false + * @return true/false * * removes the user from a group. */ @@ -78,7 +78,7 @@ abstract class OC_Group_Example { /** * @brief Get all groups a user belongs to * @param $uid Name of the user - * @returns array with group names + * @return array with group names * * This function fetches all groups a user belongs to. It does not check * if the user exists at all. @@ -87,7 +87,7 @@ abstract class OC_Group_Example { /** * @brief get a list of all groups - * @returns array with group names + * @return array with group names * * Returns a list with all groups */ @@ -102,7 +102,7 @@ abstract class OC_Group_Example { /** * @brief get a list of all users in a group - * @returns array with user ids + * @return array with user ids */ abstract public static function usersInGroup($gid, $search = '', $limit = -1, $offset = 0); diff --git a/lib/private/helper.php b/lib/private/helper.php index 6bc054bce86..ae957846082 100644 --- a/lib/private/helper.php +++ b/lib/private/helper.php @@ -36,7 +36,7 @@ class OC_Helper { * @param array $parameters * @return * @internal param array $args with param=>value, will be appended to the returned url - * @returns string the url + * @return string the url * * Returns a url to the given app and file. */ diff --git a/lib/private/installer.php b/lib/private/installer.php index 64e8e3a5e7a..d7d43779d92 100644 --- a/lib/private/installer.php +++ b/lib/private/installer.php @@ -221,7 +221,7 @@ class OC_Installer{ /** * @brief checks whether or not an app is installed * @param string $app app - * @returns true/false + * @return true/false * * Checks whether or not an app is installed, i.e. registered in apps table. */ diff --git a/lib/private/l10n.php b/lib/private/l10n.php index c1596a64163..9ab60e871d0 100644 --- a/lib/private/l10n.php +++ b/lib/private/l10n.php @@ -278,7 +278,7 @@ class OC_L10N implements \OCP\IL10N { /** * @brief getTranslations - * @returns array Fetch all translations + * @return array Fetch all translations * * Returns an associative array with all translations */ @@ -289,7 +289,7 @@ class OC_L10N implements \OCP\IL10N { /** * @brief getPluralFormString - * @returns string containing the gettext "Plural-Forms"-string + * @return string containing the gettext "Plural-Forms"-string * * Returns a string like "nplurals=2; plural=(n != 1);" */ @@ -300,7 +300,7 @@ class OC_L10N implements \OCP\IL10N { /** * @brief getPluralFormFunction - * @returns string the plural form function + * @return string the plural form function * * returned function accepts the argument $n */ @@ -314,7 +314,7 @@ class OC_L10N implements \OCP\IL10N { /** * @brief get localizations - * @returns array Fetch all localizations + * @return array Fetch all localizations * * Returns an associative array with all localizations */ @@ -327,7 +327,7 @@ class OC_L10N implements \OCP\IL10N { * @brief Localization * @param string $type Type of localization * @param array|int|string $data parameters for this localization - * @returns String or false + * @return String or false * * Returns the localized data. * @@ -381,7 +381,7 @@ class OC_L10N implements \OCP\IL10N { /** * @brief Choose a language * @param array $text Associative Array with possible strings - * @returns String + * @return String * * $text is an array 'de' => 'hallo welt', 'en' => 'hello world', ... * @@ -404,7 +404,7 @@ class OC_L10N implements \OCP\IL10N { /** * @brief find the best language * @param array|string $app details below - * @returns string language + * @return string language * * If $app is an array, ownCloud assumes that these are the available * languages. Otherwise ownCloud tries to find the files in the l10n @@ -477,7 +477,7 @@ class OC_L10N implements \OCP\IL10N { /** * @brief find the l10n directory * @param string $app App that needs to be translated - * @returns directory + * @return directory */ protected static function findI18nDir($app) { // find the i18n dir @@ -497,7 +497,7 @@ class OC_L10N implements \OCP\IL10N { /** * @brief find all available languages for an app * @param string $app App that needs to be translated - * @returns array an array of available languages + * @return array an array of available languages */ public static function findAvailableLanguages($app=null) { $available=array('en');//english is always available @@ -517,7 +517,7 @@ class OC_L10N implements \OCP\IL10N { /** * @param string $app * @param string $lang - * @returns bool + * @return bool */ public static function languageExists($app, $lang) { if ($lang == 'en') {//english is always available diff --git a/lib/private/ocsclient.php b/lib/private/ocsclient.php index b0480caf028..a08c862b0cb 100644 --- a/lib/private/ocsclient.php +++ b/lib/private/ocsclient.php @@ -30,7 +30,7 @@ class OC_OCSClient{ /** * @brief Get the url of the OCS AppStore server. - * @returns string of the AppStore server + * @return string of the AppStore server * * This function returns the url of the OCS AppStore server. It´s possible * to set it in the config file or it will fallback to the default @@ -48,7 +48,7 @@ class OC_OCSClient{ /** * @brief Get the content of an OCS url call. - * @returns string of the response + * @return string of the response * This function calls an OCS server and returns the response. It also sets a sane timeout * @param string $url */ @@ -59,7 +59,7 @@ class OC_OCSClient{ /** * @brief Get all the categories from the OCS server - * @returns array with category ids + * @return array with category ids * @note returns NULL if config value appstoreenabled is set to false * This function returns a list of all the application categories on the OCS server */ @@ -92,7 +92,7 @@ class OC_OCSClient{ /** * @brief Get all the applications from the OCS server - * @returns array with application data + * @return array with application data * * This function returns a list of all the applications on the OCS server * @param $categories @@ -150,7 +150,7 @@ class OC_OCSClient{ /** * @brief Get an the applications from the OCS server * @param string $id - * @returns array with application data + * @return array with application data * * This function returns an applications from the OCS server */ @@ -192,7 +192,7 @@ class OC_OCSClient{ /** * @brief Get the download url for an application from the OCS server - * @returns array with application data + * @return array with application data * * This function returns an download url for an applications from the OCS server * @param string $id diff --git a/lib/private/request.php b/lib/private/request.php index 90f7488eea5..cf9a316b851 100755 --- a/lib/private/request.php +++ b/lib/private/request.php @@ -18,7 +18,7 @@ class OC_Request { /** * @brief Check overwrite condition * @param string $type - * @returns bool + * @return bool */ private static function isOverwriteCondition($type = '') { $regex = '/' . OC_Config::getValue('overwritecondaddr', '') . '/'; @@ -49,7 +49,7 @@ class OC_Request { /** * @brief Returns the unverified server host from the headers without checking * whether it is a trusted domain - * @returns string the server host + * @return string the server host * * Returns the server host, even if the website uses one or more * reverse proxies @@ -89,7 +89,7 @@ class OC_Request { /** * @brief Returns the server host from the headers, or the first configured * trusted domain if the host isn't in the trusted list - * @returns string the server host + * @return string the server host * * Returns the server host, even if the website uses one or more * reverse proxies @@ -121,7 +121,7 @@ class OC_Request { /** * @brief Returns the server protocol - * @returns string the server protocol + * @return string the server protocol * * Returns the server protocol. It respects reverse proxy servers and load balancers */ @@ -143,7 +143,7 @@ class OC_Request { /** * @brief Returns the request uri - * @returns string the request uri + * @return string the request uri * * Returns the request uri, even if the website uses one or more * reverse proxies diff --git a/lib/private/template/functions.php b/lib/private/template/functions.php index 3c42d441efa..0a32dc48f22 100644 --- a/lib/private/template/functions.php +++ b/lib/private/template/functions.php @@ -71,7 +71,7 @@ function mimetype_icon( $mimetype ) { * @brief make preview_icon available as a simple function * Returns the path to the preview of the image. * @param $path path of file - * @returns link to the preview + * @return link to the preview * * For further information have a look at OC_Helper::previewIcon */ diff --git a/lib/private/user.php b/lib/private/user.php index 7106d664aca..bf101a29b99 100644 --- a/lib/private/user.php +++ b/lib/private/user.php @@ -77,7 +77,7 @@ class OC_User { /** * @brief gets available backends * @deprecated - * @returns array of backends + * @return array of backends * * Returns the names of all backends. */ @@ -88,7 +88,7 @@ class OC_User { /** * @brief gets used backends * @deprecated - * @returns array of backends + * @return array of backends * * Returns the names of all used backends. */ @@ -321,7 +321,7 @@ class OC_User { /** * @brief Check if the user is logged in - * @returns bool + * @return bool * * Checks if the user is logged in */ @@ -517,7 +517,7 @@ class OC_User { /** * @brief Get a list of all users - * @returns array with all uids + * @return array with all uids * * Get a list of all users. * @param string $search diff --git a/lib/private/user/backend.php b/lib/private/user/backend.php index f4e5618e04a..3994c1bb8ff 100644 --- a/lib/private/user/backend.php +++ b/lib/private/user/backend.php @@ -103,7 +103,7 @@ abstract class OC_User_Backend implements OC_User_Interface { /** * @brief Get a list of all users - * @returns array with all uids + * @return array with all uids * * Get a list of all users. */ @@ -140,7 +140,7 @@ abstract class OC_User_Backend implements OC_User_Interface { /** * @brief Get a list of all display names - * @returns array with all displayNames (value) and the corresponding uids (key) + * @return array with all displayNames (value) and the corresponding uids (key) * * Get a list of all display names and user ids. */ diff --git a/lib/private/user/database.php b/lib/private/user/database.php index dec38464f98..d70ccd8ad43 100644 --- a/lib/private/user/database.php +++ b/lib/private/user/database.php @@ -59,7 +59,7 @@ class OC_User_Database extends OC_User_Backend { * @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 + * @return true/false * * Creates a new user. Basic checking of username is done in OC_User * itself, not in its subclasses. @@ -80,7 +80,7 @@ class OC_User_Database extends OC_User_Backend { /** * @brief delete a user * @param $uid The username of the user to delete - * @returns true/false + * @return true/false * * Deletes a user */ @@ -100,7 +100,7 @@ class OC_User_Database extends OC_User_Backend { * @brief Set password * @param $uid The username * @param $password The new password - * @returns true/false + * @return true/false * * Change the password of a user */ @@ -121,7 +121,7 @@ class OC_User_Database extends OC_User_Backend { * @brief Set display name * @param $uid The username * @param $displayName The new display name - * @returns true/false + * @return true/false * * Change the display name of a user */ @@ -149,7 +149,7 @@ class OC_User_Database extends OC_User_Backend { /** * @brief Get a list of all display names - * @returns array with all displayNames (value) and the correspondig uids (key) + * @return array with all displayNames (value) and the correspondig uids (key) * * Get a list of all display names and user ids. */ @@ -171,7 +171,7 @@ class OC_User_Database extends OC_User_Backend { * @brief Check if the password is correct * @param $uid The username * @param $password The password - * @returns string + * @return string * * Check if the password is correct without logging in the user * returns the user id or false @@ -203,7 +203,7 @@ class OC_User_Database extends OC_User_Backend { /** * @brief Load an user in the cache * @param string $uid the username - * @returns boolean + * @return boolean */ private function loadUser($uid) { if (empty($this->cache[$uid])) { @@ -226,7 +226,7 @@ class OC_User_Database extends OC_User_Backend { /** * @brief Get a list of all users - * @returns array with all uids + * @return array with all uids * * Get a list of all users. */ diff --git a/lib/private/user/example.php b/lib/private/user/example.php index b2d0dc25410..e6e2744b405 100644 --- a/lib/private/user/example.php +++ b/lib/private/user/example.php @@ -30,7 +30,7 @@ abstract class OC_User_Example extends OC_User_Backend { * @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 + * @return true/false * * Creates a new user. Basic checking of username is done in OC_User * itself, not in its subclasses. @@ -41,7 +41,7 @@ abstract class OC_User_Example extends OC_User_Backend { * @brief Set password * @param $uid The username * @param $password The new password - * @returns true/false + * @return true/false * * Change the password of a user */ @@ -51,7 +51,7 @@ abstract class OC_User_Example extends OC_User_Backend { * @brief Check if the password is correct * @param $uid The username * @param $password The password - * @returns string + * @return string * * Check if the password is correct without logging in the user * returns the user id or false @@ -61,7 +61,7 @@ abstract class OC_User_Example extends OC_User_Backend { /** * @brief get the user's home directory * @param $uid The username - * @returns string + * @return string * * get the user's home directory * returns the path or false diff --git a/lib/private/user/http.php b/lib/private/user/http.php index a0394521012..806378a7c2c 100644 --- a/lib/private/user/http.php +++ b/lib/private/user/http.php @@ -57,7 +57,7 @@ class OC_User_HTTP extends OC_User_Backend { * @brief Check if the password is correct * @param $uid The username * @param $password The password - * @returns string + * @return string * * Check if the password is correct without logging in the user * returns the user id or false diff --git a/lib/private/user/interface.php b/lib/private/user/interface.php index cdcab3e5d00..eee18aea167 100644 --- a/lib/private/user/interface.php +++ b/lib/private/user/interface.php @@ -26,7 +26,7 @@ interface OC_User_Interface { /** * @brief Check if backend implements actions * @param $actions bitwise-or'ed actions - * @returns boolean + * @return boolean * * Returns the supported actions as int to be * compared with OC_USER_BACKEND_CREATE_USER etc. @@ -37,7 +37,7 @@ interface OC_User_Interface { /** * @brief delete a user * @param $uid The username of the user to delete - * @returns true/false + * @return true/false * * Deletes a user * @return boolean @@ -46,7 +46,7 @@ interface OC_User_Interface { /** * @brief Get a list of all users - * @returns array with all uids + * @return array with all uids * * Get a list of all users. */ @@ -68,7 +68,7 @@ interface OC_User_Interface { /** * @brief Get a list of all display names - * @returns array with all displayNames (value) and the corresponding uids (key) + * @return array with all displayNames (value) and the corresponding uids (key) * * Get a list of all display names and user ids. */ diff --git a/lib/private/vobject.php b/lib/private/vobject.php index a3e9f7ef790..20cacd926ba 100644 --- a/lib/private/vobject.php +++ b/lib/private/vobject.php @@ -28,7 +28,7 @@ class OC_VObject{ protected $vobject; /** - * @returns Sabre\VObject\Component + * @return Sabre\VObject\Component */ public function getVObject() { return $this->vobject; @@ -37,7 +37,7 @@ class OC_VObject{ /** * @brief Parses the VObject * @param string $data VObject as string - * @returns Sabre\VObject\Reader|null + * @return Sabre\VObject\Reader|null */ public static function parse($data) { try { @@ -116,7 +116,7 @@ class OC_VObject{ * @param object $name of property * @param object $value of property * @param array|object $parameters of property - * @returns Sabre\VObject\Property newly created + * @return Sabre\VObject\Property newly created */ public function addProperty($name, $value, $parameters=array()) { if(is_array($value)) { diff --git a/lib/public/itags.php b/lib/public/itags.php index f8ebaa668f1..1cba07e9b53 100644 --- a/lib/public/itags.php +++ b/lib/public/itags.php @@ -62,7 +62,7 @@ interface ITags { * ['id' => 1, 'name' = 'Second tag'], * ] * - * @returns array + * @return array */ public function getTags(); diff --git a/lib/public/util.php b/lib/public/util.php index 3b0fc09f7e5..006a828dca2 100644 --- a/lib/public/util.php +++ b/lib/public/util.php @@ -293,7 +293,7 @@ class Util { /** * Returns the script name, even if the website uses one or more reverse proxies - * @returns string the script name + * @return string the script name */ public static function getScriptName() { return(\OC_Request::scriptName()); -- cgit v1.2.3 From b5bc37d2e40aba0ab8d3e72e7f7075352839096d Mon Sep 17 00:00:00 2001 From: Robin McCorkell Date: Sun, 11 May 2014 18:13:51 +0100 Subject: Fix @return array PHPDocs, in /lib --- lib/private/app.php | 4 ++-- lib/private/appconfig.php | 4 ++-- lib/private/config.php | 2 +- lib/private/contactsmanager.php | 4 ++-- lib/private/files/cache/cache.php | 2 +- lib/private/files/cache/scanner.php | 6 +++--- lib/private/files/cache/updater.php | 2 +- lib/private/files/filesystem.php | 2 +- lib/private/files/view.php | 2 +- lib/private/group.php | 12 ++++++------ lib/private/group/backend.php | 6 +++--- lib/private/group/database.php | 6 +++--- lib/private/group/dummy.php | 6 +++--- lib/private/group/example.php | 6 +++--- lib/private/group/interface.php | 6 +++--- lib/private/group/manager.php | 2 +- lib/private/legacy/appconfig.php | 4 ++-- lib/private/legacy/config.php | 2 +- lib/private/legacy/preferences.php | 4 ++-- lib/private/migrate.php | 2 +- lib/private/navigationmanager.php | 2 +- lib/private/ocsclient.php | 8 ++++---- lib/private/preferences.php | 4 ++-- lib/private/preview.php | 2 +- lib/private/share/mailnotifications.php | 2 +- lib/private/user.php | 6 +++--- lib/private/user/backend.php | 4 ++-- lib/private/user/database.php | 4 ++-- lib/private/user/interface.php | 4 ++-- lib/private/user/manager.php | 2 +- lib/private/util.php | 2 +- lib/public/backgroundjob.php | 4 ++-- lib/public/contacts.php | 4 ++-- lib/public/contacts/imanager.php | 4 ++-- lib/public/iaddressbook.php | 4 ++-- lib/public/iappconfig.php | 4 ++-- lib/public/user.php | 4 ++-- lib/public/util.php | 2 +- 38 files changed, 75 insertions(+), 75 deletions(-) (limited to 'lib/private') diff --git a/lib/private/app.php b/lib/private/app.php index 2f55b54b328..a35248f2552 100644 --- a/lib/private/app.php +++ b/lib/private/app.php @@ -307,7 +307,7 @@ class OC_App{ /** * @brief Get the navigation entries for the $app * @param string $app app - * @return array of the $data added with addNavigationEntry + * @return array an array of the $data added with addNavigationEntry * * Warning: destroys the existing entries */ @@ -660,7 +660,7 @@ class OC_App{ /** * @brief: get a list of all apps in the apps folder - * @return array or app names (string IDs) + * @return array an array of app names (string IDs) * @todo: change the name of this method to getInstalledApps, which is more accurate */ public static function getAllApps() { diff --git a/lib/private/appconfig.php b/lib/private/appconfig.php index 0cd6b3bc35b..5fba7514de0 100644 --- a/lib/private/appconfig.php +++ b/lib/private/appconfig.php @@ -90,7 +90,7 @@ class AppConfig implements \OCP\IAppConfig { /** * @brief Get all apps using the config - * @return array with app ids + * @return array an array of app ids * * This function returns a list of all apps that have at least one * entry in the appconfig table. @@ -109,7 +109,7 @@ class AppConfig implements \OCP\IAppConfig { /** * @brief Get the available keys for an app * @param string $app the app we are looking for - * @return array with key names + * @return array an array of key names * * This function gets all keys of an app. Please note that the values are * not returned. diff --git a/lib/private/config.php b/lib/private/config.php index 6701ca0532b..2320db9d6bd 100644 --- a/lib/private/config.php +++ b/lib/private/config.php @@ -65,7 +65,7 @@ class Config { /** * @brief Lists all available config keys - * @return array with key names + * @return array an array of key names * * This function returns all keys saved in config.php. Please note that it * does not return the values. diff --git a/lib/private/contactsmanager.php b/lib/private/contactsmanager.php index 4299d88017a..26264d4e988 100644 --- a/lib/private/contactsmanager.php +++ b/lib/private/contactsmanager.php @@ -31,7 +31,7 @@ namespace OC { * @param string $pattern which should match within the $searchProperties * @param array $searchProperties defines the properties within the query pattern should match * @param array $options - for future use. One should always have options! - * @return array of contacts which are arrays of key-value-pairs + * @return array an array of contacts which are arrays of key-value-pairs */ public function search($pattern, $searchProperties = array(), $options = array()) { $result = array(); @@ -72,7 +72,7 @@ namespace OC { * * @param array $properties this array if key-value-pairs defines a contact * @param string $address_book_key identifier of the address book in which the contact shall be created or updated - * @return array representing the contact just created or updated + * @return array an array representing the contact just created or updated */ public function createOrUpdate($properties, $address_book_key) { diff --git a/lib/private/files/cache/cache.php b/lib/private/files/cache/cache.php index c4f03b4d9ef..e857d451881 100644 --- a/lib/private/files/cache/cache.php +++ b/lib/private/files/cache/cache.php @@ -450,7 +450,7 @@ class Cache { * search for files matching $pattern * * @param string $pattern - * @return array of file data + * @return array an array of file data */ public function search($pattern) { diff --git a/lib/private/files/cache/scanner.php b/lib/private/files/cache/scanner.php index c0bdde06a75..8c2ec057ca7 100644 --- a/lib/private/files/cache/scanner.php +++ b/lib/private/files/cache/scanner.php @@ -61,7 +61,7 @@ class Scanner extends BasicEmitter { * * * * @param string $path - * @return array with metadata of the file + * @return array an array of metadata of the file */ public function getData($path) { if (!$this->storage->isReadable($path)) { @@ -88,7 +88,7 @@ class Scanner extends BasicEmitter { * @param string $file * @param int $reuseExisting * @param bool $parentExistsInCache - * @return array with metadata of the scanned file + * @return array an array of metadata of the scanned file */ public function scanFile($file, $reuseExisting = 0, $parentExistsInCache = false) { if (!self::isPartialFile($file) @@ -174,7 +174,7 @@ class Scanner extends BasicEmitter { * @param string $path * @param bool $recursive * @param int $reuse - * @return array with the meta data of the scanned file or folder + * @return array an array of the meta data of the scanned file or folder */ public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1) { if ($reuse === -1) { diff --git a/lib/private/files/cache/updater.php b/lib/private/files/cache/updater.php index 199ce5dee78..95f77a81fa2 100644 --- a/lib/private/files/cache/updater.php +++ b/lib/private/files/cache/updater.php @@ -17,7 +17,7 @@ class Updater { * resolve a path to a storage and internal path * * @param string $path the relative path - * @return array consisting of the storage and the internal path + * @return array an array consisting of the storage and the internal path */ static public function resolvePath($path) { $view = \OC\Files\Filesystem::getView(); diff --git a/lib/private/files/filesystem.php b/lib/private/files/filesystem.php index 52df1bec611..a4994e4dfb6 100644 --- a/lib/private/files/filesystem.php +++ b/lib/private/files/filesystem.php @@ -270,7 +270,7 @@ class Filesystem { * resolve a path to a storage and internal path * * @param string $path - * @return array consisting of the storage and the internal path + * @return array an array consisting of the storage and the internal path */ static public function resolvePath($path) { if (!self::$mounts) { diff --git a/lib/private/files/view.php b/lib/private/files/view.php index 39c71cfc0b0..d3772e264a0 100644 --- a/lib/private/files/view.php +++ b/lib/private/files/view.php @@ -109,7 +109,7 @@ class View { * resolve a path to a storage and internal path * * @param string $path - * @return array consisting of the storage and the internal path + * @return array an array consisting of the storage and the internal path */ public function resolvePath($path) { $a = $this->getAbsolutePath($path); diff --git a/lib/private/group.php b/lib/private/group.php index 3191de5310a..5b291d7f2f6 100644 --- a/lib/private/group.php +++ b/lib/private/group.php @@ -179,7 +179,7 @@ class OC_Group { /** * @brief Get all groups a user belongs to * @param string $uid Name of the user - * @return array with group names + * @return array an array of group names * * This function fetches all groups a user belongs to. It does not check * if the user exists at all. @@ -203,7 +203,7 @@ class OC_Group { * @param string $search * @param int|null $limit * @param int|null $offset - * @return array with group names + * @return array an array of group names * * Returns a list with all groups */ @@ -232,7 +232,7 @@ class OC_Group { * @param string $search * @param int $limit * @param int $offset - * @return array with user ids + * @return array an array of user ids */ public static function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { $group = self::getManager()->get($gid); @@ -254,7 +254,7 @@ class OC_Group { * @param string $search * @param int $limit * @param int $offset - * @return array with user ids + * @return array an array of user ids */ public static function usersInGroups($gids, $search = '', $limit = -1, $offset = 0) { $users = array(); @@ -271,7 +271,7 @@ class OC_Group { * @param string $search * @param int $limit * @param int $offset - * @return array with display names (value) and user ids(key) + * @return array an array of display names (value) and user ids(key) */ public static function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) { return self::getManager()->displayNamesInGroup($gid, $search, $limit, $offset); @@ -283,7 +283,7 @@ class OC_Group { * @param string $search * @param int $limit * @param int $offset - * @return array with display names (Key) user ids (value) + * @return array an array of display names (Key) user ids (value) */ public static function displayNamesInGroups($gids, $search = '', $limit = -1, $offset = 0) { $displayNames = array(); diff --git a/lib/private/group/backend.php b/lib/private/group/backend.php index cc61fce1615..c1de99bca58 100644 --- a/lib/private/group/backend.php +++ b/lib/private/group/backend.php @@ -93,7 +93,7 @@ abstract class OC_Group_Backend implements OC_Group_Interface { /** * @brief Get all groups a user belongs to * @param string $uid Name of the user - * @return array with group names + * @return array an array of group names * * This function fetches all groups a user belongs to. It does not check * if the user exists at all. @@ -107,7 +107,7 @@ abstract class OC_Group_Backend implements OC_Group_Interface { * @param string $search * @param int $limit * @param int $offset - * @return array with group names + * @return array an array of group names * * Returns a list with all groups */ @@ -131,7 +131,7 @@ abstract class OC_Group_Backend implements OC_Group_Interface { * @param string $search * @param int $limit * @param int $offset - * @return array with user ids + * @return array an array of user ids */ public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { return array(); diff --git a/lib/private/group/database.php b/lib/private/group/database.php index df0d84d0d2a..abdf09a9222 100644 --- a/lib/private/group/database.php +++ b/lib/private/group/database.php @@ -140,7 +140,7 @@ class OC_Group_Database extends OC_Group_Backend { /** * @brief Get all groups a user belongs to * @param string $uid Name of the user - * @return array with group names + * @return array an array of group names * * This function fetches all groups a user belongs to. It does not check * if the user exists at all. @@ -163,7 +163,7 @@ class OC_Group_Database extends OC_Group_Backend { * @param string $search * @param int $limit * @param int $offset - * @return array with group names + * @return array an array of group names * * Returns a list with all groups */ @@ -197,7 +197,7 @@ class OC_Group_Database extends OC_Group_Backend { * @param string $search * @param int $limit * @param int $offset - * @return array with user ids + * @return array an array of user ids */ public function usersInGroup($gid, $search = '', $limit = null, $offset = null) { $stmt = OC_DB::prepare('SELECT `uid` FROM `*PREFIX*group_user` WHERE `gid` = ? AND `uid` LIKE ?', diff --git a/lib/private/group/dummy.php b/lib/private/group/dummy.php index 37987f20128..1ef81c6bf99 100644 --- a/lib/private/group/dummy.php +++ b/lib/private/group/dummy.php @@ -119,7 +119,7 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief Get all groups a user belongs to * @param $uid Name of the user - * @return array with group names + * @return array an array of group names * * This function fetches all groups a user belongs to. It does not check * if the user exists at all. @@ -137,7 +137,7 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief get a list of all groups - * @return array with group names + * @return array an array of group names * * Returns a list with all groups */ @@ -147,7 +147,7 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief get a list of all users in a group - * @return array with user ids + * @return array an array of user ids */ public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { if(isset($this->groups[$gid])) { diff --git a/lib/private/group/example.php b/lib/private/group/example.php index bcd6f814356..12be5421c1c 100644 --- a/lib/private/group/example.php +++ b/lib/private/group/example.php @@ -78,7 +78,7 @@ abstract class OC_Group_Example { /** * @brief Get all groups a user belongs to * @param $uid Name of the user - * @return array with group names + * @return array an array of group names * * This function fetches all groups a user belongs to. It does not check * if the user exists at all. @@ -87,7 +87,7 @@ abstract class OC_Group_Example { /** * @brief get a list of all groups - * @return array with group names + * @return array an array of group names * * Returns a list with all groups */ @@ -102,7 +102,7 @@ abstract class OC_Group_Example { /** * @brief get a list of all users in a group - * @return array with user ids + * @return array an array of user ids */ abstract public static function usersInGroup($gid, $search = '', $limit = -1, $offset = 0); diff --git a/lib/private/group/interface.php b/lib/private/group/interface.php index 4ef3663837f..74d288d42c0 100644 --- a/lib/private/group/interface.php +++ b/lib/private/group/interface.php @@ -45,7 +45,7 @@ interface OC_Group_Interface { /** * @brief Get all groups a user belongs to * @param string $uid Name of the user - * @return array with group names + * @return array an array of group names * * This function fetches all groups a user belongs to. It does not check * if the user exists at all. @@ -57,7 +57,7 @@ interface OC_Group_Interface { * @param string $search * @param int $limit * @param int $offset - * @return array with group names + * @return array an array of group names * * Returns a list with all groups */ @@ -76,7 +76,7 @@ interface OC_Group_Interface { * @param string $search * @param int $limit * @param int $offset - * @return array with user ids + * @return array an array of user ids */ public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0); diff --git a/lib/private/group/manager.php b/lib/private/group/manager.php index d31225e3c2e..3eb894a644a 100644 --- a/lib/private/group/manager.php +++ b/lib/private/group/manager.php @@ -165,7 +165,7 @@ class Manager extends PublicEmitter { * @param string $search * @param int $limit * @param int $offset - * @return array with display names (value) and user ids (key) + * @return array an array of display names (value) and user ids (key) */ public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) { $group = $this->get($gid); diff --git a/lib/private/legacy/appconfig.php b/lib/private/legacy/appconfig.php index cb5cef7e350..209f42ffe38 100644 --- a/lib/private/legacy/appconfig.php +++ b/lib/private/legacy/appconfig.php @@ -35,7 +35,7 @@ class OC_Appconfig { /** * @brief Get all apps using the config - * @return array with app ids + * @return array an array of app ids * * This function returns a list of all apps that have at least one * entry in the appconfig table. @@ -47,7 +47,7 @@ class OC_Appconfig { /** * @brief Get the available keys for an app * @param string $app the app we are looking for - * @return array with key names + * @return array an array of key names * * This function gets all keys of an app. Please note that the values are * not returned. diff --git a/lib/private/legacy/config.php b/lib/private/legacy/config.php index 6c2103179ab..76a53d3f627 100644 --- a/lib/private/legacy/config.php +++ b/lib/private/legacy/config.php @@ -51,7 +51,7 @@ class OC_Config { /** * @brief Lists all available config keys - * @return array with key names + * @return array an array of key names * * This function returns all keys saved in config.php. Please note that it * does not return the values. diff --git a/lib/private/legacy/preferences.php b/lib/private/legacy/preferences.php index fcde12796ca..eed6730a529 100644 --- a/lib/private/legacy/preferences.php +++ b/lib/private/legacy/preferences.php @@ -29,7 +29,7 @@ class OC_Preferences{ public static $object; /** * @brief Get all users using the preferences - * @return array with user ids + * @return array an array of user ids * * This function returns a list of all users that have at least one entry * in the preferences table. @@ -54,7 +54,7 @@ class OC_Preferences{ * @brief Get the available keys for an app * @param string $user user * @param string $app the app we are looking for - * @return array with key names + * @return array an array of key names * * This function gets all keys of an app of an user. Please note that the * values are not returned. diff --git a/lib/private/migrate.php b/lib/private/migrate.php index 5bcc11b061b..2ec9a0978ad 100644 --- a/lib/private/migrate.php +++ b/lib/private/migrate.php @@ -538,7 +538,7 @@ class OC_Migrate{ * @param string $db string path to migration.db * @param $info object of migration info * @param string|null|int $uid uid to use - * @return array of apps with import statuses, or false on failure. + * @return array an array of apps with import statuses, or false on failure. */ public static function importAppData( $db, $info, $uid=null ) { // Check if the db exists diff --git a/lib/private/navigationmanager.php b/lib/private/navigationmanager.php index 1f657b9ad80..d7111af03cf 100644 --- a/lib/private/navigationmanager.php +++ b/lib/private/navigationmanager.php @@ -30,7 +30,7 @@ class NavigationManager implements \OCP\INavigationManager { /** * @brief returns all the added Menu entries - * @return array of the added entries + * @return array an array of the added entries */ public function getAll() { return $this->entries; diff --git a/lib/private/ocsclient.php b/lib/private/ocsclient.php index a08c862b0cb..8b8930df937 100644 --- a/lib/private/ocsclient.php +++ b/lib/private/ocsclient.php @@ -59,7 +59,7 @@ class OC_OCSClient{ /** * @brief Get all the categories from the OCS server - * @return array with category ids + * @return array an array of category ids * @note returns NULL if config value appstoreenabled is set to false * This function returns a list of all the application categories on the OCS server */ @@ -92,7 +92,7 @@ class OC_OCSClient{ /** * @brief Get all the applications from the OCS server - * @return array with application data + * @return array an array of application data * * This function returns a list of all the applications on the OCS server * @param $categories @@ -150,7 +150,7 @@ class OC_OCSClient{ /** * @brief Get an the applications from the OCS server * @param string $id - * @return array with application data + * @return array an array of application data * * This function returns an applications from the OCS server */ @@ -192,7 +192,7 @@ class OC_OCSClient{ /** * @brief Get the download url for an application from the OCS server - * @return array with application data + * @return array an array of application data * * This function returns an download url for an applications from the OCS server * @param string $id diff --git a/lib/private/preferences.php b/lib/private/preferences.php index d45e6e77089..3cadb6a2e97 100644 --- a/lib/private/preferences.php +++ b/lib/private/preferences.php @@ -69,7 +69,7 @@ class Preferences { /** * @brief Get all users using the preferences - * @return array with user ids + * @return array an array of user ids * * This function returns a list of all users that have at least one entry * in the preferences table. @@ -125,7 +125,7 @@ class Preferences { * @brief Get the available keys for an app * @param string $user user * @param string $app the app we are looking for - * @return array with key names + * @return array an array of key names * * This function gets all keys of an app of an user. Please note that the * values are not returned. diff --git a/lib/private/preview.php b/lib/private/preview.php index 2964b83c508..941f9f26c6a 100755 --- a/lib/private/preview.php +++ b/lib/private/preview.php @@ -382,7 +382,7 @@ class Preview { /** * @brief get possible bigger thumbnails of the given image * @param int $fileId fileId of the original image - * @return array of paths to bigger thumbnails + * @return array an array of paths to bigger thumbnails */ private function getPossibleThumbnails($fileId) { diff --git a/lib/private/share/mailnotifications.php b/lib/private/share/mailnotifications.php index 4799db52330..5110df0e571 100644 --- a/lib/private/share/mailnotifications.php +++ b/lib/private/share/mailnotifications.php @@ -136,7 +136,7 @@ class MailNotifications { * @param string $filename the shared file * @param string $link link to the shared file * @param int $expiration expiration date (timestamp) - * @return array with the html mail body and the plain text mail body + * @return array an array of the html mail body and the plain text mail body */ private function createMailBody($filename, $link, $expiration) { diff --git a/lib/private/user.php b/lib/private/user.php index bf101a29b99..7f8d7bf263b 100644 --- a/lib/private/user.php +++ b/lib/private/user.php @@ -77,7 +77,7 @@ class OC_User { /** * @brief gets available backends * @deprecated - * @return array of backends + * @return array an array of backends * * Returns the names of all backends. */ @@ -88,7 +88,7 @@ class OC_User { /** * @brief gets used backends * @deprecated - * @return array of backends + * @return array an array of backends * * Returns the names of all used backends. */ @@ -517,7 +517,7 @@ class OC_User { /** * @brief Get a list of all users - * @return array with all uids + * @return array an array of all uids * * Get a list of all users. * @param string $search diff --git a/lib/private/user/backend.php b/lib/private/user/backend.php index 3994c1bb8ff..8d2f0e935de 100644 --- a/lib/private/user/backend.php +++ b/lib/private/user/backend.php @@ -103,7 +103,7 @@ abstract class OC_User_Backend implements OC_User_Interface { /** * @brief Get a list of all users - * @return array with all uids + * @return array an array of all uids * * Get a list of all users. */ @@ -140,7 +140,7 @@ abstract class OC_User_Backend implements OC_User_Interface { /** * @brief Get a list of all display names - * @return array with all displayNames (value) and the corresponding uids (key) + * @return array an array of all displayNames (value) and the corresponding uids (key) * * Get a list of all display names and user ids. */ diff --git a/lib/private/user/database.php b/lib/private/user/database.php index d70ccd8ad43..d54b0567a18 100644 --- a/lib/private/user/database.php +++ b/lib/private/user/database.php @@ -149,7 +149,7 @@ class OC_User_Database extends OC_User_Backend { /** * @brief Get a list of all display names - * @return array with all displayNames (value) and the correspondig uids (key) + * @return array an array of all displayNames (value) and the correspondig uids (key) * * Get a list of all display names and user ids. */ @@ -226,7 +226,7 @@ class OC_User_Database extends OC_User_Backend { /** * @brief Get a list of all users - * @return array with all uids + * @return array an array of all uids * * Get a list of all users. */ diff --git a/lib/private/user/interface.php b/lib/private/user/interface.php index eee18aea167..80da765cd9f 100644 --- a/lib/private/user/interface.php +++ b/lib/private/user/interface.php @@ -46,7 +46,7 @@ interface OC_User_Interface { /** * @brief Get a list of all users - * @return array with all uids + * @return array an array of all uids * * Get a list of all users. */ @@ -68,7 +68,7 @@ interface OC_User_Interface { /** * @brief Get a list of all display names - * @return array with all displayNames (value) and the corresponding uids (key) + * @return array an array of all displayNames (value) and the corresponding uids (key) * * Get a list of all display names and user ids. */ diff --git a/lib/private/user/manager.php b/lib/private/user/manager.php index 6f6fd80a8ef..939f99618d1 100644 --- a/lib/private/user/manager.php +++ b/lib/private/user/manager.php @@ -261,7 +261,7 @@ class Manager extends PublicEmitter { /** * returns how many users per backend exist (if supported by backend) * - * @return array with backend class as key and count number as value + * @return array an array of backend class as key and count number as value */ public function countUsers() { $userCountStatistics = array(); diff --git a/lib/private/util.php b/lib/private/util.php index 96d80beb4d1..f3fa7b1f220 100755 --- a/lib/private/util.php +++ b/lib/private/util.php @@ -819,7 +819,7 @@ class OC_Util { * string or array of strings before displaying it on a web page. * * @param string|array of strings - * @return array with sanitized strings or a single sanitized string, depends on the input parameter. + * @return array an array of sanitized strings or a single sanitized string, depends on the input parameter. */ public static function sanitizeHTML( &$value ) { if (is_array($value)) { diff --git a/lib/public/backgroundjob.php b/lib/public/backgroundjob.php index 03b94403b47..1832f766ea3 100644 --- a/lib/public/backgroundjob.php +++ b/lib/public/backgroundjob.php @@ -125,7 +125,7 @@ class BackgroundJob { /** * @deprecated * Gets all queued tasks - * @return array with associative arrays + * @return array an array of associative arrays */ public static function allQueuedTasks() { $jobList = \OC::$server->getJobList(); @@ -145,7 +145,7 @@ class BackgroundJob { * @deprecated * Gets all queued tasks of a specific app * @param string $app app name - * @return array with associative arrays + * @return array an array of associative arrays */ public static function queuedTaskWhereAppIs($app) { $jobList = \OC::$server->getJobList(); diff --git a/lib/public/contacts.php b/lib/public/contacts.php index 1b61d7aa4ff..70c67c75731 100644 --- a/lib/public/contacts.php +++ b/lib/public/contacts.php @@ -87,7 +87,7 @@ namespace OCP { * @param string $pattern which should match within the $searchProperties * @param array $searchProperties defines the properties within the query pattern should match * @param array $options - for future use. One should always have options! - * @return array of contacts which are arrays of key-value-pairs + * @return array an array of contacts which are arrays of key-value-pairs */ public static function search($pattern, $searchProperties = array(), $options = array()) { $cm = \OC::$server->getContactsManager(); @@ -112,7 +112,7 @@ namespace OCP { * * @param array $properties this array if key-value-pairs defines a contact * @param $address_book_key string to identify the address book in which the contact shall be created or updated - * @return array representing the contact just created or updated + * @return array an array representing the contact just created or updated */ public static function createOrUpdate($properties, $address_book_key) { $cm = \OC::$server->getContactsManager(); diff --git a/lib/public/contacts/imanager.php b/lib/public/contacts/imanager.php index 005b71f298b..32559220091 100644 --- a/lib/public/contacts/imanager.php +++ b/lib/public/contacts/imanager.php @@ -88,7 +88,7 @@ namespace OCP\Contacts { * @param string $pattern which should match within the $searchProperties * @param array $searchProperties defines the properties within the query pattern should match * @param array $options - for future use. One should always have options! - * @return array of contacts which are arrays of key-value-pairs + * @return array an array of contacts which are arrays of key-value-pairs */ function search($pattern, $searchProperties = array(), $options = array()); @@ -107,7 +107,7 @@ namespace OCP\Contacts { * * @param array $properties this array if key-value-pairs defines a contact * @param string $address_book_key identifier of the address book in which the contact shall be created or updated - * @return array representing the contact just created or updated + * @return array an array representing the contact just created or updated */ function createOrUpdate($properties, $address_book_key); diff --git a/lib/public/iaddressbook.php b/lib/public/iaddressbook.php index dcfe08012e6..70309e8c57a 100644 --- a/lib/public/iaddressbook.php +++ b/lib/public/iaddressbook.php @@ -45,7 +45,7 @@ namespace OCP { * @param string $pattern which should match within the $searchProperties * @param array $searchProperties defines the properties within the query pattern should match * @param array $options - for future use. One should always have options! - * @return array of contacts which are arrays of key-value-pairs + * @return array an array of contacts which are arrays of key-value-pairs */ public function search($pattern, $searchProperties, $options); // // dummy results @@ -56,7 +56,7 @@ namespace OCP { /** * @param array $properties this array if key-value-pairs defines a contact - * @return array representing the contact just created or updated + * @return array an array representing the contact just created or updated */ public function createOrUpdate($properties); // // dummy diff --git a/lib/public/iappconfig.php b/lib/public/iappconfig.php index 2b014df2e42..16c0752f073 100644 --- a/lib/public/iappconfig.php +++ b/lib/public/iappconfig.php @@ -45,7 +45,7 @@ interface IAppConfig { /** * @brief Get the available keys for an app * @param string $app the app we are looking for - * @return array with key names + * @return array an array of key names * * This function gets all keys of an app. Please note that the values are * not returned. @@ -74,7 +74,7 @@ interface IAppConfig { /** * @brief Get all apps using the config - * @return array with app ids + * @return array an array of app ids * * This function returns a list of all apps that have at least one * entry in the appconfig table. diff --git a/lib/public/user.php b/lib/public/user.php index 7bac938b838..e79ad4e7190 100644 --- a/lib/public/user.php +++ b/lib/public/user.php @@ -48,7 +48,7 @@ class User { * @param string search pattern * @param integer $limit * @param integer $offset - * @return array with all uids + * @return array an array of all uids */ public static function getUsers( $search = '', $limit = null, $offset = null ) { return \OC_User::getUsers( $search, $limit, $offset ); @@ -68,7 +68,7 @@ class User { * @param string search pattern * @param int limit * @param int offset - * @return array with all display names (value) and the correspondig uids (key) + * @return array an array of all display names (value) and the correspondig uids (key) */ public static function getDisplayNames( $search = '', $limit = null, $offset = null ) { return \OC_User::getDisplayNames( $search, $limit, $offset ); diff --git a/lib/public/util.php b/lib/public/util.php index 006a828dca2..0ca6f7928c3 100644 --- a/lib/public/util.php +++ b/lib/public/util.php @@ -381,7 +381,7 @@ class Util { * string or array of strings before displaying it on a web page. * * @param string|array of strings - * @return array with sanitized strings or a single sinitized string, depends on the input parameter. + * @return array an array of sanitized strings or a single sinitized string, depends on the input parameter. */ public static function sanitizeHTML( $value ) { return(\OC_Util::sanitizeHTML($value)); -- cgit v1.2.3 From a7ae2e874a28aed2c190840634db50a19ab1d2e7 Mon Sep 17 00:00:00 2001 From: Robin McCorkell Date: Sun, 11 May 2014 18:28:45 +0100 Subject: Squash 'a | b' into 'a|b', in /lib --- lib/private/connector/sabre/file.php | 2 +- lib/private/db/mdb2schemareader.php | 2 +- lib/private/db/statementwrapper.php | 2 +- lib/private/files.php | 2 +- lib/private/files/cache/cache.php | 4 ++-- lib/private/files/cache/watcher.php | 2 +- lib/private/files/fileinfo.php | 2 +- lib/private/files/mount/mount.php | 2 +- lib/private/files/type/templatemanager.php | 2 +- lib/private/files/view.php | 4 ++-- lib/private/group/database.php | 2 +- lib/private/group/dummy.php | 2 +- lib/private/group/group.php | 4 ++-- lib/private/group/manager.php | 2 +- lib/private/share/share.php | 2 +- lib/private/updater.php | 2 +- lib/private/user.php | 2 +- lib/private/user/database.php | 2 +- lib/private/user/dummy.php | 2 +- lib/private/user/manager.php | 2 +- lib/private/user/user.php | 2 +- lib/public/files/fileinfo.php | 2 +- lib/public/share.php | 2 +- 23 files changed, 26 insertions(+), 26 deletions(-) (limited to 'lib/private') diff --git a/lib/private/connector/sabre/file.php b/lib/private/connector/sabre/file.php index 66b50a87552..ab9d3e47d0e 100644 --- a/lib/private/connector/sabre/file.php +++ b/lib/private/connector/sabre/file.php @@ -123,7 +123,7 @@ class OC_Connector_Sabre_File extends OC_Connector_Sabre_Node implements Sabre_D /** * Returns the data * - * @return string | resource + * @return string|resource */ public function get() { diff --git a/lib/private/db/mdb2schemareader.php b/lib/private/db/mdb2schemareader.php index 1c16d03eab2..0923b6cf1a9 100644 --- a/lib/private/db/mdb2schemareader.php +++ b/lib/private/db/mdb2schemareader.php @@ -303,7 +303,7 @@ class MDB2SchemaReader { } /** - * @param \SimpleXMLElement | string $xml + * @param \SimpleXMLElement|string $xml * @return bool */ private function asBool($xml) { diff --git a/lib/private/db/statementwrapper.php b/lib/private/db/statementwrapper.php index 492209b883b..70d1f985a41 100644 --- a/lib/private/db/statementwrapper.php +++ b/lib/private/db/statementwrapper.php @@ -41,7 +41,7 @@ class OC_DB_StatementWrapper { * make execute return the result instead of a bool * * @param array $input - * @return \OC_DB_StatementWrapper | int + * @return \OC_DB_StatementWrapper|int */ public function execute($input=array()) { if(OC_Config::getValue( "log_query", false)) { diff --git a/lib/private/files.php b/lib/private/files.php index c435f8d1684..7c437a16a98 100644 --- a/lib/private/files.php +++ b/lib/private/files.php @@ -225,7 +225,7 @@ class OC_Files { * checks if the selected files are within the size constraint. If not, outputs an error page. * * @param string $dir - * @param array | string $files + * @param array|string $files */ static function validateZipDownload($dir, $files) { if (!OC_Config::getValue('allowZipDownload', true)) { diff --git a/lib/private/files/cache/cache.php b/lib/private/files/cache/cache.php index e857d451881..6aab2173da7 100644 --- a/lib/private/files/cache/cache.php +++ b/lib/private/files/cache/cache.php @@ -109,7 +109,7 @@ class Cache { * get the stored metadata of a file or folder * * @param string/int $file - * @return array | false + * @return array|false */ public function get($file) { if (is_string($file) or $file == '') { @@ -597,7 +597,7 @@ class Cache { * get the path of a file on this storage by it's id * * @param int $id - * @return string | null + * @return string|null */ public function getPathById($id) { $sql = 'SELECT `path` FROM `*PREFIX*filecache` WHERE `fileid` = ? AND `storage` = ?'; diff --git a/lib/private/files/cache/watcher.php b/lib/private/files/cache/watcher.php index 48aa6f853ce..599752a6eff 100644 --- a/lib/private/files/cache/watcher.php +++ b/lib/private/files/cache/watcher.php @@ -55,7 +55,7 @@ class Watcher { * check $path for updates * * @param string $path - * @return boolean | array true if path was updated, otherwise the cached data is returned + * @return boolean|array true if path was updated, otherwise the cached data is returned */ public function checkUpdate($path) { if ($this->watchPolicy === self::CHECK_ALWAYS or ($this->watchPolicy === self::CHECK_ONCE and array_search($path, $this->checkedPaths) === false)) { diff --git a/lib/private/files/fileinfo.php b/lib/private/files/fileinfo.php index d6940f50bf1..b64c5d4e112 100644 --- a/lib/private/files/fileinfo.php +++ b/lib/private/files/fileinfo.php @@ -147,7 +147,7 @@ class FileInfo implements \OCP\Files\FileInfo, \ArrayAccess { } /** - * @return \OCP\Files\FileInfo::TYPE_FILE | \OCP\Files\FileInfo::TYPE_FOLDER + * @return \OCP\Files\FileInfo::TYPE_FILE|\OCP\Files\FileInfo::TYPE_FOLDER */ public function getType() { if (isset($this->data['type'])) { diff --git a/lib/private/files/mount/mount.php b/lib/private/files/mount/mount.php index 08d5ddf348b..256630726d2 100644 --- a/lib/private/files/mount/mount.php +++ b/lib/private/files/mount/mount.php @@ -28,7 +28,7 @@ class Mount { private $loader; /** - * @param string | \OC\Files\Storage\Storage $storage + * @param string|\OC\Files\Storage\Storage $storage * @param string $mountpoint * @param array $arguments (optional)\ * @param \OC\Files\Storage\Loader $loader diff --git a/lib/private/files/type/templatemanager.php b/lib/private/files/type/templatemanager.php index cd1536d2732..e693e7079a5 100644 --- a/lib/private/files/type/templatemanager.php +++ b/lib/private/files/type/templatemanager.php @@ -19,7 +19,7 @@ class TemplateManager { * get the path of the template for a mimetype * * @param string $mimetype - * @return string | null + * @return string|null */ public function getTemplatePath($mimetype) { if (isset($this->templates[$mimetype])) { diff --git a/lib/private/files/view.php b/lib/private/files/view.php index d3772e264a0..a53c2fbb322 100644 --- a/lib/private/files/view.php +++ b/lib/private/files/view.php @@ -796,7 +796,7 @@ class View { * @param string $path * @param boolean $includeMountPoints whether to add mountpoint sizes, * defaults to true - * @return \OC\Files\FileInfo | false + * @return \OC\Files\FileInfo|false */ public function getFileInfo($path, $includeMountPoints = true) { $data = array(); @@ -991,7 +991,7 @@ class View { * change file metadata * * @param string $path - * @param array | \OCP\Files\FileInfo $data + * @param array|\OCP\Files\FileInfo $data * @return int * * returns the fileid of the updated file diff --git a/lib/private/group/database.php b/lib/private/group/database.php index abdf09a9222..18c060e9b22 100644 --- a/lib/private/group/database.php +++ b/lib/private/group/database.php @@ -217,7 +217,7 @@ class OC_Group_Database extends OC_Group_Backend { * @param string $search * @param int $limit * @param int $offset - * @return int | false + * @return int|false */ public function countUsersInGroup($gid, $search = '') { $stmt = OC_DB::prepare('SELECT COUNT(`uid`) AS `count` FROM `*PREFIX*group_user` WHERE `gid` = ? AND `uid` LIKE ?'); diff --git a/lib/private/group/dummy.php b/lib/private/group/dummy.php index 1ef81c6bf99..7a766a6b35d 100644 --- a/lib/private/group/dummy.php +++ b/lib/private/group/dummy.php @@ -159,7 +159,7 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief get the number of all users in a group - * @return int | bool + * @return int|bool */ public function countUsersInGroup($gid, $search = '', $limit = -1, $offset = 0) { if(isset($this->groups[$gid])) { diff --git a/lib/private/group/group.php b/lib/private/group/group.php index 7593bb68d1a..69641854dc5 100644 --- a/lib/private/group/group.php +++ b/lib/private/group/group.php @@ -26,7 +26,7 @@ class Group { private $usersLoaded; /** - * @var \OC_Group_Backend[] | \OC_Group_Database[] $backend + * @var \OC_Group_Backend[]|\OC_Group_Database[] $backend */ private $backends; @@ -184,7 +184,7 @@ class Group { * returns the number of users matching the search string * * @param string $search - * @return int | bool + * @return int|bool */ public function count($search) { $users = false; diff --git a/lib/private/group/manager.php b/lib/private/group/manager.php index 3eb894a644a..f03f7004132 100644 --- a/lib/private/group/manager.php +++ b/lib/private/group/manager.php @@ -28,7 +28,7 @@ use OC\Hooks\PublicEmitter; */ class Manager extends PublicEmitter { /** - * @var \OC_Group_Backend[] | \OC_Group_Database[] $backends + * @var \OC_Group_Backend[]|\OC_Group_Database[] $backends */ private $backends = array(); diff --git a/lib/private/share/share.php b/lib/private/share/share.php index 6f8830e73f2..211c7e7cb1c 100644 --- a/lib/private/share/share.php +++ b/lib/private/share/share.php @@ -362,7 +362,7 @@ class Share extends \OC\Share\Constants { /** * Based on the given token the share information will be returned - password protected shares will be verified * @param string $token - * @return array | boolean false will be returned in case the token is unknown or unauthorized + * @return array|boolean false will be returned in case the token is unknown or unauthorized */ public static function getShareByToken($token, $checkPasswordProtection = true) { $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1); diff --git a/lib/private/updater.php b/lib/private/updater.php index 7b09f580176..d8694ac6ed5 100644 --- a/lib/private/updater.php +++ b/lib/private/updater.php @@ -35,7 +35,7 @@ class Updater extends BasicEmitter { /** * Check if a new version is available * @param string $updaterUrl the url to check, i.e. 'http://apps.owncloud.com/updater.php' - * @return array | bool + * @return array|bool */ public function check($updaterUrl) { diff --git a/lib/private/user.php b/lib/private/user.php index 7f8d7bf263b..2ba681cd4a4 100644 --- a/lib/private/user.php +++ b/lib/private/user.php @@ -98,7 +98,7 @@ class OC_User { /** * @brief Adds the backend to the list of used backends - * @param string | OC_User_Backend $backend default: database The backend to use for user management + * @param string|OC_User_Backend $backend default: database The backend to use for user management * @return bool * * Set the User Authentication Module diff --git a/lib/private/user/database.php b/lib/private/user/database.php index d54b0567a18..284b3582598 100644 --- a/lib/private/user/database.php +++ b/lib/private/user/database.php @@ -273,7 +273,7 @@ class OC_User_Database extends OC_User_Backend { /** * counts the users in the database * - * @return int | bool + * @return int|bool */ public function countUsers() { $query = OC_DB::prepare('SELECT COUNT(*) FROM `*PREFIX*users`'); diff --git a/lib/private/user/dummy.php b/lib/private/user/dummy.php index 2fb51d02de3..d2ada37c80f 100644 --- a/lib/private/user/dummy.php +++ b/lib/private/user/dummy.php @@ -127,7 +127,7 @@ class OC_User_Dummy extends OC_User_Backend { /** * counts the users in the database * - * @return int | bool + * @return int|bool */ public function countUsers() { return 0; diff --git a/lib/private/user/manager.php b/lib/private/user/manager.php index 939f99618d1..6765491e695 100644 --- a/lib/private/user/manager.php +++ b/lib/private/user/manager.php @@ -222,7 +222,7 @@ class Manager extends PublicEmitter { * @param string $uid * @param string $password * @throws \Exception - * @return bool | \OC\User\User the created user of false + * @return bool|\OC\User\User the created user of false */ public function createUser($uid, $password) { $l = \OC_L10N::get('lib'); diff --git a/lib/private/user/user.php b/lib/private/user/user.php index ef5364cbf7b..abdbef38d9a 100644 --- a/lib/private/user/user.php +++ b/lib/private/user/user.php @@ -33,7 +33,7 @@ class User { private $enabled; /** - * @var Emitter | Manager $emitter + * @var Emitter|Manager $emitter */ private $emitter; diff --git a/lib/public/files/fileinfo.php b/lib/public/files/fileinfo.php index 37162e09336..bf0c31918cb 100644 --- a/lib/public/files/fileinfo.php +++ b/lib/public/files/fileinfo.php @@ -104,7 +104,7 @@ interface FileInfo { /** * Check whether this is a file or a folder * - * @return \OCP\Files\FileInfo::TYPE_FILE | \OCP\Files\FileInfo::TYPE_FOLDER + * @return \OCP\Files\FileInfo::TYPE_FILE|\OCP\Files\FileInfo::TYPE_FOLDER */ public function getType(); diff --git a/lib/public/share.php b/lib/public/share.php index b21b3a7b963..018386253bc 100644 --- a/lib/public/share.php +++ b/lib/public/share.php @@ -160,7 +160,7 @@ class Share extends \OC\Share\Constants { /** * Based on the given token the share information will be returned - password protected shares will be verified * @param string $token - * @return array | bool false will be returned in case the token is unknown or unauthorized + * @return array|bool false will be returned in case the token is unknown or unauthorized */ public static function getShareByToken($token, $checkPasswordProtection = true) { return \OC\Share\Share::getShareByToken($token, $checkPasswordProtection); -- cgit v1.2.3 From 87b548ed91c03f051a93cc39bf94650922c1f55f Mon Sep 17 00:00:00 2001 From: Robin McCorkell Date: Sun, 11 May 2014 21:51:30 +0100 Subject: Fix all PHPDoc types and variable names, in /lib --- .../dependencyinjection/dicontainer.php | 4 ++-- lib/private/appframework/http.php | 2 +- lib/private/appframework/routing/routeconfig.php | 12 +++++----- lib/private/archive/tar.php | 2 +- lib/private/avatar.php | 6 ++--- lib/private/avatarmanager.php | 2 +- lib/private/backgroundjob/joblist.php | 8 +++---- lib/private/cache/file.php | 2 +- lib/private/connector/sabre/auth.php | 2 ++ lib/private/connector/sabre/filesplugin.php | 2 +- lib/private/connector/sabre/quotaplugin.php | 2 +- lib/private/db.php | 2 +- lib/private/db/connectionwrapper.php | 4 ++-- lib/private/db/mdb2schemamanager.php | 2 +- lib/private/db/mdb2schemareader.php | 2 +- lib/private/defaults.php | 2 +- lib/private/fileproxy.php | 2 +- lib/private/files/cache/cache.php | 2 +- lib/private/files/cache/scanner.php | 2 +- lib/private/files/filesystem.php | 4 ++-- lib/private/files/mapper.php | 4 ++-- lib/private/files/mount/manager.php | 6 ++--- lib/private/files/node/folder.php | 2 +- lib/private/files/storage/common.php | 4 ++-- lib/private/files/storage/wrapper/quota.php | 2 +- lib/private/geo.php | 4 ++-- lib/private/group.php | 2 +- lib/private/group/dummy.php | 26 ++++++++++---------- lib/private/group/example.php | 28 +++++++++++----------- lib/private/helper.php | 14 +++++------ lib/private/image.php | 2 +- lib/private/installer.php | 4 ++-- lib/private/l10n.php | 2 +- lib/private/l10n/factory.php | 4 ++-- lib/private/migrate.php | 4 ++-- lib/private/migration/content.php | 16 ++++++------- lib/private/ocs.php | 4 ++-- lib/private/ocs/cloud.php | 4 ++-- lib/private/ocs/result.php | 6 ++--- lib/private/ocsclient.php | 2 +- lib/private/preview.php | 10 ++++---- lib/private/response.php | 6 ++--- lib/private/route/route.php | 2 +- lib/private/route/router.php | 2 +- lib/private/share/helper.php | 20 ++++++++-------- lib/private/share/hooks.php | 10 ++++---- lib/private/share/mailnotifications.php | 4 ++-- lib/private/share/searchresultsorter.php | 4 ++-- lib/private/share/share.php | 22 ++++++++--------- lib/private/subadmin.php | 4 ++-- lib/private/tags.php | 2 +- lib/private/template/functions.php | 2 +- lib/private/template/resourcelocator.php | 10 +++----- lib/private/templatelayout.php | 6 ++--- lib/private/urlgenerator.php | 2 +- lib/private/user/database.php | 28 +++++++++++----------- lib/private/user/example.php | 18 +++++++------- lib/private/user/http.php | 8 +++---- lib/private/user/interface.php | 12 ++++------ lib/private/util.php | 10 ++++---- lib/private/vobject.php | 16 ++++++------- lib/public/app.php | 10 ++++---- lib/public/backgroundjob.php | 4 ++-- lib/public/backgroundjob/ijoblist.php | 6 ++--- lib/public/contacts.php | 4 ++-- lib/public/db.php | 2 +- lib/public/iavatar.php | 2 +- lib/public/iavatarmanager.php | 2 +- lib/public/idbconnection.php | 4 ++-- lib/public/il10n.php | 2 +- lib/public/route/iroute.php | 2 +- lib/public/share.php | 24 +++++++++---------- lib/public/template.php | 22 ++++++++--------- lib/public/user.php | 14 +++++------ lib/public/util.php | 16 ++++++------- 75 files changed, 255 insertions(+), 263 deletions(-) (limited to 'lib/private') diff --git a/lib/private/appframework/dependencyinjection/dicontainer.php b/lib/private/appframework/dependencyinjection/dicontainer.php index 97a6569a0f6..ee492b8a9e5 100644 --- a/lib/private/appframework/dependencyinjection/dicontainer.php +++ b/lib/private/appframework/dependencyinjection/dicontainer.php @@ -190,8 +190,8 @@ class DIContainer extends SimpleContainer implements IAppContainer{ } /** - * @param $message - * @param $level + * @param string $message + * @param string $level * @return mixed */ function log($message, $level) { diff --git a/lib/private/appframework/http.php b/lib/private/appframework/http.php index d09e1d3ce2e..2b1387af715 100644 --- a/lib/private/appframework/http.php +++ b/lib/private/appframework/http.php @@ -33,7 +33,7 @@ class Http extends BaseHttp { protected $headers; /** - * @param $_SERVER $server + * @param array $server $_SERVER * @param string $protocolVersion the http version to use defaults to HTTP/1.1 */ public function __construct($server, $protocolVersion='HTTP/1.1') { diff --git a/lib/private/appframework/routing/routeconfig.php b/lib/private/appframework/routing/routeconfig.php index a3bbde6af53..91ea7778d08 100644 --- a/lib/private/appframework/routing/routeconfig.php +++ b/lib/private/appframework/routing/routeconfig.php @@ -61,7 +61,7 @@ class RouteConfig { /** * Creates one route base on the give configuration - * @param $routes + * @param array $routes * @throws \UnexpectedValueException */ private function processSimpleRoutes($routes) @@ -105,7 +105,7 @@ class RouteConfig { * - update * - destroy * - * @param $routes + * @param array $routes */ private function processResources($routes) { @@ -151,7 +151,7 @@ class RouteConfig { /** * Based on a given route name the controller name is generated - * @param $controller + * @param string $controller * @return string */ private function buildControllerName($controller) @@ -161,7 +161,7 @@ class RouteConfig { /** * Based on the action part of the route name the controller method name is generated - * @param $action + * @param string $action * @return string */ private function buildActionName($action) { @@ -170,7 +170,7 @@ class RouteConfig { /** * Generates the id used in the url part o the route url - * @param $resource + * @param string $resource * @return string */ private function buildResourceId($resource) { @@ -179,7 +179,7 @@ class RouteConfig { /** * Underscored strings are converted to camel case strings - * @param $str string + * @param string $str * @return string */ private function underScoreToCamelCase($str) { diff --git a/lib/private/archive/tar.php b/lib/private/archive/tar.php index cbdb565ba35..21a995d9e50 100644 --- a/lib/private/archive/tar.php +++ b/lib/private/archive/tar.php @@ -154,7 +154,7 @@ class OC_Archive_TAR extends OC_Archive{ } /** * get the last modified time of a file in the archive - * @param string path + * @param string $path * @return int */ function mtime($path) { diff --git a/lib/private/avatar.php b/lib/private/avatar.php index e97f55eecaf..45959798476 100644 --- a/lib/private/avatar.php +++ b/lib/private/avatar.php @@ -16,7 +16,7 @@ class OC_Avatar implements \OCP\IAvatar { /** * @brief constructor - * @param $user string user to do avatar-management with + * @param string $user user to do avatar-management with */ public function __construct ($user) { $this->view = new \OC\Files\View('/'.$user); @@ -24,7 +24,7 @@ class OC_Avatar implements \OCP\IAvatar { /** * @brief get the users avatar - * @param $size integer size in px of the avatar, avatars are square, defaults to 64 + * @param int $size size in px of the avatar, avatars are square, defaults to 64 * @return boolean|\OC_Image containing the avatar or false if there's no image */ public function get ($size = 64) { @@ -44,7 +44,7 @@ class OC_Avatar implements \OCP\IAvatar { /** * @brief sets the users avatar - * @param $data mixed OC_Image, imagedata or path to set a new avatar + * @param \OC_Image|resource|string $data OC_Image, imagedata or path to set a new avatar * @throws Exception if the provided file is not a jpg or png image * @throws Exception if the provided image is not valid * @throws \OC\NotSquareException if the image is not square diff --git a/lib/private/avatarmanager.php b/lib/private/avatarmanager.php index 3ca46868ea6..f462e6ac5fd 100644 --- a/lib/private/avatarmanager.php +++ b/lib/private/avatarmanager.php @@ -17,7 +17,7 @@ class AvatarManager implements IAvatarManager { /** * @brief return a user specific instance of \OCP\IAvatar * @see \OCP\IAvatar - * @param $user string the ownCloud user id + * @param string $user the ownCloud user id * @return \OCP\IAvatar */ function getAvatar($user) { diff --git a/lib/private/backgroundjob/joblist.php b/lib/private/backgroundjob/joblist.php index 26c90269349..9fa13c25851 100644 --- a/lib/private/backgroundjob/joblist.php +++ b/lib/private/backgroundjob/joblist.php @@ -31,7 +31,7 @@ class JobList implements IJobList { } /** - * @param \Test\BackgroundJob\TestJob $job + * @param Job|string $job * @param mixed $argument */ public function add($job, $argument = null) { @@ -48,7 +48,7 @@ class JobList implements IJobList { } /** - * @param Job $job + * @param Job|string $job * @param mixed $argument */ public function remove($job, $argument = null) { @@ -70,7 +70,7 @@ class JobList implements IJobList { /** * check if a job is in the list * - * @param $job + * @param Job|string $job * @param mixed $argument * @return bool */ @@ -126,7 +126,7 @@ class JobList implements IJobList { /** * @param int $id - * @return Job + * @return Job|null */ public function getById($id) { $query = $this->conn->prepare('SELECT `id`, `class`, `last_run`, `argument` FROM `*PREFIX*jobs` WHERE `id` = ?'); diff --git a/lib/private/cache/file.php b/lib/private/cache/file.php index feee9cc32b6..4e7c065678e 100644 --- a/lib/private/cache/file.php +++ b/lib/private/cache/file.php @@ -48,7 +48,7 @@ class File { /** * Returns the size of the stored/cached data * - * @param $key + * @param string $key * @return int */ public function size($key) { diff --git a/lib/private/connector/sabre/auth.php b/lib/private/connector/sabre/auth.php index 5577273df8c..9ebf5fc05cf 100644 --- a/lib/private/connector/sabre/auth.php +++ b/lib/private/connector/sabre/auth.php @@ -69,6 +69,8 @@ class OC_Connector_Sabre_Auth extends Sabre_DAV_Auth_Backend_AbstractBasic { * even if there are no HTTP Basic Auth headers. * In other case, just fallback to the parent implementation. * + * @param Sabre_DAV_Server $server + * @param $realm * @return bool */ public function authenticate(Sabre_DAV_Server $server, $realm) { diff --git a/lib/private/connector/sabre/filesplugin.php b/lib/private/connector/sabre/filesplugin.php index 65231040fb5..f8495b40524 100644 --- a/lib/private/connector/sabre/filesplugin.php +++ b/lib/private/connector/sabre/filesplugin.php @@ -73,7 +73,7 @@ class OC_Connector_Sabre_FilesPlugin extends Sabre_DAV_ServerPlugin } /** - * @param $filePath + * @param string $filePath * @param Sabre_DAV_INode $node * @throws Sabre_DAV_Exception_BadRequest */ diff --git a/lib/private/connector/sabre/quotaplugin.php b/lib/private/connector/sabre/quotaplugin.php index 1e73e1645c3..c9b8336b57b 100644 --- a/lib/private/connector/sabre/quotaplugin.php +++ b/lib/private/connector/sabre/quotaplugin.php @@ -97,7 +97,7 @@ class OC_Connector_Sabre_QuotaPlugin extends Sabre_DAV_ServerPlugin { } /** - * @param $parentUri + * @param string $parentUri * @return mixed */ public function getFreeSpace($parentUri) { diff --git a/lib/private/db.php b/lib/private/db.php index 322a13642ae..52bf570d1d0 100644 --- a/lib/private/db.php +++ b/lib/private/db.php @@ -401,7 +401,7 @@ class OC_DB { /** * @brief replaces the ownCloud tables with a new set - * @param $file string path to the MDB2 xml db export file + * @param string $file path to the MDB2 xml db export file */ public static function replaceDB( $file ) { $schemaManager = self::getMDB2SchemaManager(); diff --git a/lib/private/db/connectionwrapper.php b/lib/private/db/connectionwrapper.php index c2cfc21d204..132e76666ab 100644 --- a/lib/private/db/connectionwrapper.php +++ b/lib/private/db/connectionwrapper.php @@ -41,8 +41,8 @@ class ConnectionWrapper implements \OCP\IDBConnection { /** * Insert a row if a matching row doesn't exists. - * @param string The table name (will replace *PREFIX*) to perform the replace on. - * @param array + * @param string $table The table name (will replace *PREFIX*) to perform the replace on. + * @param array $input * * The input array if in the form: * diff --git a/lib/private/db/mdb2schemamanager.php b/lib/private/db/mdb2schemamanager.php index aaf2ea543b9..d98197445e9 100644 --- a/lib/private/db/mdb2schemamanager.php +++ b/lib/private/db/mdb2schemamanager.php @@ -126,7 +126,7 @@ class MDB2SchemaManager { /** * @brief replaces the ownCloud tables with a new set - * @param $file string path to the MDB2 xml db export file + * @param string $file path to the MDB2 xml db export file */ public function replaceDB( $file ) { $apps = \OC_App::getAllApps(); diff --git a/lib/private/db/mdb2schemareader.php b/lib/private/db/mdb2schemareader.php index 0923b6cf1a9..597650985fa 100644 --- a/lib/private/db/mdb2schemareader.php +++ b/lib/private/db/mdb2schemareader.php @@ -66,7 +66,7 @@ class MDB2SchemaReader { } /** - * @param\Doctrine\DBAL\Schema\Schema $schema + * @param \Doctrine\DBAL\Schema\Schema $schema * @param \SimpleXMLElement $xml * @throws \DomainException */ diff --git a/lib/private/defaults.php b/lib/private/defaults.php index fca798568c5..663c327a3b0 100644 --- a/lib/private/defaults.php +++ b/lib/private/defaults.php @@ -185,7 +185,7 @@ class OC_Defaults { /** * Returns mail header color - * @return mail header color + * @return string */ public function getMailHeaderColor() { if ($this->themeExist('getMailHeaderColor')) { diff --git a/lib/private/fileproxy.php b/lib/private/fileproxy.php index 88976c1b8e5..2835e974642 100644 --- a/lib/private/fileproxy.php +++ b/lib/private/fileproxy.php @@ -47,7 +47,7 @@ class OC_FileProxy{ /** * fallback function when a proxy operation is not implemented * @param string $function the name of the proxy operation - * @param mixed + * @param mixed $arguments * * this implements a dummy proxy for all operations */ diff --git a/lib/private/files/cache/cache.php b/lib/private/files/cache/cache.php index 6aab2173da7..3e4f6dfb132 100644 --- a/lib/private/files/cache/cache.php +++ b/lib/private/files/cache/cache.php @@ -640,7 +640,7 @@ class Cache { /** * normalize the given path - * @param $path + * @param string $path * @return string */ public function normalize($path) { diff --git a/lib/private/files/cache/scanner.php b/lib/private/files/cache/scanner.php index 8c2ec057ca7..51454a71458 100644 --- a/lib/private/files/cache/scanner.php +++ b/lib/private/files/cache/scanner.php @@ -273,7 +273,7 @@ class Scanner extends BasicEmitter { * @brief check if the file should be ignored when scanning * NOTE: files with a '.part' extension are ignored as well! * prevents unfinished put requests to be scanned - * @param String $file + * @param string $file * @return boolean */ public static function isPartialFile($file) { diff --git a/lib/private/files/filesystem.php b/lib/private/files/filesystem.php index a4994e4dfb6..22d15840c32 100644 --- a/lib/private/files/filesystem.php +++ b/lib/private/files/filesystem.php @@ -245,7 +245,7 @@ class Filesystem { } /** - * @param $id + * @param string $id * @return Mount\Mount[] */ public static function getMountByStorageId($id) { @@ -256,7 +256,7 @@ class Filesystem { } /** - * @param $id + * @param int $id * @return Mount\Mount[] */ public static function getMountByNumericId($id) { diff --git a/lib/private/files/mapper.php b/lib/private/files/mapper.php index 833d4bd8d1c..666719da12d 100644 --- a/lib/private/files/mapper.php +++ b/lib/private/files/mapper.php @@ -97,8 +97,8 @@ class Mapper } /** - * @param $path - * @param $root + * @param string $path + * @param string $root * @return false|string */ public function stripRootFolder($path, $root) { diff --git a/lib/private/files/mount/manager.php b/lib/private/files/mount/manager.php index 91460b72730..db1f4600c74 100644 --- a/lib/private/files/mount/manager.php +++ b/lib/private/files/mount/manager.php @@ -33,7 +33,7 @@ class Manager { /** * Find the mount for $path * - * @param $path + * @param string $path * @return Mount */ public function find($path) { @@ -61,7 +61,7 @@ class Manager { /** * Find all mounts in $path * - * @param $path + * @param string $path * @return Mount[] */ public function findIn($path) { @@ -112,7 +112,7 @@ class Manager { /** * Find mounts by numeric storage id * - * @param string $id + * @param int $id * @return Mount[] */ public function findByNumericId($id) { diff --git a/lib/private/files/node/folder.php b/lib/private/files/node/folder.php index d9e0ddc2d61..1af34fc2be6 100644 --- a/lib/private/files/node/folder.php +++ b/lib/private/files/node/folder.php @@ -296,7 +296,7 @@ class Folder extends Node implements \OCP\Files\Folder { } /** - * @param $id + * @param int $id * @return \OC\Files\Node\Node[] */ public function getById($id) { diff --git a/lib/private/files/storage/common.php b/lib/private/files/storage/common.php index 8a263d4ce1e..fef33cabd87 100644 --- a/lib/private/files/storage/common.php +++ b/lib/private/files/storage/common.php @@ -317,7 +317,7 @@ abstract class Common implements \OC\Files\Storage\Storage { * clean a path, i.e. remove all redundant '.' and '..' * making sure that it can't point to higher than '/' * - * @param $path The path to clean + * @param string $path The path to clean * @return string cleaned path */ public function cleanPath($path) { @@ -347,7 +347,7 @@ abstract class Common implements \OC\Files\Storage\Storage { /** * get the free space in the storage * - * @param $path + * @param string $path * @return int */ public function free_space($path) { diff --git a/lib/private/files/storage/wrapper/quota.php b/lib/private/files/storage/wrapper/quota.php index a878b2c5cf6..c57c797f87a 100644 --- a/lib/private/files/storage/wrapper/quota.php +++ b/lib/private/files/storage/wrapper/quota.php @@ -30,7 +30,7 @@ class Quota extends Wrapper { } /** - * @return quota value + * @return int quota value */ public function getQuota() { return $this->quota; diff --git a/lib/private/geo.php b/lib/private/geo.php index cd62511f0c1..a0ad2b799ab 100644 --- a/lib/private/geo.php +++ b/lib/private/geo.php @@ -8,8 +8,8 @@ class OC_Geo{ /** * @brief returns the closest timezone to coordinates - * @param $latitude - * @param $longitude + * @param float $latitude + * @param float $longitude * @return mixed Closest timezone */ public static function timezone($latitude, $longitude) { diff --git a/lib/private/group.php b/lib/private/group.php index 5b291d7f2f6..845b3655bab 100644 --- a/lib/private/group.php +++ b/lib/private/group.php @@ -58,7 +58,7 @@ class OC_Group { /** * @brief set the group backend - * @param \OC_Group_Backend $backend The backend to use for user managment + * @param \OC_Group_Backend $backend The backend to use for user managment * @return bool */ public static function useBackend($backend) { diff --git a/lib/private/group/dummy.php b/lib/private/group/dummy.php index 7a766a6b35d..553aae54291 100644 --- a/lib/private/group/dummy.php +++ b/lib/private/group/dummy.php @@ -29,7 +29,7 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief Try to create a new group * @param string $gid The name of the group to create - * @return true/false + * @return bool * * Trys to create a new group. If the group name already exists, false will * be returned. @@ -45,8 +45,8 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief delete a group - * @param $gid gid of the group to delete - * @return true/false + * @param string $gid gid of the group to delete + * @return bool * * Deletes a group and removes it from the group_user-table */ @@ -61,9 +61,9 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief is user in group? - * @param $uid uid of the user - * @param $gid gid of the group - * @return true/false + * @param string $uid uid of the user + * @param string $gid gid of the group + * @return bool * * Checks whether the user is member of a group or not. */ @@ -77,9 +77,9 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief Add a user to a group - * @param $uid Name of the user to add to group - * @param $gid Name of the group in which add the user - * @return true/false + * @param string $uid Name of the user to add to group + * @param string $gid Name of the group in which add the user + * @return bool * * Adds a user to a group. */ @@ -98,9 +98,9 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief Removes a user from a group - * @param $uid NameUSER of the user to remove from group - * @param $gid Name of the group from which remove the user - * @return true/false + * @param string $uid Name of the user to remove from group + * @param string $gid Name of the group from which remove the user + * @return bool * * removes the user from a group. */ @@ -118,7 +118,7 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief Get all groups a user belongs to - * @param $uid Name of the user + * @param string $uid Name of the user * @return array an array of group names * * This function fetches all groups a user belongs to. It does not check diff --git a/lib/private/group/example.php b/lib/private/group/example.php index 12be5421c1c..cfcc0d245d1 100644 --- a/lib/private/group/example.php +++ b/lib/private/group/example.php @@ -28,8 +28,8 @@ abstract class OC_Group_Example { /** * @brief Try to create a new group - * @param $gid The name of the group to create - * @return true/false + * @param string $gid The name of the group to create + * @return bool * * Trys to create a new group. If the group name already exists, false will * be returned. @@ -38,8 +38,8 @@ abstract class OC_Group_Example { /** * @brief delete a group - * @param $gid gid of the group to delete - * @return true/false + * @param string $gid gid of the group to delete + * @return bool * * Deletes a group and removes it from the group_user-table */ @@ -47,9 +47,9 @@ abstract class OC_Group_Example { /** * @brief is user in group? - * @param $uid uid of the user - * @param $gid gid of the group - * @return true/false + * @param string $uid uid of the user + * @param string $gid gid of the group + * @return bool * * Checks whether the user is member of a group or not. */ @@ -57,9 +57,9 @@ abstract class OC_Group_Example { /** * @brief Add a user to a group - * @param $uid Name of the user to add to group - * @param $gid Name of the group in which add the user - * @return true/false + * @param string $uid Name of the user to add to group + * @param string $gid Name of the group in which add the user + * @return bool * * Adds a user to a group. */ @@ -67,9 +67,9 @@ abstract class OC_Group_Example { /** * @brief Removes a user from a group - * @param $uid NameUSER of the user to remove from group - * @param $gid Name of the group from which remove the user - * @return true/false + * @param string $uid Name of the user to remove from group + * @param string $gid Name of the group from which remove the user + * @return bool * * removes the user from a group. */ @@ -77,7 +77,7 @@ abstract class OC_Group_Example { /** * @brief Get all groups a user belongs to - * @param $uid Name of the user + * @param string $uid Name of the user * @return array an array of group names * * This function fetches all groups a user belongs to. It does not check diff --git a/lib/private/helper.php b/lib/private/helper.php index ae957846082..12d82f6fb45 100644 --- a/lib/private/helper.php +++ b/lib/private/helper.php @@ -32,7 +32,7 @@ class OC_Helper { /** * @brief Creates an url using a defined route - * @param $route + * @param string $route * @param array $parameters * @return * @internal param array $args with param=>value, will be appended to the returned url @@ -495,7 +495,7 @@ class OC_Helper { /** * detect if a given program is found in the search PATH * - * @param $name + * @param string $name * @param bool $path * @internal param string $program name * @internal param string $optional search path, defaults to $PATH @@ -670,8 +670,8 @@ class OC_Helper { /** * Adds a suffix to the name in case the file exists * - * @param $path - * @param $filename + * @param string $path + * @param string $filename * @return string */ public static function buildNotExistingFileName($path, $filename) { @@ -682,8 +682,8 @@ class OC_Helper { /** * Adds a suffix to the name in case the file exists * - * @param $path - * @param $filename + * @param string $path + * @param string $filename * @return string */ public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) { @@ -775,7 +775,7 @@ class OC_Helper { /** * @brief replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement. * - * @param $string + * @param string $string * @param string $replacement The replacement string. * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string. * @param int $length Length of the part to be replaced diff --git a/lib/private/image.php b/lib/private/image.php index 14aa64d12da..341bfaaf818 100644 --- a/lib/private/image.php +++ b/lib/private/image.php @@ -424,7 +424,7 @@ class OC_Image { * @brief Loads an image from an open file handle. * It is the responsibility of the caller to position the pointer at the correct place and to close the handle again. * @param resource $handle - * @return An image resource or false on error + * @return resource|false An image resource or false on error */ public function loadFromFileHandle($handle) { OC_Log::write('core', __METHOD__.'(): Trying', OC_Log::DEBUG); diff --git a/lib/private/installer.php b/lib/private/installer.php index d7d43779d92..9417c32bc89 100644 --- a/lib/private/installer.php +++ b/lib/private/installer.php @@ -221,7 +221,7 @@ class OC_Installer{ /** * @brief checks whether or not an app is installed * @param string $app app - * @return true/false + * @return bool * * Checks whether or not an app is installed, i.e. registered in apps table. */ @@ -313,7 +313,7 @@ class OC_Installer{ /** * @brief Removes an app * @param string $name name of the application to remove - * @param $options array with options + * @param array $options options * @return boolean|null * * This function removes an app. $options is an associative array. The diff --git a/lib/private/l10n.php b/lib/private/l10n.php index 9ab60e871d0..c9d9e8131b1 100644 --- a/lib/private/l10n.php +++ b/lib/private/l10n.php @@ -183,7 +183,7 @@ class OC_L10N implements \OCP\IL10N { * * Parts of the code is copied from Habari: * https://github.com/habari/system/blob/master/classes/locale.php - * @param $string string + * @param string $string * @return string */ protected function createPluralFormFunction($string){ diff --git a/lib/private/l10n/factory.php b/lib/private/l10n/factory.php index 8c65f368171..d0c3799b9c2 100644 --- a/lib/private/l10n/factory.php +++ b/lib/private/l10n/factory.php @@ -20,8 +20,8 @@ class Factory { /** * get an L10N instance - * @param $app string - * @param $lang string|null + * @param string $app + * @param string|null $lang * @return \OC_L10N */ public function get($app) { diff --git a/lib/private/migrate.php b/lib/private/migrate.php index 2ec9a0978ad..98c825aafd8 100644 --- a/lib/private/migrate.php +++ b/lib/private/migrate.php @@ -333,7 +333,7 @@ class OC_Migrate{ /** * @brief tries to extract the import zip - * @param $path string path to the zip + * @param string $path path to the zip * @return string path to extract location (with a trailing slash) or false on failure */ static private function extractZip( $path ) { @@ -536,7 +536,7 @@ class OC_Migrate{ /** * @brief imports a new user * @param string $db string path to migration.db - * @param $info object of migration info + * @param object $info object of migration info * @param string|null|int $uid uid to use * @return array an array of apps with import statuses, or false on failure. */ diff --git a/lib/private/migration/content.php b/lib/private/migration/content.php index b0e7a4e9528..d3b2fe836a4 100644 --- a/lib/private/migration/content.php +++ b/lib/private/migration/content.php @@ -35,7 +35,7 @@ class OC_Migration_Content{ /** * @brief sets up the * @param ZipArchive $zip ZipArchive object - * @param $db a database object (required for exporttype user) + * @param object $db a database object (required for exporttype user) * @return bool|null */ public function __construct( $zip, $db=null ) { @@ -45,11 +45,9 @@ class OC_Migration_Content{ } - // @brief prepares the db - // @param $query the sql query to prepare - /** - * @param string $query + * @brief prepares the db + * @param string $query the sql query to prepare */ public function prepare( $query ) { @@ -88,7 +86,7 @@ class OC_Migration_Content{ /** * @brief copys rows to migration.db from the main database - * @param $options array of options. + * @param array $options array of options. * @return bool */ public function copyRows( $options ) { @@ -131,7 +129,7 @@ class OC_Migration_Content{ /** * @brief saves a sql data set into migration.db * @param OC_DB_StatementWrapper $data a sql data set returned from self::prepare()->query() - * @param $options array of copyRows options + * @param array $options array of copyRows options * @return void */ private function insertData( $data, $options ) { @@ -170,8 +168,8 @@ class OC_Migration_Content{ /** * @brief adds a directory to the zip object * @param boolean|string $dir string path of the directory to add - * @param $recursive bool - * @param $internaldir string path of folder to add dir to in zip + * @param bool $recursive + * @param string $internaldir path of folder to add dir to in zip * @return bool */ public function addDir( $dir, $recursive=true, $internaldir='' ) { diff --git a/lib/private/ocs.php b/lib/private/ocs.php index 211e8222145..aeb3d259b30 100644 --- a/lib/private/ocs.php +++ b/lib/private/ocs.php @@ -213,8 +213,8 @@ class OC_OCS { } /** - * @param $writer - * @param $data + * @param resource $writer + * @param array $data * @param string $node */ public static function toXml($writer, $data, $node) { diff --git a/lib/private/ocs/cloud.php b/lib/private/ocs/cloud.php index c8bb9425f1a..3ced0af8ee1 100644 --- a/lib/private/ocs/cloud.php +++ b/lib/private/ocs/cloud.php @@ -57,8 +57,8 @@ class OC_OCS_Cloud { * * * - * @param $parameters object should contain parameter 'userid' which identifies - * the user from whom the information will be returned + * @param array $parameters should contain parameter 'userid' which identifies + * the user from whom the information will be returned */ public static function getUser($parameters) { $return = array(); diff --git a/lib/private/ocs/result.php b/lib/private/ocs/result.php index 0e3b85d5905..567fe7f87fe 100644 --- a/lib/private/ocs/result.php +++ b/lib/private/ocs/result.php @@ -26,7 +26,7 @@ class OC_OCS_Result{ /** * create the OCS_Result object - * @param $data mixed the data to return + * @param mixed $data the data to return */ public function __construct($data=null, $code=100, $message=null) { if ($data === null) { @@ -42,7 +42,7 @@ class OC_OCS_Result{ /** * optionally set the total number of items available - * @param $items int + * @param int $items */ public function setTotalItems(int $items) { $this->items = $items; @@ -50,7 +50,7 @@ class OC_OCS_Result{ /** * optionally set the the number of items per page - * @param $items int + * @param int $items */ public function setItemsPerPage(int $items) { $this->perPage = $items; diff --git a/lib/private/ocsclient.php b/lib/private/ocsclient.php index 8b8930df937..fb8282747eb 100644 --- a/lib/private/ocsclient.php +++ b/lib/private/ocsclient.php @@ -95,7 +95,7 @@ class OC_OCSClient{ * @return array an array of application data * * This function returns a list of all the applications on the OCS server - * @param $categories + * @param array|string $categories * @param int $page * @param string $filter */ diff --git a/lib/private/preview.php b/lib/private/preview.php index 941f9f26c6a..bf8c04e0998 100755 --- a/lib/private/preview.php +++ b/lib/private/preview.php @@ -191,7 +191,7 @@ class Preview { /** * @brief set the path of the file you want a thumbnail from * @param string $file - * @return $this + * @return object $this */ public function setFile($file) { $this->file = $file; @@ -217,7 +217,7 @@ class Preview { * @brief set the the max width of the preview * @param int $maxX * @throws \Exception - * @return $this + * @return \OC\Preview $this */ public function setMaxX($maxX = 1) { if ($maxX <= 0) { @@ -238,7 +238,7 @@ class Preview { * @brief set the the max height of the preview * @param int $maxY * @throws \Exception - * @return $this + * @return \OC\Preview $this */ public function setMaxY($maxY = 1) { if ($maxY <= 0) { @@ -258,7 +258,7 @@ class Preview { /** * @brief set whether or not scalingup is enabled * @param bool $scalingUp - * @return $this + * @return \OC\Preview $this */ public function setScalingup($scalingUp) { if ($this->getMaxScaleFactor() === 1) { @@ -750,7 +750,7 @@ class Preview { } /** - * @param $fileId + * @param int $fileId * @return string */ private function buildCachePath($fileId) { diff --git a/lib/private/response.php b/lib/private/response.php index 4905c0a787b..f976925fb2e 100644 --- a/lib/private/response.php +++ b/lib/private/response.php @@ -93,7 +93,7 @@ class OC_Response { /** * @brief Set reponse expire time - * @param $expires date-time when the response expires + * @param string|DateTime $expires date-time when the response expires * string for DateInterval from now * DateTime object when to expire response */ @@ -113,7 +113,7 @@ class OC_Response { /** * Checks and set ETag header, when the request matches sends a * 'not modified' response - * @param $etag token to use for modification check + * @param string $etag token to use for modification check */ static public function setETagHeader($etag) { if (empty($etag)) { @@ -131,7 +131,7 @@ class OC_Response { /** * Checks and set Last-Modified header, when the request matches sends a * 'not modified' response - * @param $lastModified time when the reponse was last modified + * @param int|DateTime|string $lastModified time when the reponse was last modified */ static public function setLastModifiedHeader($lastModified) { if (empty($lastModified)) { diff --git a/lib/private/route/route.php b/lib/private/route/route.php index df80facf9c1..87030ad7853 100644 --- a/lib/private/route/route.php +++ b/lib/private/route/route.php @@ -124,7 +124,7 @@ class Route extends SymfonyRoute implements IRoute { /** * The action to execute when this route matches, includes a file like * it is called directly - * @param $file + * @param string $file * @return void */ public function actionInclude($file) { diff --git a/lib/private/route/router.php b/lib/private/route/router.php index 44b0b941508..a72ac2bb3f1 100644 --- a/lib/private/route/router.php +++ b/lib/private/route/router.php @@ -239,7 +239,7 @@ class Router implements IRouter { /** * To isolate the variable scope used inside the $file it is required in it's own method - * @param $file + * @param string $file */ private function requireRouteFile($file) { require_once $file; diff --git a/lib/private/share/helper.php b/lib/private/share/helper.php index 515ec85909a..68f4a35af19 100644 --- a/lib/private/share/helper.php +++ b/lib/private/share/helper.php @@ -25,13 +25,13 @@ class Helper extends \OC\Share\Constants { /** * Generate a unique target for the item - * @param string Item type - * @param string Item source - * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK - * @param string User or group the item is being shared with - * @param string User that is the owner of shared item - * @param string The suggested target originating from a reshare (optional) - * @param int The id of the parent group share (optional) + * @param string $itemType + * @param string $itemSource + * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK + * @param string $shareWith User or group the item is being shared with + * @param string $uidOwner User that is the owner of shared item + * @param string $suggestedTarget The suggested target originating from a reshare (optional) + * @param int $groupParent The id of the parent group share (optional) * @return string Item target */ public static function generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, @@ -142,9 +142,9 @@ class Helper extends \OC\Share\Constants { /** * Delete all reshares of an item - * @param int Id of item to delete - * @param bool If true, exclude the parent from the delete (optional) - * @param string The user that the parent was shared with (optinal) + * @param int $parent Id of item to delete + * @param bool $excludeParent If true, exclude the parent from the delete (optional) + * @param string $uidOwner The user that the parent was shared with (optinal) */ public static function delete($parent, $excludeParent = false, $uidOwner = null) { $ids = array($parent); diff --git a/lib/private/share/hooks.php b/lib/private/share/hooks.php index a33c71eedd2..9ac64d888ea 100644 --- a/lib/private/share/hooks.php +++ b/lib/private/share/hooks.php @@ -22,9 +22,9 @@ namespace OC\Share; class Hooks extends \OC\Share\Constants { - /** + /** * Function that is called after a user is deleted. Cleans up the shares of that user. - * @param array arguments + * @param array $arguments */ public static function post_deleteUser($arguments) { // Delete any items shared with the deleted user @@ -42,7 +42,7 @@ class Hooks extends \OC\Share\Constants { /** * Function that is called after a user is added to a group. * TODO what does it do? - * @param array arguments + * @param array $arguments */ public static function post_addToGroup($arguments) { // Find the group shares and check if the user needs a unique target @@ -76,7 +76,7 @@ class Hooks extends \OC\Share\Constants { /** * Function that is called after a user is removed from a group. Shares are cleaned up. - * @param array arguments + * @param array $arguments */ public static function post_removeFromGroup($arguments) { $sql = 'SELECT `id`, `share_type` FROM `*PREFIX*share`' @@ -95,7 +95,7 @@ class Hooks extends \OC\Share\Constants { /** * Function that is called after a group is removed. Cleans up the shares to that group. - * @param array arguments + * @param array $arguments */ public static function post_deleteGroup($arguments) { $sql = 'SELECT `id` FROM `*PREFIX*share` WHERE `share_type` = ? AND `share_with` = ?'; diff --git a/lib/private/share/mailnotifications.php b/lib/private/share/mailnotifications.php index 5110df0e571..0cd36e97d54 100644 --- a/lib/private/share/mailnotifications.php +++ b/lib/private/share/mailnotifications.php @@ -50,8 +50,8 @@ class MailNotifications { * @brief inform users if a file was shared with them * * @param array $recipientList list of recipients - * @param type $itemSource shared item source - * @param type $itemType shared item type + * @param string $itemSource shared item source + * @param string $itemType shared item type * @return array list of user to whom the mail send operation failed */ public function sendInternalShareMail($recipientList, $itemSource, $itemType) { diff --git a/lib/private/share/searchresultsorter.php b/lib/private/share/searchresultsorter.php index 76abbf30846..91709902fff 100644 --- a/lib/private/share/searchresultsorter.php +++ b/lib/private/share/searchresultsorter.php @@ -18,8 +18,8 @@ class SearchResultSorter { * @param string $search the search term as was given by the user * @param string $key the array key containing the value that should be compared * against - * @param $encoding optional, encoding to use, defaults to UTF-8 - * @param $log optional, an \OC\Log instance + * @param string $encoding optional, encoding to use, defaults to UTF-8 + * @param \OC\Log $log optional */ public function __construct($search, $key, \OC\Log $log = null, $encoding = 'UTF-8') { $this->encoding = $encoding; diff --git a/lib/private/share/share.php b/lib/private/share/share.php index 211c7e7cb1c..98275a59a6f 100644 --- a/lib/private/share/share.php +++ b/lib/private/share/share.php @@ -254,12 +254,12 @@ class Share extends \OC\Share\Constants { /** * Get the items of item type shared with a user - * @param string Item type - * @param sting user id for which user we want the shares - * @param int Format (optional) Format type must be defined by the backend - * @param mixed Parameters (optional) - * @param int Number of items to return (optional) Returns all by default - * @param boolean include collections (optional) + * @param string $itemType + * @param string $user id for which user we want the shares + * @param int $format (optional) Format type must be defined by the backend + * @param mixed $parameters (optional) + * @param int $limit Number of items to return (optional) Returns all by default + * @param boolean $includeCollections (optional) * @return Return depends on format */ public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE, @@ -388,8 +388,8 @@ class Share extends \OC\Share\Constants { /** * resolves reshares down to the last real share - * @param $linkItem - * @return $fileOwner + * @param array $linkItem + * @return array file owner */ public static function resolveReShare($linkItem) { @@ -446,7 +446,7 @@ class Share extends \OC\Share\Constants { * @param string $uidOwner * @param boolean $includeCollections * @param boolean $checkExpireDate - * @return Return array of users + * @return array Return array of users */ public static function getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections = false, $checkExpireDate = true) { @@ -1000,10 +1000,10 @@ class Share extends \OC\Share\Constants { /** * Get shared items from the database * @param string $itemType - * @param string Item source or target (optional) + * @param string $item Item source or target (optional) * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique * @param string $shareWith User or group the item is being shared with - * @param string uidOwner User that is the owner of shared items (optional) + * @param string $uidOwner User that is the owner of shared items (optional) * @param int $format Format to convert items to with formatItems() (optional) * @param mixed $parameters to pass to formatItems() (optional) * @param int $limit Number of items to return, -1 to return all matches (optional) diff --git a/lib/private/subadmin.php b/lib/private/subadmin.php index 5b6072987ad..3e8b73d55b0 100644 --- a/lib/private/subadmin.php +++ b/lib/private/subadmin.php @@ -167,7 +167,7 @@ class OC_SubAdmin{ /** * @brief delete all SubAdmins by uid - * @param $parameters + * @param array $parameters * @return boolean */ public static function post_deleteUser($parameters) { @@ -178,7 +178,7 @@ class OC_SubAdmin{ /** * @brief delete all SubAdmins by gid - * @param $parameters + * @param array $parameters * @return boolean */ public static function post_deleteGroup($parameters) { diff --git a/lib/private/tags.php b/lib/private/tags.php index 2e786e3fd7b..0b62caf2dd8 100644 --- a/lib/private/tags.php +++ b/lib/private/tags.php @@ -393,7 +393,7 @@ class Tags implements \OCP\ITags { * * For hooking up on post_deleteUser * - * @param array + * @param array $arguments */ public static function post_deleteUser($arguments) { // Find all objectid/tagId pairs. diff --git a/lib/private/template/functions.php b/lib/private/template/functions.php index 0a32dc48f22..3f5312c0a7b 100644 --- a/lib/private/template/functions.php +++ b/lib/private/template/functions.php @@ -70,7 +70,7 @@ function mimetype_icon( $mimetype ) { /** * @brief make preview_icon available as a simple function * Returns the path to the preview of the image. - * @param $path path of file + * @param string $path path of file * @return link to the preview * * For further information have a look at OC_Helper::previewIcon diff --git a/lib/private/template/resourcelocator.php b/lib/private/template/resourcelocator.php index 8a3dd5e7fa9..900aa6a8f08 100644 --- a/lib/private/template/resourcelocator.php +++ b/lib/private/template/resourcelocator.php @@ -53,13 +53,9 @@ abstract class ResourceLocator { /* * @brief append the $file resource if exist at $root - * @param $root path to check - * @param $file the filename - * @param $web base for path, default map $root to $webroot - */ - /** - * @param string $file - * @param string|false $webroot + * @param string $root path to check + * @param string $file the filename + * @param string|null $webroot base for path, default map $root to $webroot */ protected function appendIfExist($root, $file, $webroot = null) { if (is_file($root.'/'.$file)) { diff --git a/lib/private/templatelayout.php b/lib/private/templatelayout.php index b7ac02a753d..0672ffc4a3d 100644 --- a/lib/private/templatelayout.php +++ b/lib/private/templatelayout.php @@ -98,7 +98,7 @@ class OC_TemplateLayout extends OC_Template { } /** - * @param $styles + * @param array $styles * @return array */ static public function findStylesheetFiles($styles) { @@ -116,7 +116,7 @@ class OC_TemplateLayout extends OC_Template { } /** - * @param $scripts + * @param array $scripts * @return array */ static public function findJavascriptFiles($scripts) { @@ -175,7 +175,7 @@ class OC_TemplateLayout extends OC_Template { } /** - * @param $files + * @param array $files * @return string */ private static function hashScriptNames($files) diff --git a/lib/private/urlgenerator.php b/lib/private/urlgenerator.php index a56b0fe3378..b37ef89d40d 100644 --- a/lib/private/urlgenerator.php +++ b/lib/private/urlgenerator.php @@ -30,7 +30,7 @@ class URLGenerator implements IURLGenerator { /** * @brief Creates an url using a defined route - * @param $route + * @param string $route * @param array $parameters * @internal param array $args with param=>value, will be appended to the returned url * @return string the url diff --git a/lib/private/user/database.php b/lib/private/user/database.php index 284b3582598..747895a8a95 100644 --- a/lib/private/user/database.php +++ b/lib/private/user/database.php @@ -57,9 +57,9 @@ class OC_User_Database extends OC_User_Backend { /** * @brief Create a new user - * @param $uid The username of the user to create - * @param $password The password of the new user - * @return true/false + * @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. @@ -79,8 +79,8 @@ class OC_User_Database extends OC_User_Backend { /** * @brief delete a user - * @param $uid The username of the user to delete - * @return true/false + * @param string $uid The username of the user to delete + * @return bool * * Deletes a user */ @@ -98,9 +98,9 @@ class OC_User_Database extends OC_User_Backend { /** * @brief Set password - * @param $uid The username - * @param $password The new password - * @return true/false + * @param string $uid The username + * @param string $password The new password + * @return bool * * Change the password of a user */ @@ -119,9 +119,9 @@ class OC_User_Database extends OC_User_Backend { /** * @brief Set display name - * @param $uid The username - * @param $displayName The new display name - * @return true/false + * @param string $uid The username + * @param string $displayName The new display name + * @return bool * * Change the display name of a user */ @@ -139,7 +139,7 @@ class OC_User_Database extends OC_User_Backend { /** * @brief get display name of the user - * @param $uid user ID of the user + * @param string $uid user ID of the user * @return string display name */ public function getDisplayName($uid) { @@ -169,8 +169,8 @@ class OC_User_Database extends OC_User_Backend { /** * @brief Check if the password is correct - * @param $uid The username - * @param $password The password + * @param string $uid The username + * @param string $password The password * @return string * * Check if the password is correct without logging in the user diff --git a/lib/private/user/example.php b/lib/private/user/example.php index e6e2744b405..4bf3652330e 100644 --- a/lib/private/user/example.php +++ b/lib/private/user/example.php @@ -28,9 +28,9 @@ abstract class OC_User_Example extends OC_User_Backend { /** * @brief Create a new user - * @param $uid The username of the user to create - * @param $password The password of the new user - * @return true/false + * @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. @@ -39,9 +39,9 @@ abstract class OC_User_Example extends OC_User_Backend { /** * @brief Set password - * @param $uid The username - * @param $password The new password - * @return true/false + * @param string $uid The username + * @param string $password The new password + * @return bool * * Change the password of a user */ @@ -49,8 +49,8 @@ abstract class OC_User_Example extends OC_User_Backend { /** * @brief Check if the password is correct - * @param $uid The username - * @param $password The password + * @param string $uid The username + * @param string $password The password * @return string * * Check if the password is correct without logging in the user @@ -60,7 +60,7 @@ abstract class OC_User_Example extends OC_User_Backend { /** * @brief get the user's home directory - * @param $uid The username + * @param string $uid The username * @return string * * get the user's home directory diff --git a/lib/private/user/http.php b/lib/private/user/http.php index 806378a7c2c..67f7156b498 100644 --- a/lib/private/user/http.php +++ b/lib/private/user/http.php @@ -27,7 +27,7 @@ class OC_User_HTTP extends OC_User_Backend { /** * split http://user@host/path into a user and url part - * @param string path + * @param string $url * @return array */ private function parseUrl($url) { @@ -46,7 +46,7 @@ class OC_User_HTTP extends OC_User_Backend { /** * check if an url is a valid login - * @param string url + * @param string $url * @return boolean */ private function matchUrl($url) { @@ -55,8 +55,8 @@ class OC_User_HTTP extends OC_User_Backend { /** * @brief Check if the password is correct - * @param $uid The username - * @param $password The password + * @param string $uid The username + * @param string $password The password * @return string * * Check if the password is correct without logging in the user diff --git a/lib/private/user/interface.php b/lib/private/user/interface.php index 80da765cd9f..e130e5b569c 100644 --- a/lib/private/user/interface.php +++ b/lib/private/user/interface.php @@ -30,17 +30,13 @@ interface OC_User_Interface { * * Returns the supported actions as int to be * compared with OC_USER_BACKEND_CREATE_USER etc. - * @return boolean */ public function implementsActions($actions); /** * @brief delete a user - * @param $uid The username of the user to delete - * @return true/false - * - * Deletes a user - * @return boolean + * @param string $uid The username of the user to delete + * @return bool */ public function deleteUser($uid); @@ -61,8 +57,8 @@ interface 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); diff --git a/lib/private/util.php b/lib/private/util.php index f3fa7b1f220..1c3177af435 100755 --- a/lib/private/util.php +++ b/lib/private/util.php @@ -818,8 +818,8 @@ class OC_Util { * This function is used to sanitize HTML and should be applied on any * string or array of strings before displaying it on a web page. * - * @param string|array of strings - * @return array an array of sanitized strings or a single sanitized string, depends on the input parameter. + * @param string|array &$value + * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter. */ public static function sanitizeHTML( &$value ) { if (is_array($value)) { @@ -1028,8 +1028,8 @@ class OC_Util { /** * @brief Generates a cryptographic secure pseudo-random string - * @param Int $length of the random string - * @return String + * @param int $length of the random string + * @return string * Please also update secureRNGAvailable if you change something here */ public static function generateRandomBytes($length = 30) { @@ -1287,7 +1287,7 @@ class OC_Util { /** * Returns whether the given file name is valid - * @param $file string file name to check + * @param string $file file name to check * @return bool true if the file name is valid, false otherwise */ public static function isValidFileName($file) { diff --git a/lib/private/vobject.php b/lib/private/vobject.php index 20cacd926ba..cb556e07c9e 100644 --- a/lib/private/vobject.php +++ b/lib/private/vobject.php @@ -89,7 +89,7 @@ class OC_VObject{ /** * Constructor - * @param Sabre\VObject\Component or string + * @param Sabre\VObject\Component|string $vobject_or_name */ public function __construct($vobject_or_name) { if (is_object($vobject_or_name)) { @@ -101,7 +101,7 @@ class OC_VObject{ /** * @todo Write documentation - * @param $item + * @param \OC_VObject|\Sabre\VObject\Component $item * @param null $itemValue */ public function add($item, $itemValue = null) { @@ -138,7 +138,7 @@ class OC_VObject{ /** * @todo Write documentation - * @param mixed $name + * @param mixed $name * @param string $string */ public function setString($name, $string) { @@ -175,7 +175,7 @@ class OC_VObject{ /** * @todo Write documentation - * @param $name + * @param string $name * @return string */ public function getAsString($name) { @@ -186,7 +186,7 @@ class OC_VObject{ /** * @todo Write documentation - * @param $name + * @param string $name * @return array */ public function getAsArray($name) { @@ -200,7 +200,7 @@ class OC_VObject{ /** * @todo Write documentation - * @param $name + * @param string $name * @return array|OC_VObject|\Sabre\VObject\Property */ public function &__get($name) { @@ -242,8 +242,8 @@ class OC_VObject{ /** * @todo Write documentation - * @param $function - * @param $arguments + * @param callable $function + * @param array $arguments * @return mixed */ public function __call($function, $arguments) { diff --git a/lib/public/app.php b/lib/public/app.php index 96162299ec4..bef4e96ae02 100644 --- a/lib/public/app.php +++ b/lib/public/app.php @@ -36,7 +36,7 @@ namespace OCP; class App { /** * Makes ownCloud aware of this app - * @param array with all information + * @param array $data with all information * @return boolean * * @deprecated This method is deprecated. Do not call it anymore. @@ -49,7 +49,7 @@ class App { /** * Adds an entry to the navigation - * @param array containing the data + * @param array $data containing the data * @return boolean * * This function adds a new entry to the navigation visible to users. $data @@ -70,7 +70,7 @@ class App { /** * Marks a navigation entry as active - * @param string id of the entry + * @param string $id id of the entry * @return boolean * * This function sets a navigation entry as active and removes the 'active' @@ -83,8 +83,8 @@ class App { /** * Register a Configuration Screen that should appear in the personal settings section. - * @param $app string appid - * @param $page string page to be included + * @param string $app appid + * @param string $page page to be included * @return void */ public static function registerPersonal( $app, $page ) { diff --git a/lib/public/backgroundjob.php b/lib/public/backgroundjob.php index 1832f766ea3..562228e1e52 100644 --- a/lib/public/backgroundjob.php +++ b/lib/public/backgroundjob.php @@ -94,7 +94,7 @@ class BackgroundJob { /** * @deprecated * gets all regular tasks - * @return associative array + * @return array * * key is string "$klass-$method", value is array( $klass, $method ) */ @@ -115,7 +115,7 @@ class BackgroundJob { * @deprecated * Gets one queued task * @param int $id ID of the task - * @return BackgroundJob\IJob array + * @return BackgroundJob\IJob|null */ public static function findQueuedTask($id) { $jobList = \OC::$server->getJobList(); diff --git a/lib/public/backgroundjob/ijoblist.php b/lib/public/backgroundjob/ijoblist.php index c9b546605b8..366b0e37368 100644 --- a/lib/public/backgroundjob/ijoblist.php +++ b/lib/public/backgroundjob/ijoblist.php @@ -12,7 +12,7 @@ interface IJobList { /** * Add a job to the list * - * @param \OCP\BackgroundJob\IJob |string $job + * @param \OCP\BackgroundJob\IJob|string $job * @param mixed $argument The argument to be passed to $job->run() when the job is exectured * @param string $job * @return void @@ -22,7 +22,7 @@ interface IJobList { /** * Remove a job from the list * - * @param IJob $job + * @param \OCP\BackgroundJob\IJob|string $job * @param mixed $argument * @return void */ @@ -31,7 +31,7 @@ interface IJobList { /** * check if a job is in the list * - * @param $job + * @param \OCP\BackgroundJob\IJob|string $job * @param mixed $argument * @return bool */ diff --git a/lib/public/contacts.php b/lib/public/contacts.php index 70c67c75731..0d12e91c67f 100644 --- a/lib/public/contacts.php +++ b/lib/public/contacts.php @@ -98,7 +98,7 @@ namespace OCP { * This function can be used to delete the contact identified by the given id * * @param object $id the unique identifier to a contact - * @param $address_book_key + * @param string $address_book_key * @return bool successful or not */ public static function delete($id, $address_book_key) { @@ -111,7 +111,7 @@ namespace OCP { * Otherwise the contact will be updated by replacing the entire data set. * * @param array $properties this array if key-value-pairs defines a contact - * @param $address_book_key string to identify the address book in which the contact shall be created or updated + * @param string $address_book_key identifier of the address book in which the contact shall be created or updated * @return array an array representing the contact just created or updated */ public static function createOrUpdate($properties, $address_book_key) { diff --git a/lib/public/db.php b/lib/public/db.php index cb876b4d1f9..ba3a4724ce0 100644 --- a/lib/public/db.php +++ b/lib/public/db.php @@ -50,7 +50,7 @@ class DB { /** * Insert a row if a matching row doesn't exists. * @param string $table The optional table name (will replace *PREFIX*) and add sequence suffix - * @param $input array + * @param array $input * * The input array if in the form: * diff --git a/lib/public/iavatar.php b/lib/public/iavatar.php index 43fa32556de..fc7e8e79fed 100644 --- a/lib/public/iavatar.php +++ b/lib/public/iavatar.php @@ -15,7 +15,7 @@ interface IAvatar { /** * @brief get the users avatar - * @param $size integer size in px of the avatar, avatars are square, defaults to 64 + * @param int $size size in px of the avatar, avatars are square, defaults to 64 * @return boolean|\OC_Image containing the avatar or false if there's no image */ function get($size = 64); diff --git a/lib/public/iavatarmanager.php b/lib/public/iavatarmanager.php index 9b185ae0467..b09b456a0da 100644 --- a/lib/public/iavatarmanager.php +++ b/lib/public/iavatarmanager.php @@ -16,7 +16,7 @@ interface IAvatarManager { /** * @brief return a user specific instance of \OCP\IAvatar * @see \OCP\IAvatar - * @param $user string the ownCloud user id + * @param string $user the ownCloud user id * @return \OCP\IAvatar */ function getAvatar($user); diff --git a/lib/public/idbconnection.php b/lib/public/idbconnection.php index 656b5e7e5b2..3e6624e07e9 100644 --- a/lib/public/idbconnection.php +++ b/lib/public/idbconnection.php @@ -52,8 +52,8 @@ interface IDBConnection { /** * Insert a row if a matching row doesn't exists. - * @param string The table name (will replace *PREFIX*) to perform the replace on. - * @param array + * @param string $table The table name (will replace *PREFIX*) to perform the replace on. + * @param array $input * * The input array if in the form: * diff --git a/lib/public/il10n.php b/lib/public/il10n.php index 1388274c21a..c228be6a0a3 100644 --- a/lib/public/il10n.php +++ b/lib/public/il10n.php @@ -53,7 +53,7 @@ interface IL10N { * Localization * @param string $type Type of localization * @param array $data parameters for this localization - * @return String or false + * @return string|false * * Returns the localized data. * diff --git a/lib/public/route/iroute.php b/lib/public/route/iroute.php index d5610e762a8..f511e7af720 100644 --- a/lib/public/route/iroute.php +++ b/lib/public/route/iroute.php @@ -26,7 +26,7 @@ interface IRoute { * The action to execute when this route matches, includes a file like * it is called directly * - * @param $file + * @param string $file * @return void */ public function actionInclude($file); diff --git a/lib/public/share.php b/lib/public/share.php index 018386253bc..33c5069ac57 100644 --- a/lib/public/share.php +++ b/lib/public/share.php @@ -92,13 +92,13 @@ class Share extends \OC\Share\Constants { /** * Get the items of item type shared with a user - * @param string Item type - * @param sting user id for which user we want the shares - * @param int Format (optional) Format type must be defined by the backend - * @param mixed Parameters (optional) - * @param int Number of items to return (optional) Returns all by default - * @param bool include collections (optional) - * @return Return depends on format + * @param string $itemType + * @param string $user for which user we want the shares + * @param int $format (optional) Format type must be defined by the backend + * @param mixed $parameters (optional) + * @param int $limit Number of items to return (optional) Returns all by default + * @param bool $includeCollections (optional) + * @return mixed Return depends on format */ public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE, $parameters = null, $limit = -1, $includeCollections = false) { @@ -111,8 +111,8 @@ class Share extends \OC\Share\Constants { * @param string $itemType * @param string $itemTarget * @param int $format (optional) Format type must be defined by the backend - * @param mixed Parameters (optional) - * @param bool include collections (optional) + * @param mixed $parameters (optional) + * @param bool $includeCollections (optional) * @return mixed Return depends on format */ public static function getItemSharedWith($itemType, $itemTarget, $format = self::FORMAT_NONE, @@ -168,8 +168,8 @@ class Share extends \OC\Share\Constants { /** * resolves reshares down to the last real share - * @param $linkItem - * @return $fileOwner + * @param array $linkItem + * @return array file owner */ public static function resolveReShare($linkItem) { return \OC\Share\Share::resolveReShare($linkItem); @@ -213,7 +213,7 @@ class Share extends \OC\Share\Constants { * @param string $uidOwner * @param bool $includeCollections * @param bool $checkExpireDate - * @return Return array of users + * @return array Return array of users */ public static function getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections = false, $checkExpireDate = true) { return \OC\Share\Share::getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections, $checkExpireDate); diff --git a/lib/public/template.php b/lib/public/template.php index 6cc984b12d5..b1264e0c3ad 100644 --- a/lib/public/template.php +++ b/lib/public/template.php @@ -33,8 +33,8 @@ namespace OCP; /** * Make OC_Helper::imagePath available as a simple function - * @param string app - * @param string image + * @param string $app + * @param string $image * @return string to the image * * @see OC_Helper::imagePath @@ -46,7 +46,7 @@ function image_path( $app, $image ) { /** * Make OC_Helper::mimetypeIcon available as a simple function - * @param string mimetype + * @param string $mimetype * @return string to the image of this file type. */ function mimetype_icon( $mimetype ) { @@ -55,7 +55,7 @@ function mimetype_icon( $mimetype ) { /** * Make preview_icon available as a simple function - * @param string path of file + * @param string $path path to file * @return string to the preview of the image */ function preview_icon( $path ) { @@ -76,7 +76,7 @@ function publicPreview_icon ( $path, $token ) { /** * Make OC_Helper::humanFileSize available as a simple function * Example: 2048 to 2 kB. - * @param int size in bytes + * @param int $size in bytes * @return string size as string */ function human_file_size( $bytes ) { @@ -86,8 +86,8 @@ function human_file_size( $bytes ) { /** * Return the relative date in relation to today. Returns something like "last hour" or "two month ago" - * @param int unix timestamp - * @param boolean date only + * @param int $timestamp unix timestamp + * @param boolean $dateOnly * @return OC_L10N_String human readable interpretation of the timestamp */ function relative_modified_date( $timestamp, $dateOnly = false ) { @@ -98,7 +98,7 @@ function relative_modified_date( $timestamp, $dateOnly = false ) { /** * Return a human readable outout for a file size. * @deprecated human_file_size() instead - * @param integer size of a file in byte + * @param integer $bytes size of a file in byte * @return string human readable interpretation of a file size */ function simple_file_size($bytes) { @@ -108,9 +108,9 @@ function simple_file_size($bytes) { /** * Generate html code for an options block. - * @param $options the options - * @param $selected which one is selected? - * @param array the parameters + * @param array $options the options + * @param mixed $selected which one is selected? + * @param array $params the parameters * @return string html options */ function html_select_options($options, $selected, $params=array()) { diff --git a/lib/public/user.php b/lib/public/user.php index e79ad4e7190..925410d37d5 100644 --- a/lib/public/user.php +++ b/lib/public/user.php @@ -45,9 +45,9 @@ class User { /** * Get a list of all users - * @param string search pattern - * @param integer $limit - * @param integer $offset + * @param string $search search pattern + * @param int|null $limit + * @param int|null $offset * @return array an array of all uids */ public static function getUsers( $search = '', $limit = null, $offset = null ) { @@ -56,7 +56,7 @@ class User { /** * Get the user display name of the user currently logged in. - * @param string user id or null for current user + * @param string|null $user user id or null for current user * @return string display name */ public static function getDisplayName( $user = null ) { @@ -65,9 +65,9 @@ class User { /** * Get a list of all display names and user ids. - * @param string search pattern - * @param int limit - * @param int offset + * @param string $search search pattern + * @param int|null $limit + * @param int|null $offset * @return array an array of all display names (value) and the correspondig uids (key) */ public static function getDisplayNames( $search = '', $limit = null, $offset = null ) { diff --git a/lib/public/util.php b/lib/public/util.php index 0ca6f7928c3..8aeb03aef8e 100644 --- a/lib/public/util.php +++ b/lib/public/util.php @@ -203,7 +203,7 @@ class Util { /** * Creates an url using a defined route - * @param $route + * @param string $route * @param array $parameters * @internal param array $args with param=>value, will be appended to the returned url * @return string the url @@ -380,8 +380,8 @@ class Util { * This function is used to sanitize HTML and should be applied on any * string or array of strings before displaying it on a web page. * - * @param string|array of strings - * @return array an array of sanitized strings or a single sinitized string, depends on the input parameter. + * @param string|array $value + * @return string|array an array of sanitized strings or a single sinitized string, depends on the input parameter. */ public static function sanitizeHTML( $value ) { return(\OC_Util::sanitizeHTML($value)); @@ -458,7 +458,7 @@ class Util { * * @param string $dir the current folder where the user currently operates * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly - * @return number of bytes representing + * @return int number of bytes representing */ public static function maxUploadFilesize($dir, $free = null) { return \OC_Helper::maxUploadFilesize($dir, $free); @@ -476,7 +476,7 @@ class Util { /** * Calculate PHP upload limit * - * @return number of bytes representing + * @return int number of bytes representing */ public static function uploadLimit() { return \OC_Helper::uploadLimit(); @@ -484,7 +484,7 @@ class Util { /** * Returns whether the given file name is valid - * @param $file string file name to check + * @param string $file file name to check * @return bool true if the file name is valid, false otherwise */ public static function isValidFileName($file) { @@ -493,8 +493,8 @@ class Util { /** * @brief Generates a cryptographic secure pseudo-random string - * @param Int $length of the random string - * @return String + * @param int $length of the random string + * @return string */ public static function generateRandomBytes($length = 30) { return \OC_Util::generateRandomBytes($length); -- cgit v1.2.3 From 3bed3d2a23748f40c041d9daf9af26a2e16fe03b Mon Sep 17 00:00:00 2001 From: Robin McCorkell Date: Sun, 11 May 2014 22:32:26 +0100 Subject: Change parameter type for useBackend --- lib/private/user.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/user.php b/lib/private/user.php index 2ba681cd4a4..90aac88cdc8 100644 --- a/lib/private/user.php +++ b/lib/private/user.php @@ -98,7 +98,7 @@ class OC_User { /** * @brief Adds the backend to the list of used backends - * @param string|OC_User_Backend $backend default: database The backend to use for user management + * @param string|OC_User_Interface $backend default: database The backend to use for user management * @return bool * * Set the User Authentication Module -- cgit v1.2.3 From 7e448a376f96b31dc9c41d0e0ff6492aa8c9f8ca Mon Sep 17 00:00:00 2001 From: Lukas Reschke Date: Sat, 10 May 2014 22:32:13 +0200 Subject: Fix PHPDoc and typos Some things my IDE complained about while creating a custom backend. Fix PHPDoc and typos Some things my IDE complained about while creating a custom backend. Conflicts: lib/private/group/database.php lib/private/group/dummy.php lib/private/group/example.php --- lib/private/group/backend.php | 2 +- lib/private/group/database.php | 3 +-- lib/private/group/dummy.php | 23 ++++++++++++++++------- lib/private/group/example.php | 14 +++++++++----- 4 files changed, 27 insertions(+), 15 deletions(-) (limited to 'lib/private') diff --git a/lib/private/group/backend.php b/lib/private/group/backend.php index c1de99bca58..38522d0c43c 100644 --- a/lib/private/group/backend.php +++ b/lib/private/group/backend.php @@ -69,7 +69,7 @@ abstract class OC_Group_Backend implements OC_Group_Interface { /** * @brief Check if backend implements actions * @param int $actions bitwise-or'ed actions - * @return boolean + * @return bool * * Returns the supported actions as int to be * compared with OC_GROUP_BACKEND_CREATE_GROUP etc. diff --git a/lib/private/group/database.php b/lib/private/group/database.php index 18c060e9b22..91baa3140cc 100644 --- a/lib/private/group/database.php +++ b/lib/private/group/database.php @@ -215,9 +215,8 @@ class OC_Group_Database extends OC_Group_Backend { * @brief get the number of all users matching the search string in a group * @param string $gid * @param string $search - * @param int $limit - * @param int $offset * @return int|false + * @throws DatabaseException */ public function countUsersInGroup($gid, $search = '') { $stmt = OC_DB::prepare('SELECT COUNT(`uid`) AS `count` FROM `*PREFIX*group_user` WHERE `gid` = ? AND `uid` LIKE ?'); diff --git a/lib/private/group/dummy.php b/lib/private/group/dummy.php index 553aae54291..75bab31a337 100644 --- a/lib/private/group/dummy.php +++ b/lib/private/group/dummy.php @@ -31,7 +31,7 @@ class OC_Group_Dummy extends OC_Group_Backend { * @param string $gid The name of the group to create * @return bool * - * Trys to create a new group. If the group name already exists, false will + * Tries to create a new group. If the group name already exists, false will * be returned. */ public function createGroup($gid) { @@ -136,18 +136,23 @@ class OC_Group_Dummy extends OC_Group_Backend { } /** - * @brief get a list of all groups + * @brief Get a list of all groups + * @param string $search + * @param int $limit + * @param int $offset * @return array an array of group names - * - * Returns a list with all groups */ public function getGroups($search = '', $limit = -1, $offset = 0) { return array_keys($this->groups); } /** - * @brief get a list of all users in a group - * @return array an array of user ids + * @brief Get a list of all users in a group + * @param string $gid + * @param string $search + * @param int $limit + * @param int $offset + * @return array an array of user IDs */ public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { if(isset($this->groups[$gid])) { @@ -159,7 +164,11 @@ class OC_Group_Dummy extends OC_Group_Backend { /** * @brief get the number of all users in a group - * @return int|bool + * @param string $gid + * @param string $search + * @param int $limit + * @param int $offset + * @return int */ public function countUsersInGroup($gid, $search = '', $limit = -1, $offset = 0) { if(isset($this->groups[$gid])) { diff --git a/lib/private/group/example.php b/lib/private/group/example.php index cfcc0d245d1..76c9ce2433d 100644 --- a/lib/private/group/example.php +++ b/lib/private/group/example.php @@ -31,7 +31,7 @@ abstract class OC_Group_Example { * @param string $gid The name of the group to create * @return bool * - * Trys to create a new group. If the group name already exists, false will + * Tries to create a new group. If the group name already exists, false will * be returned. */ abstract public static function createGroup($gid); @@ -87,14 +87,15 @@ abstract class OC_Group_Example { /** * @brief get a list of all groups + * @param string $search + * @param int $limit + * @param int $offset * @return array an array of group names - * - * Returns a list with all groups */ abstract public static function getGroups($search = '', $limit = -1, $offset = 0); /** - * check if a group exists + * @brief Check if a group exists * @param string $gid * @return bool */ @@ -102,8 +103,11 @@ abstract class OC_Group_Example { /** * @brief get a list of all users in a group + * @param string $gid + * @param string $search + * @param int $limit + * @param int $offset * @return array an array of user ids */ abstract public static function usersInGroup($gid, $search = '', $limit = -1, $offset = 0); - } -- cgit v1.2.3 From 8ab01599a9d1f62b4d897199e83c9df74cc1ab7b Mon Sep 17 00:00:00 2001 From: Robin McCorkell Date: Mon, 12 May 2014 13:10:09 +0100 Subject: Use OC_User_Interface instead of OC_User_Backend --- lib/private/user/manager.php | 8 ++++---- lib/private/user/user.php | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'lib/private') diff --git a/lib/private/user/manager.php b/lib/private/user/manager.php index 6765491e695..0fcf1ceb6ab 100644 --- a/lib/private/user/manager.php +++ b/lib/private/user/manager.php @@ -26,7 +26,7 @@ use OC\Hooks\PublicEmitter; */ class Manager extends PublicEmitter { /** - * @var \OC_User_Backend[] $backends + * @var \OC_User_Interface[] $backends */ private $backends = array(); @@ -57,7 +57,7 @@ class Manager extends PublicEmitter { /** * register a user backend * - * @param \OC_User_Backend $backend + * @param \OC_User_Interface $backend */ public function registerBackend($backend) { $this->backends[] = $backend; @@ -66,7 +66,7 @@ class Manager extends PublicEmitter { /** * remove a user backend * - * @param \OC_User_Backend $backend + * @param \OC_User_Interface $backend */ public function removeBackend($backend) { $this->cachedUsers = array(); @@ -105,7 +105,7 @@ class Manager extends PublicEmitter { * get or construct the user object * * @param string $uid - * @param \OC_User_Backend $backend + * @param \OC_User_Interface $backend * @return \OC\User\User */ protected function getUserObject($uid, $backend) { diff --git a/lib/private/user/user.php b/lib/private/user/user.php index abdbef38d9a..229cbf68ff1 100644 --- a/lib/private/user/user.php +++ b/lib/private/user/user.php @@ -23,7 +23,7 @@ class User { private $displayName; /** - * @var \OC_User_Backend $backend + * @var \OC_User_Interface $backend */ private $backend; @@ -49,7 +49,7 @@ class User { /** * @param string $uid - * @param \OC_User_Backend $backend + * @param \OC_User_Interface $backend * @param \OC\Hooks\Emitter $emitter * @param \OC\AllConfig $config */ -- cgit v1.2.3 From bac8962bbc8cbeb4382df6bf5c8b9244c0f6340e Mon Sep 17 00:00:00 2001 From: Robin McCorkell Date: Mon, 12 May 2014 23:27:36 +0100 Subject: Fix Scrutinizer errors --- lib/private/config.php | 6 +++--- lib/private/files/view.php | 5 +++++ lib/private/hook.php | 2 +- lib/private/user/session.php | 6 +++--- 4 files changed, 12 insertions(+), 7 deletions(-) (limited to 'lib/private') diff --git a/lib/private/config.php b/lib/private/config.php index 2320db9d6bd..4242682af3d 100644 --- a/lib/private/config.php +++ b/lib/private/config.php @@ -77,8 +77,8 @@ class Config { /** * @brief Gets a value from config.php * @param string $key key - * @param array|bool|string|null $default = null default value - * @return string the value or $default + * @param mixed $default = null default value + * @return mixed the value or $default * * This function gets the value from config.php. If it does not exist, * $default will be returned. @@ -94,7 +94,7 @@ class Config { /** * @brief Sets a value * @param string $key key - * @param string $value value + * @param mixed $value value * * This function sets the value and writes the config.php. * diff --git a/lib/private/files/view.php b/lib/private/files/view.php index a53c2fbb322..1f424757bb8 100644 --- a/lib/private/files/view.php +++ b/lib/private/files/view.php @@ -552,6 +552,11 @@ class View { } } + /** + * @param string $path + * @param string $mode + * @return resource + */ public function fopen($path, $mode) { $hooks = array(); switch ($mode) { diff --git a/lib/private/hook.php b/lib/private/hook.php index 7ae6496f91d..b715db2d16c 100644 --- a/lib/private/hook.php +++ b/lib/private/hook.php @@ -45,7 +45,7 @@ class OC_Hook{ * @brief emits a signal * @param string $signalclass class name of emitter * @param string $signalname name of signal - * @param array $params default: array() array with additional data + * @param mixed $params default: array() array with additional data * @return bool, true if slots exists or false if not * * Emits a signal. To get data from the slot use references! diff --git a/lib/private/user/session.php b/lib/private/user/session.php index 1740bad5abe..3d10b134b83 100644 --- a/lib/private/user/session.php +++ b/lib/private/user/session.php @@ -82,7 +82,7 @@ class Session implements Emitter, \OCP\IUserSession { /** * set the currently active user * - * @param \OC\User\User $user + * @param \OC\User\User|null $user */ public function setUser($user) { if (is_null($user)) { @@ -115,7 +115,7 @@ class Session implements Emitter, \OCP\IUserSession { /** * set the login name * - * @param string $loginName for the logged in user + * @param string|null $loginName for the logged in user */ public function setLoginName($loginName) { if (is_null($loginName)) { @@ -191,7 +191,7 @@ class Session implements Emitter, \OCP\IUserSession { $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); + setcookie("oc_remember_login", "1", $expires, \OC::$WEBROOT, '', $secure_cookie); } /** -- cgit v1.2.3 From f7e777f7d2fc330dbf55c0190b5e0071c8f997ac Mon Sep 17 00:00:00 2001 From: Robin McCorkell Date: Mon, 12 May 2014 23:28:26 +0100 Subject: Fix various code errors detected by Scrutinizer Fixed: - An error with a misplaced bracket in lib/private/util.php - An error with an incorrect function being called in lib/public/contacts.php --- lib/private/util.php | 2 +- lib/public/contacts.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/util.php b/lib/private/util.php index 1c3177af435..f76ee7b338a 100755 --- a/lib/private/util.php +++ b/lib/private/util.php @@ -1113,7 +1113,7 @@ class OC_Util { curl_setopt($curl, CURLOPT_PROXYUSERPWD, OC_Config::getValue('proxyuserpwd')); } - if (ini_get('open_basedir') === '' && ini_get('safe_mode' === 'Off')) { + if (ini_get('open_basedir') === '' && ini_get('safe_mode') === 'Off') { curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_MAXREDIRS, $max_redirects); $data = curl_exec($curl); diff --git a/lib/public/contacts.php b/lib/public/contacts.php index 0d12e91c67f..fb88c13bd1b 100644 --- a/lib/public/contacts.php +++ b/lib/public/contacts.php @@ -116,7 +116,7 @@ namespace OCP { */ public static function createOrUpdate($properties, $address_book_key) { $cm = \OC::$server->getContactsManager(); - return $cm->search($properties, $address_book_key); + return $cm->createOrUpdate($properties, $address_book_key); } /** -- cgit v1.2.3 From 4755392c65ba707d0dbf25c862e766fc2b31d3f3 Mon Sep 17 00:00:00 2001 From: Robin McCorkell Date: Mon, 12 May 2014 23:56:31 +0100 Subject: More PHPDoc for file functions --- lib/private/files/stream/oc.php | 8 ++++++++ lib/private/files/view.php | 4 ++++ 2 files changed, 12 insertions(+) (limited to 'lib/private') diff --git a/lib/private/files/stream/oc.php b/lib/private/files/stream/oc.php index 88e7e062df9..c206b41f55e 100644 --- a/lib/private/files/stream/oc.php +++ b/lib/private/files/stream/oc.php @@ -18,7 +18,15 @@ class OC { static private $rootView; private $path; + + /** + * @var resource + */ private $dirSource; + + /** + * @var resource + */ private $fileSource; private $meta; diff --git a/lib/private/files/view.php b/lib/private/files/view.php index 1f424757bb8..3b99bd12b8a 100644 --- a/lib/private/files/view.php +++ b/lib/private/files/view.php @@ -168,6 +168,10 @@ class View { } } + /** + * @param string $path + * @return resource + */ public function opendir($path) { return $this->basicOperation('opendir', $path, array('read')); } -- cgit v1.2.3 From 147007bdd8e2f60d2a39685623f34130c87edc0c Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Tue, 13 May 2014 12:17:30 +0200 Subject: fixing typo and missing @throws --- lib/private/share/helper.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/share/helper.php b/lib/private/share/helper.php index 68f4a35af19..bc83d569840 100644 --- a/lib/private/share/helper.php +++ b/lib/private/share/helper.php @@ -32,6 +32,7 @@ class Helper extends \OC\Share\Constants { * @param string $uidOwner User that is the owner of shared item * @param string $suggestedTarget The suggested target originating from a reshare (optional) * @param int $groupParent The id of the parent group share (optional) + * @throws \Exception * @return string Item target */ public static function generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, @@ -144,7 +145,7 @@ class Helper extends \OC\Share\Constants { * Delete all reshares of an item * @param int $parent Id of item to delete * @param bool $excludeParent If true, exclude the parent from the delete (optional) - * @param string $uidOwner The user that the parent was shared with (optinal) + * @param string $uidOwner The user that the parent was shared with (optional) */ public static function delete($parent, $excludeParent = false, $uidOwner = null) { $ids = array($parent); -- cgit v1.2.3 From 7853bc4cacee0e5361fd25ea0c2a67cf7a526c91 Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Tue, 13 May 2014 12:21:04 +0200 Subject: adding PHPDoc --- lib/private/share/mailnotifications.php | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/share/mailnotifications.php b/lib/private/share/mailnotifications.php index 0cd36e97d54..ca0dff6562d 100644 --- a/lib/private/share/mailnotifications.php +++ b/lib/private/share/mailnotifications.php @@ -21,11 +21,30 @@ namespace OC\Share; +use DateTime; + class MailNotifications { - private $senderId; // sender userId - private $from; // sender email address + /** + * sender userId + * @var null|string + */ + private $senderId; + + /** + * sender email address + * @var string + */ + private $from; + + /** + * @var string + */ private $senderDisplayName; + + /** + * @var \OC_L10N + */ private $l; /** -- cgit v1.2.3 From 650a55e2ba1c22ee6dc5c6902a90b1dcd2c00155 Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Tue, 13 May 2014 12:22:18 +0200 Subject: object -> \OC\Preview --- lib/private/preview.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/preview.php b/lib/private/preview.php index bf8c04e0998..eb932470a47 100755 --- a/lib/private/preview.php +++ b/lib/private/preview.php @@ -191,7 +191,7 @@ class Preview { /** * @brief set the path of the file you want a thumbnail from * @param string $file - * @return object $this + * @return \OC\Preview $this */ public function setFile($file) { $this->file = $file; -- cgit v1.2.3 From fa503a4772af010d8b59ea8eb26aba0a08b100b9 Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Tue, 13 May 2014 12:27:35 +0200 Subject: fix PHPDoc --- lib/private/share/share.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'lib/private') diff --git a/lib/private/share/share.php b/lib/private/share/share.php index 98275a59a6f..a8537a916fb 100644 --- a/lib/private/share/share.php +++ b/lib/private/share/share.php @@ -260,7 +260,7 @@ class Share extends \OC\Share\Constants { * @param mixed $parameters (optional) * @param int $limit Number of items to return (optional) Returns all by default * @param boolean $includeCollections (optional) - * @return Return depends on format + * @return mixed Return depends on format */ public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE, $parameters = null, $limit = -1, $includeCollections = false) { @@ -352,7 +352,7 @@ class Share extends \OC\Share\Constants { * @param string $itemType * @param string $itemSource * @param string $uidOwner Owner of link - * @return Item + * @return array */ public static function getItemSharedWithByLink($itemType, $itemSource, $uidOwner) { return self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE, @@ -926,6 +926,7 @@ class Share extends \OC\Share\Constants { /** * Get the backend class for the specified item type * @param string $itemType + * @throws \Exception * @return \OCP\Share_Backend */ public static function getBackend($itemType) { @@ -1353,6 +1354,7 @@ class Share extends \OC\Share\Constants { * @param boolean|array $parentFolder Parent folder target (optional) * @param string $token (optional) * @param string $itemSourceName name of the source item (optional) + * @throws \Exception * @return boolean Returns true on success or false on failure */ private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, @@ -1641,7 +1643,7 @@ class Share extends \OC\Share\Constants { } /** - * @breif construct select statement + * @brief construct select statement * @param int $format * @param boolean $fileDependent ist it a file/folder share or a generla share * @param string $uidOwner -- cgit v1.2.3 From 37ba6f503abfdd0f24ac515d1c71aa4a705a211f Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Tue, 13 May 2014 12:38:17 +0200 Subject: fixing variable naming --- lib/private/vobject.php | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) (limited to 'lib/private') diff --git a/lib/private/vobject.php b/lib/private/vobject.php index cb556e07c9e..e472429b23e 100644 --- a/lib/private/vobject.php +++ b/lib/private/vobject.php @@ -25,13 +25,13 @@ */ class OC_VObject{ /** @var Sabre\VObject\Component */ - protected $vobject; + protected $vObject; /** * @return Sabre\VObject\Component */ public function getVObject() { - return $this->vobject; + return $this->vObject; } /** @@ -42,11 +42,11 @@ class OC_VObject{ public static function parse($data) { try { Sabre\VObject\Property::$classMap['LAST-MODIFIED'] = 'Sabre\VObject\Property\DateTime'; - $vobject = Sabre\VObject\Reader::read($data); - if ($vobject instanceof Sabre\VObject\Component) { - $vobject = new OC_VObject($vobject); + $vObject = Sabre\VObject\Reader::read($data); + if ($vObject instanceof Sabre\VObject\Component) { + $vObject = new OC_VObject($vObject); } - return $vobject; + return $vObject; } catch (Exception $e) { OC_Log::write('vobject', $e->getMessage(), OC_Log::ERROR); return null; @@ -93,9 +93,9 @@ class OC_VObject{ */ public function __construct($vobject_or_name) { if (is_object($vobject_or_name)) { - $this->vobject = $vobject_or_name; + $this->vObject = $vobject_or_name; } else { - $this->vobject = new Sabre\VObject\Component($vobject_or_name); + $this->vObject = new Sabre\VObject\Component($vobject_or_name); } } @@ -108,7 +108,7 @@ class OC_VObject{ if ($item instanceof OC_VObject) { $item = $item->getVObject(); } - $this->vobject->add($item, $itemValue); + $this->vObject->add($item, $itemValue); } /** @@ -127,13 +127,13 @@ class OC_VObject{ $property->parameters[] = new Sabre\VObject\Parameter($name, $value); } - $this->vobject->add($property); + $this->vObject->add($property); return $property; } public function setUID() { $uid = substr(md5(rand().time()), 0, 10); - $this->vobject->add('UID', $uid); + $this->vObject->add('UID', $uid); } /** @@ -144,9 +144,9 @@ class OC_VObject{ public function setString($name, $string) { if ($string != '') { $string = strtr($string, array("\r\n"=>"\n")); - $this->vobject->__set($name, $string); + $this->vObject->__set($name, $string); }else{ - $this->vobject->__unset($name); + $this->vObject->__unset($name); } } @@ -167,9 +167,9 @@ class OC_VObject{ if ($datetime instanceof DateTime) { $datetime_element = new Sabre\VObject\Property\DateTime($name); $datetime_element->setDateTime($datetime, $dateType); - $this->vobject->__set($name, $datetime_element); + $this->vObject->__set($name, $datetime_element); }else{ - $this->vobject->__unset($name); + $this->vObject->__unset($name); } } @@ -179,8 +179,8 @@ class OC_VObject{ * @return string */ public function getAsString($name) { - return $this->vobject->__isset($name) ? - $this->vobject->__get($name)->value : + return $this->vObject->__isset($name) ? + $this->vObject->__get($name)->value : ''; } @@ -191,7 +191,7 @@ class OC_VObject{ */ public function getAsArray($name) { $values = array(); - if ($this->vobject->__isset($name)) { + if ($this->vObject->__isset($name)) { $values = explode(',', $this->getAsString($name)); $values = array_map('trim', $values); } @@ -205,9 +205,9 @@ class OC_VObject{ */ public function &__get($name) { if ($name == 'children') { - return $this->vobject->children; + return $this->vObject->children; } - $return = $this->vobject->__get($name); + $return = $this->vObject->__get($name); if ($return instanceof Sabre\VObject\Component) { $return = new OC_VObject($return); } @@ -220,7 +220,7 @@ class OC_VObject{ * @param string $value */ public function __set($name, $value) { - return $this->vobject->__set($name, $value); + return $this->vObject->__set($name, $value); } /** @@ -228,7 +228,7 @@ class OC_VObject{ * @param string $name */ public function __unset($name) { - return $this->vobject->__unset($name); + return $this->vObject->__unset($name); } /** @@ -237,7 +237,7 @@ class OC_VObject{ * @return bool */ public function __isset($name) { - return $this->vobject->__isset($name); + return $this->vObject->__isset($name); } /** @@ -247,6 +247,6 @@ class OC_VObject{ * @return mixed */ public function __call($function, $arguments) { - return call_user_func_array(array($this->vobject, $function), $arguments); + return call_user_func_array(array($this->vObject, $function), $arguments); } } -- cgit v1.2.3 From 512373fadf64c4ea982e12d921684b298f112314 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Wed, 14 May 2014 01:06:14 +0200 Subject: provide a way to detect the language that is being used (e.g. for clientside javascript language selection --- lib/private/l10n.php | 17 +++++++++++++++++ lib/public/il10n.php | 14 ++++++++++++++ 2 files changed, 31 insertions(+) (limited to 'lib/private') diff --git a/lib/private/l10n.php b/lib/private/l10n.php index c9d9e8131b1..40eeb98d6bb 100644 --- a/lib/private/l10n.php +++ b/lib/private/l10n.php @@ -401,6 +401,23 @@ class OC_L10N implements \OCP\IL10N { self::$language = $lang; } + + /** + * @brief find the best language + * @param array|string $app details below + * @returns string language + * + * If $app is an array, ownCloud assumes that these are the available + * languages. Otherwise ownCloud tries to find the files in the l10n + * folder. + * + * If nothing works it returns 'en' + */ + public function getLanguageCode($app=null) { + return self::findLanguage($app); + } + + /** * @brief find the best language * @param array|string $app details below diff --git a/lib/public/il10n.php b/lib/public/il10n.php index c228be6a0a3..7649a1ea538 100644 --- a/lib/public/il10n.php +++ b/lib/public/il10n.php @@ -72,4 +72,18 @@ interface IL10N { * - params: timestamp (int/string) */ public function l($type, $data); + + + /** + * @brief find the best language + * @param array|string $app details below + * @returns string language + * + * If $app is an array, ownCloud assumes that these are the available + * languages. Otherwise ownCloud tries to find the files in the l10n + * folder. + * + * If nothing works it returns 'en' + */ + public function getLanguageCode($app=null); } -- cgit v1.2.3 From d8020c3506b3f09d090b427dcfa4c5a6ed3e0476 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Wed, 14 May 2014 01:08:14 +0200 Subject: use registerService method instead of array access --- lib/private/server.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/server.php b/lib/private/server.php index fd8c2c38ad0..47bdee4b0f8 100644 --- a/lib/private/server.php +++ b/lib/private/server.php @@ -186,7 +186,7 @@ class Server extends SimpleContainer implements IServerContainer { } return $router; }); - $this['Db'] = $this->share(function($c){ + $this->registerService('Db', function($c){ return new Db(); }); } -- cgit v1.2.3 From 04f73275ba222f0aae80cf80890477b141cd4902 Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Mon, 9 Dec 2013 13:18:13 +0100 Subject: Now settings CSS class with appid in content DIV --- core/templates/layout.user.php | 2 +- lib/private/template.php | 4 +++- lib/private/templatelayout.php | 4 +++- 3 files changed, 7 insertions(+), 3 deletions(-) (limited to 'lib/private') diff --git a/core/templates/layout.user.php b/core/templates/layout.user.php index a217446ca73..b0ae8637acc 100644 --- a/core/templates/layout.user.php +++ b/core/templates/layout.user.php @@ -123,7 +123,7 @@
-
+
diff --git a/lib/private/template.php b/lib/private/template.php index 3d18b52bac9..dfeb5d14b08 100644 --- a/lib/private/template.php +++ b/lib/private/template.php @@ -30,6 +30,7 @@ class OC_Template extends \OC\Template\Base { private $renderas; // Create a full page? private $path; // The path to the template private $headers=array(); //custom headers + protected $app; // app id /** * @brief Constructor @@ -62,6 +63,7 @@ class OC_Template extends \OC\Template\Base { // Set the private data $this->renderas = $renderas; $this->path = $path; + $this->app = $app; parent::__construct($template, $requesttoken, $l10n, $themeDefaults); } @@ -172,7 +174,7 @@ class OC_Template extends \OC\Template\Base { $data = parent::fetchPage(); if( $this->renderas ) { - $page = new OC_TemplateLayout($this->renderas); + $page = new OC_TemplateLayout($this->renderas, $this->app); // Add custom headers $page->assign('headers', $this->headers, false); diff --git a/lib/private/templatelayout.php b/lib/private/templatelayout.php index 0672ffc4a3d..a5dd9a0c614 100644 --- a/lib/private/templatelayout.php +++ b/lib/private/templatelayout.php @@ -15,8 +15,9 @@ class OC_TemplateLayout extends OC_Template { /** * @param string $renderas + * @param string $appid application id */ - public function __construct( $renderas ) { + public function __construct( $renderas, $appid = '' ) { // Decide which page we show if( $renderas == 'user' ) { @@ -43,6 +44,7 @@ class OC_TemplateLayout extends OC_Template { // Add navigation entry $this->assign( 'application', '', false ); + $this->assign( 'appid', $appid ); $navigation = OC_App::getNavigation(); $this->assign( 'navigation', $navigation); $this->assign( 'settingsnavigation', OC_App::getSettingsNavigation()); -- cgit v1.2.3 From b6e14af861481d0b2ebf6ca752d994c5adfce866 Mon Sep 17 00:00:00 2001 From: Bjoern Schiessle Date: Mon, 12 May 2014 12:19:07 +0200 Subject: allow admin to enforce passwords for public link shares --- apps/files_sharing/lib/api.php | 19 ++++++++------ apps/files_sharing/tests/api.php | 54 ++++++++++++++++++++++++++++++++++++++++ core/js/config.php | 1 + core/js/share.js | 52 ++++++++++++++++++++++++-------------- lib/private/share/share.php | 11 +++++++- lib/private/util.php | 10 ++++++++ lib/public/util.php | 8 ++++++ settings/admin.php | 1 + settings/templates/admin.php | 5 ++-- 9 files changed, 132 insertions(+), 29 deletions(-) (limited to 'lib/private') diff --git a/apps/files_sharing/lib/api.php b/apps/files_sharing/lib/api.php index d554d68c6bd..fd3c4a7756a 100644 --- a/apps/files_sharing/lib/api.php +++ b/apps/files_sharing/lib/api.php @@ -418,13 +418,18 @@ class Api { return new \OC_OCS_Result(null, 404, "share doesn't exists, can't change password"); } - $result = \OCP\Share::shareItem( - $itemType, - $itemSource, - \OCP\Share::SHARE_TYPE_LINK, - $shareWith, - $permissions - ); + try { + $result = \OCP\Share::shareItem( + $itemType, + $itemSource, + \OCP\Share::SHARE_TYPE_LINK, + $shareWith, + $permissions + ); + } catch (\Exception $e) { + return new \OC_OCS_Result(null, 403, $e->getMessage()); + } + if($result) { return new \OC_OCS_Result(); } diff --git a/apps/files_sharing/tests/api.php b/apps/files_sharing/tests/api.php index 2193717f4b4..a908caf6632 100644 --- a/apps/files_sharing/tests/api.php +++ b/apps/files_sharing/tests/api.php @@ -113,11 +113,65 @@ class Test_Files_Sharing_Api extends Test_Files_Sharing_Base { $fileinfo = $this->view->getFileInfo($this->folder); \OCP\Share::unshare('folder', $fileinfo['fileid'], \OCP\Share::SHARE_TYPE_LINK, null); + } + + function testEnfoceLinkPassword() { + + $appConfig = \OC::$server->getAppConfig(); + $appConfig->setValue('core', 'shareapi_enforce_links_password', 'yes'); + + // don't allow to share link without a password + $_POST['path'] = $this->folder; + $_POST['shareType'] = \OCP\Share::SHARE_TYPE_LINK; + + + $result = Share\Api::createShare(array()); + $this->assertFalse($result->succeeded()); + + + // don't allow to share link without a empty password + $_POST['path'] = $this->folder; + $_POST['shareType'] = \OCP\Share::SHARE_TYPE_LINK; + $_POST['password'] = ''; + + $result = Share\Api::createShare(array()); + $this->assertFalse($result->succeeded()); + + // share with password should succeed + $_POST['path'] = $this->folder; + $_POST['shareType'] = \OCP\Share::SHARE_TYPE_LINK; + $_POST['password'] = 'foo'; + $result = Share\Api::createShare(array()); + $this->assertTrue($result->succeeded()); + + $data = $result->getData(); + + // setting new password should succeed + $params = array(); + $params['id'] = $data['id']; + $params['_put'] = array(); + $params['_put']['password'] = 'bar'; + + $result = Share\Api::updateShare($params); + $this->assertTrue($result->succeeded()); + // removing password should fail + $params = array(); + $params['id'] = $data['id']; + $params['_put'] = array(); + $params['_put']['password'] = ''; + + $result = Share\Api::updateShare($params); + $this->assertFalse($result->succeeded()); + // cleanup + $fileinfo = $this->view->getFileInfo($this->folder); + \OCP\Share::unshare('folder', $fileinfo['fileid'], \OCP\Share::SHARE_TYPE_LINK, null); + $appConfig->setValue('core', 'shareapi_enforce_links_password', 'no'); } + /** * @medium * @depends testCreateShare diff --git a/core/js/config.php b/core/js/config.php index 9169cc14a7b..33665b8401c 100644 --- a/core/js/config.php +++ b/core/js/config.php @@ -79,6 +79,7 @@ $array = array( 'defaultExpireDateEnabled' => $defaultExpireDateEnabled, 'defaultExpireDate' => $defaultExpireDate, 'defaultExpireDateEnforced' => $enforceDefaultExpireDate, + 'enforcePasswordForPublicLink' => \OCP\Util::isPublicLinkPasswordRequired(), ) ) ), diff --git a/core/js/share.js b/core/js/share.js index 9ceca85bff7..6c6631aa2b2 100644 --- a/core/js/share.js +++ b/core/js/share.js @@ -230,11 +230,11 @@ OC.Share={ } html += ''; - html += ''; html += '
'; - html += ''; + html += ''; html += '
'; + if (itemType === 'folder' && (possiblePermissions & OC.PERMISSION_CREATE) && publicUploadEnabled === 'yes') { html += ' diff --git a/tests/lib/util.php b/tests/lib/util.php index c4780cc5f48..4dc7813d918 100644 --- a/tests/lib/util.php +++ b/tests/lib/util.php @@ -235,4 +235,59 @@ class Test_Util extends PHPUnit_Framework_TestCase { array(' .', false), ); } + + /** + * @dataProvider dataProviderForTestIsSharingDisabledForUser + * @param array $groups existing groups + * @param array $membership groups the user belong to + * @param array $excludedGroups groups which should be excluded from sharing + * @param bool $expected expected result + */ + function testIsSharingDisabledForUser($groups, $membership, $excludedGroups, $expected) { + $uid = "user1"; + \OC_User::setUserId($uid); + + \OC_User::createUser($uid, "passwd"); + + foreach($groups as $group) { + \OC_Group::createGroup($group); + } + + foreach($membership as $group) { + \OC_Group::addToGroup($uid, $group); + } + + $appConfig = \OC::$server->getAppConfig(); + $appConfig->setValue('core', 'shareapi_exclude_groups_list', implode(',', $excludedGroups)); + $appConfig->setValue('core', 'shareapi_exclude_groups', 'yes'); + + $result = \OCP\Util::isSharingDisabledForUser(); + + $this->assertSame($expected, $result); + + // cleanup + \OC_User::deleteUser($uid); + \OC_User::setUserId(''); + + foreach($groups as $group) { + \OC_Group::deleteGroup($group); + } + + $appConfig->setValue('core', 'shareapi_exclude_groups_list', ''); + $appConfig->setValue('core', 'shareapi_exclude_groups', 'no'); + + } + + public function dataProviderForTestIsSharingDisabledForUser() { + return array( + // existing groups, groups the user belong to, groups excluded from sharing, expected result + array(array('g1', 'g2', 'g3'), array(), array('g1'), false), + array(array('g1', 'g2', 'g3'), array(), array(), false), + array(array('g1', 'g2', 'g3'), array('g2'), array('g1'), false), + array(array('g1', 'g2', 'g3'), array('g2'), array(), false), + array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1'), false), + array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1', 'g2'), true), + array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1', 'g2', 'g3'), true), + ); + } } -- cgit v1.2.3 From ff1f341d9776401f4e68a5de12b546ca26f229d1 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Thu, 22 May 2014 13:30:32 +0200 Subject: Fix phpdoc --- lib/private/files/cache/watcher.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/files/cache/watcher.php b/lib/private/files/cache/watcher.php index 599752a6eff..5a4f53fb73d 100644 --- a/lib/private/files/cache/watcher.php +++ b/lib/private/files/cache/watcher.php @@ -45,7 +45,7 @@ class Watcher { } /** - * @param int $policy either \OC\Files\Cache\Watcher::UPDATE_NEVER, \OC\Files\Cache\Watcher::UPDATE_ONCE, \OC\Files\Cache\Watcher::UPDATE_ALWAYS + * @param int $policy either \OC\Files\Cache\Watcher::CHECK_NEVER, \OC\Files\Cache\Watcher::CHECK_ONCE, \OC\Files\Cache\Watcher::CHECK_ALWAYS */ public function setPolicy($policy) { $this->watchPolicy = $policy; -- cgit v1.2.3 From 2e85d5a852aeda82a470c8cdc55ff143fdc570e5 Mon Sep 17 00:00:00 2001 From: Arthur Schiwon Date: Fri, 23 May 2014 11:20:46 +0200 Subject: increase scrutinizer happyiness by removing minor/informational issues --- lib/private/user/manager.php | 2 +- tests/lib/user/session.php | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) (limited to 'lib/private') diff --git a/lib/private/user/manager.php b/lib/private/user/manager.php index 914baebdf6f..f2964fecca3 100644 --- a/lib/private/user/manager.php +++ b/lib/private/user/manager.php @@ -52,7 +52,7 @@ class Manager extends PublicEmitter { unset($cachedUsers[$i]); } }); - $this->listen('\OC\User', 'postLogin', function ($user, $pw) { + $this->listen('\OC\User', 'postLogin', function ($user) { $user->updateLastLoginTimestamp(); }); $this->listen('\OC\User', 'postRememberedLogin', function ($user) { diff --git a/tests/lib/user/session.php b/tests/lib/user/session.php index 3f9d43e2952..2845a9c964a 100644 --- a/tests/lib/user/session.php +++ b/tests/lib/user/session.php @@ -196,10 +196,8 @@ class Session extends \PHPUnit_Framework_TestCase { switch($key) { case 'user_id': return true; - break; default: return false; - break; } }, 'foo')); -- cgit v1.2.3 From 151c48494e0e1c6b8bed2551c50196a67284db0c Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Thu, 22 May 2014 13:45:55 +0200 Subject: Add a config option fro setting the filesystem watcher policy --- config/config.sample.php | 11 ++++++++++- lib/private/files/storage/common.php | 2 ++ 2 files changed, 12 insertions(+), 1 deletion(-) (limited to 'lib/private') diff --git a/config/config.sample.php b/config/config.sample.php index 708e8367023..80694837edc 100755 --- a/config/config.sample.php +++ b/config/config.sample.php @@ -283,5 +283,14 @@ $CONFIG = array( * cache directory and "$user" is the user. * */ -'cache_path' => '' +'cache_path' => '', + +/* + * specifies how often the filesystem is checked for changes made outside owncloud + * 0 -> never check the filesystem for outside changes, provides a performance increase when it's certain that no changes are made directly to the filesystem + * 1 -> check each file or folder at most once per request, recomended for general use if outside changes might happen + * 2 -> check every time the filesystem is used, causes a performance hit when using external storages, not recomended for regular use + */ +'filesystem_check_changes' => 1 + ); diff --git a/lib/private/files/storage/common.php b/lib/private/files/storage/common.php index fef33cabd87..45db51c1659 100644 --- a/lib/private/files/storage/common.php +++ b/lib/private/files/storage/common.php @@ -7,6 +7,7 @@ */ namespace OC\Files\Storage; +use OC\Files\Cache\Watcher; /** * Storage backend class for providing common filesystem operation methods @@ -276,6 +277,7 @@ abstract class Common implements \OC\Files\Storage\Storage { public function getWatcher($path = '') { if (!isset($this->watcher)) { $this->watcher = new \OC\Files\Cache\Watcher($this); + $this->watcher->setPolicy(\OC::$server->getConfig()->getSystemValue('filesystem_check_changes', Watcher::CHECK_ONCE)); } return $this->watcher; } -- cgit v1.2.3 From be8326668aa29170b93570036936d174247cdbeb Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Fri, 23 May 2014 13:31:45 +0200 Subject: Make the recursive delete more robust --- lib/private/helper.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/helper.php b/lib/private/helper.php index 4ad792dfb13..e9ca036a32c 100644 --- a/lib/private/helper.php +++ b/lib/private/helper.php @@ -407,7 +407,7 @@ class OC_Helper { if (is_dir($dir)) { $files = scandir($dir); foreach ($files as $file) { - if ($file != "." && $file != "..") { + if ($file !== '' && $file !== "." && $file !== "..") { self::rmdirr("$dir/$file"); } } -- cgit v1.2.3 From 748a2192434918324a4cd42b855fb77d8769680a Mon Sep 17 00:00:00 2001 From: Arthur Schiwon Date: Mon, 26 May 2014 13:53:26 +0200 Subject: add preRememberedLogin hook and document this and postRememberedLogin in class descripttion. Also fixes documentation of postLogin hook --- lib/private/user/session.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/user/session.php b/lib/private/user/session.php index 91e203f044a..5f0dee607ae 100644 --- a/lib/private/user/session.php +++ b/lib/private/user/session.php @@ -22,7 +22,9 @@ use OC\Hooks\Emitter; * - preCreateUser(string $uid, string $password) * - postCreateUser(\OC\User\User $user) * - preLogin(string $user, string $password) - * - postLogin(\OC\User\User $user) + * - postLogin(\OC\User\User $user, string $password) + * - preRememberedLogin(string $uid) + * - postRememberedLogin(\OC\User\User $user) * - logout() * * @package OC\User @@ -178,6 +180,7 @@ class Session implements Emitter, \OCP\IUserSession { * @return bool */ public function loginWithCookie($uid, $currentToken) { + $this->manager->emit('\OC\User', 'preRememberedLogin', array($uid)); $user = $this->manager->get($uid); if(is_null($user)) { // user does not exist -- cgit v1.2.3 From 4a4ea67a31cda773dc84fb1fd617bfc27f77d5b8 Mon Sep 17 00:00:00 2001 From: Arthur Schiwon Date: Mon, 26 May 2014 13:56:08 +0200 Subject: drop superflous statement in phpdoc --- lib/private/user/user.php | 2 -- 1 file changed, 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/user/user.php b/lib/private/user/user.php index e0598813642..8aba7188e24 100644 --- a/lib/private/user/user.php +++ b/lib/private/user/user.php @@ -125,8 +125,6 @@ class User { /** * updates the timestamp of the most recent login of this user - * - * @return null */ public function updateLastLoginTimestamp() { $this->lastLogin = time(); -- cgit v1.2.3 From d43a7c5f6ec2806c43c374d598c756a116c3d95b Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Tue, 27 May 2014 11:54:12 +0200 Subject: Added requiremin/requiremax fields for apps Apps can now specify a minimum and maximum version of ownCloud in which they are supported. --- lib/private/app.php | 84 ++++++++++---- lib/private/installer.php | 5 +- tests/lib/app.php | 274 +++++++++++++++++++++++++++++++++++----------- 3 files changed, 272 insertions(+), 91 deletions(-) (limited to 'lib/private') diff --git a/lib/private/app.php b/lib/private/app.php index 575cc9f41af..50065197eb4 100644 --- a/lib/private/app.php +++ b/lib/private/app.php @@ -231,7 +231,7 @@ class OC_App{ // check if the app is compatible with this version of ownCloud $info=OC_App::getAppInfo($app); $version=OC_Util::getVersion(); - if(!isset($info['require']) or !self::isAppVersionCompatible($version, $info['require'])) { + if(!self::isAppCompatible($version, $info)) { throw new \Exception( $l->t("App \"%s\" can't be installed because it is not compatible with this version of ownCloud.", array($info['name']) @@ -898,7 +898,7 @@ class OC_App{ foreach($apps as $app) { // check if the app is compatible with this version of ownCloud $info = OC_App::getAppInfo($app); - if(!isset($info['require']) or !self::isAppVersionCompatible($version, $info['require'])) { + if(!self::isAppCompatible($version, $info)) { OC_Log::write('core', 'App "'.$info['name'].'" ('.$app.') can\'t be used because it is' .' not compatible with this version of ownCloud', @@ -909,38 +909,78 @@ class OC_App{ } } + /** + * Ajust the number of version parts of $version1 to match + * the number of version parts of $version2. + * + * @param string $version1 version to adjust + * @param string $version2 version to take the number of parts from + * @return string shortened $version1 + */ + private static function adjustVersionParts($version1, $version2) { + $version1 = explode('.', $version1); + $version2 = explode('.', $version2); + // reduce $version1 to match the number of parts in $version2 + while (count($version1) > count($version2)) { + array_pop($version1); + } + // if $version1 does not have enough parts, add some + while (count($version1) < count($version2)) { + $version1[] = '0'; + } + return implode('.', $version1); + } /** - * Compares the app version with the owncloud version to see if the app - * requires a newer version than the currently active one - * @param array $owncloudVersions array with 3 entries: major minor bugfix - * @param string $appRequired the required version from the xml - * major.minor.bugfix + * Check whether the current ownCloud version matches the given + * application's version requirements. + * + * The comparison is made based on the number of parts that the + * app info version has. For example for ownCloud 6.0.3 if the + * app info version is expecting version 6.0, the comparison is + * made on the first two parts of the ownCloud version. + * This means that it's possible to specify "requiremin" => 6 + * and "requiremax" => 6 and it will still match ownCloud 6.0.3. + * + * @param string $ocVersion ownCloud version to check against + * @param array $appInfo app info (from xml) + * * @return boolean true if compatible, otherwise false */ - public static function isAppVersionCompatible($owncloudVersions, $appRequired){ - $appVersions = explode('.', $appRequired); + public static function isAppCompatible($ocVersion, $appInfo){ + $requireMin = ''; + $requireMax = ''; + if (isset($appInfo['requiremin'])) { + $requireMin = $appInfo['requiremin']; + } else if (isset($appInfo['require'])) { + $requireMin = $appInfo['require']; + } - for($i=0; $i $appVersion) { - return true; - } + if (!empty($requireMin) + && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<') + ) { + + return false; + } + + if (!empty($requireMax) + && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>') + ) { + + return false; } return true; } - /** * get the installed version of all apps */ diff --git a/lib/private/installer.php b/lib/private/installer.php index 667c05c9c16..3bddfa6a3b7 100644 --- a/lib/private/installer.php +++ b/lib/private/installer.php @@ -133,10 +133,7 @@ class OC_Installer{ } // check if the app is compatible with this version of ownCloud - if( - !isset($info['require']) - or !OC_App::isAppVersionCompatible(OC_Util::getVersion(), $info['require']) - ) { + if(!OC_App::isAppCompatible(OC_Util::getVersion(), $info)) { OC_Helper::rmdirr($extractDir); throw new \Exception($l->t("App can't be installed because it is not compatible with this version of ownCloud")); } diff --git a/tests/lib/app.php b/tests/lib/app.php index 683820cabb6..e2b578fe6b9 100644 --- a/tests/lib/app.php +++ b/tests/lib/app.php @@ -1,6 +1,7 @@ + * Copyright (c) 2014 Vincent Petry * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. @@ -8,75 +9,218 @@ class Test_App extends PHPUnit_Framework_TestCase { - - public function testIsAppVersionCompatibleSingleOCNumber(){ - $oc = array(4); - $app = '4.0'; - - $this->assertTrue(OC_App::isAppVersionCompatible($oc, $app)); - } - - - public function testIsAppVersionCompatibleMultipleOCNumber(){ - $oc = array(4, 3, 1); - $app = '4.3'; - - $this->assertTrue(OC_App::isAppVersionCompatible($oc, $app)); - } - - - public function testIsAppVersionCompatibleSingleNumber(){ - $oc = array(4); - $app = '4'; - - $this->assertTrue(OC_App::isAppVersionCompatible($oc, $app)); - } - - - public function testIsAppVersionCompatibleSingleAppNumber(){ - $oc = array(4, 3); - $app = '4'; - - $this->assertTrue(OC_App::isAppVersionCompatible($oc, $app)); - } - - - public function testIsAppVersionCompatibleComplex(){ - $oc = array(5, 0, 0); - $app = '4.5.1'; - - $this->assertTrue(OC_App::isAppVersionCompatible($oc, $app)); - } - - - public function testIsAppVersionCompatibleShouldFail(){ - $oc = array(4, 3, 1); - $app = '4.3.2'; - - $this->assertFalse(OC_App::isAppVersionCompatible($oc, $app)); + function appVersionsProvider() { + return array( + // exact match + array( + '6.0.0.0', + array( + 'requiremin' => '6.0', + 'requiremax' => '6.0', + ), + true + ), + // in-between match + array( + '6.0.0.0', + array( + 'requiremin' => '5.0', + 'requiremax' => '7.0', + ), + true + ), + // app too old + array( + '6.0.0.0', + array( + 'requiremin' => '5.0', + 'requiremax' => '5.0', + ), + false + ), + // app too new + array( + '5.0.0.0', + array( + 'requiremin' => '6.0', + 'requiremax' => '6.0', + ), + false + ), + // only min specified + array( + '6.0.0.0', + array( + 'requiremin' => '6.0', + ), + true + ), + // only min specified fail + array( + '5.0.0.0', + array( + 'requiremin' => '6.0', + ), + false + ), + // only min specified legacy + array( + '6.0.0.0', + array( + 'require' => '6.0', + ), + true + ), + // only min specified legacy fail + array( + '4.0.0.0', + array( + 'require' => '6.0', + ), + false + ), + // only max specified + array( + '5.0.0.0', + array( + 'requiremax' => '6.0', + ), + true + ), + // only max specified fail + array( + '7.0.0.0', + array( + 'requiremax' => '6.0', + ), + false + ), + // variations of versions + // single OC number + array( + '4', + array( + 'require' => '4.0', + ), + true + ), + // multiple OC number + array( + '4.3.1', + array( + 'require' => '4.3', + ), + true + ), + // single app number + array( + '4', + array( + 'require' => '4', + ), + true + ), + // single app number fail + array( + '4.3', + array( + 'require' => '5', + ), + false + ), + // complex + array( + '5.0.0', + array( + 'require' => '4.5.1', + ), + true + ), + // complex fail + array( + '4.3.1', + array( + 'require' => '4.3.2', + ), + false + ), + // two numbers + array( + '4.3.1', + array( + 'require' => '4.4', + ), + false + ), + // one number fail + array( + '4.3.1', + array( + 'require' => '5', + ), + false + ), + // pre-alpha app + array( + '5.0.3', + array( + 'require' => '4.93', + ), + true + ), + // pre-alpha OC + array( + '6.90.0.2', + array( + 'require' => '6.90', + ), + true + ), + // pre-alpha OC max + array( + '6.90.0.2', + array( + 'requiremax' => '7', + ), + true + ), + // expect same major number match + array( + '5.0.3', + array( + 'require' => '5', + ), + true + ), + // expect same major number match + array( + '5.0.3', + array( + 'requiremax' => '5', + ), + true + ), + ); } - public function testIsAppVersionCompatibleShouldFailTwoVersionNumbers(){ - $oc = array(4, 3, 1); - $app = '4.4'; - - $this->assertFalse(OC_App::isAppVersionCompatible($oc, $app)); - } - - - public function testIsAppVersionCompatibleShouldWorkForPreAlpha(){ - $oc = array(5, 0, 3); - $app = '4.93'; - - $this->assertTrue(OC_App::isAppVersionCompatible($oc, $app)); + /** + * @dataProvider appVersionsProvider + */ + public function testIsAppCompatible($ocVersion, $appInfo, $expectedResult) { + $this->assertEquals($expectedResult, OC_App::isAppCompatible($ocVersion, $appInfo)); } - - public function testIsAppVersionCompatibleShouldFailOneVersionNumbers(){ - $oc = array(4, 3, 1); - $app = '5'; - - $this->assertFalse(OC_App::isAppVersionCompatible($oc, $app)); + /** + * Test that the isAppCompatible method also supports passing an array + * as $ocVersion + */ + public function testIsAppCompatibleWithArray() { + $ocVersion = array(6); + $appInfo = array( + 'requiremin' => '6', + 'requiremax' => '6', + ); + $this->assertTrue(OC_App::isAppCompatible($ocVersion, $appInfo)); } /** -- cgit v1.2.3 From 02f682b156998a3f3f94fd506867c28eba878da9 Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Tue, 27 May 2014 15:20:33 +0200 Subject: Now showing disabled apps as upgrade status line - Added app id in update overview. - Added status message for disabled app for CLI upgrade and web upgrade --- core/ajax/update.php | 8 ++++++++ core/command/upgrade.php | 3 +++ core/templates/update.admin.php | 4 ++-- lib/base.php | 2 +- lib/private/app.php | 8 ++++++++ lib/private/updater.php | 5 ++++- 6 files changed, 26 insertions(+), 4 deletions(-) (limited to 'lib/private') diff --git a/core/ajax/update.php b/core/ajax/update.php index 55e8ab15ec2..84d7a21209e 100644 --- a/core/ajax/update.php +++ b/core/ajax/update.php @@ -15,6 +15,14 @@ if (OC::checkUpgrade(false)) { $updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Updated database')); }); + $updater->listen('\OC\Updater', 'disabledApps', function ($appList) use ($eventSource, $l) { + $list = array(); + foreach ($appList as $appId) { + $info = OC_App::getAppInfo($appId); + $list[] = $info['name'] . ' (' . $info['id'] . ')'; + } + $eventSource->send('success', (string)$l->t('Disabled incompatible apps: %s', implode(', ', $list))); + }); $updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource) { $eventSource->send('failure', $message); $eventSource->close(); diff --git a/core/command/upgrade.php b/core/command/upgrade.php index ed72d136e24..8ce8ef9b6e5 100644 --- a/core/command/upgrade.php +++ b/core/command/upgrade.php @@ -56,6 +56,9 @@ class Upgrade extends Command { $updater->listen('\OC\Updater', 'dbUpgrade', function () use($output) { $output->writeln('Updated database'); }); + $updater->listen('\OC\Updater', 'disabledApps', function ($appList) use($output) { + $output->writeln('Disabled incompatible apps: ' . implode(', ', $appList) . ''); + }); $updater->listen('\OC\Updater', 'failure', function ($message) use($output) { $output->writeln($message); diff --git a/core/templates/update.admin.php b/core/templates/update.admin.php index 0b1ae7854de..b9b0fdb7748 100644 --- a/core/templates/update.admin.php +++ b/core/templates/update.admin.php @@ -8,8 +8,8 @@
t('The following apps will be disabled during the upgrade:')) ?>
    - -
  • + +
  • ()
diff --git a/lib/base.php b/lib/base.php index 455e8ad4613..7bca1b7c877 100644 --- a/lib/base.php +++ b/lib/base.php @@ -298,7 +298,7 @@ class OC { foreach ($apps as $appId) { $info = OC_App::getAppInfo($appId); if(!OC_App::isAppCompatible($version, $info)) { - $incompatibleApps[] = $info['name']; + $incompatibleApps[] = $info; } } $tmpl->assign('appList', $incompatibleApps); diff --git a/lib/private/app.php b/lib/private/app.php index 50065197eb4..ea0453e58ea 100644 --- a/lib/private/app.php +++ b/lib/private/app.php @@ -889,8 +889,14 @@ class OC_App{ * ownCloud version. disable them if not. * This is important if you upgrade ownCloud and have non ported 3rd * party apps installed. + * + * @param array $apps optional app id list to check, uses all enabled apps + * when not specified + * + * @return array containing the list of ids of the disabled apps */ public static function checkAppsRequirements($apps = array()) { + $disabledApps = array(); if (empty($apps)) { $apps = OC_App::getEnabledApps(); } @@ -905,8 +911,10 @@ class OC_App{ OC_Log::ERROR); OC_App::disable( $app ); OC_Hook::emit('update', 'success', 'Disabled '.$info['name'].' app because it is not compatible'); + $disabledApps[] = $app; } } + return $disabledApps; } /** diff --git a/lib/private/updater.php b/lib/private/updater.php index d8694ac6ed5..58d3cab73aa 100644 --- a/lib/private/updater.php +++ b/lib/private/updater.php @@ -134,7 +134,10 @@ class Updater extends BasicEmitter { $this->emit('\OC\Updater', 'failure', array($exception->getMessage())); } \OC_Config::setValue('version', implode('.', \OC_Util::getVersion())); - \OC_App::checkAppsRequirements(); + $disabledApps = \OC_App::checkAppsRequirements(); + if (!empty($disabledApps)) { + $this->emit('\OC\Updater', 'disabledApps', array($disabledApps)); + } // load all apps to also upgrade enabled apps \OC_App::loadApps(); -- cgit v1.2.3 From 645e7035a45e400d02c56e588f6946d20b522731 Mon Sep 17 00:00:00 2001 From: ringmaster Date: Thu, 15 May 2014 22:38:46 -0400 Subject: Allow apps to control via a hook to skip adding/removing a file during filescan --- lib/private/files/cache/scanner.php | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/cache/scanner.php b/lib/private/files/cache/scanner.php index b3ab94f4599..19321da8ec1 100644 --- a/lib/private/files/cache/scanner.php +++ b/lib/private/files/cache/scanner.php @@ -161,7 +161,11 @@ class Scanner extends BasicEmitter { \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId)); } } else { - $this->cache->remove($file); + $removeFromCache = true; + \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $file, 'removeFromCache' => &$removeFromCache)); + if($removeFromCache) { + $this->cache->remove($file); + } } return $data; } @@ -244,7 +248,11 @@ class Scanner extends BasicEmitter { $removedChildren = \array_diff($existingChildren, $newChildren); foreach ($removedChildren as $childName) { $child = ($path) ? $path . '/' . $childName : $childName; - $this->cache->remove($child); + $addToCache = true; + \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $child, 'removeFromCache' => &$addToCache)); + if($addToCache) { + $this->cache->remove($child); + } } \OC_DB::commit(); if ($exceptionOccurred){ @@ -263,7 +271,11 @@ class Scanner extends BasicEmitter { $size += $childSize; } } - $this->cache->put($path, array('size' => $size)); + $addToCache = true; + \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'addToCache' => &$addToCache, 'size' => &$size)); + if($addToCache) { + $this->cache->put($path, array('size' => $size)); + } } $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId)); return $size; -- cgit v1.2.3 From fdf26c5a3f4718fcadc214eb69a91f780ce4045c Mon Sep 17 00:00:00 2001 From: ringmaster Date: Fri, 16 May 2014 12:12:27 -0400 Subject: Rename variable to something more appropriate. --- lib/private/files/cache/scanner.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/cache/scanner.php b/lib/private/files/cache/scanner.php index 19321da8ec1..2790d8581f7 100644 --- a/lib/private/files/cache/scanner.php +++ b/lib/private/files/cache/scanner.php @@ -248,9 +248,9 @@ class Scanner extends BasicEmitter { $removedChildren = \array_diff($existingChildren, $newChildren); foreach ($removedChildren as $childName) { $child = ($path) ? $path . '/' . $childName : $childName; - $addToCache = true; - \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $child, 'removeFromCache' => &$addToCache)); - if($addToCache) { + $removeFromCache = true; + \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $child, 'removeFromCache' => &$removeFromCache)); + if($removeFromCache) { $this->cache->remove($child); } } -- cgit v1.2.3 From 3b287f8274ef263d3144410bb6e3bf1a966f9d6d Mon Sep 17 00:00:00 2001 From: ringmaster Date: Tue, 20 May 2014 12:48:48 -0400 Subject: Allow the default behavior to come from the config. --- lib/private/files/cache/scanner.php | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/cache/scanner.php b/lib/private/files/cache/scanner.php index 2790d8581f7..24d406f7cd5 100644 --- a/lib/private/files/cache/scanner.php +++ b/lib/private/files/cache/scanner.php @@ -10,6 +10,7 @@ namespace OC\Files\Cache; use OC\Files\Filesystem; use OC\Hooks\BasicEmitter; +use OCP\Config; /** * Class Scanner @@ -156,12 +157,16 @@ class Scanner extends BasicEmitter { } } if (!empty($newData)) { - $data['fileid'] = $this->cache->put($file, $newData); + $addToCache = Config::getSystemValue('allow_scanner_to_affect_cache', true); + \OC_Hook::emit('Scanner', 'addToCache', array('file' => $file, 'addToCache' => &$addToCache, 'data' => &$newData)); + if($addToCache) { + $data['fileid'] = $this->cache->put($file, $newData); + } $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId)); \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId)); } } else { - $removeFromCache = true; + $removeFromCache = Config::getSystemValue('allow_scanner_to_affect_cache', true); \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $file, 'removeFromCache' => &$removeFromCache)); if($removeFromCache) { $this->cache->remove($file); @@ -248,7 +253,7 @@ class Scanner extends BasicEmitter { $removedChildren = \array_diff($existingChildren, $newChildren); foreach ($removedChildren as $childName) { $child = ($path) ? $path . '/' . $childName : $childName; - $removeFromCache = true; + $removeFromCache = Config::getSystemValue('allow_scanner_to_affect_cache', true); \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $child, 'removeFromCache' => &$removeFromCache)); if($removeFromCache) { $this->cache->remove($child); @@ -271,10 +276,11 @@ class Scanner extends BasicEmitter { $size += $childSize; } } - $addToCache = true; - \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'addToCache' => &$addToCache, 'size' => &$size)); + $newData = array('size' => $size); + $addToCache = Config::getSystemValue('allow_scanner_to_affect_cache', true); + \OC_Hook::emit('Scanner', 'addToCache', array('file' => $child, 'addToCache' => &$addToCache, 'data' => &$newData)); if($addToCache) { - $this->cache->put($path, array('size' => $size)); + $this->cache->put($path, $newData); } } $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId)); -- cgit v1.2.3 From 26d169b27c43d06db1158990e33939b85d14a60d Mon Sep 17 00:00:00 2001 From: ringmaster Date: Tue, 27 May 2014 16:01:16 -0400 Subject: Use 'filesystem_check_enable' as a config option. --- config/config.sample.php | 5 ++++- lib/private/files/cache/scanner.php | 8 ++++---- 2 files changed, 8 insertions(+), 5 deletions(-) (limited to 'lib/private') diff --git a/config/config.sample.php b/config/config.sample.php index 80694837edc..8fb782e7cf4 100755 --- a/config/config.sample.php +++ b/config/config.sample.php @@ -291,6 +291,9 @@ $CONFIG = array( * 1 -> check each file or folder at most once per request, recomended for general use if outside changes might happen * 2 -> check every time the filesystem is used, causes a performance hit when using external storages, not recomended for regular use */ -'filesystem_check_changes' => 1 +'filesystem_check_changes' => 1, + +/* specifies whether changes in the filesystem outside of owncloud affect cached data about those files */ +'filesystem_check_enable' => 1, ); diff --git a/lib/private/files/cache/scanner.php b/lib/private/files/cache/scanner.php index 24d406f7cd5..e838a8b6258 100644 --- a/lib/private/files/cache/scanner.php +++ b/lib/private/files/cache/scanner.php @@ -157,7 +157,7 @@ class Scanner extends BasicEmitter { } } if (!empty($newData)) { - $addToCache = Config::getSystemValue('allow_scanner_to_affect_cache', true); + $addToCache = Config::getSystemValue('filesystem_check_enable', true); \OC_Hook::emit('Scanner', 'addToCache', array('file' => $file, 'addToCache' => &$addToCache, 'data' => &$newData)); if($addToCache) { $data['fileid'] = $this->cache->put($file, $newData); @@ -166,7 +166,7 @@ class Scanner extends BasicEmitter { \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId)); } } else { - $removeFromCache = Config::getSystemValue('allow_scanner_to_affect_cache', true); + $removeFromCache = Config::getSystemValue('filesystem_check_enable', true); \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $file, 'removeFromCache' => &$removeFromCache)); if($removeFromCache) { $this->cache->remove($file); @@ -253,7 +253,7 @@ class Scanner extends BasicEmitter { $removedChildren = \array_diff($existingChildren, $newChildren); foreach ($removedChildren as $childName) { $child = ($path) ? $path . '/' . $childName : $childName; - $removeFromCache = Config::getSystemValue('allow_scanner_to_affect_cache', true); + $removeFromCache = Config::getSystemValue('filesystem_check_enable', true); \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $child, 'removeFromCache' => &$removeFromCache)); if($removeFromCache) { $this->cache->remove($child); @@ -277,7 +277,7 @@ class Scanner extends BasicEmitter { } } $newData = array('size' => $size); - $addToCache = Config::getSystemValue('allow_scanner_to_affect_cache', true); + $addToCache = Config::getSystemValue('filesystem_check_enable', true); \OC_Hook::emit('Scanner', 'addToCache', array('file' => $child, 'addToCache' => &$addToCache, 'data' => &$newData)); if($addToCache) { $this->cache->put($path, $newData); -- cgit v1.2.3 From c100da33bbba70264016103f93a3e4cb72544345 Mon Sep 17 00:00:00 2001 From: Volkan Gezer Date: Tue, 27 May 2014 23:16:49 +0200 Subject: upgraded phpmailer into v5.2.8 via composer --- 3rdparty | 2 +- lib/private/mail.php | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) (limited to 'lib/private') diff --git a/3rdparty b/3rdparty index ef80977061d..cb0e42027de 160000 --- a/3rdparty +++ b/3rdparty @@ -1 +1 @@ -Subproject commit ef80977061d4bc3a2d8ee0bf23a8287a3222b628 +Subproject commit cb0e42027def10363ac37a8e02132ffbb6e38ae3 diff --git a/lib/private/mail.php b/lib/private/mail.php index f9083cc4e64..81bcb3d8deb 100644 --- a/lib/private/mail.php +++ b/lib/private/mail.php @@ -12,8 +12,6 @@ * A class to handle mail sending. */ -require_once 'class.phpmailer.php'; - class OC_Mail { /** -- cgit v1.2.3 From 5e9ea2b3659eebf6d21c253771e477abe16496c9 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Wed, 28 May 2014 02:12:01 +0200 Subject: fix 8757, get rid of service locator antipattern --- .../dependencyinjection/dicontainer.php | 15 +- .../middleware/security/securitymiddleware.php | 58 ++++--- .../middleware/MiddlewareDispatcherTest.php | 8 +- .../lib/appframework/middleware/MiddlewareTest.php | 6 +- .../middleware/security/SecurityMiddlewareTest.php | 176 +++++++++------------ 5 files changed, 129 insertions(+), 134 deletions(-) (limited to 'lib/private') diff --git a/lib/private/appframework/dependencyinjection/dicontainer.php b/lib/private/appframework/dependencyinjection/dicontainer.php index ee492b8a9e5..61a2333ecee 100644 --- a/lib/private/appframework/dependencyinjection/dicontainer.php +++ b/lib/private/appframework/dependencyinjection/dicontainer.php @@ -83,8 +83,8 @@ class DIContainer extends SimpleContainer implements IAppContainer{ $this['Dispatcher'] = $this->share(function($c) { return new Dispatcher( - $c['Protocol'], - $c['MiddlewareDispatcher'], + $c['Protocol'], + $c['MiddlewareDispatcher'], $c['ControllerMethodReflector'], $c['Request'] ); @@ -97,9 +97,14 @@ class DIContainer extends SimpleContainer implements IAppContainer{ $app = $this; $this['SecurityMiddleware'] = $this->share(function($c) use ($app){ return new SecurityMiddleware( - $app, - $c['Request'], - $c['ControllerMethodReflector'] + $c['Request'], + $c['ControllerMethodReflector'], + $app->getServer()->getNavigationManager(), + $app->getServer()->getURLGenerator(), + $app->getServer()->getLogger(), + $c['AppName'], + $app->isLoggedIn(), + $app->isAdminUser() ); }); diff --git a/lib/private/appframework/middleware/security/securitymiddleware.php b/lib/private/appframework/middleware/security/securitymiddleware.php index d7e398fe445..5b56210024d 100644 --- a/lib/private/appframework/middleware/security/securitymiddleware.php +++ b/lib/private/appframework/middleware/security/securitymiddleware.php @@ -30,8 +30,10 @@ use OCP\AppFramework\Http\RedirectResponse; use OCP\AppFramework\Middleware; use OCP\AppFramework\Http\Response; use OCP\AppFramework\Http\JSONResponse; -use OCP\AppFramework\IAppContainer; +use OCP\INavigationManager; +use OCP\IURLGenerator; use OCP\IRequest; +use OCP\ILogger; /** @@ -42,31 +44,41 @@ use OCP\IRequest; */ class SecurityMiddleware extends Middleware { - /** - * @var \OCP\AppFramework\IAppContainer - */ - private $app; - - /** - * @var \OCP\IRequest - */ + private $navigationManager; private $request; - - /** - * @var OC\AppFramework\Utility\ControllerMethodReflector - */ private $reflector; + private $appName; + private $urlGenerator; + private $logger; + private $isLoggedIn; + private $isAdminUser; /** - * @param IAppContainer $app * @param IRequest $request * @param ControllerMethodReflector $reflector + * @param INavigationManager $navigationManager + * @param IURLGenerator $urlGenerator + * @param ILogger $logger + * @param string $appName + * @param bool $isLoggedIn + * @param bool $isAdminUser */ - public function __construct(IAppContainer $app, IRequest $request, - ControllerMethodReflector $reflector){ - $this->app = $app; + public function __construct(IRequest $request, + ControllerMethodReflector $reflector, + INavigationManager $navigationManager, + IURLGenerator $urlGenerator, + ILogger $logger, + $appName, + $isLoggedIn, + $isAdminUser){ + $this->navigationManager = $navigationManager; $this->request = $request; $this->reflector = $reflector; + $this->appName = $appName; + $this->urlGenerator = $urlGenerator; + $this->logger = $logger; + $this->isLoggedIn = $isLoggedIn; + $this->isAdminUser = $isAdminUser; } @@ -82,17 +94,17 @@ class SecurityMiddleware extends Middleware { // this will set the current navigation entry of the app, use this only // for normal HTML requests and not for AJAX requests - $this->app->getServer()->getNavigationManager()->setActiveEntry($this->app->getAppName()); + $this->navigationManager->setActiveEntry($this->appName); // security checks $isPublicPage = $this->reflector->hasAnnotation('PublicPage'); if(!$isPublicPage) { - if(!$this->app->isLoggedIn()) { + if(!$this->isLoggedIn) { throw new SecurityException('Current user is not logged in', Http::STATUS_UNAUTHORIZED); } if(!$this->reflector->hasAnnotation('NoAdminRequired')) { - if(!$this->app->isAdminUser()) { + if(!$this->isAdminUser) { throw new SecurityException('Logged in user must be an admin', Http::STATUS_FORBIDDEN); } } @@ -126,13 +138,13 @@ class SecurityMiddleware extends Middleware { array('message' => $exception->getMessage()), $exception->getCode() ); - $this->app->log($exception->getMessage(), 'debug'); + $this->logger->debug($exception->getMessage()); } else { // TODO: replace with link to route - $url = $this->app->getServer()->getURLGenerator()->getAbsoluteURL('index.php'); + $url = $this->urlGenerator->getAbsoluteURL('index.php'); $response = new RedirectResponse($url); - $this->app->log($exception->getMessage(), 'debug'); + $this->logger->debug($exception->getMessage()); } return $response; diff --git a/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php b/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php index b1a58e21289..b1e221aab99 100644 --- a/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php +++ b/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php @@ -124,15 +124,9 @@ class MiddlewareDispatcherTest extends \PHPUnit_Framework_TestCase { } - private function getAPIMock(){ - return $this->getMock('OC\AppFramework\DependencyInjection\DIContainer', - array('getAppName'), array('app')); - } - - private function getControllerMock(){ return $this->getMock('OCP\AppFramework\Controller', array('method'), - array($this->getAPIMock(), new Request(array('method' => 'GET')))); + array('app', new Request(array('method' => 'GET')))); } diff --git a/tests/lib/appframework/middleware/MiddlewareTest.php b/tests/lib/appframework/middleware/MiddlewareTest.php index 814efdd8118..9d952f61573 100644 --- a/tests/lib/appframework/middleware/MiddlewareTest.php +++ b/tests/lib/appframework/middleware/MiddlewareTest.php @@ -44,8 +44,10 @@ class MiddlewareTest extends \PHPUnit_Framework_TestCase { protected function setUp(){ $this->middleware = new ChildMiddleware(); - $this->api = $this->getMock('OC\AppFramework\DependencyInjection\DIContainer', - array(), array('test')); + $this->api = $this->getMockBuilder( + 'OC\AppFramework\DependencyInjection\DIContainer') + ->disableOriginalConstructor() + ->getMock(); $this->controller = $this->getMock('OCP\AppFramework\Controller', array(), array($this->api, new Request())); diff --git a/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php b/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php index 6a1bbf72c13..ae0b05bdb3c 100644 --- a/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php +++ b/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php @@ -39,41 +39,48 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { private $secAjaxException; private $request; private $reader; + private $logger; + private $navigationManager; + private $urlGenerator; public function setUp() { - $api = $this->getMock('OC\AppFramework\DependencyInjection\DIContainer', array(), array('test')); - $this->controller = $this->getMock('OCP\AppFramework\Controller', - array(), array($api, new Request())); + $this->controller = $this->getMockBuilder('OCP\AppFramework\Controller') + ->disableOriginalConstructor() + ->getMock(); $this->reader = new ControllerMethodReflector(); - - $this->request = new Request(); - $this->middleware = new SecurityMiddleware($api, $this->request, $this->reader); + $this->logger = $this->getMockBuilder( + 'OCP\ILogger') + ->disableOriginalConstructor() + ->getMock(); + $this->navigationManager = $this->getMockBuilder( + 'OCP\INavigationManager') + ->disableOriginalConstructor() + ->getMock(); + $this->urlGenerator = $this->getMockBuilder( + 'OCP\IURLGenerator') + ->disableOriginalConstructor() + ->getMock(); + $this->request = $this->getMockBuilder( + 'OCP\IRequest') + ->disableOriginalConstructor() + ->getMock(); + $this->middleware = $this->getMiddleware(true, true); $this->secException = new SecurityException('hey', false); $this->secAjaxException = new SecurityException('hey', true); } - private function getAPI(){ - return $this->getMock('OC\AppFramework\DependencyInjection\DIContainer', - array('isLoggedIn', 'passesCSRFCheck', 'isAdminUser', - 'isSubAdminUser', 'getUserId'), - array('app')); - } - - - /** - * @param string $method - */ - private function checkNavEntry($method){ - $api = $this->getAPI(); - - $serverMock = $this->getMock('\OC\Server', array()); - $api->expects($this->any())->method('getServer') - ->will($this->returnValue($serverMock)); - - $sec = new SecurityMiddleware($api, $this->request, $this->reader); - $this->reader->reflect('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', $method); - $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', $method); + private function getMiddleware($isLoggedIn, $isAdminUser){ + return new SecurityMiddleware( + $this->request, + $this->reader, + $this->navigationManager, + $this->urlGenerator, + $this->logger, + 'test', + $isLoggedIn, + $isAdminUser + ); } @@ -82,7 +89,12 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { * @NoCSRFRequired */ public function testSetNavigationEntry(){ - $this->checkNavEntry('testSetNavigationEntry'); + $this->navigationManager->expects($this->once()) + ->method('setActiveEntry') + ->with($this->equalTo('test')); + + $this->reader->reflect(__CLASS__, __FUNCTION__); + $this->middleware->beforeController(__CLASS__, __FUNCTION__); } @@ -91,24 +103,19 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { * @param string $test */ private function ajaxExceptionStatus($method, $test, $status) { - $api = $this->getAPI(); - $api->expects($this->any()) - ->method($test) - ->will($this->returnValue(false)); + $isLoggedIn = false; + $isAdminUser = false; // isAdminUser requires isLoggedIn call to return true if ($test === 'isAdminUser') { - $api->expects($this->any()) - ->method('isLoggedIn') - ->will($this->returnValue(true)); + $isLoggedIn = true; } - $sec = new SecurityMiddleware($api, $this->request, $this->reader); + $sec = $this->getMiddleware($isLoggedIn, $isAdminUser); try { - $controller = '\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest'; - $this->reader->reflect($controller, $method); - $sec->beforeController($controller, $method); + $this->reader->reflect(__CLASS__, $method); + $sec->beforeController(__CLASS__, $method); } catch (SecurityException $ex){ $this->assertEquals($status, $ex->getCode()); } @@ -178,22 +185,14 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { * @NoCSRFRequired */ public function testNoChecks(){ - $api = $this->getAPI(); - $api->expects($this->never()) + $this->request->expects($this->never()) ->method('passesCSRFCheck') - ->will($this->returnValue(true)); - $api->expects($this->never()) - ->method('isAdminUser') - ->will($this->returnValue(true)); - $api->expects($this->never()) - ->method('isLoggedIn') - ->will($this->returnValue(true)); - - $sec = new SecurityMiddleware($api, $this->request, $this->reader); - $this->reader->reflect('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', - 'testNoChecks'); - $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', - 'testNoChecks'); + ->will($this->returnValue(false)); + + $sec = $this->getMiddleware(false, false); + + $this->reader->reflect(__CLASS__, __FUNCTION__); + $sec->beforeController(__CLASS__, __FUNCTION__); } @@ -202,19 +201,16 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { * @param string $expects */ private function securityCheck($method, $expects, $shouldFail=false){ - $api = $this->getAPI(); - $api->expects($this->once()) - ->method($expects) - ->will($this->returnValue(!$shouldFail)); - // admin check requires login if ($expects === 'isAdminUser') { - $api->expects($this->once()) - ->method('isLoggedIn') - ->will($this->returnValue(true)); + $isLoggedIn = true; + $isAdminUser = !$shouldFail; + } else { + $isLoggedIn = !$shouldFail; + $isAdminUser = false; } - $sec = new SecurityMiddleware($api, $this->request, $this->reader); + $sec = $this->getMiddleware($isLoggedIn, $isAdminUser); if($shouldFail){ $this->setExpectedException('\OC\AppFramework\Middleware\Security\SecurityException'); @@ -222,8 +218,8 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { $this->setExpectedException(null); } - $this->reader->reflect('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', $method); - $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', $method); + $this->reader->reflect(__CLASS__, $method); + $sec->beforeController(__CLASS__, $method); } @@ -232,15 +228,12 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { * @expectedException \OC\AppFramework\Middleware\Security\SecurityException */ public function testCsrfCheck(){ - $api = $this->getAPI(); - $request = $this->getMock('OC\AppFramework\Http\Request', array('passesCSRFCheck')); - $request->expects($this->once()) + $this->request->expects($this->once()) ->method('passesCSRFCheck') ->will($this->returnValue(false)); - $sec = new SecurityMiddleware($api, $request, $this->reader); - $this->reader->reflect('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testCsrfCheck'); - $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testCsrfCheck'); + $this->reader->reflect(__CLASS__, __FUNCTION__); + $this->middleware->beforeController(__CLASS__, __FUNCTION__); } @@ -249,15 +242,12 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { * @NoCSRFRequired */ public function testNoCsrfCheck(){ - $api = $this->getAPI(); - $request = $this->getMock('OC\AppFramework\Http\Request', array('passesCSRFCheck')); - $request->expects($this->never()) + $this->request->expects($this->never()) ->method('passesCSRFCheck') ->will($this->returnValue(false)); - $sec = new SecurityMiddleware($api, $request, $this->reader); - $this->reader->reflect('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testNoCsrfCheck'); - $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testNoCsrfCheck'); + $this->reader->reflect(__CLASS__, __FUNCTION__); + $this->middleware->beforeController(__CLASS__, __FUNCTION__); } @@ -265,15 +255,12 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { * @PublicPage */ public function testFailCsrfCheck(){ - $api = $this->getAPI(); - $request = $this->getMock('OC\AppFramework\Http\Request', array('passesCSRFCheck')); - $request->expects($this->once()) + $this->request->expects($this->once()) ->method('passesCSRFCheck') ->will($this->returnValue(true)); - $sec = new SecurityMiddleware($api, $request, $this->reader); - $this->reader->reflect('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testFailCsrfCheck'); - $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testFailCsrfCheck'); + $this->reader->reflect(__CLASS__, __FUNCTION__); + $this->middleware->beforeController(__CLASS__, __FUNCTION__); } @@ -282,7 +269,7 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { * @NoAdminRequired */ public function testLoggedInCheck(){ - $this->securityCheck('testLoggedInCheck', 'isLoggedIn'); + $this->securityCheck(__FUNCTION__, 'isLoggedIn'); } @@ -291,7 +278,7 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { * @NoAdminRequired */ public function testFailLoggedInCheck(){ - $this->securityCheck('testFailLoggedInCheck', 'isLoggedIn', true); + $this->securityCheck(__FUNCTION__, 'isLoggedIn', true); } @@ -299,7 +286,7 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { * @NoCSRFRequired */ public function testIsAdminCheck(){ - $this->securityCheck('testIsAdminCheck', 'isAdminUser'); + $this->securityCheck(__FUNCTION__, 'isAdminUser'); } @@ -307,7 +294,7 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { * @NoCSRFRequired */ public function testFailIsAdminCheck(){ - $this->securityCheck('testFailIsAdminCheck', 'isAdminUser', true); + $this->securityCheck(__FUNCTION__, 'isAdminUser', true); } @@ -319,17 +306,12 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { public function testAfterExceptionReturnsRedirect(){ - $api = $this->getMock('OC\AppFramework\DependencyInjection\DIContainer', array(), array('test')); - $serverMock = $this->getMock('\OC\Server', array('getNavigationManager')); - $api->expects($this->once())->method('getServer') - ->will($this->returnValue($serverMock)); - - $this->controller = $this->getMock('OCP\AppFramework\Controller', - array(), array($api, new Request())); - $this->request = new Request( - array('server' => array('HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'))); - $this->middleware = new SecurityMiddleware($api, $this->request, $this->reader); + array('server' => + array('HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8') + ) + ); + $this->middleware = $this->getMiddleware(true, true); $response = $this->middleware->afterException($this->controller, 'test', $this->secException); -- cgit v1.2.3 From 3d1ba574e430d14c9215d889e47b07c05b3429d9 Mon Sep 17 00:00:00 2001 From: ringmaster Date: Wed, 28 May 2014 07:59:38 -0400 Subject: Change visibility of scanner internals so that descendant classes can access them. --- lib/private/files/cache/scanner.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/cache/scanner.php b/lib/private/files/cache/scanner.php index b3ab94f4599..61b22ea75a0 100644 --- a/lib/private/files/cache/scanner.php +++ b/lib/private/files/cache/scanner.php @@ -26,22 +26,22 @@ class Scanner extends BasicEmitter { /** * @var \OC\Files\Storage\Storage $storage */ - private $storage; + protected $storage; /** * @var string $storageId */ - private $storageId; + protected $storageId; /** * @var \OC\Files\Cache\Cache $cache */ - private $cache; + protected $cache; /** * @var \OC\Files\Cache\Permissions $permissionsCache */ - private $permissionsCache; + protected $permissionsCache; const SCAN_RECURSIVE = true; const SCAN_SHALLOW = false; -- cgit v1.2.3 From a2e4bc8d33d0e7e3cc967db2857041e2817de4db Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Thu, 8 May 2014 15:19:54 +0200 Subject: # This is a combination of 2 commits. # The first commit's message is: adding tests for long paths increment path field in database up to 4000 (maximum for Oracle - otherwise we could use php's 4096) increment version to trigger database migration adding unit test for too long path # This is the 2nd commit message: fix too long path --- db_structure.xml | 2 +- lib/private/files/view.php | 21 ++++++-- tests/lib/files/view.php | 121 +++++++++++++++++++++++++++++++++++++++++++++ version.php | 2 +- 4 files changed, 141 insertions(+), 5 deletions(-) (limited to 'lib/private') diff --git a/db_structure.xml b/db_structure.xml index 3cb2af287af..21ac47a781b 100644 --- a/db_structure.xml +++ b/db_structure.xml @@ -257,7 +257,7 @@ text false - 512 + 4000 diff --git a/lib/private/files/view.php b/lib/private/files/view.php index 940f31fe420..b698d87866c 100644 --- a/lib/private/files/view.php +++ b/lib/private/files/view.php @@ -29,14 +29,13 @@ use OC\Files\Cache\Updater; class View { private $fakeRoot = ''; - private $internal_path_cache = array(); - private $storage_cache = array(); public function __construct($root = '') { $this->fakeRoot = $root; } public function getAbsolutePath($path = '/') { + $this->assertPathLength($path); if ($path === '') { $path = '/'; } @@ -77,6 +76,7 @@ class View { * @return string */ public function getRelativePath($path) { + $this->assertPathLength($path); if ($this->fakeRoot == '') { return $path; } @@ -208,6 +208,7 @@ class View { } public function readfile($path) { + $this->assertPathLength($path); @ob_end_clean(); $handle = $this->fopen($path, 'rb'); if ($handle) { @@ -595,6 +596,7 @@ class View { } public function toTmpFile($path) { + $this->assertPathLength($path); if (Filesystem::isValidPath($path)) { $source = $this->fopen($path, 'r'); if ($source) { @@ -611,7 +613,7 @@ class View { } public function fromTmpFile($tmpFile, $path) { - + $this->assertPathLength($path); if (Filesystem::isValidPath($path)) { // Get directory that the file is going into @@ -640,6 +642,7 @@ class View { } public function getMimeType($path) { + $this->assertPathLength($path); return $this->basicOperation('getMimeType', $path); } @@ -669,6 +672,7 @@ class View { } public function free_space($path = '/') { + $this->assertPathLength($path); return $this->basicOperation('free_space', $path); } @@ -808,6 +812,7 @@ class View { * @return \OC\Files\FileInfo|false */ public function getFileInfo($path, $includeMountPoints = true) { + $this->assertPathLength($path); $data = array(); if (!Filesystem::isValidPath($path)) { return $data; @@ -878,6 +883,7 @@ class View { * @return FileInfo[] */ public function getDirectoryContent($directory, $mimetype_filter = '') { + $this->assertPathLength($directory); $result = array(); if (!Filesystem::isValidPath($directory)) { return $result; @@ -1006,6 +1012,7 @@ class View { * returns the fileid of the updated file */ public function putFileInfo($path, $data) { + $this->assertPathLength($path); if ($data instanceof FileInfo) { $data = $data->getData(); } @@ -1153,4 +1160,12 @@ class View { } return null; } + + private function assertPathLength($path) { + $maxLen = min(PHP_MAXPATHLEN, 4000); + $pathLen = strlen($path); + if ($pathLen > $maxLen) { + throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path"); + } + } } diff --git a/tests/lib/files/view.php b/tests/lib/files/view.php index 201eb9ff6cb..b5e4d792350 100644 --- a/tests/lib/files/view.php +++ b/tests/lib/files/view.php @@ -20,6 +20,7 @@ class View extends \PHPUnit_Framework_TestCase { * @var \OC\Files\Storage\Storage[] $storages */ private $storages = array(); + private $user; public function setUp() { \OC_User::clearBackends(); @@ -569,6 +570,47 @@ class View extends \PHPUnit_Framework_TestCase { } } + public function testLongPath() { + + $storage = new \OC\Files\Storage\Temporary(array()); + \OC\Files\Filesystem::mount($storage, array(), '/'); + + $rootView = new \OC\Files\View(''); + + $longPath = ''; + // 4000 is the maximum path length in file_cache.path + $folderName = 'abcdefghijklmnopqrstuvwxyz012345678901234567890123456789'; + $depth = (4000/57); + foreach (range(0, $depth-1) as $i) { + $longPath .= '/'.$folderName; + $result = $rootView->mkdir($longPath); + $this->assertTrue($result, "mkdir failed on $i - path length: " . strlen($longPath)); + + $result = $rootView->file_put_contents($longPath . '/test.txt', 'lorem'); + $this->assertEquals(5, $result, "file_put_contents failed on $i"); + + $this->assertTrue($rootView->file_exists($longPath)); + $this->assertTrue($rootView->file_exists($longPath . '/test.txt')); + } + + $cache = $storage->getCache(); + $scanner = $storage->getScanner(); + $scanner->scan(''); + + $longPath = $folderName; + foreach (range(0, $depth-1) as $i) { + $cachedFolder = $cache->get($longPath); + $this->assertTrue(is_array($cachedFolder), "No cache entry for folder at $i"); + $this->assertEquals($folderName, $cachedFolder['name'], "Wrong cache entry for folder at $i"); + + $cachedFile = $cache->get($longPath . '/test.txt'); + $this->assertTrue(is_array($cachedFile), "No cache entry for file at $i"); + $this->assertEquals('test.txt', $cachedFile['name'], "Wrong cache entry for file at $i"); + + $longPath .= '/' . $folderName; + } + } + public function testTouchNotSupported() { $storage = new TemporaryNoTouch(array()); $scanner = $storage->getScanner(); @@ -605,4 +647,83 @@ class View extends \PHPUnit_Framework_TestCase { array('/files/test', '/test'), ); } + + /** + * @dataProvider tooLongPathDataProvider + * @expectedException \OCP\Files\InvalidPathException + */ + public function testTooLongPath($operation, $param0 = NULL) { + + $longPath = ''; + // 4000 is the maximum path length in file_cache.path + $folderName = 'abcdefghijklmnopqrstuvwxyz012345678901234567890123456789'; + $depth = (4000/57); + foreach (range(0, $depth+1) as $i) { + $longPath .= '/'.$folderName; + } + + $storage = new \OC\Files\Storage\Temporary(array()); + \OC\Files\Filesystem::mount($storage, array(), '/'); + + $rootView = new \OC\Files\View(''); + + + if ($param0 === '@0') { + $param0 = $longPath; + } + + if ($operation === 'hash') { + $param0 = $longPath; + $longPath = 'md5'; + } + + call_user_func(array($rootView, $operation), $longPath, $param0); + + } + + public function tooLongPathDataProvider() { + return array( + array('getAbsolutePath'), + array('getRelativePath'), + array('getMountPoint'), + array('resolvePath'), + array('getLocalFile'), + array('getLocalFolder'), + array('mkdir'), + array('rmdir'), + array('opendir'), + array('is_dir'), + array('is_file'), + array('stat'), + array('filetype'), + array('filesize'), + array('readfile'), + array('isCreatable'), + array('isReadable'), + array('isUpdatable'), + array('isDeletable'), + array('isSharable'), + array('file_exists'), + array('filemtime'), + array('touch'), + array('file_get_contents'), + array('unlink'), + array('deleteAll'), + array('toTmpFile'), + array('getMimeType'), + array('free_space'), + array('getFileInfo'), + array('getDirectoryContent'), + array('getOwner'), + array('getETag'), + array('file_put_contents', 'ipsum'), + array('rename', '@0'), + array('copy', '@0'), + array('fopen', 'r'), + array('fromTmpFile', '@0'), + array('hash'), + array('hasUpdated', 0), + array('putFileInfo', array()), + ); + } } diff --git a/version.php b/version.php index 079af525454..28ef5ea72d0 100644 --- a/version.php +++ b/version.php @@ -3,7 +3,7 @@ // We only can count up. The 4. digit is only for the internal patchlevel to trigger DB upgrades // between betas, final and RCs. This is _not_ the public version number. Reset minor/patchlevel // when updating major/minor version number. -$OC_Version=array(6, 90, 0, 2); +$OC_Version=array(6, 90, 0, 3); // The human readable string $OC_VersionString='7.0 pre alpha'; -- cgit v1.2.3 From e83b41493fe28eca612f3993a5a1cc3e44e9c145 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Mon, 1 Jul 2013 17:41:49 +0200 Subject: remove unneeded delTree --- lib/private/files/storage/local.php | 26 +------------------------- 1 file changed, 1 insertion(+), 25 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/local.php b/lib/private/files/storage/local.php index de940fc7cdb..aaa9f3c858e 100644 --- a/lib/private/files/storage/local.php +++ b/lib/private/files/storage/local.php @@ -164,7 +164,7 @@ if (\OC_Util::runningOnWindows()) { } public function unlink($path) { - return $this->delTree($path); + return unlink($this->datadir . $path); } public function rename($path1, $path2) { @@ -212,30 +212,6 @@ if (\OC_Util::runningOnWindows()) { return $return; } - /** - * @param string $dir - */ - private function delTree($dir) { - $dirRelative = $dir; - $dir = $this->datadir . $dir; - if (!file_exists($dir)) return true; - if (!is_dir($dir) || is_link($dir)) return unlink($dir); - foreach (scandir($dir) as $item) { - if ($item == '.' || $item == '..') continue; - if (is_file($dir . '/' . $item)) { - if (unlink($dir . '/' . $item)) { - } - } elseif (is_dir($dir . '/' . $item)) { - if (!$this->delTree($dirRelative . "/" . $item)) { - return false; - }; - } - } - if ($return = rmdir($dir)) { - } - return $return; - } - /** * @param string $fullPath */ -- cgit v1.2.3 From 38c1da09768d034ee788f0c6a4284591e914fe4a Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Mon, 1 Jul 2013 17:45:01 +0200 Subject: fix recursive rename for local storage backend --- lib/private/files/storage/local.php | 6 ++++-- tests/lib/files/storage/storage.php | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/local.php b/lib/private/files/storage/local.php index aaa9f3c858e..ec28ebac6ee 100644 --- a/lib/private/files/storage/local.php +++ b/lib/private/files/storage/local.php @@ -177,9 +177,11 @@ if (\OC_Util::runningOnWindows()) { return false; } - if ($return = rename($this->datadir . $path1, $this->datadir . $path2)) { + if ($this->is_dir($path2)) { + $this->rmdir($path2); } - return $return; + + return rename($this->datadir . $path1, $this->datadir . $path2); } public function copy($path1, $path2) { diff --git a/tests/lib/files/storage/storage.php b/tests/lib/files/storage/storage.php index 92afd47673a..4a4626fc5c5 100644 --- a/tests/lib/files/storage/storage.php +++ b/tests/lib/files/storage/storage.php @@ -385,4 +385,20 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->assertEquals('qwerty', $this->instance->file_get_contents('target/test2.txt')); $this->assertEquals('bar', $this->instance->file_get_contents('target/subfolder/test.txt')); } + + public function testRenameOverWriteDirectory() { + $this->instance->mkdir('source'); + $this->instance->file_put_contents('source/test1.txt', 'foo'); + + $this->instance->mkdir('target'); + $this->instance->file_put_contents('target/test1.txt', 'bar'); + $this->instance->file_put_contents('target/test2.txt', 'bar'); + + $this->instance->rename('source', 'target'); + + $this->assertFalse($this->instance->file_exists('source')); + $this->assertFalse($this->instance->file_exists('source/test1.txt')); + $this->assertFalse($this->instance->file_exists('target/test2.txt')); + $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); + } } -- cgit v1.2.3 From 03ba497a8c1e149857d6c3a4d4cab49dea5903c1 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Mon, 1 Jul 2013 17:57:40 +0200 Subject: add recursive copy to local storage backend --- lib/private/files/storage/local.php | 26 +++++++++++---- tests/lib/files/storage/storage.php | 65 ++++++++++++++++++++++++++++++++++++- 2 files changed, 84 insertions(+), 7 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/local.php b/lib/private/files/storage/local.php index ec28ebac6ee..dc6e7a12c65 100644 --- a/lib/private/files/storage/local.php +++ b/lib/private/files/storage/local.php @@ -179,20 +179,34 @@ if (\OC_Util::runningOnWindows()) { if ($this->is_dir($path2)) { $this->rmdir($path2); + } else if ($this->is_file($path2)) { + $this->unlink($path2); } return rename($this->datadir . $path1, $this->datadir . $path2); } public function copy($path1, $path2) { - if ($this->is_dir($path2)) { - if (!$this->file_exists($path2)) { - $this->mkdir($path2); + if ($this->is_dir($path1)) { + if ($this->is_dir($path2)) { + $this->rmdir($path2); + } else if ($this->is_file($path2)) { + $this->unlink($path2); + } + $dir = $this->opendir($path1); + $this->mkdir($path2); + while ($file = readdir($dir)) { + if (($file != '.') && ($file != '..')) { + if (!$this->copy($path1 . '/' . $file, $path2 . '/' . $file)) { + return false; + } + } } - $source = substr($path1, strrpos($path1, '/') + 1); - $path2 .= $source; + closedir($dir); + return true; + } else { + return copy($this->datadir . $path1, $this->datadir . $path2); } - return copy($this->datadir . $path1, $this->datadir . $path2); } public function fopen($path, $mode) { diff --git a/tests/lib/files/storage/storage.php b/tests/lib/files/storage/storage.php index 4a4626fc5c5..24390f05367 100644 --- a/tests/lib/files/storage/storage.php +++ b/tests/lib/files/storage/storage.php @@ -373,7 +373,7 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->assertFalse($this->instance->file_exists('source/test1.txt')); $this->assertFalse($this->instance->file_exists('source/test2.txt')); $this->assertFalse($this->instance->file_exists('source/subfolder')); - $this->assertFalse($this->instance->file_exists('source/test.txt')); + $this->assertFalse($this->instance->file_exists('source/subfolder/test.txt')); $this->assertTrue($this->instance->file_exists('target')); $this->assertTrue($this->instance->file_exists('target/test1.txt')); @@ -401,4 +401,67 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->assertFalse($this->instance->file_exists('target/test2.txt')); $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); } + + public function testRenameOverWriteDirectoryOverFile() { + $this->instance->mkdir('source'); + $this->instance->file_put_contents('source/test1.txt', 'foo'); + + $this->instance->file_put_contents('target', 'bar'); + + $this->instance->rename('source', 'target'); + + $this->assertFalse($this->instance->file_exists('source')); + $this->assertFalse($this->instance->file_exists('source/test1.txt')); + $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); + } + + public function testCopyDirectory() { + $this->instance->mkdir('source'); + $this->instance->file_put_contents('source/test1.txt', 'foo'); + $this->instance->file_put_contents('source/test2.txt', 'qwerty'); + $this->instance->mkdir('source/subfolder'); + $this->instance->file_put_contents('source/subfolder/test.txt', 'bar'); + $this->instance->copy('source', 'target'); + + $this->assertTrue($this->instance->file_exists('source')); + $this->assertTrue($this->instance->file_exists('source/test1.txt')); + $this->assertTrue($this->instance->file_exists('source/test2.txt')); + $this->assertTrue($this->instance->file_exists('source/subfolder')); + $this->assertTrue($this->instance->file_exists('source/subfolder/test.txt')); + + $this->assertTrue($this->instance->file_exists('target')); + $this->assertTrue($this->instance->file_exists('target/test1.txt')); + $this->assertTrue($this->instance->file_exists('target/test2.txt')); + $this->assertTrue($this->instance->file_exists('target/subfolder')); + $this->assertTrue($this->instance->file_exists('target/subfolder/test.txt')); + + $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); + $this->assertEquals('qwerty', $this->instance->file_get_contents('target/test2.txt')); + $this->assertEquals('bar', $this->instance->file_get_contents('target/subfolder/test.txt')); + } + + public function testCopyOverWriteDirectory() { + $this->instance->mkdir('source'); + $this->instance->file_put_contents('source/test1.txt', 'foo'); + + $this->instance->mkdir('target'); + $this->instance->file_put_contents('target/test1.txt', 'bar'); + $this->instance->file_put_contents('target/test2.txt', 'bar'); + + $this->instance->copy('source', 'target'); + + $this->assertFalse($this->instance->file_exists('target/test2.txt')); + $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); + } + + public function testCopyOverWriteDirectoryOverFile() { + $this->instance->mkdir('source'); + $this->instance->file_put_contents('source/test1.txt', 'foo'); + + $this->instance->file_put_contents('target', 'bar'); + + $this->instance->copy('source', 'target'); + + $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); + } } -- cgit v1.2.3 From c3c9612c99c0bd8b2da9cac262045c43775f2988 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Mon, 1 Jul 2013 18:02:56 +0200 Subject: fix recursive copy and rename for mapped local storage backend --- lib/private/files/storage/mappedlocal.php | 37 ++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 10 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/mappedlocal.php b/lib/private/files/storage/mappedlocal.php index 07691661644..9d3fa01d883 100644 --- a/lib/private/files/storage/mappedlocal.php +++ b/lib/private/files/storage/mappedlocal.php @@ -177,6 +177,12 @@ class MappedLocal extends \OC\Files\Storage\Common{ return false; } + if ($this->is_dir($path2)) { + $this->rmdir($path2); + } else if ($this->is_file($path2)) { + $this->unlink($path2); + } + $physicPath1 = $this->buildPath($path1); $physicPath2 = $this->buildPath($path2); if($return=rename($physicPath1, $physicPath2)) { @@ -187,18 +193,29 @@ class MappedLocal extends \OC\Files\Storage\Common{ return $return; } public function copy($path1, $path2) { - if($this->is_dir($path2)) { - if(!$this->file_exists($path2)) { - $this->mkdir($path2); + if ($this->is_dir($path1)) { + if ($this->is_dir($path2)) { + $this->rmdir($path2); + } else if ($this->is_file($path2)) { + $this->unlink($path2); } - $source=substr($path1, strrpos($path1, '/')+1); - $path2.=$source; - } - if($return=copy($this->buildPath($path1), $this->buildPath($path2))) { - // mapper needs to create copies or all children - $this->copyMapping($path1, $path2); + $dir = $this->opendir($path1); + $this->mkdir($path2); + while ($file = readdir($dir)) { + if (($file != '.') && ($file != '..')) { + if (!$this->copy($path1 . '/' . $file, $path2 . '/' . $file)) { + return false; + } + } + } + closedir($dir); + return true; + } else { + if ($return = copy($this->buildPath($path1), $this->buildPath($path2))) { + $this->copyMapping($path1, $path2); + } + return $return; } - return $return; } public function fopen($path, $mode) { if($return=fopen($this->buildPath($path), $mode)) { -- cgit v1.2.3 From ea44f0e20f9685e5d8396380a5fcb383d9efee90 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Mon, 1 Jul 2013 18:11:05 +0200 Subject: fix recursive copy and rename for common storage backend --- lib/private/files/storage/common.php | 47 +++++++++++++++++++++++++++++------- 1 file changed, 38 insertions(+), 9 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/common.php b/lib/private/files/storage/common.php index cfca8ca008c..5fae43d8bf7 100644 --- a/lib/private/files/storage/common.php +++ b/lib/private/files/storage/common.php @@ -137,20 +137,49 @@ abstract class Common implements \OC\Files\Storage\Storage { } public function rename($path1, $path2) { - if ($this->copy($path1, $path2)) { - $this->removeCachedFile($path1); - return $this->unlink($path1); + if ($this->file_exists($path2)) { + if ($this->is_dir($path2)) { + $this->rmdir($path2); + } else if ($this->is_file($path2)) { + $this->unlink($path2); + } + } + + $this->removeCachedFile($path1); + if ($this->is_dir($path1)) { + return $this->copy($path1, $path2) and $this->rmdir($path1); } else { - return false; + return $this->copy($path1, $path2) and $this->unlink($path1); } } public function copy($path1, $path2) { - $source = $this->fopen($path1, 'r'); - $target = $this->fopen($path2, 'w'); - list($count, $result) = \OC_Helper::streamCopy($source, $target); - $this->removeCachedFile($path2); - return $result; + if ($this->is_dir($path1)) { + if ($this->file_exists($path2)) { + if ($this->is_dir($path2)) { + $this->rmdir($path2); + } else if ($this->is_file($path2)) { + $this->unlink($path2); + } + } + $dir = $this->opendir($path1); + $this->mkdir($path2); + while ($file = readdir($dir)) { + if (($file != '.') && ($file != '..')) { + if (!$this->copy($path1 . '/' . $file, $path2 . '/' . $file)) { + return false; + } + } + } + closedir($dir); + return true; + } else { + $source = $this->fopen($path1, 'r'); + $target = $this->fopen($path2, 'w'); + list(, $result) = \OC_Helper::streamCopy($source, $target); + $this->removeCachedFile($path2); + return $result; + } } public function getMimeType($path) { -- cgit v1.2.3 From d15ed9b4d39c290a9643be69ad9fbb9478570321 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Mon, 1 Jul 2013 19:12:48 +0200 Subject: use \OC\Files\Filesystem::isIgnoredDir --- lib/private/files/storage/common.php | 2 +- lib/private/files/storage/local.php | 2 +- lib/private/files/storage/mappedlocal.php | 144 +++++++++++++++++------------- 3 files changed, 86 insertions(+), 62 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/common.php b/lib/private/files/storage/common.php index 5fae43d8bf7..ed51bbf6470 100644 --- a/lib/private/files/storage/common.php +++ b/lib/private/files/storage/common.php @@ -165,7 +165,7 @@ abstract class Common implements \OC\Files\Storage\Storage { $dir = $this->opendir($path1); $this->mkdir($path2); while ($file = readdir($dir)) { - if (($file != '.') && ($file != '..')) { + if (!\OC\Files\Filesystem::isIgnoredDir($file)) { if (!$this->copy($path1 . '/' . $file, $path2 . '/' . $file)) { return false; } diff --git a/lib/private/files/storage/local.php b/lib/private/files/storage/local.php index dc6e7a12c65..bbb4ae77e4f 100644 --- a/lib/private/files/storage/local.php +++ b/lib/private/files/storage/local.php @@ -196,7 +196,7 @@ if (\OC_Util::runningOnWindows()) { $dir = $this->opendir($path1); $this->mkdir($path2); while ($file = readdir($dir)) { - if (($file != '.') && ($file != '..')) { + if (!\OC\Files\Filesystem::isIgnoredDir($file)) { if (!$this->copy($path1 . '/' . $file, $path2 . '/' . $file)) { return false; } diff --git a/lib/private/files/storage/mappedlocal.php b/lib/private/files/storage/mappedlocal.php index 9d3fa01d883..3ebdcf9538f 100644 --- a/lib/private/files/storage/mappedlocal.php +++ b/lib/private/files/storage/mappedlocal.php @@ -10,29 +10,33 @@ namespace OC\Files\Storage; /** * for local filestore, we only have to map the paths */ -class MappedLocal extends \OC\Files\Storage\Common{ +class MappedLocal extends \OC\Files\Storage\Common { protected $datadir; private $mapper; public function __construct($arguments) { - $this->datadir=$arguments['datadir']; - if(substr($this->datadir, -1)!=='/') { - $this->datadir.='/'; + $this->datadir = $arguments['datadir']; + if (substr($this->datadir, -1) !== '/') { + $this->datadir .= '/'; } - $this->mapper= new \OC\Files\Mapper($this->datadir); + $this->mapper = new \OC\Files\Mapper($this->datadir); } + public function __destruct() { if (defined('PHPUNIT_RUN')) { $this->mapper->removePath($this->datadir, true, true); } } - public function getId(){ - return 'local::'.$this->datadir; + + public function getId() { + return 'local::' . $this->datadir; } + public function mkdir($path) { return @mkdir($this->buildPath($path), 0777, true); } + public function rmdir($path) { try { $it = new \RecursiveIteratorIterator( @@ -68,9 +72,10 @@ class MappedLocal extends \OC\Files\Storage\Common{ return false; } } + public function opendir($path) { $files = array('.', '..'); - $physicalPath= $this->buildPath($path); + $physicalPath = $this->buildPath($path); $logicalPath = $this->mapper->physicalToLogic($physicalPath); $dh = opendir($physicalPath); @@ -80,7 +85,7 @@ class MappedLocal extends \OC\Files\Storage\Common{ continue; } - $logicalFilePath = $this->mapper->physicalToLogic($physicalPath.'/'.$file); + $logicalFilePath = $this->mapper->physicalToLogic($physicalPath . '/' . $file); $file= $this->mapper->stripRootFolder($logicalFilePath, $logicalPath); $file = $this->stripLeading($file); @@ -88,18 +93,21 @@ class MappedLocal extends \OC\Files\Storage\Common{ } } - \OC\Files\Stream\Dir::register('local-win32'.$path, $files); - return opendir('fakedir://local-win32'.$path); + \OC\Files\Stream\Dir::register('local-win32' . $path, $files); + return opendir('fakedir://local-win32' . $path); } + public function is_dir($path) { - if(substr($path, -1)=='/') { - $path=substr($path, 0, -1); + if (substr($path, -1) == '/') { + $path = substr($path, 0, -1); } return is_dir($this->buildPath($path)); } + public function is_file($path) { return is_file($this->buildPath($path)); } + public function stat($path) { $fullPath = $this->buildPath($path); $statResult = stat($fullPath); @@ -111,17 +119,19 @@ class MappedLocal extends \OC\Files\Storage\Common{ } return $statResult; } + public function filetype($path) { - $filetype=filetype($this->buildPath($path)); - if($filetype=='link') { - $filetype=filetype(realpath($this->buildPath($path))); + $filetype = filetype($this->buildPath($path)); + if ($filetype == 'link') { + $filetype = filetype(realpath($this->buildPath($path))); } return $filetype; } + public function filesize($path) { - if($this->is_dir($path)) { + if ($this->is_dir($path)) { return 0; - }else{ + } else { $fullPath = $this->buildPath($path); $fileSize = filesize($fullPath); if ($fileSize < 0) { @@ -131,49 +141,58 @@ class MappedLocal extends \OC\Files\Storage\Common{ return $fileSize; } } + public function isReadable($path) { return is_readable($this->buildPath($path)); } + public function isUpdatable($path) { return is_writable($this->buildPath($path)); } + public function file_exists($path) { return file_exists($this->buildPath($path)); } + public function filemtime($path) { return filemtime($this->buildPath($path)); } - public function touch($path, $mtime=null) { + + public function touch($path, $mtime = null) { // sets the modification time of the file to the given value. // If mtime is nil the current time is set. // note that the access time of the file always changes to the current time. - if(!is_null($mtime)) { - $result=touch( $this->buildPath($path), $mtime ); - }else{ - $result=touch( $this->buildPath($path)); + if (!is_null($mtime)) { + $result = touch($this->buildPath($path), $mtime); + } else { + $result = touch($this->buildPath($path)); } - if( $result ) { - clearstatcache( true, $this->buildPath($path) ); + if ($result) { + clearstatcache(true, $this->buildPath($path)); } return $result; } + public function file_get_contents($path) { return file_get_contents($this->buildPath($path)); } + public function file_put_contents($path, $data) { return file_put_contents($this->buildPath($path), $data); } + public function unlink($path) { return $this->delTree($path); } + public function rename($path1, $path2) { if (!$this->isUpdatable($path1)) { - \OC_Log::write('core', 'unable to rename, file is not writable : '.$path1, \OC_Log::ERROR); + \OC_Log::write('core', 'unable to rename, file is not writable : ' . $path1, \OC_Log::ERROR); return false; } - if(! $this->file_exists($path1)) { - \OC_Log::write('core', 'unable to rename, file does not exists : '.$path1, \OC_Log::ERROR); + if (!$this->file_exists($path1)) { + \OC_Log::write('core', 'unable to rename, file does not exists : ' . $path1, \OC_Log::ERROR); return false; } @@ -185,13 +204,14 @@ class MappedLocal extends \OC\Files\Storage\Common{ $physicPath1 = $this->buildPath($path1); $physicPath2 = $this->buildPath($path2); - if($return=rename($physicPath1, $physicPath2)) { + if ($return = rename($physicPath1, $physicPath2)) { // mapper needs to create copies or all children $this->copyMapping($path1, $path2); $this->cleanMapper($physicPath1, false, true); } return $return; } + public function copy($path1, $path2) { if ($this->is_dir($path1)) { if ($this->is_dir($path2)) { @@ -202,7 +222,7 @@ class MappedLocal extends \OC\Files\Storage\Common{ $dir = $this->opendir($path1); $this->mkdir($path2); while ($file = readdir($dir)) { - if (($file != '.') && ($file != '..')) { + if (!\OC\Files\Filesystem::isIgnoredDir($file)) { if (!$this->copy($path1 . '/' . $file, $path2 . '/' . $file)) { return false; } @@ -217,9 +237,10 @@ class MappedLocal extends \OC\Files\Storage\Common{ return $return; } } + public function fopen($path, $mode) { - if($return=fopen($this->buildPath($path), $mode)) { - switch($mode) { + if ($return = fopen($this->buildPath($path), $mode)) { + switch ($mode) { case 'r': break; case 'r+': @@ -240,15 +261,15 @@ class MappedLocal extends \OC\Files\Storage\Common{ * @param string $dir */ private function delTree($dir, $isLogicPath=true) { - $dirRelative=$dir; + $dirRelative = $dir; if ($isLogicPath) { - $dir=$this->buildPath($dir); + $dir = $this->buildPath($dir); } if (!file_exists($dir)) { return true; } if (!is_dir($dir) || is_link($dir)) { - if($return=unlink($dir)) { + if ($return = unlink($dir)) { $this->cleanMapper($dir, false); return $return; } @@ -257,17 +278,17 @@ class MappedLocal extends \OC\Files\Storage\Common{ if ($item == '.' || $item == '..') { continue; } - if(is_file($dir.'/'.$item)) { - if(unlink($dir.'/'.$item)) { - $this->cleanMapper($dir.'/'.$item, false); + if (is_file($dir . '/' . $item)) { + if (unlink($dir . '/' . $item)) { + $this->cleanMapper($dir . '/' . $item, false); } - }elseif(is_dir($dir.'/'.$item)) { - if (!$this->delTree($dir. "/" . $item, false)) { + } elseif (is_dir($dir . '/' . $item)) { + if (!$this->delTree($dir . "/" . $item, false)) { return false; }; } } - if($return=rmdir($dir)) { + if ($return = rmdir($dir)) { $this->cleanMapper($dir, false); } return $return; @@ -295,14 +316,14 @@ class MappedLocal extends \OC\Files\Storage\Common{ } } else { \OC_Log::write('core', - 'Unable to determine file size of "'.$fullPath.'". Unknown OS: '.$name, + 'Unable to determine file size of "' . $fullPath . '". Unknown OS: ' . $name, \OC_Log::ERROR); } return 0; } - public function hash($type, $path, $raw=false) { + public function hash($type, $path, $raw = false) { return hash_file($type, $this->buildPath($path), $raw); } @@ -313,9 +334,11 @@ class MappedLocal extends \OC\Files\Storage\Common{ public function search($query) { return $this->searchInDir($query); } + public function getLocalFile($path) { return $this->buildPath($path); } + public function getLocalFolder($path) { return $this->buildPath($path); } @@ -323,20 +346,20 @@ class MappedLocal extends \OC\Files\Storage\Common{ /** * @param string $query */ - protected function searchInDir($query, $dir='') { - $files=array(); + protected function searchInDir($query, $dir = '') { + $files = array(); $physicalDir = $this->buildPath($dir); foreach (scandir($physicalDir) as $item) { if ($item == '.' || $item == '..') continue; - $physicalItem = $this->mapper->physicalToLogic($physicalDir.'/'.$item); - $item = substr($physicalItem, strlen($physicalDir)+1); + $physicalItem = $this->mapper->physicalToLogic($physicalDir . '/' . $item); + $item = substr($physicalItem, strlen($physicalDir) + 1); - if(strstr(strtolower($item), strtolower($query)) !== false) { - $files[]=$dir.'/'.$item; + if (strstr(strtolower($item), strtolower($query)) !== false) { + $files[] = $dir . '/' . $item; } - if(is_dir($physicalItem)) { - $files=array_merge($files, $this->searchInDir($query, $dir.'/'.$item)); + if (is_dir($physicalItem)) { + $files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item)); } } return $files; @@ -344,30 +367,31 @@ class MappedLocal extends \OC\Files\Storage\Common{ /** * check if a file or folder has been updated since $time + * * @param string $path * @param int $time * @return bool */ public function hasUpdated($path, $time) { - return $this->filemtime($path)>$time; + return $this->filemtime($path) > $time; } /** * @param string $path */ - private function buildPath($path, $create=true) { + private function buildPath($path, $create = true) { $path = $this->stripLeading($path); - $fullPath = $this->datadir.$path; + $fullPath = $this->datadir . $path; return $this->mapper->logicToPhysical($fullPath, $create); } /** * @param string $path */ - private function cleanMapper($path, $isLogicPath=true, $recursive=true) { + private function cleanMapper($path, $isLogicPath = true, $recursive=true) { $fullPath = $path; if ($isLogicPath) { - $fullPath = $this->datadir.$path; + $fullPath = $this->datadir . $path; } $this->mapper->removePath($fullPath, $isLogicPath, $recursive); } @@ -380,8 +404,8 @@ class MappedLocal extends \OC\Files\Storage\Common{ $path1 = $this->stripLeading($path1); $path2 = $this->stripLeading($path2); - $fullPath1 = $this->datadir.$path1; - $fullPath2 = $this->datadir.$path2; + $fullPath1 = $this->datadir . $path1; + $fullPath2 = $this->datadir . $path2; $this->mapper->copy($fullPath1, $fullPath2); } @@ -390,10 +414,10 @@ class MappedLocal extends \OC\Files\Storage\Common{ * @param string $path */ private function stripLeading($path) { - if(strpos($path, '/') === 0) { + if (strpos($path, '/') === 0) { $path = substr($path, 1); } - if(strpos($path, '\\') === 0) { + if (strpos($path, '\\') === 0) { $path = substr($path, 1); } if ($path === false) { -- cgit v1.2.3 From 488fc402e4c144692a1a4c84d5cfacaae9bea2b8 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Thu, 4 Jul 2013 21:17:52 +0200 Subject: remove unneeded check --- lib/private/files/storage/common.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/common.php b/lib/private/files/storage/common.php index ed51bbf6470..8ebc0bcddb5 100644 --- a/lib/private/files/storage/common.php +++ b/lib/private/files/storage/common.php @@ -140,7 +140,7 @@ abstract class Common implements \OC\Files\Storage\Storage { if ($this->file_exists($path2)) { if ($this->is_dir($path2)) { $this->rmdir($path2); - } else if ($this->is_file($path2)) { + } else { $this->unlink($path2); } } @@ -158,7 +158,7 @@ abstract class Common implements \OC\Files\Storage\Storage { if ($this->file_exists($path2)) { if ($this->is_dir($path2)) { $this->rmdir($path2); - } else if ($this->is_file($path2)) { + } else { $this->unlink($path2); } } -- cgit v1.2.3 From 8187164fe1c125c478f1c9f64700626d329aa0d1 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Wed, 10 Jul 2013 21:39:58 +0200 Subject: re-use rescursive copy from common storage --- lib/private/files/storage/local.php | 17 +---------------- 1 file changed, 1 insertion(+), 16 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/local.php b/lib/private/files/storage/local.php index bbb4ae77e4f..43ffeaf80c7 100644 --- a/lib/private/files/storage/local.php +++ b/lib/private/files/storage/local.php @@ -188,22 +188,7 @@ if (\OC_Util::runningOnWindows()) { public function copy($path1, $path2) { if ($this->is_dir($path1)) { - if ($this->is_dir($path2)) { - $this->rmdir($path2); - } else if ($this->is_file($path2)) { - $this->unlink($path2); - } - $dir = $this->opendir($path1); - $this->mkdir($path2); - while ($file = readdir($dir)) { - if (!\OC\Files\Filesystem::isIgnoredDir($file)) { - if (!$this->copy($path1 . '/' . $file, $path2 . '/' . $file)) { - return false; - } - } - } - closedir($dir); - return true; + return parent::copy($path1, $path2); } else { return copy($this->datadir . $path1, $this->datadir . $path2); } -- cgit v1.2.3 From af35b6ad9db6490f5bfd25143d214f5b1d8dfd34 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Tue, 6 May 2014 15:54:48 +0200 Subject: Fix LocalStorage->unlink to work on folder as expected --- lib/private/files/storage/local.php | 9 ++++++++- lib/private/files/view.php | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/local.php b/lib/private/files/storage/local.php index 43ffeaf80c7..943c4163088 100644 --- a/lib/private/files/storage/local.php +++ b/lib/private/files/storage/local.php @@ -164,7 +164,14 @@ if (\OC_Util::runningOnWindows()) { } public function unlink($path) { - return unlink($this->datadir . $path); + if ($this->is_dir($path)) { + return $this->rmdir($path); + } else if ($this->is_file($path)) { + return unlink($this->datadir . $path); + } else { + return false; + } + } public function rename($path1, $path2) { diff --git a/lib/private/files/view.php b/lib/private/files/view.php index 940f31fe420..0743d5c6d93 100644 --- a/lib/private/files/view.php +++ b/lib/private/files/view.php @@ -432,7 +432,7 @@ class View { if ($this->is_dir($path1)) { $result = $this->copy($path1, $path2); if ($result === true) { - $result = $storage1->unlink($internalPath1); + $result = $storage1->rmdir($internalPath1); } } else { $source = $this->fopen($path1 . $postFix1, 'r'); -- cgit v1.2.3 From 467e9c2bb0dadb58e6cdb03830318b725123c7aa Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Fri, 23 May 2014 12:46:12 +0200 Subject: Remove code duplication --- lib/private/files/storage/common.php | 41 ++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 20 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/common.php b/lib/private/files/storage/common.php index 8ebc0bcddb5..1ed0d79817b 100644 --- a/lib/private/files/storage/common.php +++ b/lib/private/files/storage/common.php @@ -7,6 +7,7 @@ */ namespace OC\Files\Storage; +use OC\Files\Filesystem; use OC\Files\Cache\Watcher; /** @@ -36,6 +37,22 @@ abstract class Common implements \OC\Files\Storage\Storage { public function __construct($parameters) { } + /** + * Remove a file of folder + * + * @param string $path + * @return bool + */ + protected function remove($path) { + if ($this->is_dir($path)) { + return $this->rmdir($path); + } else if($this->is_file($path)) { + return $this->unlink($path); + } else { + return false; + } + } + public function is_dir($path) { return $this->filetype($path) == 'dir'; } @@ -137,35 +154,19 @@ abstract class Common implements \OC\Files\Storage\Storage { } public function rename($path1, $path2) { - if ($this->file_exists($path2)) { - if ($this->is_dir($path2)) { - $this->rmdir($path2); - } else { - $this->unlink($path2); - } - } + $this->remove($path2); $this->removeCachedFile($path1); - if ($this->is_dir($path1)) { - return $this->copy($path1, $path2) and $this->rmdir($path1); - } else { - return $this->copy($path1, $path2) and $this->unlink($path1); - } + return $this->copy($path1, $path2) and $this->remove($path1); } public function copy($path1, $path2) { if ($this->is_dir($path1)) { - if ($this->file_exists($path2)) { - if ($this->is_dir($path2)) { - $this->rmdir($path2); - } else { - $this->unlink($path2); - } - } + $this->remove($path2); $dir = $this->opendir($path1); $this->mkdir($path2); while ($file = readdir($dir)) { - if (!\OC\Files\Filesystem::isIgnoredDir($file)) { + if (!Filesystem::isIgnoredDir($file)) { if (!$this->copy($path1 . '/' . $file, $path2 . '/' . $file)) { return false; } -- cgit v1.2.3 From f79948f519f5532f95fd744b8ba28329cc45b022 Mon Sep 17 00:00:00 2001 From: ringmaster Date: Wed, 28 May 2014 13:20:20 -0400 Subject: Prevent apps from affecting the scanner via hook. --- lib/private/files/cache/scanner.php | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/cache/scanner.php b/lib/private/files/cache/scanner.php index e838a8b6258..d4942d7dc2e 100644 --- a/lib/private/files/cache/scanner.php +++ b/lib/private/files/cache/scanner.php @@ -138,9 +138,12 @@ class Scanner extends BasicEmitter { $parent = ''; } $parentCacheData = $this->cache->get($parent); - $this->cache->update($parentCacheData['fileid'], array( - 'etag' => $this->storage->getETag($parent), - )); + \OC_Hook::emit('Scanner', 'updateCache', array('file' => $file, 'data' => $data)); + if(Config::getSystemValue('filesystem_check_enable', true)) { + $this->cache->update($parentCacheData['fileid'], array( + 'etag' => $this->storage->getETag($parent), + )); + } } } } @@ -157,18 +160,16 @@ class Scanner extends BasicEmitter { } } if (!empty($newData)) { - $addToCache = Config::getSystemValue('filesystem_check_enable', true); - \OC_Hook::emit('Scanner', 'addToCache', array('file' => $file, 'addToCache' => &$addToCache, 'data' => &$newData)); - if($addToCache) { + \OC_Hook::emit('Scanner', 'addToCache', array('file' => $file, 'data' => $newData)); + if(Config::getSystemValue('filesystem_check_enable', true)) { $data['fileid'] = $this->cache->put($file, $newData); } $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId)); \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId)); } } else { - $removeFromCache = Config::getSystemValue('filesystem_check_enable', true); - \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $file, 'removeFromCache' => &$removeFromCache)); - if($removeFromCache) { + \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $file)); + if(Config::getSystemValue('filesystem_check_enable', true)) { $this->cache->remove($file); } } @@ -253,9 +254,8 @@ class Scanner extends BasicEmitter { $removedChildren = \array_diff($existingChildren, $newChildren); foreach ($removedChildren as $childName) { $child = ($path) ? $path . '/' . $childName : $childName; - $removeFromCache = Config::getSystemValue('filesystem_check_enable', true); - \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $child, 'removeFromCache' => &$removeFromCache)); - if($removeFromCache) { + \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $child)); + if(Config::getSystemValue('filesystem_check_enable', true)) { $this->cache->remove($child); } } @@ -277,9 +277,8 @@ class Scanner extends BasicEmitter { } } $newData = array('size' => $size); - $addToCache = Config::getSystemValue('filesystem_check_enable', true); - \OC_Hook::emit('Scanner', 'addToCache', array('file' => $child, 'addToCache' => &$addToCache, 'data' => &$newData)); - if($addToCache) { + \OC_Hook::emit('Scanner', 'addToCache', array('file' => $child, 'data' => $newData)); + if(Config::getSystemValue('filesystem_check_enable', true)) { $this->cache->put($path, $newData); } } @@ -308,7 +307,10 @@ class Scanner extends BasicEmitter { $lastPath = null; while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) { $this->scan($path, self::SCAN_RECURSIVE, self::REUSE_ETAG); - $this->cache->correctFolderSize($path); + \OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path)); + if(Config::getSystemValue('filesystem_check_enable', true)) { + $this->cache->correctFolderSize($path); + } $lastPath = $path; } } -- cgit v1.2.3 From 8c5521fdfc2e9e85037c61cd77a254e3b7cd1b94 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Thu, 29 May 2014 13:45:50 +0200 Subject: Add $storage->instanceOfStorage to handle instanceof for storage wrappers --- lib/private/files/storage/common.php | 14 ++++++++++++-- lib/private/files/storage/wrapper/wrapper.php | 10 ++++++++++ lib/public/files/storage.php | 8 ++++++++ tests/lib/files/storage/storage.php | 6 ++++++ tests/lib/files/storage/wrapper/quota.php | 6 ++++++ tests/lib/files/storage/wrapper/wrapper.php | 5 +++++ 6 files changed, 47 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/common.php b/lib/private/files/storage/common.php index 1ed0d79817b..6b11603323a 100644 --- a/lib/private/files/storage/common.php +++ b/lib/private/files/storage/common.php @@ -7,6 +7,7 @@ */ namespace OC\Files\Storage; + use OC\Files\Filesystem; use OC\Files\Cache\Watcher; @@ -21,7 +22,6 @@ use OC\Files\Cache\Watcher; * Some \OC\Files\Storage\Common methods call functions which are first defined * in classes which extend it, e.g. $this->stat() . */ - abstract class Common implements \OC\Files\Storage\Storage { protected $cache; protected $scanner; @@ -46,7 +46,7 @@ abstract class Common implements \OC\Files\Storage\Storage { protected function remove($path) { if ($this->is_dir($path)) { return $this->rmdir($path); - } else if($this->is_file($path)) { + } else if ($this->is_file($path)) { return $this->unlink($path); } else { return false; @@ -412,4 +412,14 @@ abstract class Common implements \OC\Files\Storage\Storage { protected function removeCachedFile($path) { unset($this->cachedFiles[$path]); } + + /** + * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class + * + * @param string $class + * @return bool + */ + public function instanceOfStorage($class) { + return is_a($this, $class); + } } diff --git a/lib/private/files/storage/wrapper/wrapper.php b/lib/private/files/storage/wrapper/wrapper.php index 11ea9f71da7..dd2f76e05b8 100644 --- a/lib/private/files/storage/wrapper/wrapper.php +++ b/lib/private/files/storage/wrapper/wrapper.php @@ -440,4 +440,14 @@ class Wrapper implements \OC\Files\Storage\Storage { public function isLocal() { return $this->storage->isLocal(); } + + /** + * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class + * + * @param string $class + * @return bool + */ + public function instanceOfStorage($class) { + return is_a($this, $class) or $this->storage->instanceOfStorage($class); + } } diff --git a/lib/public/files/storage.php b/lib/public/files/storage.php index 5ec8ac6245c..323d20db564 100644 --- a/lib/public/files/storage.php +++ b/lib/public/files/storage.php @@ -327,4 +327,12 @@ interface Storage { * @return bool true if the files are stored locally, false otherwise */ public function isLocal(); + + /** + * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class + * + * @param string $class + * @return bool + */ + public function instanceOfStorage($class); } diff --git a/tests/lib/files/storage/storage.php b/tests/lib/files/storage/storage.php index 24390f05367..dd73491d7ee 100644 --- a/tests/lib/files/storage/storage.php +++ b/tests/lib/files/storage/storage.php @@ -464,4 +464,10 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); } + + public function testInstanceOfStorage() { + $this->assertTrue($this->instance->instanceOfStorage('\OCP\Files\Storage')); + $this->assertTrue($this->instance->instanceOfStorage(get_class($this->instance))); + $this->assertFalse($this->instance->instanceOfStorage('\OC')); + } } diff --git a/tests/lib/files/storage/wrapper/quota.php b/tests/lib/files/storage/wrapper/quota.php index 777529fd85e..954fe199cc8 100644 --- a/tests/lib/files/storage/wrapper/quota.php +++ b/tests/lib/files/storage/wrapper/quota.php @@ -155,4 +155,10 @@ class Quota extends \Test\Files\Storage\Storage { $this->assertEquals(1024 - 50, $instance->free_space('')); } + + public function testInstanceOfStorageWrapper() { + $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Local')); + $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Wrapper\Wrapper')); + $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')); + } } diff --git a/tests/lib/files/storage/wrapper/wrapper.php b/tests/lib/files/storage/wrapper/wrapper.php index e31abfc7324..8bcf42035d4 100644 --- a/tests/lib/files/storage/wrapper/wrapper.php +++ b/tests/lib/files/storage/wrapper/wrapper.php @@ -23,4 +23,9 @@ class Wrapper extends \Test\Files\Storage\Storage { public function tearDown() { \OC_Helper::rmdirr($this->tmpDir); } + + public function testInstanceOfStorageWrapper() { + $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Local')); + $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Wrapper\Wrapper')); + } } -- cgit v1.2.3 From 99d46af0b42dcf4ae221aebc862085615fc70af1 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Thu, 29 May 2014 13:52:58 +0200 Subject: Use instanceOfStorage instead of instanceof --- apps/files_sharing/lib/proxy.php | 2 +- apps/files_sharing/lib/sharedstorage.php | 2 +- lib/private/util.php | 5 ++++- 3 files changed, 6 insertions(+), 3 deletions(-) (limited to 'lib/private') diff --git a/apps/files_sharing/lib/proxy.php b/apps/files_sharing/lib/proxy.php index c899a4b4dd3..f595328cc63 100644 --- a/apps/files_sharing/lib/proxy.php +++ b/apps/files_sharing/lib/proxy.php @@ -57,7 +57,7 @@ class Proxy extends \OC_FileProxy { $mountManager = \OC\Files\Filesystem::getMountManager(); $mountedShares = $mountManager->findIn($path); foreach ($mountedShares as $mount) { - if ($mount->getStorage() instanceof \OC\Files\Storage\Shared) { + if ($mount->getStorage()->instanceOfStorage('\OC\Files\Storage\Shared')) { $mountPoint = $mount->getMountPoint(); $mountPointName = $mount->getMountPointName(); $target = \OCA\Files_Sharing\Helper::generateUniqueTarget(dirname($path) . '/' . $mountPointName, array(), $view); diff --git a/apps/files_sharing/lib/sharedstorage.php b/apps/files_sharing/lib/sharedstorage.php index 67ccbd13403..a7dd2b3afa1 100644 --- a/apps/files_sharing/lib/sharedstorage.php +++ b/apps/files_sharing/lib/sharedstorage.php @@ -300,7 +300,7 @@ class Shared extends \OC\Files\Storage\Common { // it shouldn't be possible to move a Shared storage into another one list($targetStorage, ) = \OC\Files\Filesystem::resolvePath($targetPath); - if ($targetStorage instanceof \OC\Files\Storage\Shared) { + if ($targetStorage->instanceOfStorage('\OC\Files\Storage\Shared')) { \OCP\Util::writeLog('file sharing', 'It is not allowed to move one mount point into another one', \OCP\Util::DEBUG); diff --git a/lib/private/util.php b/lib/private/util.php index 23c7053002c..bf7f39ebb20 100755 --- a/lib/private/util.php +++ b/lib/private/util.php @@ -57,7 +57,10 @@ class OC_Util { // set up quota for home storages, even for other users // which can happen when using sharing - if ($storage instanceof \OC\Files\Storage\Home) { + /** + * @var \OC\Files\Storage\Storage $storage + */ + if ($storage->instanceOfStorage('\OC\Files\Storage\Home')) { $user = $storage->getUser()->getUID(); $quota = OC_Util::getUserQuota($user); if ($quota !== \OC\Files\SPACE_UNLIMITED) { -- cgit v1.2.3 From 0ae7a49c8e025a35189f62d125e1b4a8f5930c27 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Thu, 29 May 2014 14:15:48 +0200 Subject: Fix storage wrapper being called with null --- lib/private/files/mount/mount.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/files/mount/mount.php b/lib/private/files/mount/mount.php index d4a4e186fb9..7c40853ac95 100644 --- a/lib/private/files/mount/mount.php +++ b/lib/private/files/mount/mount.php @@ -161,6 +161,6 @@ class Mount { * @param callable $wrapper */ public function wrapStorage($wrapper) { - $this->storage = $wrapper($this->mountPoint, $this->storage); + $this->storage = $wrapper($this->mountPoint, $this->getStorage()); } } -- cgit v1.2.3 From 998fa2d9be4a876cec00073b0706a793276ddd8f Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Thu, 29 May 2014 16:13:05 +0200 Subject: Pass any methods custom to specific storage implementations to the wrapped storage --- lib/private/files/storage/wrapper/wrapper.php | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'lib/private') diff --git a/lib/private/files/storage/wrapper/wrapper.php b/lib/private/files/storage/wrapper/wrapper.php index dd2f76e05b8..364475a68e0 100644 --- a/lib/private/files/storage/wrapper/wrapper.php +++ b/lib/private/files/storage/wrapper/wrapper.php @@ -450,4 +450,15 @@ class Wrapper implements \OC\Files\Storage\Storage { public function instanceOfStorage($class) { return is_a($this, $class) or $this->storage->instanceOfStorage($class); } + + /** + * Pass any methods custom to specific storage implementations to the wrapped storage + * + * @param string $method + * @param array $args + * @return mixed + */ + public function __call($method, $args) { + return call_user_func_array(array($this->storage, $method), $args); + } } -- cgit v1.2.3 From 6195f13bda086b242cbcdbff86260a81bf6163c9 Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Wed, 16 Oct 2013 15:37:58 +0200 Subject: Use CURL to get filesize on 32bit systems. --- lib/private/files/storage/local.php | 75 +++++++++++++++++++++++++++++++------ 1 file changed, 64 insertions(+), 11 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/local.php b/lib/private/files/storage/local.php index 943c4163088..fc2a590f6c8 100644 --- a/lib/private/files/storage/local.php +++ b/lib/private/files/storage/local.php @@ -90,10 +90,10 @@ if (\OC_Util::runningOnWindows()) { $fullPath = $this->datadir . $path; $statResult = stat($fullPath); - if ($statResult['size'] < 0) { - $size = self::getFileSizeFromOS($fullPath); - $statResult['size'] = $size; - $statResult[7] = $size; + $filesize = self::getFileSizeWithTricks($fullPath); + if (!is_null($filesize)) { + $statResult['size'] = $filesize; + $statResult[7] = $filesize; } return $statResult; } @@ -111,12 +111,13 @@ if (\OC_Util::runningOnWindows()) { return 0; } else { $fullPath = $this->datadir . $path; - $fileSize = filesize($fullPath); - if ($fileSize < 0) { - return self::getFileSizeFromOS($fullPath); + + $filesize = self::getFileSizeWithTricks($fullPath); + if (!is_null($filesize)) { + return $filesize; } - return $fileSize; + return filesize($fullPath); } } @@ -221,8 +222,60 @@ if (\OC_Util::runningOnWindows()) { } /** - * @param string $fullPath - */ + * @brief Tries to get the filesize via various workarounds if necessary. + * @param string $fullPath + * @return mixed Number of bytes as float on success and workaround necessary, null otherwise. + */ + private static function getFileSizeWithTricks($fullPath) { + if (PHP_INT_SIZE === 4) { + // filesize() and stat() are unreliable on 32bit systems + // for big files. + // In some cases they cause an E_WARNING and return false, + // in some other cases they silently wrap around at 2^32, + // i.e. e.g. report 674347008 bytes instead of 4969314304. + $filesize = self::getFileSizeFromCurl($fullPath); + if (!is_null($filesize)) { + return $filesize; + } + $filesize = self::getFileSizeFromOS($fullPath); + if (!is_null($filesize)) { + return $filesize; + } + } + + return null; + } + + /** + * @brief Tries to get the filesize via a CURL HEAD request. + * @param string $fullPath + * @return mixed Number of bytes as float on success, null otherwise. + */ + private static function getFileSizeFromCurl($fullPath) { + if (function_exists('curl_init')) { + $ch = curl_init("file://$fullPath"); + curl_setopt($ch, CURLOPT_NOBODY, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_HEADER, true); + $data = curl_exec($ch); + curl_close($ch); + if ($data !== false) { + $matches = array(); + preg_match('/Content-Length: (\d+)/', $data, $matches); + if (isset($matches[1])) { + return (float) $matches[1]; + } + } + } + + return null; + } + + /** + * @brief Tries to get the filesize via COM and exec(). + * @param string $fullPath + * @return mixed Number of bytes as float on success, null otherwise. + */ private static function getFileSizeFromOS($fullPath) { $name = strtolower(php_uname('s')); // Windows OS: we use COM to access the filesystem @@ -246,7 +299,7 @@ if (\OC_Util::runningOnWindows()) { \OC_Log::ERROR); } - return 0; + return null; } public function hash($type, $path, $raw = false) { -- cgit v1.2.3 From 3f8f8027d25ab39283d0ab13afcf7252dde8f240 Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Tue, 7 Jan 2014 13:50:57 +0100 Subject: Cast to numeric instead of float, i.e. use an integer if possible. --- lib/private/files/storage/local.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/local.php b/lib/private/files/storage/local.php index fc2a590f6c8..7fa748a7fd7 100644 --- a/lib/private/files/storage/local.php +++ b/lib/private/files/storage/local.php @@ -224,7 +224,7 @@ if (\OC_Util::runningOnWindows()) { /** * @brief Tries to get the filesize via various workarounds if necessary. * @param string $fullPath - * @return mixed Number of bytes as float on success and workaround necessary, null otherwise. + * @return mixed Number of bytes on success and workaround necessary, null otherwise. */ private static function getFileSizeWithTricks($fullPath) { if (PHP_INT_SIZE === 4) { @@ -249,7 +249,7 @@ if (\OC_Util::runningOnWindows()) { /** * @brief Tries to get the filesize via a CURL HEAD request. * @param string $fullPath - * @return mixed Number of bytes as float on success, null otherwise. + * @return mixed Number of bytes on success, null otherwise. */ private static function getFileSizeFromCurl($fullPath) { if (function_exists('curl_init')) { @@ -263,7 +263,7 @@ if (\OC_Util::runningOnWindows()) { $matches = array(); preg_match('/Content-Length: (\d+)/', $data, $matches); if (isset($matches[1])) { - return (float) $matches[1]; + return 0 + $matches[1]; } } } @@ -274,7 +274,7 @@ if (\OC_Util::runningOnWindows()) { /** * @brief Tries to get the filesize via COM and exec(). * @param string $fullPath - * @return mixed Number of bytes as float on success, null otherwise. + * @return mixed Number of bytes on success, null otherwise. */ private static function getFileSizeFromOS($fullPath) { $name = strtolower(php_uname('s')); @@ -287,11 +287,11 @@ if (\OC_Util::runningOnWindows()) { } } else if (strpos($name, 'bsd') !== false) { if (\OC_Helper::is_function_enabled('exec')) { - return (float)exec('stat -f %z ' . escapeshellarg($fullPath)); + return 0 + exec('stat -f %z ' . escapeshellarg($fullPath)); } } else if (strpos($name, 'linux') !== false) { if (\OC_Helper::is_function_enabled('exec')) { - return (float)exec('stat -c %s ' . escapeshellarg($fullPath)); + return 0 + exec('stat -c %s ' . escapeshellarg($fullPath)); } } else { \OC_Log::write('core', -- cgit v1.2.3 From c8fa1fd68784c48c1df537310f16d6753f79b029 Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Sun, 9 Feb 2014 01:25:33 +0100 Subject: Refactor Large File handling code. --- lib/private/files/storage/local.php | 98 +++------------------------- lib/private/files/storage/mappedlocal.php | 53 ++++----------- lib/private/largefilehelper.php | 103 ++++++++++++++++++++++++++++++ 3 files changed, 123 insertions(+), 131 deletions(-) create mode 100644 lib/private/largefilehelper.php (limited to 'lib/private') diff --git a/lib/private/files/storage/local.php b/lib/private/files/storage/local.php index 7fa748a7fd7..883a69d7681 100644 --- a/lib/private/files/storage/local.php +++ b/lib/private/files/storage/local.php @@ -89,9 +89,8 @@ if (\OC_Util::runningOnWindows()) { public function stat($path) { $fullPath = $this->datadir . $path; $statResult = stat($fullPath); - - $filesize = self::getFileSizeWithTricks($fullPath); - if (!is_null($filesize)) { + if (PHP_INT_SIZE === 4) { + $filesize = $this->filesize($path); $statResult['size'] = $filesize; $statResult[7] = $filesize; } @@ -109,16 +108,16 @@ if (\OC_Util::runningOnWindows()) { public function filesize($path) { if ($this->is_dir($path)) { return 0; - } else { - $fullPath = $this->datadir . $path; - - $filesize = self::getFileSizeWithTricks($fullPath); + } + $fullPath = $this->datadir . $path; + if (PHP_INT_SIZE === 4) { + $helper = new \OC\LargeFileHelper; + $filesize = $helper->getFilesize($fullPath); if (!is_null($filesize)) { return $filesize; } - - return filesize($fullPath); } + return filesize($fullPath); } public function isReadable($path) { @@ -221,87 +220,6 @@ if (\OC_Util::runningOnWindows()) { return $return; } - /** - * @brief Tries to get the filesize via various workarounds if necessary. - * @param string $fullPath - * @return mixed Number of bytes on success and workaround necessary, null otherwise. - */ - private static function getFileSizeWithTricks($fullPath) { - if (PHP_INT_SIZE === 4) { - // filesize() and stat() are unreliable on 32bit systems - // for big files. - // In some cases they cause an E_WARNING and return false, - // in some other cases they silently wrap around at 2^32, - // i.e. e.g. report 674347008 bytes instead of 4969314304. - $filesize = self::getFileSizeFromCurl($fullPath); - if (!is_null($filesize)) { - return $filesize; - } - $filesize = self::getFileSizeFromOS($fullPath); - if (!is_null($filesize)) { - return $filesize; - } - } - - return null; - } - - /** - * @brief Tries to get the filesize via a CURL HEAD request. - * @param string $fullPath - * @return mixed Number of bytes on success, null otherwise. - */ - private static function getFileSizeFromCurl($fullPath) { - if (function_exists('curl_init')) { - $ch = curl_init("file://$fullPath"); - curl_setopt($ch, CURLOPT_NOBODY, true); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_HEADER, true); - $data = curl_exec($ch); - curl_close($ch); - if ($data !== false) { - $matches = array(); - preg_match('/Content-Length: (\d+)/', $data, $matches); - if (isset($matches[1])) { - return 0 + $matches[1]; - } - } - } - - return null; - } - - /** - * @brief Tries to get the filesize via COM and exec(). - * @param string $fullPath - * @return mixed Number of bytes on success, null otherwise. - */ - private static function getFileSizeFromOS($fullPath) { - $name = strtolower(php_uname('s')); - // Windows OS: we use COM to access the filesystem - if (strpos($name, 'win') !== false) { - if (class_exists('COM')) { - $fsobj = new \COM("Scripting.FileSystemObject"); - $f = $fsobj->GetFile($fullPath); - return $f->Size; - } - } else if (strpos($name, 'bsd') !== false) { - if (\OC_Helper::is_function_enabled('exec')) { - return 0 + exec('stat -f %z ' . escapeshellarg($fullPath)); - } - } else if (strpos($name, 'linux') !== false) { - if (\OC_Helper::is_function_enabled('exec')) { - return 0 + exec('stat -c %s ' . escapeshellarg($fullPath)); - } - } else { - \OC_Log::write('core', - 'Unable to determine file size of "' . $fullPath . '". Unknown OS: ' . $name, - \OC_Log::ERROR); - } - - return null; - } - public function hash($type, $path, $raw = false) { return hash_file($type, $this->datadir . $path, $raw); } diff --git a/lib/private/files/storage/mappedlocal.php b/lib/private/files/storage/mappedlocal.php index 3ebdcf9538f..78d2616ba9d 100644 --- a/lib/private/files/storage/mappedlocal.php +++ b/lib/private/files/storage/mappedlocal.php @@ -111,11 +111,10 @@ class MappedLocal extends \OC\Files\Storage\Common { public function stat($path) { $fullPath = $this->buildPath($path); $statResult = stat($fullPath); - - if ($statResult['size'] < 0) { - $size = self::getFileSizeFromOS($fullPath); - $statResult['size'] = $size; - $statResult[7] = $size; + if (PHP_INT_SIZE === 4) { + $filesize = $this->filesize($path); + $statResult['size'] = $filesize; + $statResult[7] = $filesize; } return $statResult; } @@ -131,15 +130,16 @@ class MappedLocal extends \OC\Files\Storage\Common { public function filesize($path) { if ($this->is_dir($path)) { return 0; - } else { - $fullPath = $this->buildPath($path); - $fileSize = filesize($fullPath); - if ($fileSize < 0) { - return self::getFileSizeFromOS($fullPath); + } + $fullPath = $this->buildPath($path); + if (PHP_INT_SIZE === 4) { + $helper = new \OC\LargeFileHelper; + $filesize = $helper->getFilesize($fullPath); + if (!is_null($filesize)) { + return $filesize; } - - return $fileSize; } + return filesize($fullPath); } public function isReadable($path) { @@ -294,35 +294,6 @@ class MappedLocal extends \OC\Files\Storage\Common { return $return; } - /** - * @param string $fullPath - */ - private static function getFileSizeFromOS($fullPath) { - $name = strtolower(php_uname('s')); - // Windows OS: we use COM to access the filesystem - if (strpos($name, 'win') !== false) { - if (class_exists('COM')) { - $fsobj = new \COM("Scripting.FileSystemObject"); - $f = $fsobj->GetFile($fullPath); - return $f->Size; - } - } else if (strpos($name, 'bsd') !== false) { - if (\OC_Helper::is_function_enabled('exec')) { - return (float)exec('stat -f %z ' . escapeshellarg($fullPath)); - } - } else if (strpos($name, 'linux') !== false) { - if (\OC_Helper::is_function_enabled('exec')) { - return (float)exec('stat -c %s ' . escapeshellarg($fullPath)); - } - } else { - \OC_Log::write('core', - 'Unable to determine file size of "' . $fullPath . '". Unknown OS: ' . $name, - \OC_Log::ERROR); - } - - return 0; - } - public function hash($type, $path, $raw = false) { return hash_file($type, $this->buildPath($path), $raw); } diff --git a/lib/private/largefilehelper.php b/lib/private/largefilehelper.php new file mode 100644 index 00000000000..ca8f7522177 --- /dev/null +++ b/lib/private/largefilehelper.php @@ -0,0 +1,103 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OC; + +/** + * Helper class for large files on 32-bit platforms. + */ +class LargeFileHelper { + /** + * @brief Tries to get the filesize of a file via various workarounds that + * even work for large files on 32-bit platforms. + * + * @param string $filename Path to the file. + * + * @return null|int|float Number of bytes as number (float or int) or + * null on failure. + */ + public function getFilesize($filename) { + $filesize = $this->getFilesizeViaCurl($filename); + if (!is_null($filesize)) { + return $filesize; + } + $filesize = $this->getFilesizeViaCOM($filename); + if (!is_null($filesize)) { + return $filesize; + } + $filesize = $this->getFilesizeViaExec($filename); + if (!is_null($filesize)) { + return $filesize; + } + return null; + } + + /** + * @brief Tries to get the filesize of a file via a CURL HEAD request. + * + * @param string $filename Path to the file. + * + * @return null|int|float Number of bytes as number (float or int) or + * null on failure. + */ + public function getFilesizeViaCurl($filename) { + if (function_exists('curl_init')) { + $ch = curl_init("file://$filename"); + curl_setopt($ch, CURLOPT_NOBODY, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_HEADER, true); + $data = curl_exec($ch); + curl_close($ch); + if ($data !== false) { + $matches = array(); + preg_match('/Content-Length: (\d+)/', $data, $matches); + if (isset($matches[1])) { + return 0 + $matches[1]; + } + } + } + return null; + } + + /** + * @brief Tries to get the filesize of a file via the Windows DOM extension. + * + * @param string $filename Path to the file. + * + * @return null|int|float Number of bytes as number (float or int) or + * null on failure. + */ + public function getFilesizeViaCOM($filename) { + if (class_exists('COM')) { + $fsobj = new \COM("Scripting.FileSystemObject"); + $file = $fsobj->GetFile($filename); + return 0 + $file->Size; + } + return null; + } + + /** + * @brief Tries to get the filesize of a file via an exec() call. + * + * @param string $filename Path to the file. + * + * @return null|int|float Number of bytes as number (float or int) or + * null on failure. + */ + public function getFilesizeViaExec($filename) { + if (\OC_Helper::is_function_enabled('exec')) { + $os = strtolower(php_uname('s')); + if (strpos($os, 'linux') !== false) { + return 0 + exec('stat -c %s ' . escapeshellarg($filename)); + } else if (strpos($os, 'bsd') !== false) { + return 0 + exec('stat -f %z ' . escapeshellarg($filename)); + } + } + return null; + } +} -- cgit v1.2.3 From 626e87aa542adaee123c7c4104411238b43b3333 Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Sun, 9 Feb 2014 15:56:26 +0100 Subject: Output validation for exec() method. --- lib/private/largefilehelper.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/largefilehelper.php b/lib/private/largefilehelper.php index ca8f7522177..751e60de539 100644 --- a/lib/private/largefilehelper.php +++ b/lib/private/largefilehelper.php @@ -92,10 +92,15 @@ class LargeFileHelper { public function getFilesizeViaExec($filename) { if (\OC_Helper::is_function_enabled('exec')) { $os = strtolower(php_uname('s')); + $result = ''; if (strpos($os, 'linux') !== false) { - return 0 + exec('stat -c %s ' . escapeshellarg($filename)); + $result = trim(exec('stat -c %s ' . escapeshellarg($filename))); } else if (strpos($os, 'bsd') !== false) { - return 0 + exec('stat -f %z ' . escapeshellarg($filename)); + $result = trim(exec('stat -f %z ' . escapeshellarg($filename))); + } + + if (ctype_digit($result)) { + return 0 + $result; } } return null; -- cgit v1.2.3 From df29eec72b2b094acca97636c6b91ab2eafc245d Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Sun, 9 Feb 2014 16:16:01 +0100 Subject: Windows exec() implementation. --- lib/private/largefilehelper.php | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) (limited to 'lib/private') diff --git a/lib/private/largefilehelper.php b/lib/private/largefilehelper.php index 751e60de539..5f5e14aca35 100644 --- a/lib/private/largefilehelper.php +++ b/lib/private/largefilehelper.php @@ -92,17 +92,26 @@ class LargeFileHelper { public function getFilesizeViaExec($filename) { if (\OC_Helper::is_function_enabled('exec')) { $os = strtolower(php_uname('s')); + $arg = escapeshellarg($filename); $result = ''; if (strpos($os, 'linux') !== false) { - $result = trim(exec('stat -c %s ' . escapeshellarg($filename))); + $result = $this->exec("stat -c %s $arg"); } else if (strpos($os, 'bsd') !== false) { - $result = trim(exec('stat -f %z ' . escapeshellarg($filename))); - } - - if (ctype_digit($result)) { - return 0 + $result; + $result = $this->exec("stat -f %z $arg"); + } else if (strpos($os, 'win') !== false) { + $result = $this->exec("for %F in ($arg) do @echo %~zF"); + if (is_null($result)) { + // PowerShell + $result = $this->exec("(Get-Item $arg).length"); + } } + return $result; } return null; } + + protected function exec($cmd) { + $result = trim(exec($cmd)); + return ctype_digit($result) ? 0 + $result : null; + } } -- cgit v1.2.3 From fb7ec2bb22055886d55a779b9c19f48daee438c5 Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Wed, 12 Feb 2014 13:58:07 +0100 Subject: Only call $this->filesize() for files. --- lib/private/files/storage/local.php | 2 +- lib/private/files/storage/mappedlocal.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/local.php b/lib/private/files/storage/local.php index 883a69d7681..f4bc5085364 100644 --- a/lib/private/files/storage/local.php +++ b/lib/private/files/storage/local.php @@ -89,7 +89,7 @@ if (\OC_Util::runningOnWindows()) { public function stat($path) { $fullPath = $this->datadir . $path; $statResult = stat($fullPath); - if (PHP_INT_SIZE === 4) { + if (PHP_INT_SIZE === 4 && !$this->is_dir($path)) { $filesize = $this->filesize($path); $statResult['size'] = $filesize; $statResult[7] = $filesize; diff --git a/lib/private/files/storage/mappedlocal.php b/lib/private/files/storage/mappedlocal.php index 78d2616ba9d..f38b48db5de 100644 --- a/lib/private/files/storage/mappedlocal.php +++ b/lib/private/files/storage/mappedlocal.php @@ -111,7 +111,7 @@ class MappedLocal extends \OC\Files\Storage\Common { public function stat($path) { $fullPath = $this->buildPath($path); $statResult = stat($fullPath); - if (PHP_INT_SIZE === 4) { + if (PHP_INT_SIZE === 4 && !$this->is_dir($path)) { $filesize = $this->filesize($path); $statResult['size'] = $filesize; $statResult[7] = $filesize; -- cgit v1.2.3 From 2c36a4b07a088bca4f20c2f6386765dfc8ad07b7 Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Sat, 15 Feb 2014 23:21:23 +0100 Subject: Add helper method for turning int|float into base-10 unsigned integer string. --- lib/private/largefilehelper.php | 24 +++++++++++++++++++++ tests/lib/largefilehelper.php | 46 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 tests/lib/largefilehelper.php (limited to 'lib/private') diff --git a/lib/private/largefilehelper.php b/lib/private/largefilehelper.php index 5f5e14aca35..66626b4a7fe 100644 --- a/lib/private/largefilehelper.php +++ b/lib/private/largefilehelper.php @@ -12,6 +12,30 @@ namespace OC; * Helper class for large files on 32-bit platforms. */ class LargeFileHelper { + /** + * @brief Formats a signed integer or float as an unsigned integer base-10 + * string. Passed strings will be checked for being base-10. + * + * @param int|float|string $number Number containing unsigned integer data + * + * @return string Unsigned integer base-10 string + */ + public function formatUnsignedInteger($number) { + if (is_float($number)) { + // Undo the effect of the php.ini setting 'precision'. + return number_format($number, 0, '', ''); + } else if (is_string($number) && ctype_digit($number)) { + return $number; + } else if (is_int($number)) { + // Interpret signed integer as unsigned integer. + return sprintf('%u', $number); + } else { + throw new \UnexpectedValueException( + 'Expected int, float or base-10 string' + ); + } + } + /** * @brief Tries to get the filesize of a file via various workarounds that * even work for large files on 32-bit platforms. diff --git a/tests/lib/largefilehelper.php b/tests/lib/largefilehelper.php new file mode 100644 index 00000000000..5db1f9c5a74 --- /dev/null +++ b/tests/lib/largefilehelper.php @@ -0,0 +1,46 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; + +class LargeFileHelper extends \PHPUnit_Framework_TestCase { + protected $helper; + + public function setUp() { + parent::setUp(); + $this->helper = new \OC\LargeFileHelper; + } + + public function testFormatUnsignedIntegerFloat() { + $this->assertSame( + '9007199254740992', + $this->helper->formatUnsignedInteger((float) 9007199254740992) + ); + } + + public function testFormatUnsignedIntegerInt() { + $this->assertSame( + PHP_INT_SIZE === 4 ? '4294967295' : '18446744073709551615', + $this->helper->formatUnsignedInteger(-1) + ); + } + + public function testFormatUnsignedIntegerString() { + $this->assertSame( + '9007199254740993', + $this->helper->formatUnsignedInteger('9007199254740993') + ); + } + + /** + * @expectedException \UnexpectedValueException + */ + public function testFormatUnsignedIntegerStringException() { + $this->helper->formatUnsignedInteger('900ABCD254740993'); + } +} -- cgit v1.2.3 From a9b28323dd1116aef8c53d8e050380895fa1bb74 Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Sat, 15 Feb 2014 23:41:58 +0100 Subject: Add LargeFileHelper::__construct() verifying that our assumptions hold. --- lib/private/largefilehelper.php | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'lib/private') diff --git a/lib/private/largefilehelper.php b/lib/private/largefilehelper.php index 66626b4a7fe..08869d7c82a 100644 --- a/lib/private/largefilehelper.php +++ b/lib/private/largefilehelper.php @@ -12,6 +12,31 @@ namespace OC; * Helper class for large files on 32-bit platforms. */ class LargeFileHelper { + /** + * pow(2, 53) as a base-10 string. + * @var string + */ + const POW_2_53 = '9007199254740992'; + + /** + * pow(2, 53) - 1 as a base-10 string. + * @var string + */ + const POW_2_53_MINUS_1 = '9007199254740991'; + + /** + * @brief Constructor. Checks whether our assumptions hold on the platform + * we are on, throws an exception if they do not hold. + */ + public function __construct() { + $pow_2_53 = floatval(self::POW_2_53_MINUS_1) + 1.0; + if ($this->formatUnsignedInteger($pow_2_53) !== self::POW_2_53) { + throw new \RunTimeException( + 'This class assumes floats to be double precision or "better".' + ); + } + } + /** * @brief Formats a signed integer or float as an unsigned integer base-10 * string. Passed strings will be checked for being base-10. -- cgit v1.2.3 From a34aa1959aeeb9bc92c71c6f217db80a09cfbbd3 Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Sun, 16 Feb 2014 00:50:03 +0100 Subject: Cast to number instead of integer in OC\Files\Cache\Cache --- lib/private/files/cache/cache.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/cache/cache.php b/lib/private/files/cache/cache.php index 3e4f6dfb132..59963f41e3d 100644 --- a/lib/private/files/cache/cache.php +++ b/lib/private/files/cache/cache.php @@ -142,11 +142,11 @@ class Cache { } else { //fix types $data['fileid'] = (int)$data['fileid']; - $data['size'] = (int)$data['size']; + $data['size'] = 0 + $data['size']; $data['mtime'] = (int)$data['mtime']; $data['storage_mtime'] = (int)$data['storage_mtime']; $data['encrypted'] = (bool)$data['encrypted']; - $data['unencrypted_size'] = (int)$data['unencrypted_size']; + $data['unencrypted_size'] = 0 + $data['unencrypted_size']; $data['storage'] = $this->storageId; $data['mimetype'] = $this->getMimetype($data['mimetype']); $data['mimepart'] = $this->getMimetype($data['mimepart']); @@ -532,9 +532,9 @@ class Cache { $result = \OC_DB::executeAudited($sql, array($id, $this->getNumericStorageId())); if ($row = $result->fetchRow()) { list($sum, $min, $unencryptedSum) = array_values($row); - $sum = (int)$sum; - $min = (int)$min; - $unencryptedSum = (int)$unencryptedSum; + $sum = 0 + $sum; + $min = 0 + $min; + $unencryptedSum = 0 + $unencryptedSum; if ($min === -1) { $totalSize = $min; } else { -- cgit v1.2.3 From 0bae68017ee93ec087e04acce83f189f5c3eeea7 Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Sun, 16 Feb 2014 01:03:39 +0100 Subject: Cast to number instead of integer in OC\Files\Cache\HomeCache --- lib/private/files/cache/homecache.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/cache/homecache.php b/lib/private/files/cache/homecache.php index 2326c46e8d0..f61769f0b9b 100644 --- a/lib/private/files/cache/homecache.php +++ b/lib/private/files/cache/homecache.php @@ -36,8 +36,10 @@ class HomeCache extends Cache { $result = \OC_DB::executeAudited($sql, array($id, $this->getNumericStorageId())); if ($row = $result->fetchRow()) { list($sum, $unencryptedSum) = array_values($row); - $totalSize = (int)$sum; - $unencryptedSize = (int)$unencryptedSum; + $totalSize = 0 + $sum; + $unencryptedSize = 0 + $unencryptedSum; + $entry['size'] += 0; + $entry['unencrypted_size'] += 0; if ($entry['size'] !== $totalSize) { $this->update($id, array('size' => $totalSize)); } -- cgit v1.2.3 From fb4556033a9d39698dbc15b59f3ba76ef6510e33 Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Sun, 16 Feb 2014 14:42:59 +0100 Subject: Cast '{DAV:}getcontentlength' to number instead of int. --- lib/private/connector/sabre/file.php | 2 +- lib/private/connector/sabre/server.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/connector/sabre/file.php b/lib/private/connector/sabre/file.php index ab9d3e47d0e..8a16ba55e7a 100644 --- a/lib/private/connector/sabre/file.php +++ b/lib/private/connector/sabre/file.php @@ -156,7 +156,7 @@ class OC_Connector_Sabre_File extends OC_Connector_Sabre_Node implements Sabre_D /** * Returns the size of the node, in bytes * - * @return int + * @return int|float */ public function getSize() { return $this->info->getSize(); diff --git a/lib/private/connector/sabre/server.php b/lib/private/connector/sabre/server.php index 2660b043f46..cf28b11163f 100644 --- a/lib/private/connector/sabre/server.php +++ b/lib/private/connector/sabre/server.php @@ -170,7 +170,7 @@ class OC_Connector_Sabre_Server extends Sabre_DAV_Server { if ($node instanceof Sabre_DAV_IFile) { $size = $node->getSize(); if (!is_null($size)) { - $newProperties[200][$prop] = (int)$node->getSize(); + $newProperties[200][$prop] = 0 + $size; } } break; -- cgit v1.2.3 From 0417e52134e87c379b3b4c22a53a0c06a711baef Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Tue, 18 Feb 2014 12:57:44 +0100 Subject: Increase file size limit from 2 GiB to 4 GiB when workarounds are unavailable. --- lib/private/files/storage/local.php | 5 +---- lib/private/files/storage/mappedlocal.php | 5 +---- lib/private/largefilehelper.php | 23 ++++++++++++++++++++++- tests/lib/largefilehelpergetfilesize.php | 7 +++++++ 4 files changed, 31 insertions(+), 9 deletions(-) (limited to 'lib/private') diff --git a/lib/private/files/storage/local.php b/lib/private/files/storage/local.php index f4bc5085364..e33747bbd52 100644 --- a/lib/private/files/storage/local.php +++ b/lib/private/files/storage/local.php @@ -112,10 +112,7 @@ if (\OC_Util::runningOnWindows()) { $fullPath = $this->datadir . $path; if (PHP_INT_SIZE === 4) { $helper = new \OC\LargeFileHelper; - $filesize = $helper->getFilesize($fullPath); - if (!is_null($filesize)) { - return $filesize; - } + return $helper->getFilesize($fullPath); } return filesize($fullPath); } diff --git a/lib/private/files/storage/mappedlocal.php b/lib/private/files/storage/mappedlocal.php index f38b48db5de..ea4deaa66e8 100644 --- a/lib/private/files/storage/mappedlocal.php +++ b/lib/private/files/storage/mappedlocal.php @@ -134,10 +134,7 @@ class MappedLocal extends \OC\Files\Storage\Common { $fullPath = $this->buildPath($path); if (PHP_INT_SIZE === 4) { $helper = new \OC\LargeFileHelper; - $filesize = $helper->getFilesize($fullPath); - if (!is_null($filesize)) { - return $filesize; - } + return $helper->getFilesize($fullPath); } return filesize($fullPath); } diff --git a/lib/private/largefilehelper.php b/lib/private/largefilehelper.php index 08869d7c82a..3d15e786042 100644 --- a/lib/private/largefilehelper.php +++ b/lib/private/largefilehelper.php @@ -83,7 +83,7 @@ class LargeFileHelper { if (!is_null($filesize)) { return $filesize; } - return null; + return $this->getFilesizeNative($filename); } /** @@ -159,6 +159,27 @@ class LargeFileHelper { return null; } + /** + * @brief Gets the filesize via a filesize() call and converts negative + * signed int to positive float. As the result of filesize() will + * wrap around after a filesize of 2^32 bytes = 4 GiB, this should + * only be used as a last resort. + * + * @param string $filename Path to the file. + * + * @return int|float Number of bytes as number (float or int). + */ + public function getFilesizeNative($filename) { + $result = filesize($filename); + if ($result < 0) { + // For filesizes between 2 GiB and 4 GiB, filesize() will return a + // negative int, as the PHP data type int is signed. Interpret the + // returned int as an unsigned integer and put it into a float. + return (float) sprintf('%u', $result); + } + return $result; + } + protected function exec($cmd) { $result = trim(exec($cmd)); return ctype_digit($result) ? 0 + $result : null; diff --git a/tests/lib/largefilehelpergetfilesize.php b/tests/lib/largefilehelpergetfilesize.php index 001f636a52a..699dd6891ad 100644 --- a/tests/lib/largefilehelpergetfilesize.php +++ b/tests/lib/largefilehelpergetfilesize.php @@ -59,4 +59,11 @@ class LargeFileHelperGetFilesize extends \PHPUnit_Framework_TestCase { $this->helper->getFilesizeViaExec($this->filename) ); } + + public function testGetFilesizeNative() { + $this->assertSame( + $this->filesize, + $this->helper->getFilesizeNative($this->filename) + ); + } } -- cgit v1.2.3 From ea246d058ed86acc6634d34888d61f2a953e6ce1 Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Sun, 16 Mar 2014 19:54:05 +0100 Subject: Use "file size" instead of "filesize", then also apply camel case. --- lib/private/largefilehelper.php | 48 ++++++++++++++++---------------- tests/lib/largefilehelpergetfilesize.php | 32 ++++++++++----------- 2 files changed, 40 insertions(+), 40 deletions(-) (limited to 'lib/private') diff --git a/lib/private/largefilehelper.php b/lib/private/largefilehelper.php index 3d15e786042..4bab197b2ee 100644 --- a/lib/private/largefilehelper.php +++ b/lib/private/largefilehelper.php @@ -62,7 +62,7 @@ class LargeFileHelper { } /** - * @brief Tries to get the filesize of a file via various workarounds that + * @brief Tries to get the size of a file via various workarounds that * even work for large files on 32-bit platforms. * * @param string $filename Path to the file. @@ -70,31 +70,31 @@ class LargeFileHelper { * @return null|int|float Number of bytes as number (float or int) or * null on failure. */ - public function getFilesize($filename) { - $filesize = $this->getFilesizeViaCurl($filename); - if (!is_null($filesize)) { - return $filesize; + public function getFileSize($filename) { + $fileSize = $this->getFileSizeViaCurl($filename); + if (!is_null($fileSize)) { + return $fileSize; } - $filesize = $this->getFilesizeViaCOM($filename); - if (!is_null($filesize)) { - return $filesize; + $fileSize = $this->getFileSizeViaCOM($filename); + if (!is_null($fileSize)) { + return $fileSize; } - $filesize = $this->getFilesizeViaExec($filename); - if (!is_null($filesize)) { - return $filesize; + $fileSize = $this->getFileSizeViaExec($filename); + if (!is_null($fileSize)) { + return $fileSize; } - return $this->getFilesizeNative($filename); + return $this->getFileSizeNative($filename); } /** - * @brief Tries to get the filesize of a file via a CURL HEAD request. + * @brief Tries to get the size of a file via a CURL HEAD request. * * @param string $filename Path to the file. * * @return null|int|float Number of bytes as number (float or int) or * null on failure. */ - public function getFilesizeViaCurl($filename) { + public function getFileSizeViaCurl($filename) { if (function_exists('curl_init')) { $ch = curl_init("file://$filename"); curl_setopt($ch, CURLOPT_NOBODY, true); @@ -114,14 +114,14 @@ class LargeFileHelper { } /** - * @brief Tries to get the filesize of a file via the Windows DOM extension. + * @brief Tries to get the size of a file via the Windows DOM extension. * * @param string $filename Path to the file. * * @return null|int|float Number of bytes as number (float or int) or * null on failure. */ - public function getFilesizeViaCOM($filename) { + public function getFileSizeViaCOM($filename) { if (class_exists('COM')) { $fsobj = new \COM("Scripting.FileSystemObject"); $file = $fsobj->GetFile($filename); @@ -131,14 +131,14 @@ class LargeFileHelper { } /** - * @brief Tries to get the filesize of a file via an exec() call. + * @brief Tries to get the size of a file via an exec() call. * * @param string $filename Path to the file. * * @return null|int|float Number of bytes as number (float or int) or * null on failure. */ - public function getFilesizeViaExec($filename) { + public function getFileSizeViaExec($filename) { if (\OC_Helper::is_function_enabled('exec')) { $os = strtolower(php_uname('s')); $arg = escapeshellarg($filename); @@ -160,19 +160,19 @@ class LargeFileHelper { } /** - * @brief Gets the filesize via a filesize() call and converts negative - * signed int to positive float. As the result of filesize() will - * wrap around after a filesize of 2^32 bytes = 4 GiB, this should - * only be used as a last resort. + * @brief Gets the size of a file via a filesize() call and converts + * negative signed int to positive float. As the result of filesize() + * will wrap around after a file size of 2^32 bytes = 4 GiB, this + * should only be used as a last resort. * * @param string $filename Path to the file. * * @return int|float Number of bytes as number (float or int). */ - public function getFilesizeNative($filename) { + public function getFileSizeNative($filename) { $result = filesize($filename); if ($result < 0) { - // For filesizes between 2 GiB and 4 GiB, filesize() will return a + // For file sizes between 2 GiB and 4 GiB, filesize() will return a // negative int, as the PHP data type int is signed. Interpret the // returned int as an unsigned integer and put it into a float. return (float) sprintf('%u', $result); diff --git a/tests/lib/largefilehelpergetfilesize.php b/tests/lib/largefilehelpergetfilesize.php index 699dd6891ad..cc25d54a36a 100644 --- a/tests/lib/largefilehelpergetfilesize.php +++ b/tests/lib/largefilehelpergetfilesize.php @@ -9,61 +9,61 @@ namespace Test; /** -* Tests whether LargeFileHelper is able to determine filesize at all. +* Tests whether LargeFileHelper is able to determine file size at all. * Large files are not considered yet. */ -class LargeFileHelperGetFilesize extends \PHPUnit_Framework_TestCase { +class LargeFileHelperGetFileSize extends \PHPUnit_Framework_TestCase { protected $filename; - protected $filesize; + protected $fileSize; protected $helper; public function setUp() { parent::setUp(); $this->filename = __DIR__ . '/../data/data.tar.gz'; - $this->filesize = 4195; + $this->fileSize = 4195; $this->helper = new \OC\LargeFileHelper; } - public function testGetFilesizeViaCurl() { + public function testGetFileSizeViaCurl() { if (!extension_loaded('curl')) { $this->markTestSkipped( 'The PHP curl extension is required for this test.' ); } $this->assertSame( - $this->filesize, - $this->helper->getFilesizeViaCurl($this->filename) + $this->fileSize, + $this->helper->getFileSizeViaCurl($this->filename) ); } - public function testGetFilesizeViaCOM() { + public function testGetFileSizeViaCOM() { if (!extension_loaded('COM')) { $this->markTestSkipped( 'The PHP Windows COM extension is required for this test.' ); } $this->assertSame( - $this->filesize, - $this->helper->getFilesizeViaDOM($this->filename) + $this->fileSize, + $this->helper->getFileSizeViaDOM($this->filename) ); } - public function testGetFilesizeViaExec() { + public function testGetFileSizeViaExec() { if (!\OC_Helper::is_function_enabled('exec')) { $this->markTestSkipped( 'The exec() function needs to be enabled for this test.' ); } $this->assertSame( - $this->filesize, - $this->helper->getFilesizeViaExec($this->filename) + $this->fileSize, + $this->helper->getFileSizeViaExec($this->filename) ); } - public function testGetFilesizeNative() { + public function testGetFileSizeNative() { $this->assertSame( - $this->filesize, - $this->helper->getFilesizeNative($this->filename) + $this->fileSize, + $this->helper->getFileSizeNative($this->filename) ); } } -- cgit v1.2.3 From 2929d19c7f0b87d8207cbeff35607b8c27674ebf Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Sun, 16 Mar 2014 20:05:06 +0100 Subject: Document exceptions thrown by \OC\LargeFileHelper. --- lib/private/largefilehelper.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'lib/private') diff --git a/lib/private/largefilehelper.php b/lib/private/largefilehelper.php index 4bab197b2ee..293e09fe2c9 100644 --- a/lib/private/largefilehelper.php +++ b/lib/private/largefilehelper.php @@ -25,8 +25,10 @@ class LargeFileHelper { const POW_2_53_MINUS_1 = '9007199254740991'; /** - * @brief Constructor. Checks whether our assumptions hold on the platform - * we are on, throws an exception if they do not hold. + * @brief Checks whether our assumptions hold on the PHP platform we are on. + * + * @throws \RunTimeException if our assumptions do not hold on the current + * PHP platform. */ public function __construct() { $pow_2_53 = floatval(self::POW_2_53_MINUS_1) + 1.0; @@ -43,6 +45,9 @@ class LargeFileHelper { * * @param int|float|string $number Number containing unsigned integer data * + * @throws \UnexpectedValueException if $number is not a float, not an int + * and not a base-10 string. + * * @return string Unsigned integer base-10 string */ public function formatUnsignedInteger($number) { -- cgit v1.2.3 From 16ae63bdfd8556dceb251fd284dc97d330ca8092 Mon Sep 17 00:00:00 2001 From: ringmaster Date: Fri, 30 May 2014 09:42:41 -0400 Subject: Updates per comments on PR: * Use "filesystem_cache_readonly" config setting, update comment in config.sample * Use $this->cacheActive to cache config setting * Add public Scanner::setCacheActive() to set $cacheActive programmatically --- config/config.sample.php | 4 ++-- lib/private/files/cache/scanner.php | 26 ++++++++++++++++++++------ 2 files changed, 22 insertions(+), 8 deletions(-) (limited to 'lib/private') diff --git a/config/config.sample.php b/config/config.sample.php index 8fb782e7cf4..e2b4c9b31ab 100755 --- a/config/config.sample.php +++ b/config/config.sample.php @@ -293,7 +293,7 @@ $CONFIG = array( */ 'filesystem_check_changes' => 1, -/* specifies whether changes in the filesystem outside of owncloud affect cached data about those files */ -'filesystem_check_enable' => 1, +/* If true, prevent owncloud from changing the cache due to changes in the filesystem for all storage */ +'filesystem_cache_readonly' => false, ); diff --git a/lib/private/files/cache/scanner.php b/lib/private/files/cache/scanner.php index d4942d7dc2e..875d941fb77 100644 --- a/lib/private/files/cache/scanner.php +++ b/lib/private/files/cache/scanner.php @@ -44,6 +44,11 @@ class Scanner extends BasicEmitter { */ private $permissionsCache; + /** + * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache + */ + protected $cacheActive; + const SCAN_RECURSIVE = true; const SCAN_SHALLOW = false; @@ -55,6 +60,7 @@ class Scanner extends BasicEmitter { $this->storageId = $this->storage->getId(); $this->cache = $storage->getCache(); $this->permissionsCache = $storage->getPermissionsCache(); + $this->cacheActive = !Config::getSystemValue('filesystem_cache_readonly', false); } /** @@ -139,7 +145,7 @@ class Scanner extends BasicEmitter { } $parentCacheData = $this->cache->get($parent); \OC_Hook::emit('Scanner', 'updateCache', array('file' => $file, 'data' => $data)); - if(Config::getSystemValue('filesystem_check_enable', true)) { + if($this->cacheActive) { $this->cache->update($parentCacheData['fileid'], array( 'etag' => $this->storage->getETag($parent), )); @@ -161,7 +167,7 @@ class Scanner extends BasicEmitter { } if (!empty($newData)) { \OC_Hook::emit('Scanner', 'addToCache', array('file' => $file, 'data' => $newData)); - if(Config::getSystemValue('filesystem_check_enable', true)) { + if(!Config::getSystemValue('filesystem_cache_readonly', false)) { $data['fileid'] = $this->cache->put($file, $newData); } $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId)); @@ -169,7 +175,7 @@ class Scanner extends BasicEmitter { } } else { \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $file)); - if(Config::getSystemValue('filesystem_check_enable', true)) { + if($this->cacheActive) { $this->cache->remove($file); } } @@ -255,7 +261,7 @@ class Scanner extends BasicEmitter { foreach ($removedChildren as $childName) { $child = ($path) ? $path . '/' . $childName : $childName; \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $child)); - if(Config::getSystemValue('filesystem_check_enable', true)) { + if($this->cacheActive) { $this->cache->remove($child); } } @@ -278,7 +284,7 @@ class Scanner extends BasicEmitter { } $newData = array('size' => $size); \OC_Hook::emit('Scanner', 'addToCache', array('file' => $child, 'data' => $newData)); - if(Config::getSystemValue('filesystem_check_enable', true)) { + if($this->cacheActive) { $this->cache->put($path, $newData); } } @@ -308,10 +314,18 @@ class Scanner extends BasicEmitter { while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) { $this->scan($path, self::SCAN_RECURSIVE, self::REUSE_ETAG); \OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path)); - if(Config::getSystemValue('filesystem_check_enable', true)) { + if($this->cacheActive) { $this->cache->correctFolderSize($path); } $lastPath = $path; } } + + /** + * Set whether the cache is affected by scan operations + * @param boolean $active The active state of the cache + */ + public function setCacheActive($active) { + $this->cacheActive = $active; + } } -- cgit v1.2.3 From 19f0c47842527d565df3383a2c65830df3f3274f Mon Sep 17 00:00:00 2001 From: ringmaster Date: Fri, 30 May 2014 10:40:26 -0400 Subject: Missed one. --- lib/private/files/cache/scanner.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/private') diff --git a/lib/private/files/cache/scanner.php b/lib/private/files/cache/scanner.php index 875d941fb77..6dceaf13ec3 100644 --- a/lib/private/files/cache/scanner.php +++ b/lib/private/files/cache/scanner.php @@ -167,7 +167,7 @@ class Scanner extends BasicEmitter { } if (!empty($newData)) { \OC_Hook::emit('Scanner', 'addToCache', array('file' => $file, 'data' => $newData)); - if(!Config::getSystemValue('filesystem_cache_readonly', false)) { + if($this->cacheActive) { $data['fileid'] = $this->cache->put($file, $newData); } $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId)); -- cgit v1.2.3 From 999f6216dcfea2d5344c2ceda744461e18d32241 Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Mon, 12 May 2014 13:54:20 +0200 Subject: - fix dropTable() and introduce tableExists() - kill replaceDB() - this function is unused and it's implementation obviously wrong - add method annotation OC_DB_StatementWrapper::fetchAll - remove duplicate code in Test_DBSchema and reuse OC_DB::tableExists - remove unused variables --- lib/private/db.php | 74 ++++++++++++++++++++++++++++-------- lib/private/db/mdb2schemamanager.php | 34 ----------------- lib/private/db/statementwrapper.php | 1 + tests/lib/dbschema.php | 54 +++----------------------- 4 files changed, 65 insertions(+), 98 deletions(-) (limited to 'lib/private') diff --git a/lib/private/db.php b/lib/private/db.php index df9d1aeca3a..422f783c745 100644 --- a/lib/private/db.php +++ b/lib/private/db.php @@ -46,9 +46,6 @@ class OC_DB { */ static private $connection; //the preferred connection to use, only Doctrine - static private $prefix=null; - static private $type=null; - /** * connects to the database * @return boolean|null true if connection can be established or false on error @@ -325,12 +322,21 @@ class OC_DB { } /** - * drop a table + * drop a table - the database prefix will be prepended * @param string $tableName the table to drop */ public static function dropTable($tableName) { - $schemaManager = self::getMDB2SchemaManager(); - $schemaManager->dropTable($tableName); + + $tableName = OC_Config::getValue('dbtableprefix', 'oc_' ) . trim($tableName); + + self::$connection->beginTransaction(); + + $platform = self::$connection->getDatabasePlatform(); + $sql = $platform->getDropTableSQL($platform->quoteIdentifier($tableName)); + + self::$connection->query($sql); + + self::$connection->commit(); } /** @@ -342,15 +348,6 @@ class OC_DB { $schemaManager->removeDBStructure($file); } - /** - * replaces the ownCloud tables with a new set - * @param string $file path to the MDB2 xml db export file - */ - public static function replaceDB( $file ) { - $schemaManager = self::getMDB2SchemaManager(); - $schemaManager->replaceDB($file); - } - /** * check if a result is an error, works with Doctrine * @param mixed $result @@ -405,4 +402,51 @@ class OC_DB { self::$connection->disableQueryStatementCaching(); } } + + /** + * Checks if a table exists in the database - the database prefix will be prepended + * + * @param string $table + * @return bool + * @throws DatabaseException + */ + public static function tableExists($table) { + + $table = OC_Config::getValue('dbtableprefix', 'oc_' ) . trim($table); + + $dbType = OC_Config::getValue( 'dbtype', 'sqlite' ); + switch ($dbType) { + case 'sqlite': + case 'sqlite3': + $sql = "SELECT name FROM sqlite_master " + . "WHERE type = 'table' AND name = ? " + . "UNION ALL SELECT name FROM sqlite_temp_master " + . "WHERE type = 'table' AND name = ?"; + $result = \OC_DB::executeAudited($sql, array($table, $table)); + break; + case 'mysql': + $sql = 'SHOW TABLES LIKE ?'; + $result = \OC_DB::executeAudited($sql, array($table)); + break; + case 'pgsql': + $sql = 'SELECT tablename AS table_name, schemaname AS schema_name ' + . 'FROM pg_tables WHERE schemaname NOT LIKE \'pg_%\' ' + . 'AND schemaname != \'information_schema\' ' + . 'AND tablename = ?'; + $result = \OC_DB::executeAudited($sql, array($table)); + break; + case 'oci': + $sql = 'SELECT TABLE_NAME FROM USER_TABLES WHERE TABLE_NAME = ?'; + $result = \OC_DB::executeAudited($sql, array($table)); + break; + case 'mssql': + $sql = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ?'; + $result = \OC_DB::executeAudited($sql, array($table)); + break; + default: + throw new DatabaseException("Unknown database type: $dbType"); + } + + return $result->fetchOne() === $table; + } } diff --git a/lib/private/db/mdb2schemamanager.php b/lib/private/db/mdb2schemamanager.php index 1e90c8bda5c..4208dbd18f4 100644 --- a/lib/private/db/mdb2schemamanager.php +++ b/lib/private/db/mdb2schemamanager.php @@ -94,19 +94,6 @@ class MDB2SchemaManager { return $this->executeSchemaChange($schemaDiff); } - /** - * drop a table - * @param string $tableName the table to drop - */ - public function dropTable($tableName) { - $sm = $this->conn->getSchemaManager(); - $fromSchema = $sm->createSchema(); - $toSchema = clone $fromSchema; - $toSchema->dropTable($tableName); - $sql = $fromSchema->getMigrateToSql($toSchema, $this->conn->getDatabasePlatform()); - $this->conn->executeQuery($sql); - } - /** * remove all tables defined in a database structure xml file * @param string $file the xml file describing the tables @@ -124,27 +111,6 @@ class MDB2SchemaManager { $this->executeSchemaChange($schemaDiff); } - /** - * replaces the ownCloud tables with a new set - * @param string $file path to the MDB2 xml db export file - */ - public function replaceDB( $file ) { - $apps = \OC_App::getAllApps(); - $this->conn->beginTransaction(); - // Delete the old tables - $this->removeDBStructure( \OC::$SERVERROOT . '/db_structure.xml' ); - - foreach($apps as $app) { - $path = \OC_App::getAppPath($app).'/appinfo/database.xml'; - if(file_exists($path)) { - $this->removeDBStructure( $path ); - } - } - - // Create new tables - $this->conn->commit(); - } - /** * @param \Doctrine\DBAL\Schema\Schema $schema * @return bool diff --git a/lib/private/db/statementwrapper.php b/lib/private/db/statementwrapper.php index 70d1f985a41..93fabc147ca 100644 --- a/lib/private/db/statementwrapper.php +++ b/lib/private/db/statementwrapper.php @@ -13,6 +13,7 @@ * @method string errorCode(); * @method array errorInfo(); * @method integer rowCount(); + * @method array fetchAll(integer $fetchMode = null); */ class OC_DB_StatementWrapper { /** diff --git a/tests/lib/dbschema.php b/tests/lib/dbschema.php index cfa2d6fd9aa..c07e32a404e 100644 --- a/tests/lib/dbschema.php +++ b/tests/lib/dbschema.php @@ -24,10 +24,8 @@ class Test_DBSchema extends PHPUnit_Framework_TestCase { $content = str_replace( '*dbprefix*', '*dbprefix*'.$r, $content ); file_put_contents( $this->schema_file2, $content ); - $prefix = OC_Config::getValue( "dbtableprefix", "oc_" ); - - $this->table1 = $prefix.$r.'cntcts_addrsbks'; - $this->table2 = $prefix.$r.'cntcts_cards'; + $this->table1 = $r.'cntcts_addrsbks'; + $this->table2 = $r.'cntcts_cards'; } public function tearDown() { @@ -71,54 +69,11 @@ class Test_DBSchema extends PHPUnit_Framework_TestCase { $this->assertTableNotExist($this->table2); } - /** - * @param string $table - */ - public function tableExist($table) { - - switch (OC_Config::getValue( 'dbtype', 'sqlite' )) { - case 'sqlite': - case 'sqlite3': - $sql = "SELECT name FROM sqlite_master " - . "WHERE type = 'table' AND name = ? " - . "UNION ALL SELECT name FROM sqlite_temp_master " - . "WHERE type = 'table' AND name = ?"; - $result = \OC_DB::executeAudited($sql, array($table, $table)); - break; - case 'mysql': - $sql = 'SHOW TABLES LIKE ?'; - $result = \OC_DB::executeAudited($sql, array($table)); - break; - case 'pgsql': - $sql = 'SELECT tablename AS table_name, schemaname AS schema_name ' - . 'FROM pg_tables WHERE schemaname NOT LIKE \'pg_%\' ' - . 'AND schemaname != \'information_schema\' ' - . 'AND tablename = ?'; - $result = \OC_DB::executeAudited($sql, array($table)); - break; - case 'oci': - $sql = 'SELECT TABLE_NAME FROM USER_TABLES WHERE TABLE_NAME = ?'; - $result = \OC_DB::executeAudited($sql, array($table)); - break; - case 'mssql': - $sql = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ?'; - $result = \OC_DB::executeAudited($sql, array($table)); - break; - } - - $name = $result->fetchOne(); - if ($name === $table) { - return true; - } else { - return false; - } - } - /** * @param string $table */ public function assertTableExist($table) { - $this->assertTrue($this->tableExist($table), 'Table ' . $table . ' does not exist'); + $this->assertTrue(OC_DB::tableExists($table), 'Table ' . $table . ' does not exist'); } /** @@ -128,8 +83,9 @@ class Test_DBSchema extends PHPUnit_Framework_TestCase { $type=OC_Config::getValue( "dbtype", "sqlite" ); if( $type == 'sqlite' || $type == 'sqlite3' ) { // sqlite removes the tables after closing the DB + $this->assertTrue(true); } else { - $this->assertFalse($this->tableExist($table), 'Table ' . $table . ' exists.'); + $this->assertFalse(OC_DB::tableExists($table), 'Table ' . $table . ' exists.'); } } } -- cgit v1.2.3