Cleanup unused methods

Signed-off-by: Morris Jobke <hey@morrisjobke.de>
This commit is contained in:
Morris Jobke 2017-08-15 10:03:21 +02:00
parent e0f479a4eb
commit f640b56bfa
5 changed files with 3 additions and 1781 deletions

View File

@ -1225,69 +1225,6 @@ class ApiTest extends TestCase {
\OCP\Share::shareItem('file', $info->getId(), \OCP\Share::SHARE_TYPE_LINK, self::TEST_FILES_SHARING_API_USER2, 31);
}
public function testDefaultExpireDate() {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
// TODO drop this once all code paths use the DI version - otherwise
// the cache inside this config object is out of date because
// OC_Appconfig is used and bypasses this cache which lead to integrity
// constraint violations
$config = \OC::$server->getConfig();
$config->deleteAppValue('core', 'shareapi_default_expire_date');
$config->deleteAppValue('core', 'shareapi_enforce_expire_date');
$config->deleteAppValue('core', 'shareapi_expire_after_n_days');
$config->setAppValue('core', 'shareapi_default_expire_date', 'yes');
$config->setAppValue('core', 'shareapi_enforce_expire_date', 'yes');
$config->setAppValue('core', 'shareapi_expire_after_n_days', '2');
// default expire date is set to 2 days
// the time when the share was created is set to 3 days in the past
// user defined expire date is set to +2 days from now on
// -> link should be already expired by the default expire date but the user
// share should still exists.
$now = time();
$dateFormat = 'Y-m-d H:i:s';
$shareCreated = $now - 3 * 24 * 60 * 60;
$expireDate = date($dateFormat, $now + 2 * 24 * 60 * 60);
$info = \OC\Files\Filesystem::getFileInfo($this->filename);
$this->assertTrue($info instanceof \OC\Files\FileInfo);
$result = \OCP\Share::shareItem('file', $info->getId(), \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ);
$this->assertTrue(is_string($result));
$result = \OCP\Share::shareItem('file', $info->getId(), \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2, 31);
$this->assertTrue($result);
$result = \OCP\Share::setExpirationDate('file', $info->getId() , $expireDate, $now);
$this->assertTrue($result);
//manipulate stime so that both shares are older then the default expire date
$statement = "UPDATE `*PREFIX*share` SET `stime` = ? WHERE `share_type` = ?";
$query = \OCP\DB::prepare($statement);
$result = $query->execute(array($shareCreated, \OCP\Share::SHARE_TYPE_LINK));
$this->assertSame(1, $result);
$query = \OCP\DB::prepare($statement);
$result = $query->execute(array($shareCreated, \OCP\Share::SHARE_TYPE_USER));
$this->assertSame(1, $result);
// now the link share should expire because of enforced default expire date
// the user share should still exist
$result = \OCP\Share::getItemShared('file', $info->getId());
$this->assertTrue(is_array($result));
$this->assertSame(1, count($result));
$share = reset($result);
$this->assertSame(\OCP\Share::SHARE_TYPE_USER, $share['share_type']);
//cleanup
$result = \OCP\Share::unshare('file', $info->getId(), \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
$this->assertTrue($result);
$config->setAppValue('core', 'shareapi_default_expire_date', 'no');
$config->setAppValue('core', 'shareapi_enforce_expire_date', 'no');
}
public function datesProvider() {
$date = new \DateTime();
$date->add(new \DateInterval('P5D'));

View File

@ -84,7 +84,7 @@ class Share extends Constants {
* @return boolean true if backend is registered or false if error
*/
public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
if (self::isEnabled()) {
if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_enabled', 'yes') == 'yes') {
if (!isset(self::$backendTypes[$itemType])) {
self::$backendTypes[$itemType] = array(
'class' => $class,
@ -105,255 +105,6 @@ class Share extends Constants {
return false;
}
/**
* Check if the Share API is enabled
* @return boolean true if enabled or false
*
* The Share API is enabled by default if not configured
*/
public static function isEnabled() {
if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_enabled', 'yes') == 'yes') {
return true;
}
return false;
}
/**
* Find which users can access a shared item
* @param string $path to the file
* @param string $ownerUser owner of the file
* @param IUserManager $userManager
* @param ILogger $logger
* @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
* @param boolean $recursive take all parent folders into account (default true)
* @return array
* @note $path needs to be relative to user data dir, e.g. 'file.txt'
* not '/admin/data/file.txt'
* @throws \OC\User\NoUserException
*/
public static function getUsersSharingFile($path,
$ownerUser,
IUserManager $userManager,
ILogger $logger,
$includeOwner = false,
$returnUserPaths = false,
$recursive = true) {
$userObject = $userManager->get($ownerUser);
if (is_null($userObject)) {
$logger->error(
sprintf(
'Backends provided no user object for %s',
$ownerUser
),
[
'app' => 'files',
]
);
throw new \OC\User\NoUserException('Backends provided no user object');
}
$ownerUser = $userObject->getUID();
Filesystem::initMountPoints($ownerUser);
$shares = $sharePaths = $fileTargets = array();
$publicShare = false;
$remoteShare = false;
$source = -1;
$cache = $mountPath = false;
$view = new \OC\Files\View('/' . $ownerUser . '/files');
$meta = $view->getFileInfo($path);
if ($meta) {
$path = substr($meta->getPath(), strlen('/' . $ownerUser . '/files'));
} else {
// if the file doesn't exists yet we start with the parent folder
$meta = $view->getFileInfo(dirname($path));
}
if($meta !== false) {
$source = $meta['fileid'];
$cache = new \OC\Files\Cache\Cache($meta['storage']);
$mountPath = $meta->getMountPoint()->getMountPoint();
if ($mountPath !== false) {
$mountPath = substr($mountPath, strlen('/' . $ownerUser . '/files'));
}
}
$paths = [];
while ($source !== -1) {
// Fetch all shares with another user
if (!$returnUserPaths) {
$query = \OC_DB::prepare(
'SELECT `share_with`, `file_source`, `file_target`
FROM
`*PREFIX*share`
WHERE
`item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'
);
$result = $query->execute(array($source, self::SHARE_TYPE_USER));
} else {
$query = \OC_DB::prepare(
'SELECT `share_with`, `file_source`, `file_target`
FROM
`*PREFIX*share`
WHERE
`item_source` = ? AND `share_type` IN (?, ?) AND `item_type` IN (\'file\', \'folder\')'
);
$result = $query->execute(array($source, self::SHARE_TYPE_USER, self::$shareTypeGroupUserUnique));
}
if (\OCP\DB::isError($result)) {
\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
} else {
while ($row = $result->fetchRow()) {
$shares[] = $row['share_with'];
if ($returnUserPaths) {
$fileTargets[(int) $row['file_source']][$row['share_with']] = $row;
}
}
}
// We also need to take group shares into account
$query = \OC_DB::prepare(
'SELECT `share_with`, `file_source`, `file_target`
FROM
`*PREFIX*share`
WHERE
`item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'
);
$result = $query->execute(array($source, self::SHARE_TYPE_GROUP));
if (\OCP\DB::isError($result)) {
\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
} else {
$groupManager = \OC::$server->getGroupManager();
while ($row = $result->fetchRow()) {
$usersInGroup = [];
$group = $groupManager->get($row['share_with']);
if ($group) {
$users = $group->searchUsers('', -1, 0);
$userIds = array();
foreach ($users as $user) {
$userIds[] = $user->getUID();
}
$usersInGroup = $userIds;
}
$shares = array_merge($shares, $usersInGroup);
if ($returnUserPaths) {
foreach ($usersInGroup as $user) {
if (!isset($fileTargets[(int) $row['file_source']][$user])) {
// When the user already has an entry for this file source
// the file is either shared directly with him as well, or
// he has an exception entry (because of naming conflict).
$fileTargets[(int) $row['file_source']][$user] = $row;
}
}
}
}
}
//check for public link shares
if (!$publicShare) {
$query = \OC_DB::prepare('
SELECT `share_with`
FROM `*PREFIX*share`
WHERE `item_source` = ? AND `share_type` IN (?, ?) AND `item_type` IN (\'file\', \'folder\')', 1
);
$result = $query->execute(array($source, self::SHARE_TYPE_LINK, self::SHARE_TYPE_EMAIL));
if (\OCP\DB::isError($result)) {
\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
} else {
if ($result->fetchRow()) {
$publicShare = true;
}
}
}
//check for remote share
if (!$remoteShare) {
$query = \OC_DB::prepare('
SELECT `share_with`
FROM `*PREFIX*share`
WHERE `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')', 1
);
$result = $query->execute(array($source, self::SHARE_TYPE_REMOTE));
if (\OCP\DB::isError($result)) {
\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
} else {
if ($result->fetchRow()) {
$remoteShare = true;
}
}
}
// let's get the parent for the next round
$meta = $cache->get((int)$source);
if ($recursive === true && $meta !== false) {
$paths[$source] = $meta['path'];
$source = (int)$meta['parent'];
} else {
$source = -1;
}
}
// Include owner in list of users, if requested
if ($includeOwner) {
$shares[] = $ownerUser;
}
if ($returnUserPaths) {
$fileTargetIDs = array_keys($fileTargets);
$fileTargetIDs = array_unique($fileTargetIDs);
if (!empty($fileTargetIDs)) {
$query = \OC_DB::prepare(
'SELECT `fileid`, `path`
FROM `*PREFIX*filecache`
WHERE `fileid` IN (' . implode(',', $fileTargetIDs) . ')'
);
$result = $query->execute();
if (\OCP\DB::isError($result)) {
\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
} else {
while ($row = $result->fetchRow()) {
foreach ($fileTargets[$row['fileid']] as $uid => $shareData) {
if ($mountPath !== false) {
$sharedPath = $shareData['file_target'];
$sharedPath .= substr($path, strlen($mountPath) + strlen($paths[$row['fileid']]));
$sharePaths[$uid] = $sharedPath;
} else {
$sharedPath = $shareData['file_target'];
$sharedPath .= substr($path, strlen($row['path']) -5);
$sharePaths[$uid] = $sharedPath;
}
}
}
$result->closeCursor();
}
}
if ($includeOwner) {
$sharePaths[$ownerUser] = $path;
} else {
unset($sharePaths[$ownerUser]);
}
return $sharePaths;
}
return array('users' => array_unique($shares), 'public' => $publicShare, 'remote' => $remoteShare);
}
/**
* Get the items of item type shared with the current user
* @param string $itemType
@ -385,21 +136,6 @@ class Share extends Constants {
$parameters, $limit, $includeCollections);
}
/**
* Get the item of item type shared with the current user
* @param string $itemType
* @param string $itemTarget
* @param int $format (optional) Format type must be defined by the backend
* @param mixed $parameters (optional)
* @param boolean $includeCollections (optional)
* @return mixed Return depends on format
*/
public static function getItemSharedWith($itemType, $itemTarget, $format = self::FORMAT_NONE,
$parameters = null, $includeCollections = false) {
return self::getItems($itemType, $itemTarget, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
$parameters, 1, $includeCollections);
}
/**
* Get the item of item type shared with a given user by source
* @param string $itemType
@ -526,18 +262,6 @@ class Share extends Constants {
$parameters, 1, $includeCollections, true);
}
/**
* Get the item of item type shared by a link
* @param string $itemType
* @param string $itemSource
* @param string $uidOwner Owner of link
* @return array
*/
public static function getItemSharedWithByLink($itemType, $itemSource, $uidOwner) {
return self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE,
null, 1);
}
/**
* Based on the given token the share information will be returned - password protected shares will be verified
* @param string $token
@ -619,42 +343,6 @@ class Share extends Constants {
$parameters, -1, $includeCollections);
}
/**
* Get all users an item is shared with
* @param string $itemType
* @param string $itemSource
* @param string $uidOwner
* @param boolean $includeCollections
* @param boolean $checkExpireDate
* @return array Return array of users
*/
public static function getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections = false, $checkExpireDate = true) {
$users = array();
$items = self::getItems($itemType, $itemSource, null, null, $uidOwner, self::FORMAT_NONE, null, -1, $includeCollections, false, $checkExpireDate);
if ($items) {
foreach ($items as $item) {
if ((int)$item['share_type'] === self::SHARE_TYPE_USER) {
$users[] = $item['share_with'];
} else if ((int)$item['share_type'] === self::SHARE_TYPE_GROUP) {
$group = \OC::$server->getGroupManager()->get($item['share_with']);
$userIds = [];
if ($group) {
$users = $group->searchUsers('', -1, 0);
foreach ($users as $user) {
$userIds[] = $user->getUID();
}
return $userIds;
}
$users = array_merge($users, $userIds);
}
}
}
return $users;
}
/**
* Share an item with a user, group, or via private link
* @param string $itemType
@ -1026,140 +714,6 @@ class Share extends Constants {
return false;
}
/**
* Unshare an item from all users, groups, and remove all links
* @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.
$query = \OC_DB::prepare( 'SELECT `uid_owner` from `*PREFIX*share` WHERE `item_type`=? AND `item_source`=?' );
$result = $query->execute(array($itemType, $itemSource));
$shares = array();
// Add each owner's shares to the array of all shares for this item.
while ($row = $result->fetchRow()) {
$shares = array_merge($shares, self::getItems($itemType, $itemSource, null, null, $row['uid_owner']));
}
if (!empty($shares)) {
// Pass all the vars we have for now, they may be useful
$hookParams = array(
'itemType' => $itemType,
'itemSource' => $itemSource,
'shares' => $shares,
);
\OC_Hook::emit('OCP\Share', 'pre_unshareAll', $hookParams);
foreach ($shares as $share) {
self::unshareItem($share);
}
\OC_Hook::emit('OCP\Share', 'post_unshareAll', $hookParams);
return true;
}
return false;
}
/**
* Unshare an item shared with the current user
* @param string $itemType
* @param string $itemOrigin Item target or source
* @param boolean $originIsSource true if $itemOrigin is the source, false if $itemOrigin is the target (optional)
* @return boolean true on success or false on failure
*
* Unsharing from self is not allowed for items inside collections
*/
public static function unshareFromSelf($itemType, $itemOrigin, $originIsSource = false) {
$originType = ($originIsSource) ? 'source' : 'target';
$uid = \OCP\User::getUser();
if ($itemType === 'file' || $itemType === 'folder') {
$statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `file_' . $originType . '` = ?';
} else {
$statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `item_' . $originType . '` = ?';
}
$query = \OCP\DB::prepare($statement);
$result = $query->execute(array($itemType, $itemOrigin));
$shares = $result->fetchAll();
$listOfUnsharedItems = array();
$itemUnshared = false;
foreach ($shares as $share) {
if ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_USER &&
$share['share_with'] === $uid) {
$deletedShares = Helper::delete($share['id']);
$shareTmp = array(
'id' => $share['id'],
'shareWith' => $share['share_with'],
'itemTarget' => $share['item_target'],
'itemType' => $share['item_type'],
'shareType' => (int)$share['share_type'],
);
if (isset($share['file_target'])) {
$shareTmp['fileTarget'] = $share['file_target'];
}
$listOfUnsharedItems = array_merge($listOfUnsharedItems, $deletedShares, array($shareTmp));
$itemUnshared = true;
break;
} elseif ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
$group = \OC::$server->getGroupManager()->get($share['share_with']);
$user = \OC::$server->getUserManager()->get($uid);
if ($group && $user && $group->inGroup($user)) {
$groupShare = $share;
}
} elseif ((int)$share['share_type'] === self::$shareTypeGroupUserUnique &&
$share['share_with'] === $uid) {
$uniqueGroupShare = $share;
}
}
if (!$itemUnshared && isset($groupShare) && !isset($uniqueGroupShare)) {
$query = \OC_DB::prepare('INSERT INTO `*PREFIX*share`'
.' (`item_type`, `item_source`, `item_target`, `parent`, `share_type`,'
.' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`, `file_target`)'
.' VALUES (?,?,?,?,?,?,?,?,?,?,?)');
$query->execute(array($groupShare['item_type'], $groupShare['item_source'], $groupShare['item_target'],
$groupShare['id'], self::$shareTypeGroupUserUnique,
\OC_User::getUser(), $groupShare['uid_owner'], 0, $groupShare['stime'], $groupShare['file_source'],
$groupShare['file_target']));
$shareTmp = array(
'id' => $groupShare['id'],
'shareWith' => $groupShare['share_with'],
'itemTarget' => $groupShare['item_target'],
'itemType' => $groupShare['item_type'],
'shareType' => (int)$groupShare['share_type'],
);
if (isset($groupShare['file_target'])) {
$shareTmp['fileTarget'] = $groupShare['file_target'];
}
$listOfUnsharedItems = array_merge($listOfUnsharedItems, [$shareTmp]);
$itemUnshared = true;
} elseif (!$itemUnshared && isset($uniqueGroupShare)) {
$query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = ? WHERE `id` = ?');
$query->execute(array(0, $uniqueGroupShare['id']));
$shareTmp = array(
'id' => $uniqueGroupShare['id'],
'shareWith' => $uniqueGroupShare['share_with'],
'itemTarget' => $uniqueGroupShare['item_target'],
'itemType' => $uniqueGroupShare['item_type'],
'shareType' => (int)$uniqueGroupShare['share_type'],
);
if (isset($uniqueGroupShare['file_target'])) {
$shareTmp['fileTarget'] = $uniqueGroupShare['file_target'];
}
$listOfUnsharedItems = array_merge($listOfUnsharedItems, [$shareTmp]);
$itemUnshared = true;
}
if ($itemUnshared) {
\OC_Hook::emit('OCP\Share', 'post_unshareFromSelf',
array('unsharedItems' => $listOfUnsharedItems, 'itemType' => $itemType));
}
return $itemUnshared;
}
/**
* sent status if users got informed by mail about share
* @param string $itemType
@ -1183,177 +737,6 @@ class Share extends Constants {
}
}
/**
* Set the permissions of an item for a specific user or group
* @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
* @throws \Exception when trying to grant more permissions then the user has himself
*/
public static function setPermissions($itemType, $itemSource, $shareType, $shareWith, $permissions) {
$l = \OC::$server->getL10N('lib');
$connection = \OC::$server->getDatabaseConnection();
$intArrayToLiteralArray = function($intArray, $eb) {
return array_map(function($int) use ($eb) {
return $eb->literal((int)$int, 'integer');
}, $intArray);
};
$sanitizeItem = function($item) {
$item['id'] = (int)$item['id'];
$item['premissions'] = (int)$item['permissions'];
return $item;
};
if ($rootItem = self::getItems($itemType, $itemSource, $shareType, $shareWith,
\OC_User::getUser(), self::FORMAT_NONE, null, 1, false)) {
// Check if this item is a reshare and verify that the permissions
// granted don't exceed the parent shared item
if (isset($rootItem['parent'])) {
$qb = $connection->getQueryBuilder();
$qb->select('permissions')
->from('share')
->where($qb->expr()->eq('id', $qb->createParameter('id')))
->setParameter(':id', $rootItem['parent']);
$dbresult = $qb->execute();
$result = $dbresult->fetch();
$dbresult->closeCursor();
if (~(int)$result['permissions'] & $permissions) {
$message = 'Setting permissions for %s failed,'
.' because the permissions exceed permissions granted to %s';
$message_t = $l->t('Setting permissions for %s failed, because the permissions exceed permissions granted to %s', array($itemSource, \OC_User::getUser()));
\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, \OC_User::getUser()), \OCP\Util::DEBUG);
throw new \Exception($message_t);
}
}
$qb = $connection->getQueryBuilder();
$qb->update('share')
->set('permissions', $qb->createParameter('permissions'))
->where($qb->expr()->eq('id', $qb->createParameter('id')))
->setParameter(':id', $rootItem['id'])
->setParameter(':permissions', $permissions);
$qb->execute();
if ($itemType === 'file' || $itemType === 'folder') {
\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
'itemType' => $itemType,
'itemSource' => $itemSource,
'shareType' => $shareType,
'shareWith' => $shareWith,
'uidOwner' => \OC_User::getUser(),
'permissions' => $permissions,
'path' => $rootItem['path'],
'share' => $rootItem
));
}
// Share id's to update with the new permissions
$ids = [];
$items = [];
// Check if permissions were removed
if ((int)$rootItem['permissions'] & ~$permissions) {
// If share permission is removed all reshares must be deleted
if (($rootItem['permissions'] & \OCP\Constants::PERMISSION_SHARE) && (~$permissions & \OCP\Constants::PERMISSION_SHARE)) {
// delete all shares, keep parent and group children
Helper::delete($rootItem['id'], true, null, null, true);
}
// Remove permission from all children
$parents = [$rootItem['id']];
while (!empty($parents)) {
$parents = $intArrayToLiteralArray($parents, $qb->expr());
$qb = $connection->getQueryBuilder();
$qb->select('id', 'permissions', 'item_type')
->from('share')
->where($qb->expr()->in('parent', $parents));
$result = $qb->execute();
// Reset parents array, only go through loop again if
// items are found that need permissions removed
$parents = [];
while ($item = $result->fetch()) {
$item = $sanitizeItem($item);
$items[] = $item;
// Check if permissions need to be removed
if ($item['permissions'] & ~$permissions) {
// Add to list of items that need permissions removed
$ids[] = $item['id'];
$parents[] = $item['id'];
}
}
$result->closeCursor();
}
// Remove the permissions for all reshares of this item
if (!empty($ids)) {
$ids = "'".implode("','", $ids)."'";
// TODO this should be done with Doctrine platform objects
if (\OC::$server->getConfig()->getSystemValue("dbtype") === 'oci') {
$andOp = 'BITAND(`permissions`, ?)';
} else {
$andOp = '`permissions` & ?';
}
$query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = '.$andOp
.' WHERE `id` IN ('.$ids.')');
$query->execute(array($permissions));
}
}
/*
* Permissions were added
* Update all USERGROUP shares. (So group shares where the user moved their mountpoint).
*/
if ($permissions & ~(int)$rootItem['permissions']) {
$qb = $connection->getQueryBuilder();
$qb->select('id', 'permissions', 'item_type')
->from('share')
->where($qb->expr()->eq('parent', $qb->createParameter('parent')))
->andWhere($qb->expr()->eq('share_type', $qb->createParameter('share_type')))
->andWhere($qb->expr()->neq('permissions', $qb->createParameter('shareDeleted')))
->setParameter(':parent', (int)$rootItem['id'])
->setParameter(':share_type', 2)
->setParameter(':shareDeleted', 0);
$result = $qb->execute();
$ids = [];
while ($item = $result->fetch()) {
$item = $sanitizeItem($item);
$items[] = $item;
$ids[] = $item['id'];
}
$result->closeCursor();
// Add permssions for all USERGROUP shares of this item
if (!empty($ids)) {
$ids = $intArrayToLiteralArray($ids, $qb->expr());
$qb = $connection->getQueryBuilder();
$qb->update('share')
->set('permissions', $qb->createParameter('permissions'))
->where($qb->expr()->in('id', $ids))
->setParameter(':permissions', $permissions);
$qb->execute();
}
}
foreach ($items as $item) {
\OC_Hook::emit('OCP\Share', 'post_update_permissions', ['share' => $item]);
}
return true;
}
$message = 'Setting permissions for %s failed, because the item was not found';
$message_t = $l->t('Setting permissions for %s failed, because the item was not found', array($itemSource));
\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
throw new \Exception($message_t);
}
/**
* validate expiration date if it meets all constraints
*
@ -1402,50 +785,6 @@ class Share extends Constants {
return $date;
}
/**
* Set expiration date for a share
* @param string $itemType
* @param string $itemSource
* @param string $date expiration date
* @param int $shareTime timestamp from when the file was shared
* @return boolean
* @throws \Exception when the expire date is not set, in the past or further in the future then the enforced date
*/
public static function setExpirationDate($itemType, $itemSource, $date, $shareTime = null) {
$user = \OC_User::getUser();
$l = \OC::$server->getL10N('lib');
if ($date == '') {
if (\OCP\Util::isDefaultExpireDateEnforced()) {
$warning = 'Cannot clear expiration date. Shares are required to have an expiration date.';
$warning_t = $l->t('Cannot clear expiration date. Shares are required to have an expiration date.');
\OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
throw new \Exception($warning_t);
} else {
$date = null;
}
} else {
$date = self::validateExpireDate($date, $shareTime, $itemType, $itemSource);
}
$query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `expiration` = ? WHERE `item_type` = ? AND `item_source` = ? AND `uid_owner` = ? AND `share_type` = ?');
$query->bindValue(1, $date, 'datetime');
$query->bindValue(2, $itemType);
$query->bindValue(3, $itemSource);
$query->bindValue(4, $user);
$query->bindValue(5, \OCP\Share::SHARE_TYPE_LINK);
$query->execute();
\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', array(
'itemType' => $itemType,
'itemSource' => $itemSource,
'date' => $date,
'uidOwner' => $user
));
return true;
}
/**
* Retrieve the owner of a connection
*
@ -1745,7 +1084,7 @@ class Share extends Constants {
public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
$uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
$includeCollections = false, $itemShareWithBySource = false, $checkExpireDate = true) {
if (!self::isEnabled()) {
if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_enabled', 'yes') != 'yes') {
return array();
}
$backend = self::getBackend($itemType);
@ -2551,18 +1890,6 @@ class Share extends Constants {
}
/**
* Delete all shares with type SHARE_TYPE_LINK
*/
public static function removeAllLinkShares() {
// Delete any link shares
$query = \OC_DB::prepare('SELECT `id` FROM `*PREFIX*share` WHERE `share_type` = ?');
$result = $query->execute(array(self::SHARE_TYPE_LINK));
while ($item = $result->fetchRow()) {
Helper::delete($item['id']);
}
}
/**
* In case a password protected link is not yet authenticated this function will return false
*

View File

@ -223,7 +223,7 @@ class JSConfigHelper {
'enforcePasswordForPublicLink' => \OCP\Util::isPublicLinkPasswordRequired(),
'enableLinkPasswordByDefault' => $enableLinkPasswordByDefault,
'sharingDisabledForUser' => \OCP\Util::isSharingDisabledForUser(),
'resharingAllowed' => \OCP\Share::isResharingAllowed(),
'resharingAllowed' => \OC\Share\Share::isResharingAllowed(),
'remoteShareAllowed' => $outgoingServer2serverShareEnabled,
'federatedCloudShareDoc' => $this->urlGenerator->linkToDocs('user-sharing-federated'),
'allowGroupSharing' => \OC::$server->getShareManager()->allowGroupSharing()

View File

@ -65,41 +65,6 @@ class Share extends \OC\Share\Constants {
return \OC\Share\Share::registerBackend($itemType, $class, $collectionOf, $supportedFileExtensions);
}
/**
* Check if the Share API is enabled
* @return boolean true if enabled or false
*
* The Share API is enabled by default if not configured
* @since 5.0.0
*/
public static function isEnabled() {
return \OC\Share\Share::isEnabled();
}
/**
* 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 bool $recursive take parent folders into account
* @return array
* @note $path needs to be relative to user data dir, e.g. 'file.txt'
* not '/admin/files/file.txt'
* @since 5.0.0 - $recursive was added in 9.0.0
*/
public static function getUsersSharingFile($path, $ownerUser, $includeOwner = false, $returnUserPaths = false, $recursive = true) {
return \OC\Share\Share::getUsersSharingFile(
$path,
$ownerUser,
\OC::$server->getUserManager(),
\OC::$server->getLogger(),
$includeOwner,
$returnUserPaths,
$recursive
);
}
/**
* Get the items of item type shared with the current user
* @param string $itemType
@ -133,22 +98,6 @@ class Share extends \OC\Share\Constants {
return \OC\Share\Share::getItemsSharedWithUser($itemType, $user, $format, $parameters, $limit, $includeCollections);
}
/**
* Get the item of item type shared with the current user
* @param string $itemType
* @param string $itemTarget
* @param int $format (optional) Format type must be defined by the backend
* @param mixed $parameters (optional)
* @param bool $includeCollections (optional)
* @return mixed Return depends on format
* @since 5.0.0
*/
public static function getItemSharedWith($itemType, $itemTarget, $format = self::FORMAT_NONE,
$parameters = null, $includeCollections = false) {
return \OC\Share\Share::getItemSharedWith($itemType, $itemTarget, $format, $parameters, $includeCollections);
}
/**
* Get the item of item type shared with a given user by source
* @param string $itemType
@ -177,18 +126,6 @@ class Share extends \OC\Share\Constants {
return \OC\Share\Share::getItemSharedWithBySource($itemType, $itemSource, $format, $parameters, $includeCollections);
}
/**
* Get the item of item type shared by a link
* @param string $itemType
* @param string $itemSource
* @param string $uidOwner Owner of link
* @return array
* @since 5.0.0
*/
public static function getItemSharedWithByLink($itemType, $itemSource, $uidOwner) {
return \OC\Share\Share::getItemSharedWithByLink($itemType, $itemSource, $uidOwner);
}
/**
* Based on the given token the share information will be returned - password protected shares will be verified
* @param string $token
@ -243,20 +180,6 @@ class Share extends \OC\Share\Constants {
return \OC\Share\Share::getItemShared($itemType, $itemSource, $format, $parameters, $includeCollections);
}
/**
* Get all users an item is shared with
* @param string $itemType
* @param string $itemSource
* @param string $uidOwner
* @param bool $includeCollections
* @param bool $checkExpireDate
* @return array Return array of users
* @since 5.0.0 - parameter $checkExpireDate was added in 7.0.0
*/
public static function getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections = false, $checkExpireDate = true) {
return \OC\Share\Share::getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections, $checkExpireDate);
}
/**
* Share an item with a user, group, or via private link
* @param string $itemType
@ -290,31 +213,6 @@ class Share extends \OC\Share\Constants {
return \OC\Share\Share::unshare($itemType, $itemSource, $shareType, $shareWith, $owner);
}
/**
* Unshare an item from all users, groups, and remove all links
* @param string $itemType
* @param string $itemSource
* @return boolean true on success or false on failure
* @since 5.0.0
*/
public static function unshareAll($itemType, $itemSource) {
return \OC\Share\Share::unshareAll($itemType, $itemSource);
}
/**
* Unshare an item shared with the current user
* @param string $itemType
* @param string $itemOrigin Item target or source
* @param boolean $originIsSource true if $itemOrigin is the source, false if $itemOrigin is the target (optional)
* @return boolean true on success or false on failure
*
* Unsharing from self is not allowed for items inside collections
* @since 5.0.0 - parameter $originIsSource was added in 8.0.0
*/
public static function unshareFromSelf($itemType, $itemOrigin, $originIsSource = false) {
return \OC\Share\Share::unshareFromSelf($itemType, $itemOrigin, $originIsSource);
}
/**
* sent status if users got informed by mail about share
* @param string $itemType
@ -328,48 +226,6 @@ class Share extends \OC\Share\Constants {
return \OC\Share\Share::setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status);
}
/**
* Set the permissions of an item for a specific user or group
* @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
* @since 5.0.0
*/
public static function setPermissions($itemType, $itemSource, $shareType, $shareWith, $permissions) {
return \OC\Share\Share::setPermissions($itemType, $itemSource, $shareType, $shareWith, $permissions);
}
/**
* Set expiration date for a share
* @param string $itemType
* @param string $itemSource
* @param string $date expiration date
* @param int $shareTime timestamp from when the file was shared
* @return boolean
* @since 5.0.0 - parameter $shareTime was added in 8.0.0
*/
public static function setExpirationDate($itemType, $itemSource, $date, $shareTime = null) {
return \OC\Share\Share::setExpirationDate($itemType, $itemSource, $date, $shareTime);
}
/**
* Set password for a public link share
* @param int $shareId
* @param string $password
* @return boolean
* @since 8.1.0
*/
public static function setPassword($shareId, $password) {
$userSession = \OC::$server->getUserSession();
$connection = \OC::$server->getDatabaseConnection();
$config = \OC::$server->getConfig();
return \OC\Share\Share::setPassword($userSession, $connection, $config, $shareId, $password);
}
/**
* Get the backend class for the specified item type
* @param string $itemType
@ -380,14 +236,6 @@ class Share extends \OC\Share\Constants {
return \OC\Share\Share::getBackend($itemType);
}
/**
* Delete all shares with type SHARE_TYPE_LINK
* @since 6.0.0
*/
public static function removeAllLinkShares() {
return \OC\Share\Share::removeAllLinkShares();
}
/**
* In case a password protected link is not yet authenticated this function will return false
*
@ -398,14 +246,4 @@ class Share extends \OC\Share\Constants {
public static function checkPasswordProtectedShare(array $linkItem) {
return \OC\Share\Share::checkPasswordProtectedShare($linkItem);
}
/**
* Check if resharing is allowed
*
* @return boolean true if allowed or false
* @since 5.0.0
*/
public static function isResharingAllowed() {
return \OC\Share\Share::isResharingAllowed();
}
}

View File

@ -143,282 +143,6 @@ class ShareTest extends \Test\TestCase {
}
}
public function testInvalidItemType() {
$message = 'Sharing backend for foobar not found';
try {
\OCP\Share::shareItem('foobar', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ);
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
try {
\OCP\Share::getItemsSharedWith('foobar');
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
try {
\OCP\Share::getItemSharedWith('foobar', 'test.txt');
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
try {
\OCP\Share::getItemSharedWithBySource('foobar', 'test.txt');
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
try {
\OCP\Share::getItemShared('foobar', 'test.txt');
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
try {
\OCP\Share::unshare('foobar', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2);
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
try {
\OCP\Share::setPermissions('foobar', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_UPDATE);
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
}
protected function shareUserOneTestFileWithUserTwo() {
\OC_User::setUserId($this->user1->getUID());
$this->assertTrue(
\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ),
'Failed asserting that user 1 successfully shared text.txt with user 2.'
);
$this->assertContains(
'test.txt',
\OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE),
'Failed asserting that test.txt is a shared file of user 1.'
);
\OC_User::setUserId($this->user2->getUID());
$this->assertContains(
'test.txt',
\OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
'Failed asserting that user 2 has access to test.txt after initial sharing.'
);
}
protected function shareUserTestFileAsLink() {
\OC_User::setUserId($this->user1->getUID());
$result = \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ);
$this->assertTrue(is_string($result));
}
/**
* @param string $sharer
* @param string $receiver
*/
protected function shareUserTestFileWithUser($sharer, $receiver) {
\OC_User::setUserId($sharer);
$this->assertTrue(
\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $receiver, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE),
'Failed asserting that ' . $sharer . ' successfully shared text.txt with ' . $receiver . '.'
);
$this->assertContains(
'test.txt',
\OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE),
'Failed asserting that test.txt is a shared file of ' . $sharer . '.'
);
\OC_User::setUserId($receiver);
$this->assertContains(
'test.txt',
\OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
'Failed asserting that ' . $receiver . ' has access to test.txt after initial sharing.'
);
}
public function testShareWithUser() {
// Invalid shares
$message = 'Sharing test.txt failed, because you can not share with yourself';
try {
\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user1->getUID(), \OCP\Constants::PERMISSION_READ);
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
$message = 'Sharing test.txt failed, because the user foobar does not exist';
try {
\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, 'foobar', \OCP\Constants::PERMISSION_READ);
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
$message = 'Sharing foobar failed, because the sharing backend for test could not find its source';
try {
\OCP\Share::shareItem('test', 'foobar', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ);
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
// Valid share
$this->shareUserOneTestFileWithUserTwo();
// Attempt to share again
\OC_User::setUserId($this->user1->getUID());
$message = 'Sharing test.txt failed, because this item is already shared with '.$this->user2->getUID();
try {
\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ);
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
// Attempt to share back
\OC_User::setUserId($this->user2->getUID());
$message = 'Sharing failed, because the user '.$this->user1->getUID().' is the original sharer';
try {
\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user1->getUID(), \OCP\Constants::PERMISSION_READ);
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
// Unshare
\OC_User::setUserId($this->user1->getUID());
$this->assertTrue(\OCP\Share::unshare('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID()));
// Attempt reshare without share permission
$this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ));
\OC_User::setUserId($this->user2->getUID());
$message = 'Sharing test.txt failed, because resharing is not allowed';
try {
\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3->getUID(), \OCP\Constants::PERMISSION_READ);
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
// Owner grants share and update permission
\OC_User::setUserId($this->user1->getUID());
$this->assertTrue(\OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE));
// Attempt reshare with escalated permissions
\OC_User::setUserId($this->user2->getUID());
$message = 'Sharing test.txt failed, because the permissions exceed permissions granted to '.$this->user2->getUID();
try {
\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3->getUID(), \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE);
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
// Valid reshare
$this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3->getUID(), \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE));
$this->assertEquals(array('test.txt'), \OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE));
\OC_User::setUserId($this->user3->getUID());
$this->assertEquals(array('test.txt'), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE));
$this->assertEquals(array(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_PERMISSIONS));
// Attempt to escalate permissions
\OC_User::setUserId($this->user2->getUID());
$message = 'Setting permissions for test.txt failed, because the permissions exceed permissions granted to '.$this->user2->getUID();
try {
\OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3->getUID(), \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE);
$this->fail('Exception was expected: '.$message);
} catch (\Exception $exception) {
$this->assertEquals($message, $exception->getMessage());
}
// Remove update permission
\OC_User::setUserId($this->user1->getUID());
$this->assertTrue(\OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE));
\OC_User::setUserId($this->user2->getUID());
$this->assertEquals(array(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_PERMISSIONS));
\OC_User::setUserId($this->user3->getUID());
$this->assertEquals(array(\OCP\Constants::PERMISSION_READ), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_PERMISSIONS));
// Remove share permission
\OC_User::setUserId($this->user1->getUID());
$this->assertTrue(\OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ));
\OC_User::setUserId($this->user2->getUID());
$this->assertEquals(array(\OCP\Constants::PERMISSION_READ), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_PERMISSIONS));
\OC_User::setUserId($this->user3->getUID());
$this->assertSame(array(), \OCP\Share::getItemSharedWith('test', 'test.txt'));
// Reshare again, and then have owner unshare
\OC_User::setUserId($this->user1->getUID());
$this->assertTrue(\OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE));
\OC_User::setUserId($this->user2->getUID());
$this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3->getUID(), \OCP\Constants::PERMISSION_READ));
\OC_User::setUserId($this->user1->getUID());
$this->assertTrue(\OCP\Share::unshare('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID()));
\OC_User::setUserId($this->user2->getUID());
$this->assertSame(array(), \OCP\Share::getItemSharedWith('test', 'test.txt'));
\OC_User::setUserId($this->user3->getUID());
$this->assertSame(array(), \OCP\Share::getItemSharedWith('test', 'test.txt'));
// Attempt target conflict
\OC_User::setUserId($this->user1->getUID());
$this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ));
\OC_User::setUserId($this->user3->getUID());
$this->assertTrue(\OCP\Share::shareItem('test', 'share.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ));
\OC_User::setUserId($this->user2->getUID());
$to_test = \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET);
$this->assertEquals(2, count($to_test));
$this->assertTrue(in_array('test.txt', $to_test));
$this->assertTrue(in_array('test1.txt', $to_test));
// Unshare from self
$this->assertTrue(\OCP\Share::unshareFromSelf('test', 'test.txt'));
$this->assertEquals(array('test1.txt'), \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET));
// Unshare from self via source
$this->assertTrue(\OCP\Share::unshareFromSelf('test', 'share.txt', true));
$this->assertEquals(array(), \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET));
\OC_User::setUserId($this->user1->getUID());
$this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ));
\OC_User::setUserId($this->user3->getUID());
$this->assertTrue(\OCP\Share::shareItem('test', 'share.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ));
\OC_User::setUserId($this->user2->getUID());
$to_test = \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET);
$this->assertEquals(2, count($to_test));
$this->assertTrue(in_array('test.txt', $to_test));
$this->assertTrue(in_array('test1.txt', $to_test));
// Remove user
\OC_User::setUserId($this->user1->getUID());
$user = \OC::$server->getUserManager()->get($this->user1->getUID());
if ($user !== null) { $user->delete(); }
\OC_User::setUserId($this->user2->getUID());
$this->assertEquals(array('test1.txt'), \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET));
}
public function testShareWithUserExpirationExpired() {
\OC_User::setUserId($this->user1->getUID());
$this->shareUserOneTestFileWithUserTwo();
$this->shareUserTestFileAsLink();
// manipulate share table and set expire date to the past
$query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `expiration` = ? WHERE `item_type` = ? AND `item_source` = ? AND `uid_owner` = ? AND `share_type` = ?');
$query->bindValue(1, new \DateTime($this->dateInPast), 'datetime');
$query->bindValue(2, 'test');
$query->bindValue(3, 'test.txt');
$query->bindValue(4, $this->user1->getUID());
$query->bindValue(5, \OCP\Share::SHARE_TYPE_LINK);
$query->execute();
$shares = \OCP\Share::getItemsShared('test');
$this->assertSame(1, count($shares));
$share = reset($shares);
$this->assertSame(\OCP\Share::SHARE_TYPE_USER, $share['share_type']);
}
public function testGetShareFromOutsideFilesFolder() {
\OC_User::setUserId($this->user1->getUID());
$view = new \OC\Files\View('/' . $this->user1->getUID() . '/');
@ -459,73 +183,6 @@ class ShareTest extends \Test\TestCase {
$this->assertEmpty($result, 'Share must not be returned for files outside of "files"');
}
public function testSetExpireDateInPast() {
\OC_User::setUserId($this->user1->getUID());
$this->shareUserOneTestFileWithUserTwo();
$this->shareUserTestFileAsLink();
$setExpireDateFailed = false;
try {
$this->assertTrue(
\OCP\Share::setExpirationDate('test', 'test.txt', $this->dateInPast, ''),
'Failed asserting that user 1 successfully set an expiration date for the test.txt share.'
);
} catch (\Exception $e) {
$setExpireDateFailed = true;
}
$this->assertTrue($setExpireDateFailed);
}
public function testShareWithUserExpirationValid() {
\OC_User::setUserId($this->user1->getUID());
$this->shareUserOneTestFileWithUserTwo();
$this->shareUserTestFileAsLink();
$this->assertTrue(
\OCP\Share::setExpirationDate('test', 'test.txt', $this->dateInFuture, ''),
'Failed asserting that user 1 successfully set an expiration date for the test.txt share.'
);
$shares = \OCP\Share::getItemsShared('test');
$this->assertSame(2, count($shares));
}
/*
* if user is in a group excluded from resharing, then the share permission should
* be removed
*/
public function testShareWithUserAndUserIsExcludedFromResharing() {
\OC_User::setUserId($this->user1->getUID());
$this->assertTrue(
\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user4->getUID(), \OCP\Constants::PERMISSION_ALL),
'Failed asserting that user 1 successfully shared text.txt with user 4.'
);
$this->assertContains(
'test.txt',
\OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE),
'Failed asserting that test.txt is a shared file of user 1.'
);
// exclude group2 from sharing
\OC::$server->getAppConfig()->setValue('core', 'shareapi_exclude_groups_list', $this->group2->getGID());
\OC::$server->getAppConfig()->setValue('core', 'shareapi_exclude_groups', "yes");
\OC_User::setUserId($this->user4->getUID());
$share = \OCP\Share::getItemSharedWith('test', 'test.txt');
$this->assertSame(\OCP\Constants::PERMISSION_ALL & ~\OCP\Constants::PERMISSION_SHARE, $share['permissions'],
'Failed asserting that user 4 is excluded from re-sharing');
\OC::$server->getAppConfig()->deleteKey('core', 'shareapi_exclude_groups_list');
\OC::$server->getAppConfig()->deleteKey('core', 'shareapi_exclude_groups');
}
public function testSharingAFolderThatIsSharedWithAGroupOfTheOwner() {
\OC_User::setUserId($this->user1->getUID());
$view = new \OC\Files\View('/' . $this->user1->getUID() . '/');
@ -595,33 +252,6 @@ class ShareTest extends \Test\TestCase {
}
}
protected function shareUserOneTestFileWithGroupOne() {
\OC_User::setUserId($this->user1->getUID());
$this->assertTrue(
\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_GROUP, $this->group1->getGID(), \OCP\Constants::PERMISSION_READ),
'Failed asserting that user 1 successfully shared text.txt with group 1.'
);
$this->assertContains(
'test.txt',
\OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE),
'Failed asserting that test.txt is a shared file of user 1.'
);
\OC_User::setUserId($this->user2->getUID());
$this->assertContains(
'test.txt',
\OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
'Failed asserting that user 2 has access to test.txt after initial sharing.'
);
\OC_User::setUserId($this->user3->getUID());
$this->assertContains(
'test.txt',
\OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
'Failed asserting that user 3 has access to test.txt after initial sharing.'
);
}
/**
* Test that unsharing from group will also delete all
* child entries
@ -668,40 +298,6 @@ class ShareTest extends \Test\TestCase {
}
}
public function testShareWithGroupAndUserBothHaveTheSameId() {
$this->shareUserTestFileWithUser($this->user1->getUID(), $this->groupAndUser_user->getUID());
\OC_User::setUserId($this->groupAndUser_user->getUID());
$this->assertEquals(array('test.txt'), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
'"groupAndUser"-User does not see the file but it was shared with him');
\OC_User::setUserId($this->user2->getUID());
$this->assertEquals(array(), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
'User2 sees test.txt but it was only shared with the user "groupAndUser" and not with group');
\OC_User::setUserId($this->user1->getUID());
$this->assertTrue(\OCP\Share::unshareAll('test', 'test.txt'));
$this->assertTrue(
\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_GROUP, $this->groupAndUser_group->getGID(), \OCP\Constants::PERMISSION_READ),
'Failed asserting that user 1 successfully shared text.txt with group 1.'
);
\OC_User::setUserId($this->groupAndUser_user->getUID());
$this->assertEquals(array(), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
'"groupAndUser"-User sees test.txt but it was only shared with the group "groupAndUser" and not with the user');
\OC_User::setUserId($this->user2->getUID());
$this->assertEquals(array('test.txt'), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
'User2 does not see test.txt but it was shared with the group "groupAndUser"');
\OC_User::setUserId($this->user1->getUID());
$this->assertTrue(\OCP\Share::unshareAll('test', 'test.txt'));
}
/**
* @param boolean|string $token
* @return array
@ -841,48 +437,6 @@ class ShareTest extends \Test\TestCase {
$qb->delete('share')->execute();
}
public function testShareItemWithLink() {
\OC_User::setUserId($this->user1->getUID());
$token = \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ);
$this->assertInternalType(
'string',
$token,
'Failed asserting that user 1 successfully shared text.txt as link with token.'
);
// testGetShareByTokenNoExpiration
$row = $this->getShareByValidToken($token);
$this->assertEmpty(
$row['expiration'],
'Failed asserting that the returned row does not have an expiration date.'
);
// testGetShareByTokenExpirationValid
$this->assertTrue(
\OCP\Share::setExpirationDate('test', 'test.txt', $this->dateInFuture, ''),
'Failed asserting that user 1 successfully set a future expiration date for the test.txt share.'
);
$row = $this->getShareByValidToken($token);
$this->assertNotEmpty(
$row['expiration'],
'Failed asserting that the returned row has an expiration date.'
);
// manipulate share table and set expire date to the past
$query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `expiration` = ? WHERE `item_type` = ? AND `item_source` = ? AND `uid_owner` = ? AND `share_type` = ?');
$query->bindValue(1, new \DateTime($this->dateInPast), 'datetime');
$query->bindValue(2, 'test');
$query->bindValue(3, 'test.txt');
$query->bindValue(4, $this->user1->getUID());
$query->bindValue(5, \OCP\Share::SHARE_TYPE_LINK);
$query->execute();
$this->assertFalse(
\OCP\Share::getShareByToken($token),
'Failed asserting that an expired share could not be found.'
);
}
public function testShareItemWithLinkAndDefaultExpireDate() {
\OC_User::setUserId($this->user1->getUID());
@ -940,59 +494,6 @@ class ShareTest extends \Test\TestCase {
\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_REMOTE, $remoteId, \OCP\Constants::PERMISSION_ALL);
}
public function testUnshareAll() {
$this->shareUserTestFileWithUser($this->user1->getUID(), $this->user2->getUID());
$this->shareUserTestFileWithUser($this->user2->getUID(), $this->user3->getUID());
$this->shareUserTestFileWithUser($this->user3->getUID(), $this->user4->getUID());
$this->shareUserOneTestFileWithGroupOne();
\OC_User::setUserId($this->user1->getUID());
$this->assertEquals(
array('test.txt', 'test.txt'),
\OCP\Share::getItemsShared('test', Backend::FORMAT_SOURCE),
'Failed asserting that the test.txt file is shared exactly two times by user1.'
);
\OC_User::setUserId($this->user2->getUID());
$this->assertEquals(
array('test.txt'),
\OCP\Share::getItemsShared('test', Backend::FORMAT_SOURCE),
'Failed asserting that the test.txt file is shared exactly once by user2.'
);
\OC_User::setUserId($this->user3->getUID());
$this->assertEquals(
array('test.txt'),
\OCP\Share::getItemsShared('test', Backend::FORMAT_SOURCE),
'Failed asserting that the test.txt file is shared exactly once by user3.'
);
$this->assertTrue(
\OCP\Share::unshareAll('test', 'test.txt'),
'Failed asserting that user 3 successfully unshared all shares of the test.txt share.'
);
$this->assertEquals(
array(),
\OCP\Share::getItemsShared('test'),
'Failed asserting that the share of the test.txt file by user 3 has been removed.'
);
\OC_User::setUserId($this->user1->getUID());
$this->assertEquals(
array(),
\OCP\Share::getItemsShared('test'),
'Failed asserting that both shares of the test.txt file by user 1 have been removed.'
);
\OC_User::setUserId($this->user2->getUID());
$this->assertEquals(
array(),
\OCP\Share::getItemsShared('test'),
'Failed asserting that the share of the test.txt file by user 2 has been removed.'
);
}
/**
* @dataProvider checkPasswordProtectedShareDataProvider
* @param $expected
@ -1165,324 +666,6 @@ class ShareTest extends \Test\TestCase {
);
}
/**
* Ensure that we do not allow removing a an expiration date from a link share if this
* is enforced by the settings.
*/
public function testClearExpireDateWhileEnforced() {
\OC_User::setUserId($this->user1->getUID());
\OC::$server->getAppConfig()->setValue('core', 'shareapi_default_expire_date', 'yes');
\OC::$server->getAppConfig()->setValue('core', 'shareapi_expire_after_n_days', '2');
\OC::$server->getAppConfig()->setValue('core', 'shareapi_enforce_expire_date', 'yes');
$token = \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ);
$this->assertInternalType(
'string',
$token,
'Failed asserting that user 1 successfully shared text.txt as link with token.'
);
$setExpireDateFailed = false;
try {
$this->assertTrue(
\OCP\Share::setExpirationDate('test', 'test.txt', '', ''),
'Failed asserting that user 1 successfully set an expiration date for the test.txt share.'
);
} catch (\Exception $e) {
$setExpireDateFailed = true;
}
$this->assertTrue($setExpireDateFailed);
\OC::$server->getAppConfig()->deleteKey('core', 'shareapi_default_expire_date');
\OC::$server->getAppConfig()->deleteKey('core', 'shareapi_expire_after_n_days');
\OC::$server->getAppConfig()->deleteKey('core', 'shareapi_enforce_expire_date');
}
/**
* Cannot set password is there is no user
*
* @expectedException \Exception
* @expectedExceptionMessage User not logged in
*/
public function testSetPasswordNoUser() {
$userSession = $this->getMockBuilder('\OCP\IUserSession')
->disableOriginalConstructor()
->getMock();
$connection = $this->getMockBuilder('\OC\DB\Connection')
->disableOriginalConstructor()
->getMock();
$config = $this->getMockBuilder('\OCP\IConfig')
->disableOriginalConstructor()
->getMock();
\OC\Share\Share::setPassword($userSession, $connection, $config, 1, 'pass');
}
public function testPasswords() {
$pass = 'secret';
$this->shareUserTestFileAsLink();
$userSession = \OC::$server->getUserSession();
$connection = \OC::$server->getDatabaseConnection();
$config = $this->getMockBuilder('\OCP\IConfig')
->disableOriginalConstructor()
->getMock();
// Find the share ID in the db
$qb = $connection->getQueryBuilder();
$qb->select('id')
->from('share')
->where($qb->expr()->eq('item_type', $qb->createParameter('type')))
->andWhere($qb->expr()->eq('item_source', $qb->createParameter('source')))
->andWhere($qb->expr()->eq('uid_owner', $qb->createParameter('owner')))
->andWhere($qb->expr()->eq('share_type', $qb->createParameter('share_type')))
->setParameter('type', 'test')
->setParameter('source', 'test.txt')
->setParameter('owner', $this->user1->getUID())
->setParameter('share_type', \OCP\Share::SHARE_TYPE_LINK);
$result = $qb->execute();
$res = $result->fetchAll();
$result->closeCursor();
$this->assertCount(1, $res);
$id = $res[0]['id'];
// Set password on share
$res = \OC\Share\Share::setPassword($userSession, $connection, $config, $id, $pass);
$this->assertTrue($res);
// Fetch the hash from the database
$qb = $connection->getQueryBuilder();
$qb->select('share_with')
->from('share')
->where($qb->expr()->eq('id', $qb->createParameter('id')))
->setParameter('id', $id);
$result = $qb->execute();
$hash = $result->fetch()['share_with'];
$result->closeCursor();
$hasher = \OC::$server->getHasher();
// Verify hash
$this->assertTrue($hasher->verify($pass, $hash));
}
/**
* Test setting a password when everything is fine
*/
public function testSetPassword() {
$user = $this->getMockBuilder('\OCP\IUser')
->disableOriginalConstructor()
->getMock();
$user->method('getUID')->willReturn('user');
$userSession = $this->getMockBuilder('\OCP\IUserSession')
->disableOriginalConstructor()
->getMock();
$userSession->method('getUser')->willReturn($user);
$ex = $this->getMockBuilder('\OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder')
->disableOriginalConstructor()
->getMock();
$qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder')
->disableOriginalConstructor()
->getMock();
$qb->method('update')->will($this->returnSelf());
$qb->method('set')->will($this->returnSelf());
$qb->method('where')->will($this->returnSelf());
$qb->method('andWhere')->will($this->returnSelf());
$qb->method('select')->will($this->returnSelf());
$qb->method('from')->will($this->returnSelf());
$qb->method('setParameter')->will($this->returnSelf());
$qb->method('expr')->willReturn($ex);
$ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement')
->disableOriginalConstructor()
->getMock();
$ret->method('fetch')->willReturn(['uid_owner' => 'user']);
$qb->method('execute')->willReturn($ret);
$connection = $this->getMockBuilder('\OC\DB\Connection')
->disableOriginalConstructor()
->getMock();
$connection->method('getQueryBuilder')->willReturn($qb);
$config = $this->getMockBuilder('\OCP\IConfig')
->disableOriginalConstructor()
->getMock();
$res = \OC\Share\Share::setPassword($userSession, $connection, $config, 1, 'pass');
$this->assertTrue($res);
}
/**
* @expectedException \Exception
* @expectedExceptionMessage Cannot remove password
*
* Test removing a password when password is enforced
*/
public function testSetPasswordRemove() {
$user = $this->getMockBuilder('\OCP\IUser')
->disableOriginalConstructor()
->getMock();
$user->method('getUID')->willReturn('user');
$userSession = $this->getMockBuilder('\OCP\IUserSession')
->disableOriginalConstructor()
->getMock();
$userSession->method('getUser')->willReturn($user);
$ex = $this->getMockBuilder('\OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder')
->disableOriginalConstructor()
->getMock();
$qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder')
->disableOriginalConstructor()
->getMock();
$qb->method('update')->will($this->returnSelf());
$qb->method('select')->will($this->returnSelf());
$qb->method('from')->will($this->returnSelf());
$qb->method('set')->will($this->returnSelf());
$qb->method('where')->will($this->returnSelf());
$qb->method('andWhere')->will($this->returnSelf());
$qb->method('setParameter')->will($this->returnSelf());
$qb->method('expr')->willReturn($ex);
$ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement')
->disableOriginalConstructor()
->getMock();
$ret->method('fetch')->willReturn(['uid_owner' => 'user']);
$qb->method('execute')->willReturn($ret);
$connection = $this->getMockBuilder('\OC\DB\Connection')
->disableOriginalConstructor()
->getMock();
$connection->method('getQueryBuilder')->willReturn($qb);
$config = $this->getMockBuilder('\OCP\IConfig')
->disableOriginalConstructor()
->getMock();
$config->method('getAppValue')->willReturn('yes');
\OC\Share\Share::setPassword($userSession, $connection, $config, 1, '');
}
/**
* @expectedException \Exception
* @expectedExceptionMessage Share not found
*
* Test modification of invaid share
*/
public function testSetPasswordInvalidShare() {
$user = $this->getMockBuilder('\OCP\IUser')
->disableOriginalConstructor()
->getMock();
$user->method('getUID')->willReturn('user');
$userSession = $this->getMockBuilder('\OCP\IUserSession')
->disableOriginalConstructor()
->getMock();
$userSession->method('getUser')->willReturn($user);
$ex = $this->getMockBuilder('\OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder')
->disableOriginalConstructor()
->getMock();
$qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder')
->disableOriginalConstructor()
->getMock();
$qb->method('update')->will($this->returnSelf());
$qb->method('set')->will($this->returnSelf());
$qb->method('where')->will($this->returnSelf());
$qb->method('andWhere')->will($this->returnSelf());
$qb->method('select')->will($this->returnSelf());
$qb->method('from')->will($this->returnSelf());
$qb->method('setParameter')->will($this->returnSelf());
$qb->method('expr')->willReturn($ex);
$ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement')
->disableOriginalConstructor()
->getMock();
$ret->method('fetch')->willReturn([]);
$qb->method('execute')->willReturn($ret);
$connection = $this->getMockBuilder('\OC\DB\Connection')
->disableOriginalConstructor()
->getMock();
$connection->method('getQueryBuilder')->willReturn($qb);
$config = $this->getMockBuilder('\OCP\IConfig')
->disableOriginalConstructor()
->getMock();
\OC\Share\Share::setPassword($userSession, $connection, $config, 1, 'pass');
}
/**
* @expectedException \Exception
* @expectedExceptionMessage Cannot update share of a different user
*
* Test modification of share of another user
*/
public function testSetPasswordShareOtherUser() {
$user = $this->getMockBuilder('\OCP\IUser')
->disableOriginalConstructor()
->getMock();
$user->method('getUID')->willReturn('user');
$userSession = $this->getMockBuilder('\OCP\IUserSession')
->disableOriginalConstructor()
->getMock();
$userSession->method('getUser')->willReturn($user);
$ex = $this->getMockBuilder('\OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder')
->disableOriginalConstructor()
->getMock();
$qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder')
->disableOriginalConstructor()
->getMock();
$qb->method('update')->will($this->returnSelf());
$qb->method('set')->will($this->returnSelf());
$qb->method('where')->will($this->returnSelf());
$qb->method('andWhere')->will($this->returnSelf());
$qb->method('select')->will($this->returnSelf());
$qb->method('from')->will($this->returnSelf());
$qb->method('setParameter')->will($this->returnSelf());
$qb->method('expr')->willReturn($ex);
$ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement')
->disableOriginalConstructor()
->getMock();
$ret->method('fetch')->willReturn(['uid_owner' => 'user2']);
$qb->method('execute')->willReturn($ret);
$connection = $this->getMockBuilder('\OC\DB\Connection')
->disableOriginalConstructor()
->getMock();
$connection->method('getQueryBuilder')->willReturn($qb);
$config = $this->getMockBuilder('\OCP\IConfig')
->disableOriginalConstructor()
->getMock();
\OC\Share\Share::setPassword($userSession, $connection, $config, 1, 'pass');
}
/**
* Make sure that a user cannot have multiple identical shares to remote users
*/
@ -1518,44 +701,6 @@ class ShareTest extends \Test\TestCase {
$this->restoreService('HTTPHelper');
}
/**
* Test case for #19119
*/
public function testReshareWithLinkDefaultExpirationDate() {
$config = \OC::$server->getConfig();
$config->setAppValue('core', 'shareapi_default_expire_date', 'yes');
$config->setAppValue('core', 'shareapi_expire_after_n_days', '2');
// Expiration date
$expireAt = time() + 2 * 24*60*60;
$date = new \DateTime();
$date->setTimestamp($expireAt);
$date->setTime(0, 0, 0);
//Share a file from user 1 to user 2
$this->shareUserTestFileWithUser($this->user1->getUID(), $this->user2->getUID());
//User 2 shares as link
\OC_User::setUserId($this->user2->getUID());
$result = \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ);
$this->assertTrue(is_string($result));
//Check if expire date is correct
$result = \OCP\Share::getItemShared('test', 'test.txt');
$this->assertCount(1, $result);
$result = reset($result);
$this->assertNotEmpty($result['expiration']);
$expireDate = new \DateTime($result['expiration']);
$this->assertEquals($date, $expireDate);
//Unshare
$this->assertTrue(\OCP\Share::unshareAll('test', 'test.txt'));
//Reset config
$config->deleteAppValue('core', 'shareapi_default_expire_date');
$config->deleteAppValue('core', 'shareapi_expire_after_n_days');
}
/**
* Test case for #17560
*/
@ -1652,31 +797,6 @@ class ShareTest extends \Test\TestCase {
$this->assertEquals('Sharing failed, because the user ' . $this->user1->getUID() . ' is the original sharer', $e->getMessage());
}
}
/**
* @expectedException \OC\User\NoUserException
* @expectedExceptionMessage Backends provided no user object
*/
public function testGetUsersSharingFileWithException() {
$userManager = $this->createMock(IUserManager::class);
$logger = $this->createMock(ILogger::class);
$userManager
->expects($this->once())
->method('get')
->with('test')
->willReturn(null);
$logger
->expects($this->once())
->method('error')
->with(
'Backends provided no user object for test',
[
'app' => 'files',
]
);
Share::getUsersSharingFile('/my/file/path', 'test', $userManager, $logger);
}
}
class DummyShareClass extends \OC\Share\Share {