/** * move file to the trash bin * * @param $file_path path to the deleted file/directory relative to the files root directory */ public static function move2trash($file_path) { $user = \OCP\User::getUser(); $view = new \OC\Files\View('/' . $user); if (!$view->is_dir('files_trashbin')) { $view->mkdir('files_trashbin'); $view->mkdir("files_trashbin/files"); $view->mkdir("files_trashbin/versions"); $view->mkdir("files_trashbin/keyfiles"); $view->mkdir("files_trashbin/share-keys"); } $path_parts = pathinfo($file_path); $filename = $path_parts['basename']; $location = $path_parts['dirname']; $timestamp = time(); $mime = $view->getMimeType('files' . $file_path); if ($view->is_dir('files' . $file_path)) { $type = 'dir'; } else { $type = 'file'; } $trashbinSize = self::getTrashbinSize($user); if ($trashbinSize === false || $trashbinSize < 0) { $trashbinSize = self::calculateSize(new \OC\Files\View('/' . $user . '/files_trashbin')); } // disable proxy to prevent recursive calls $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; $sizeOfAddedFiles = self::copy_recursive($file_path, 'files_trashbin/files/' . $filename . '.d' . $timestamp, $view); \OC_FileProxy::$enabled = $proxyStatus; if ($view->file_exists('files_trashbin/files/' . $filename . '.d' . $timestamp)) { $trashbinSize += $sizeOfAddedFiles; $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`type`,`mime`,`user`) VALUES (?,?,?,?,?,?)"); $result = $query->execute(array($filename, $timestamp, $location, $type, $mime, $user)); if (!$result) { // if file couldn't be added to the database than also don't store it in the trash bin. $view->deleteAll('files_trashbin/files/' . $filename . '.d' . $timestamp); \OC_Log::write('files_trashbin', 'trash bin database couldn\'t be updated', \OC_log::ERROR); return; } \OCP\Util::emitHook('\\OCA\\Files_Trashbin\\Trashbin', 'post_moveToTrash', array('filePath' => \OC\Files\Filesystem::normalizePath($file_path), 'trashPath' => \OC\Files\Filesystem::normalizePath($filename . '.d' . $timestamp))); $trashbinSize += self::retainVersions($view, $file_path, $filename, $timestamp); $trashbinSize += self::retainEncryptionKeys($view, $file_path, $filename, $timestamp); } else { \OC_Log::write('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OC_log::ERROR); } $trashbinSize -= self::expire($trashbinSize); self::setTrashbinSize($user, $trashbinSize); }
function testDelAllShareKeysFile() { $this->view->mkdir('/' . Test_Encryption_Keymanager::TEST_USER . '/files/folder1'); $this->view->file_put_contents('/' . Test_Encryption_Keymanager::TEST_USER . '/files/folder1/existingFile.txt', 'data'); // create folder structure for some dummy share key files $this->view->mkdir('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1'); // create some dummy share keys for the existing file $this->view->file_put_contents('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/existingFile.txt.user1.shareKey', 'data'); $this->view->file_put_contents('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/existingFile.txt.user2.shareKey', 'data'); $this->view->file_put_contents('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/existingFile.txt.user3.shareKey', 'data'); $this->view->file_put_contents('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/existingFile.txt.' . Test_Encryption_Keymanager::TEST_USER . '.shareKey', 'data'); // create some dummy share keys for a non-existing file $this->view->file_put_contents('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/nonexistingFile.txt.user1.shareKey', 'data'); $this->view->file_put_contents('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/nonexistingFile.txt.user2.shareKey', 'data'); $this->view->file_put_contents('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/nonexistingFile.txt.user3.shareKey', 'data'); $this->view->file_put_contents('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/nonexistingFile.txt.' . Test_Encryption_Keymanager::TEST_USER . '.shareKey', 'data'); // try to del all share keys from a existing file, should fail because the file still exists $result = Encryption\Keymanager::delAllShareKeys($this->view, Test_Encryption_Keymanager::TEST_USER, 'folder1/existingFile.txt'); $this->assertFalse($result); // check if share keys still exists $this->assertTrue($this->view->file_exists('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/existingFile.txt.' . Test_Encryption_Keymanager::TEST_USER . '.shareKey')); $this->assertTrue($this->view->file_exists('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/existingFile.txt.user1.shareKey')); $this->assertTrue($this->view->file_exists('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/existingFile.txt.user2.shareKey')); $this->assertTrue($this->view->file_exists('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/existingFile.txt.user3.shareKey')); // try to del all share keys froma file, should fail because the file still exists $result2 = Encryption\Keymanager::delAllShareKeys($this->view, Test_Encryption_Keymanager::TEST_USER, 'folder1/nonexistingFile.txt'); $this->assertTrue($result2); // check if share keys are really gone $this->assertFalse($this->view->file_exists('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/nonexistingFile.txt.' . Test_Encryption_Keymanager::TEST_USER . '.shareKey')); $this->assertFalse($this->view->file_exists('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/nonexistingFile.txt.user1.shareKey')); $this->assertFalse($this->view->file_exists('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/nonexistingFile.txt.user2.shareKey')); $this->assertFalse($this->view->file_exists('/' . Test_Encryption_Keymanager::TEST_USER . '/files_encryption/share-keys/folder1/nonexistingFile.txt.user3.shareKey')); // cleanup $this->view->deleteAll('/' . Test_Encryption_Keymanager::TEST_USER . '/files/folder1'); }
/** * Test clearing orphaned files */ public function testClearFiles() { $input = $this->getMockBuilder('Symfony\\Component\\Console\\Input\\InputInterface')->disableOriginalConstructor()->getMock(); $output = $this->getMockBuilder('Symfony\\Component\\Console\\Output\\OutputInterface')->disableOriginalConstructor()->getMock(); $this->loginAsUser($this->user1); $view = new \OC\Files\View('/' . $this->user1 . '/'); $view->mkdir('files/test'); $fileInfo = $view->getFileInfo('files/test'); $storageId = $fileInfo->getStorage()->getId(); $this->assertCount(1, $this->getFile($fileInfo->getId()), 'Asserts that file is available'); $this->command->execute($input, $output); $this->assertCount(1, $this->getFile($fileInfo->getId()), 'Asserts that file is still available'); $deletedRows = $this->connection->executeUpdate('DELETE FROM `*PREFIX*storages` WHERE `id` = ?', [$storageId]); $this->assertNotNull($deletedRows, 'Asserts that storage got deleted'); $this->assertSame(1, $deletedRows, 'Asserts that storage got deleted'); // parent folder, `files`, ´test` and `welcome.txt` => 4 elements $output->expects($this->once())->method('writeln')->with('4 orphaned file cache entries deleted'); $this->command->execute($input, $output); $this->assertCount(0, $this->getFile($fileInfo->getId()), 'Asserts that file gets cleaned up'); // since we deleted the storage it might throw a (valid) StorageNotAvailableException try { $view->unlink('files/test'); } catch (StorageNotAvailableException $e) { } }
/** * create unique target * @param string $filePath * @param string $shareWith * @param string $exclude * @return string */ public function generateTarget($filePath, $shareWith, $exclude = null) { $shareFolder = \OCA\Files_Sharing\Helper::getShareFolder(); $target = \OC\Files\Filesystem::normalizePath($shareFolder . '/' . basename($filePath)); // for group shares we return the target right away if ($shareWith === false) { return $target; } \OC\Files\Filesystem::initMountPoints($shareWith); $view = new \OC\Files\View('/' . $shareWith . '/files'); if (!$view->is_dir($shareFolder)) { $dir = ''; $subdirs = explode('/', $shareFolder); foreach ($subdirs as $subdir) { $dir = $dir . '/' . $subdir; if (!$view->is_dir($dir)) { $view->mkdir($dir); } } } $excludeList = \OCP\Share::getItemsSharedWithUser('file', $shareWith, self::FORMAT_TARGET_NAMES); if (is_array($exclude)) { $excludeList = array_merge($excludeList, $exclude); } return \OCA\Files_Sharing\Helper::generateUniqueTarget($target, $excludeList, $view); }
public function setUp() { //clear all proxies and hooks so we can do clean testing \OC_FileProxy::clearProxies(); \OC_Hook::clear('OC_Filesystem'); //disabled atm //enable only the encryption hook if needed //if(OC_App::isEnabled('files_encryption')) { // OC_FileProxy::register(new OC_FileProxy_Encryption()); //} //set up temporary storage \OC\Files\Filesystem::clearMounts(); $storage = new \OC\Files\Storage\Temporary(array()); \OC\Files\Filesystem::mount($storage, array(), '/'); $datadir = str_replace('local::', '', $storage->getId()); $this->datadir = \OC_Config::getValue('cachedirectory', \OC::$SERVERROOT . '/data/cache'); \OC_Config::setValue('cachedirectory', $datadir); \OC_User::clearBackends(); \OC_User::useBackend(new \OC_User_Dummy()); //login \OC_User::createUser('test', 'test'); $this->user = \OC_User::getUser(); \OC_User::setUserId('test'); //set up the users dir $rootView = new \OC\Files\View(''); $rootView->mkdir('/test'); $this->instance = new \OC\Cache\File(); }
/** * if the parent of the mount point is gone then the mount point should move up * * @medium */ function testParentOfMountPointIsGone() { // share to user $fileinfo = $this->view->getFileInfo($this->folder); $result = \OCP\Share::shareItem('folder', $fileinfo['fileid'], \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2, 31); $this->assertTrue($result); self::loginHelper(self::TEST_FILES_SHARING_API_USER2); $user2View = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files'); $this->assertTrue($user2View->file_exists($this->folder)); // create a local folder $result = $user2View->mkdir('localfolder'); $this->assertTrue($result); // move mount point to local folder $result = $user2View->rename($this->folder, '/localfolder/' . $this->folder); $this->assertTrue($result); // mount point in the root folder should no longer exist $this->assertFalse($user2View->is_dir($this->folder)); // delete the local folder $fullPath = \OC_Config::getValue('datadirectory') . '/' . self::TEST_FILES_SHARING_API_USER2 . '/files/localfolder'; rmdir($fullPath); //enforce reload of the mount points self::loginHelper(self::TEST_FILES_SHARING_API_USER2); //mount point should be back at the root $this->assertTrue($user2View->is_dir($this->folder)); //cleanup self::loginHelper(self::TEST_FILES_SHARING_API_USER1); $this->view->unlink($this->folder); }
/** * update script for the removal of the logical "Shared" folder, we create physical "Shared" folder and * update the users file_target so that it doesn't make any difference for the user * @note parameters are just for testing, please ignore them */ function removeSharedFolder($mkdirs = true, $chunkSize = 99) { $query = OCP\DB::prepare('SELECT * FROM `*PREFIX*share`'); $result = $query->execute(); $view = new \OC\Files\View('/'); $users = array(); $shares = array(); //we need to set up user backends OC_User::useBackend(new OC_User_Database()); OC_Group::useBackend(new OC_Group_Database()); OC_App::loadApps(array('authentication')); //we need to set up user backends, otherwise creating the shares will fail with "because user does not exist" while ($row = $result->fetchRow()) { //collect all user shares if ((int) $row['share_type'] === 0 && ($row['item_type'] === 'file' || $row['item_type'] === 'folder')) { $users[] = $row['share_with']; $shares[$row['id']] = $row['file_target']; } else { if ((int) $row['share_type'] === 1 && ($row['item_type'] === 'file' || $row['item_type'] === 'folder')) { //collect all group shares $users = array_merge($users, \OC_group::usersInGroup($row['share_with'])); $shares[$row['id']] = $row['file_target']; } else { if ((int) $row['share_type'] === 2) { $shares[$row['id']] = $row['file_target']; } } } } $unique_users = array_unique($users); if (!empty($unique_users) && !empty($shares)) { // create folder Shared for each user if ($mkdirs) { foreach ($unique_users as $user) { \OC\Files\Filesystem::initMountPoints($user); if (!$view->file_exists('/' . $user . '/files/Shared')) { $view->mkdir('/' . $user . '/files/Shared'); } } } $chunkedShareList = array_chunk($shares, $chunkSize, true); $connection = \OC_DB::getConnection(); foreach ($chunkedShareList as $subList) { $statement = "UPDATE `*PREFIX*share` SET `file_target` = CASE `id` "; //update share table $ids = implode(',', array_keys($subList)); foreach ($subList as $id => $target) { $statement .= "WHEN " . $connection->quote($id, \PDO::PARAM_INT) . " THEN " . $connection->quote('/Shared' . $target, \PDO::PARAM_STR); } $statement .= ' END WHERE `id` IN (' . $ids . ')'; $query = OCP\DB::prepare($statement); $query->execute(array()); } // set config to keep the Shared folder as the default location for new shares \OCA\Files_Sharing\Helper::setShareFolder('/Shared'); } }
private static function setUpTrash($user) { $view = new \OC\Files\View('/' . $user); if (!$view->is_dir('files_trashbin')) { $view->mkdir('files_trashbin'); } if (!$view->is_dir('files_trashbin/files')) { $view->mkdir('files_trashbin/files'); } if (!$view->is_dir('files_trashbin/versions')) { $view->mkdir('files_trashbin/versions'); } if (!$view->is_dir('files_trashbin/keyfiles')) { $view->mkdir('files_trashbin/keyfiles'); } if (!$view->is_dir('files_trashbin/share-keys')) { $view->mkdir('files_trashbin/share-keys'); } }
public function createVideo($title, $files, $theme) { $title = $this->cleanUpTitle($title); $xml = new XML($title, $files, $theme, $this->current_user, $this->app, $this->settings); $error = null; $result = $xml->setProducers(); if ($result) { exec('cd /home/camila/Projects/Owncloud/owncloud/apps/popcornapp/themes/ && melt6 -producer xml:' . $title . '.xml -consumer avformat:' . $title . '.ogg'); $xml_view = new \OC\Files\View('/' . $this->current_user . '/files'); $xml_view->mkdir('popcornapp'); $content = fopen('/home/camila/Projects/Owncloud/owncloud/apps/popcornapp/themes/' . $title . '.ogg', 'r+'); $xml_view->file_put_contents('/popcornapp/' . $title . '.ogg', $content); } else { $error = 'Something went wrong! We all are going to die!'; } return new DataResponse(['src' => $title . '.ogg', 'error' => $error]); }
protected function getStorage() { if (isset($this->storage)) { return $this->storage; } if (\OC_User::isLoggedIn()) { \OC\Files\Filesystem::initMountPoints(\OC_User::getUser()); $subdir = 'cache'; $view = new \OC\Files\View('/' . \OC_User::getUser()); if (!$view->file_exists($subdir)) { $view->mkdir($subdir); } $this->storage = new \OC\Files\View('/' . \OC_User::getUser() . '/' . $subdir); return $this->storage; } else { \OC_Log::write('core', 'Can\'t get cache storage, user not logged in', \OC_Log::ERROR); return false; } }
/** * test deletion of a folder which contains share mount points. Share mount * points should be unshared before the folder gets deleted so * that the mount point doesn't end up at the trash bin */ function testDeleteParentFolder() { $status = \OC_App::isEnabled('files_trashbin'); \OC_App::enable('files_trashbin'); \OCA\Files_Trashbin\Trashbin::registerHooks(); OC_FileProxy::register(new OCA\Files\Share\Proxy()); $fileinfo = \OC\Files\Filesystem::getFileInfo($this->folder); $this->assertTrue($fileinfo instanceof \OC\Files\FileInfo); \OCP\Share::shareItem('folder', $fileinfo->getId(), \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2, 31); $this->loginHelper(self::TEST_FILES_SHARING_API_USER2); $view = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files'); // check if user2 can see the shared folder $this->assertTrue($view->file_exists($this->folder)); $foldersShared = \OCP\Share::getItemsSharedWith('folder'); $this->assertSame(1, count($foldersShared)); $view->mkdir("localFolder"); $view->file_put_contents("localFolder/localFile.txt", "local file"); $view->rename($this->folder, 'localFolder/' . $this->folder); // share mount point should now be moved to the subfolder $this->assertFalse($view->file_exists($this->folder)); $this->assertTrue($view->file_exists('localFolder/' . $this->folder)); $view->unlink('localFolder'); $this->loginHelper(self::TEST_FILES_SHARING_API_USER2); // shared folder should be unshared $foldersShared = \OCP\Share::getItemsSharedWith('folder'); $this->assertTrue(empty($foldersShared)); // trashbin should contain the local file but not the mount point $rootView = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2); $trashContent = \OCA\Files_Trashbin\Helper::getTrashFiles('/', self::TEST_FILES_SHARING_API_USER2); $this->assertSame(1, count($trashContent)); $firstElement = reset($trashContent); $timestamp = $firstElement['mtime']; $this->assertTrue($rootView->file_exists('files_trashbin/files/localFolder.d' . $timestamp . '/localFile.txt')); $this->assertFalse($rootView->file_exists('files_trashbin/files/localFolder.d' . $timestamp . '/' . $this->folder)); //cleanup $rootView->deleteAll('files_trashin'); if ($status === false) { \OC_App::disable('files_trashbin'); } \OC\Files\Filesystem::getLoader()->removeStorageWrapper('oc_trashbin'); }
protected function setUp() { parent::setUp(); //clear all proxies and hooks so we can do clean testing \OC_Hook::clear('OC_Filesystem'); //set up temporary storage $this->storage = \OC\Files\Filesystem::getStorage('/'); \OC\Files\Filesystem::clearMounts(); $storage = new \OC\Files\Storage\Temporary(array()); \OC\Files\Filesystem::mount($storage, array(), '/'); $datadir = str_replace('local::', '', $storage->getId()); $this->datadir = \OC_Config::getValue('cachedirectory', \OC::$SERVERROOT . '/data/cache'); \OC_Config::setValue('cachedirectory', $datadir); \OC_User::clearBackends(); \OC_User::useBackend(new \OC_User_Dummy()); //login \OC_User::createUser('test', 'test'); $this->user = \OC_User::getUser(); \OC_User::setUserId('test'); //set up the users dir $rootView = new \OC\Files\View(''); $rootView->mkdir('/test'); $this->instance = new \OC\Cache\UserCache(); }
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; } }
/** * store private key from the user * @param string $key * @return bool * @note Encryption of the private key must be performed by client code * as no encryption takes place here */ public static function setPrivateKey($key) { $user = \OCP\User::getUser(); $view = new \OC\Files\View('/' . $user . '/files_encryption'); $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; if (!$view->file_exists('')) { $view->mkdir(''); } $result = $view->file_put_contents($user . '.private.key', $key); \OC_FileProxy::$enabled = $proxyStatus; return $result; }
/** * @medium */ public function testDeleteParentOfMountPoint() { // share to user $share = $this->share(\OCP\Share::SHARE_TYPE_USER, $this->folder, self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2, \OCP\Constants::PERMISSION_ALL); self::loginHelper(self::TEST_FILES_SHARING_API_USER2); $user2View = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files'); $this->assertTrue($user2View->file_exists($this->folder)); // create a local folder $result = $user2View->mkdir('localfolder'); $this->assertTrue($result); // move mount point to local folder $result = $user2View->rename($this->folder, '/localfolder/' . $this->folder); $this->assertTrue($result); // mount point in the root folder should no longer exist $this->assertFalse($user2View->is_dir($this->folder)); // delete the local folder $result = $user2View->unlink('/localfolder'); $this->assertTrue($result); //enforce reload of the mount points self::loginHelper(self::TEST_FILES_SHARING_API_USER2); //mount point should be back at the root $this->assertTrue($user2View->is_dir($this->folder)); //cleanup self::loginHelper(self::TEST_FILES_SHARING_API_USER1); $this->view->unlink($this->folder); }
public function testSharingAFileInsideAFolderThatIsAlreadyShared() { OC_User::setUserId($this->user1); $view = new \OC\Files\View('/' . $this->user1 . '/'); $view->mkdir('files/test'); $view->mkdir('files/test/sub1'); $view->file_put_contents('files/test/sub1/file.txt', 'abc'); $folderInfo = $view->getFileInfo('files/test/sub1'); $folderId = $folderInfo->getId(); $fileInfo = $view->getFileInfo('files/test/sub1/file.txt'); $fileId = $fileInfo->getId(); $this->assertTrue(OCP\Share::shareItem('folder', $folderId, OCP\Share::SHARE_TYPE_GROUP, $this->group2, \OCP\Constants::PERMISSION_READ + \OCP\Constants::PERMISSION_UPDATE), 'Failed asserting that user 1 successfully shared "test/sub1" with group 2.'); $this->assertTrue(OCP\Share::shareItem('file', $fileId, OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ), 'Failed asserting that user 1 successfully shared "test/sub1/file.txt" with user 2.'); $result = \OCP\Share::getItemsSharedWithUser('file', $this->user2); $this->assertCount(2, $result); foreach ($result as $share) { $itemName = substr($share['path'], strrpos($share['path'], '/')); $this->assertSame($itemName, $share['file_target'], 'Asserting that the file_target is the last segment of the path'); $this->assertSame($share['item_target'], '/' . $share['item_source'], 'Asserting that the item is the item that was shared'); } }
/** * write private system key (recovery and public share key) to disk * * @param string $key encrypted key * @param string $keyName name of the key file * @return boolean */ public static function setPrivateSystemKey($key, $keyName) { $header = Crypt::generateHeader(); $view = new \OC\Files\View('/owncloud_private_key'); $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; if (!$view->file_exists('')) { $view->mkdir(''); } $result = $view->file_put_contents($keyName, $header . $key); \OC_FileProxy::$enabled = $proxyStatus; return $result; }
public function testHooks() { if (\OC\Files\Filesystem::getView()) { $user = \OC_User::getUser(); } else { $user = self::TEST_FILESYSTEM_USER1; $backend = new \Test\Util\User\Dummy(); \OC_User::useBackend($backend); $backend->createUser($user, $user); $userObj = \OC::$server->getUserManager()->get($user); \OC::$server->getUserSession()->setUser($userObj); \OC\Files\Filesystem::init($user, '/' . $user . '/files'); } \OC_Hook::clear('OC_Filesystem'); \OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook'); \OC\Files\Filesystem::mount('OC\\Files\\Storage\\Temporary', array(), '/'); $rootView = new \OC\Files\View(''); $rootView->mkdir('/' . $user); $rootView->mkdir('/' . $user . '/files'); // \OC\Files\Filesystem::file_put_contents('/foo', 'foo'); \OC\Files\Filesystem::mkdir('/bar'); // \OC\Files\Filesystem::file_put_contents('/bar//foo', 'foo'); $tmpFile = \OC::$server->getTempManager()->getTemporaryFile(); file_put_contents($tmpFile, 'foo'); $fh = fopen($tmpFile, 'r'); // \OC\Files\Filesystem::file_put_contents('/bar//foo', $fh); }
public function testDoNotExpireOtherShares() { $this->loginAsUser($this->user1); $view = new \OC\Files\View('/' . $this->user1 . '/'); $view->mkdir('files/test'); $fileInfo = $view->getFileInfo('files/test'); $this->assertNotNull(\OCP\Share::shareItem('folder', $fileInfo->getId(), \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ), 'Failed asserting that user 1 successfully shared "test" by link with user2.'); $shares = $this->getShares(); $this->assertCount(1, $shares); reset($shares); $share = current($shares); $this->logout(); $this->job->run([]); $shares = $this->getShares(); $this->assertCount(1, $shares); }
/** * share a folder which contains a share mount point, should be forbidden */ public function testShareFolderWithAMountPoint() { // user 1 shares a folder with user2 \Test_Files_Sharing_Api::loginHelper(\Test_Files_Sharing_Api::TEST_FILES_SHARING_API_USER1); $fileInfo = $this->view->getFileInfo($this->folder); $result = \OCP\Share::shareItem('folder', $fileInfo['fileid'], \OCP\Share::SHARE_TYPE_USER, \Test_Files_Sharing_Api::TEST_FILES_SHARING_API_USER2, 31); $this->assertTrue($result); // user2 shares a file from the folder as link \Test_Files_Sharing_Api::loginHelper(\Test_Files_Sharing_Api::TEST_FILES_SHARING_API_USER2); $view = new \OC\Files\View('/' . \Test_Files_Sharing_Api::TEST_FILES_SHARING_API_USER2 . '/files'); $view->mkdir("localDir"); // move mount point to the folder "localDir" $result = $view->rename($this->folder, 'localDir/' . $this->folder); $this->assertTrue($result !== false); // try to share "localDir" $fileInfo2 = $view->getFileInfo('localDir'); $this->assertTrue($fileInfo2 instanceof \OC\Files\FileInfo); try { $result2 = \OCP\Share::shareItem('folder', $fileInfo2['fileid'], \OCP\Share::SHARE_TYPE_USER, \Test_Files_Sharing_Api::TEST_FILES_SHARING_API_USER3, 31); } catch (\Exception $e) { $result2 = false; } $this->assertFalse($result2); //cleanup $result = $view->rename('localDir/' . $this->folder, $this->folder); $this->assertTrue($result !== false); $view->unlink('localDir'); \Test_Files_Sharing_Api::loginHelper(\Test_Files_Sharing_Api::TEST_FILES_SHARING_API_USER1); \OCP\Share::unshare('folder', $fileInfo['fileid'], \OCP\Share::SHARE_TYPE_USER, \Test_Files_Sharing_Api::TEST_FILES_SHARING_API_USER2); }
/** * share a folder which contains a share mount point, should be forbidden */ public function testShareFolderWithAMountPoint() { // user 1 shares a folder with user2 \Test_Files_Sharing_Api::loginHelper(\Test_Files_Sharing_Api::TEST_FILES_SHARING_API_USER1); $fileInfo = $this->view->getFileInfo($this->folder); $share = $this->share(\OCP\Share::SHARE_TYPE_USER, $this->folder, self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2, \OCP\Constants::PERMISSION_ALL); // user2 shares a file from the folder as link \Test_Files_Sharing_Api::loginHelper(\Test_Files_Sharing_Api::TEST_FILES_SHARING_API_USER2); $view = new \OC\Files\View('/' . \Test_Files_Sharing_Api::TEST_FILES_SHARING_API_USER2 . '/files'); $view->mkdir("localDir"); // move mount point to the folder "localDir" $result = $view->rename($this->folder, 'localDir/' . $this->folder); $this->assertTrue($result !== false); // try to share "localDir" $fileInfo2 = $view->getFileInfo('localDir'); $this->assertTrue($fileInfo2 instanceof \OC\Files\FileInfo); $pass = true; try { $this->share(\OCP\Share::SHARE_TYPE_USER, 'localDir', self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_USER3, \OCP\Constants::PERMISSION_ALL); } catch (\Exception $e) { $pass = false; } $this->assertFalse($pass); //cleanup $result = $view->rename('localDir/' . $this->folder, $this->folder); $this->assertTrue($result !== false); $view->unlink('localDir'); \Test_Files_Sharing_Api::loginHelper(\Test_Files_Sharing_Api::TEST_FILES_SHARING_API_USER1); $this->shareManager->deleteShare($share); }
public function testShareWithOwnerError() { \OC_User::setUserId($this->user1); $view = new \OC\Files\View('/' . $this->user1 . '/'); $view->mkdir('files/folder1'); $fileInfo = $view->getFileInfo('files/folder1'); $this->assertInstanceOf('\\OC\\Files\\FileInfo', $fileInfo); $fileId = $fileInfo->getId(); $this->assertTrue(\OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_ALL), 'Failed asserting that user 1 successfully shared "test" with user 2.'); \OC_User::setUserId($this->user2); try { \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user1, \OCP\Constants::PERMISSION_ALL); $this->fail(); } catch (\Exception $e) { $this->assertEquals('Sharing failed, because the user ' . $this->user1 . ' is the original sharer', $e->getMessage()); } }
/** * @medium */ function testMoveFolder() { $view = new \OC\Files\View('/' . $this->userId . '/files'); $filename = '/tmp-' . uniqid(); $folder = '/folder' . uniqid(); $view->mkdir($folder); // Save long data as encrypted file using stream wrapper $cryptedFile = file_put_contents('crypt:///' . $this->userId . '/files/' . $folder . $filename, $this->dataLong); // Test that data was successfully written $this->assertTrue(is_int($cryptedFile)); // Get file decrypted contents $decrypt = file_get_contents('crypt:///' . $this->userId . '/files/' . $folder . $filename); $this->assertEquals($this->dataLong, $decrypt); $newFolder = '/newfolder/subfolder' . uniqid(); $view->mkdir('/newfolder'); $view->rename($folder, $newFolder); // Get file decrypted contents $newDecrypt = file_get_contents('crypt:///' . $this->userId . '/files/' . $newFolder . $filename); $this->assertEquals($this->dataLong, $newDecrypt); // tear down $view->unlink($newFolder); $view->unlink('/newfolder'); }
/** * Tests whether share keys can be found * * @dataProvider userNamesProvider */ function testFindShareKeys($userName) { self::setUpUsers(); // note: not using dataProvider as we want to make // sure that the correct keys are match and not any // other ones that might happen to have similar names self::setupHooks(); self::loginHelper($userName, true); $testDir = 'testFindShareKeys' . $this->getUniqueID() . '/'; $baseDir = $userName . '/files/' . $testDir; $fileList = array('t est.txt', 't est_.txt', 't est.doc.txt', 't est(.*).txt', 'multiple.dots.can.happen.too.txt', 't est.' . $userName . '.txt', 't est_.' . $userName . '.shareKey.txt', 'who would upload their.shareKey', 'user ones file.txt', 'user ones file.txt.backup', '.t est.txt'); $rootView = new \OC\Files\View('/'); $rootView->mkdir($baseDir); foreach ($fileList as $fileName) { $rootView->file_put_contents($baseDir . $fileName, 'dummy'); } $shareKeysDir = $userName . '/files_encryption/share-keys/' . $testDir; foreach ($fileList as $fileName) { // make sure that every file only gets its correct respective keys $result = Encryption\Helper::findShareKeys($baseDir . $fileName, $shareKeysDir . $fileName, $rootView); $this->assertEquals(array($shareKeysDir . $fileName . '.' . $userName . '.shareKey'), $result); } self::cleanUpUsers(); }
/** * Test locks when moving a mount point */ public function testLockMoveMountPoint() { $this->loginAsUser('test'); list($mount) = $this->createTestMovableMountPoints([$this->user . '/files/substorage']); $view = new \OC\Files\View('/' . $this->user . '/files/'); $view->mkdir('subdir'); $sourcePath = 'substorage'; $targetPath = 'subdir/substorage_moved'; $mount->expects($this->once())->method('moveMount')->will($this->returnCallback(function ($target) use($mount, $view, $sourcePath, $targetPath, &$lockTypeSourceDuring, &$lockTypeTargetDuring, &$lockTypeSharedRootDuring) { $lockTypeSourceDuring = $this->getFileLockType($view, $sourcePath, true); $lockTypeTargetDuring = $this->getFileLockType($view, $targetPath, true); $lockTypeSharedRootDuring = $this->getFileLockType($view, $sourcePath, false); $mount->setMountPoint($target); return true; })); $this->connectMockHooks('rename', $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost, true); $this->connectMockHooks('rename', $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost, true); // in pre-hook, mount point is still on $sourcePath $this->connectMockHooks('rename', $view, $sourcePath, $lockTypeSharedRootPre, $dummy, false); // in post-hook, mount point is now on $targetPath $this->connectMockHooks('rename', $view, $targetPath, $dummy, $lockTypeSharedRootPost, false); $this->assertNull($this->getFileLockType($view, $sourcePath, false), 'Shared storage root not locked before operation'); $this->assertNull($this->getFileLockType($view, $sourcePath, true), 'Source path not locked before operation'); $this->assertNull($this->getFileLockType($view, $targetPath, true), 'Target path not locked before operation'); $view->rename($sourcePath, $targetPath); $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePre, 'Source path locked properly during pre-hook'); $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeSourceDuring, 'Source path locked properly during operation'); $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePost, 'Source path locked properly during post-hook'); $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPre, 'Target path locked properly during pre-hook'); $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeTargetDuring, 'Target path locked properly during operation'); $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPost, 'Target path locked properly during post-hook'); $this->assertNull($lockTypeSharedRootPre, 'Shared storage root not locked during pre-hook'); $this->assertNull($lockTypeSharedRootDuring, 'Shared storage root not locked during move'); $this->assertNull($lockTypeSharedRootPost, 'Shared storage root not locked during post-hook'); $this->assertNull($this->getFileLockType($view, $sourcePath, false), 'Shared storage root not locked after operation'); $this->assertNull($this->getFileLockType($view, $sourcePath, true), 'Source path not locked after operation'); $this->assertNull($this->getFileLockType($view, $targetPath, true), 'Target path not locked after operation'); }
public function testSharingAFolderThatIsSharedWithAGroupOfTheOwner() { OC_User::setUserId($this->user1); $view = new \OC\Files\View('/' . $this->user1 . '/'); $view->mkdir('files/test'); $view->mkdir('files/test/sub1'); $view->mkdir('files/test/sub1/sub2'); $fileInfo = $view->getFileInfo('files/test/sub1'); $fileId = $fileInfo->getId(); $this->assertTrue(OCP\Share::shareItem('folder', $fileId, OCP\Share::SHARE_TYPE_GROUP, $this->group1, \OCP\Constants::PERMISSION_READ + \OCP\Constants::PERMISSION_CREATE), 'Failed asserting that user 1 successfully shared "test/sub1" with group 1.'); $result = OCP\Share::getItemShared('folder', $fileId, Test_Share_Backend::FORMAT_SOURCE); $this->assertNotEmpty($result); $this->assertEquals(\OCP\Constants::PERMISSION_READ + \OCP\Constants::PERMISSION_CREATE, $result['permissions']); $fileInfo = $view->getFileInfo('files/test/sub1/sub2'); $fileId = $fileInfo->getId(); $this->assertTrue(OCP\Share::shareItem('folder', $fileId, OCP\Share::SHARE_TYPE_USER, $this->user4, \OCP\Constants::PERMISSION_READ), 'Failed asserting that user 1 successfully shared "test/sub1/sub2" with user 4.'); $result = OCP\Share::getItemShared('folder', $fileId, Test_Share_Backend::FORMAT_SOURCE); $this->assertNotEmpty($result); $this->assertEquals(\OCP\Constants::PERMISSION_READ, $result['permissions']); }
/** * @param string $appId * @return \OC\Files\View */ public static function getStorage($appId) { if (OC_App::isEnabled($appId)) { //sanity check if (OC_User::isLoggedIn()) { $view = new \OC\Files\View('/' . OC_User::getUser()); if (!$view->file_exists($appId)) { $view->mkdir($appId); } return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId); } else { OC_Log::write('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', OC_Log::ERROR); return false; } } else { OC_Log::write('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', OC_Log::ERROR); return false; } }
/** * Mounts the cache directory * @param string $user user name */ private static function mountCacheDir($user) { $cacheBaseDir = \OC_Config::getValue('cache_path', ''); if ($cacheBaseDir === '') { // use local cache dir relative to the user's home $subdir = 'cache'; $view = new \OC\Files\View('/' . $user); if (!$view->file_exists($subdir)) { $view->mkdir($subdir); } } else { $cacheDir = rtrim($cacheBaseDir, '/') . '/' . $user; if (!file_exists($cacheDir)) { mkdir($cacheDir, 0770, true); } // mount external cache dir to "/$user/cache" mount point self::mount('\\OC\\Files\\Storage\\Local', array('datadir' => $cacheDir), '/' . $user . '/cache'); } }
public function xtestLongPath() { $storage = new \OC\Files\Storage\Temporary(array()); \OC\Files\Filesystem::mount($storage, array(), '/'); $rootView = new \OC\Files\View(''); $longPath = ''; $ds = DIRECTORY_SEPARATOR; /* * 4096 is the maximum path length in file_cache.path in *nix * 1024 is the max path length in mac * 228 is the max path length in windows */ $folderName = 'abcdefghijklmnopqrstuvwxyz012345678901234567890123456789'; $tmpdirLength = strlen(\OC_Helper::tmpFolder()); if (\OC_Util::runningOnWindows()) { $this->markTestSkipped('[Windows] '); $depth = (260 - $tmpdirLength) / 57; } elseif (\OC_Util::runningOnMac()) { $depth = (1024 - $tmpdirLength) / 57; } else { $depth = (4000 - $tmpdirLength) / 57; } foreach (range(0, $depth - 1) as $i) { $longPath .= $ds . $folderName; $result = $rootView->mkdir($longPath); $this->assertTrue($result, "mkdir failed on {$i} - path length: " . strlen($longPath)); $result = $rootView->file_put_contents($longPath . "{$ds}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 . "{$ds}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 .= $ds . $folderName; } }
/** * @brief enable recovery * * @param $recoveryKeyId * @param $recoveryPassword * @internal param \OCA\Encryption\Util $util * @internal param string $password * @return bool */ public static function adminEnableRecovery($recoveryKeyId, $recoveryPassword) { $view = new \OC\Files\View('/'); if ($recoveryKeyId === null) { $recoveryKeyId = 'recovery_' . substr(md5(time()), 0, 8); \OC_Appconfig::setValue('files_encryption', 'recoveryKeyId', $recoveryKeyId); } if (!$view->is_dir('/owncloud_private_key')) { $view->mkdir('/owncloud_private_key'); } if (!$view->file_exists("/public-keys/" . $recoveryKeyId . ".public.key") || !$view->file_exists("/owncloud_private_key/" . $recoveryKeyId . ".private.key")) { $keypair = \OCA\Encryption\Crypt::createKeypair(); \OC_FileProxy::$enabled = false; // Save public key if (!$view->is_dir('/public-keys')) { $view->mkdir('/public-keys'); } $view->file_put_contents('/public-keys/' . $recoveryKeyId . '.public.key', $keypair['publicKey']); // Encrypt private key empty passphrase $encryptedPrivateKey = \OCA\Encryption\Crypt::symmetricEncryptFileContent($keypair['privateKey'], $recoveryPassword); // Save private key $view->file_put_contents('/owncloud_private_key/' . $recoveryKeyId . '.private.key', $encryptedPrivateKey); \OC_FileProxy::$enabled = true; // Set recoveryAdmin as enabled \OC_Appconfig::setValue('files_encryption', 'recoveryAdminEnabled', 1); $return = true; } else { // get recovery key and check the password $util = new \OCA\Encryption\Util(new \OC_FilesystemView('/'), \OCP\User::getUser()); $return = $util->checkRecoveryPassword($recoveryPassword); if ($return) { \OC_Appconfig::setValue('files_encryption', 'recoveryAdminEnabled', 1); } } return $return; }