/** * Get the template for a specific activity-event in the activities * * @param array $activity An array with all the activity data in it * @param return string */ public static function show($activity) { $tmpl = new \OCP\Template('activity', 'activity.box'); $tmpl->assign('formattedDate', \OCP\Util::formatDate($activity['timestamp'])); $tmpl->assign('formattedTimestamp', \OCP\relative_modified_date($activity['timestamp'])); $tmpl->assign('user', $activity['user']); $tmpl->assign('displayName', \OCP\User::getDisplayName($activity['user'])); if ($activity['app'] === 'files') { // We do not link the subject as we create links for the parameters instead $activity['link'] = ''; } $tmpl->assign('event', $activity); if ($activity['file']) { $rootView = new \OC\Files\View(''); $exist = $rootView->file_exists('/' . $activity['user'] . '/files' . $activity['file']); $is_dir = $rootView->is_dir('/' . $activity['user'] . '/files' . $activity['file']); unset($rootView); // show a preview image if the file still exists if (!$is_dir && $exist) { $tmpl->assign('previewLink', \OCP\Util::linkTo('files', 'index.php', array('dir' => dirname($activity['file'])))); $tmpl->assign('previewImageLink', \OCP\Util::linkToRoute('core_ajax_preview', array('file' => $activity['file'], 'x' => 150, 'y' => 150))); } else { if ($exist) { $tmpl->assign('previewLink', \OCP\Util::linkTo('files', 'index.php', array('dir' => $activity['file']))); $tmpl->assign('previewImageLink', \OC_Helper::mimetypeIcon('dir')); $tmpl->assign('previewLinkIsDir', true); } } } return $tmpl->fetchPage(); }
/** * 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); }
/** * Background scanner main job * @return null */ public function run() { if (!$this->initFS()) { return; } // locate files that are not checked yet $dirMimeTypeId = \OC::$server->getMimeTypeLoader()->getId('httpd/unix-directory'); try { $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder(); $qb->select(['fc.fileid'])->from('filecache', 'fc')->leftJoin('fc', 'files_antivirus', 'fa', $qb->expr()->eq('fa.fileid', 'fc.fileid'))->innerJoin('fc', 'storages', 'ss', $qb->expr()->andX($qb->expr()->eq('fc.storage', 'ss.numeric_id'), $qb->expr()->orX($qb->expr()->like('ss.id', $qb->expr()->literal('local::%')), $qb->expr()->like('ss.id', $qb->expr()->literal('home::%')))))->where($qb->expr()->neq('fc.mimetype', $qb->expr()->literal($dirMimeTypeId)))->andWhere($qb->expr()->orX($qb->expr()->isNull('fa.fileid'), $qb->expr()->gt('fc.mtime', 'fa.check_time')))->andWhere($qb->expr()->like('fc.path', $qb->expr()->literal('files/%')))->andWhere($qb->expr()->neq('fc.size', '0'))->setMaxResults(5); $result = $qb->execute(); } catch (\Exception $e) { \OC::$server->getLogger()->error(__METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']); return; } $view = new \OC\Files\View(''); try { while ($row = $result->fetch()) { $path = $view->getPath($row['fileid']); if (!is_null($path)) { $item = new Item($this->l10n, $view, $path, $row['fileid']); $scanner = $this->scannerFactory->getScanner(); $status = $scanner->scan($item); $status->dispatch($item, true); } } } catch (\Exception $e) { \OC::$server->getLogger()->error(__METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']); } \OC_Util::tearDownFS(); }
/** * @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); }
/** * @medium */ function testDeleteParentOfMountPoint() { // 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 $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); }
/** * 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) { } }
/** * Background scanner main job * @return null */ public function run() { if (!$this->initFS()) { return; } // locate files that are not checked yet $dirMimetypeId = \OC::$server->getMimeTypeLoader()->getId('httpd/unix-directory'); $sql = 'SELECT `*PREFIX*filecache`.`fileid`, `*PREFIX*storages`.*' . ' FROM `*PREFIX*filecache`' . ' LEFT JOIN `*PREFIX*files_antivirus` ON `*PREFIX*files_antivirus`.`fileid` = `*PREFIX*filecache`.`fileid`' . ' JOIN `*PREFIX*storages` ON `*PREFIX*storages`.`numeric_id` = `*PREFIX*filecache`.`storage`' . ' WHERE `mimetype` != ?' . ' AND (`*PREFIX*storages`.`id` LIKE ? OR `*PREFIX*storages`.`id` LIKE ?)' . ' AND (`*PREFIX*files_antivirus`.`fileid` IS NULL OR `mtime` > `check_time`)' . ' AND `path` LIKE ?'; $stmt = \OCP\DB::prepare($sql, 5); try { $result = $stmt->execute(array($dirMimetypeId, 'local::%', 'home::%', 'files/%')); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('files_antivirus', __METHOD__ . 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR); return; } } catch (\Exception $e) { \OCP\Util::writeLog('files_antivirus', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); return; } $view = new \OC\Files\View('/'); while ($row = $result->fetchRow()) { $path = $view->getPath($row['fileid']); if (!is_null($path)) { $item = new Item($this->l10n, $view, $path, $row['fileid']); $scanner = $this->scannerFactory->getScanner(); $status = $scanner->scan($item); $status->dispatch($item, true); } } \OC_Util::tearDownFS(); }
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(); }
public function generateFileToken($fileId, $version) { // Get the FS view of the current user. $view = \OC\Files\Filesystem::getView(); // Get the virtual path (if the file is shared). $path = $view->getPath($fileId); if (!$view->is_file($path) || !$view->isUpdatable($path)) { throw new \Exception('Invalid fileId.'); } // Figure out the real owner, if not us. $owner = $view->getOwner($path); // Create a view into the owner's FS. $view = new \OC\Files\View('/' . $owner . '/files'); // Find the real path. $path = $view->getPath($fileId); if (!$view->is_file($path)) { throw new \Exception('Invalid fileId.'); } $editor = \OC::$server->getUserSession()->getUser()->getUID(); $token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(32, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER . \OCP\Security\ISecureRandom::CHAR_DIGITS); \OC::$server->getLogger()->debug('Issuing token for {editor} file {fileId}, version {version} owned by {owner}, path {path}: {token}', ['owner' => $owner, 'editor' => $editor, 'fileId' => $fileId, 'version' => $version, 'path' => $path, 'token' => $token]); $wopi = new \OCA\Richdocuments\Db\Wopi([$owner, $editor, $fileId, $version, $path, $token, time() + self::TOKEN_LIFETIME_SECONDS]); if (!$wopi->insert()) { throw new \Exception('Failed to add wopi token into database'); } return $token; }
public static function tearDownAfterClass() { \OC_Hook::clear(); \OC_FileProxy::clearProxies(); // Delete keys in /data/ $view = new \OC\Files\View('/'); $view->deleteAll('files_encryption'); parent::tearDownAfterClass(); }
/** * 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'); } }
public static function tearDownAfterClass() { // cleanup test user \OC_User::deleteUser(\Test_Encryption_Proxy::TEST_ENCRYPTION_PROXY_USER1); \OC_Hook::clear(); \OC_FileProxy::clearProxies(); // Delete keys in /data/ $view = new \OC\Files\View('/'); $view->rmdir('public-keys'); $view->rmdir('owncloud_private_key'); }
/** * Act on behalf on trash item owner * @param string $user * @return boolean */ protected function setupFS($user) { \OC_Util::tearDownFS(); \OC_Util::setupFS($user); // Check if this user has a versions directory $view = new \OC\Files\View('/' . $user); if (!$view->is_dir('/files_versions')) { return false; } return true; }
/** * @param array $share Share with info from the share_external table * @return enriched share info with data from the filecache */ private static function extendShareInfo($share) { $view = new \OC\Files\View('/' . \OC_User::getUser() . '/files/'); $info = $view->getFileInfo($share['mountpoint']); $share['mimetype'] = $info->getMimetype(); $share['mtime'] = $info->getMtime(); $share['permissions'] = $info->getPermissions(); $share['type'] = $info->getType(); $share['file_id'] = $info->getId(); return $share; }
/** * unshare shared items below the deleted folder * * @param string $path */ private function unshareChildren($path) { $view = new \OC\Files\View('/'); // find share mount points within $path and unmount them $mountManager = \OC\Files\Filesystem::getMountManager(); $mountedShares = $mountManager->findIn($path); foreach ($mountedShares as $mount) { if ($mount->getStorage()->instanceOfStorage('OCA\\Files_Sharing\\ISharedStorage')) { $mountPoint = $mount->getMountPoint(); $view->unlink($mountPoint); } } }
/** * index a file * * @author Jörn Dreyer <*****@*****.**> * * @param string $path the path of the file * * @return bool */ public static function indexFile($path = '', $user = null) { if (!Filesystem::isValidPath($path)) { return; } if ($path === '') { //ignore the empty path element return false; } if (is_null($user)) { $view = Filesystem::getView(); $user = \OCP\User::getUser(); } else { $view = new \OC\Files\View('/' . $user . '/files'); } if (!$view) { Util::writeLog('search_lucene', 'could not resolve filesystem view', Util::WARN); return false; } $root = $view->getRoot(); $pk = md5($root . $path); // the cache already knows mime and other basic stuff $data = $view->getFileInfo($path); if (isset($data['mimetype'])) { $mimetype = $data['mimetype']; if ('text/html' === $mimetype) { $doc = \Zend_Search_Lucene_Document_Html::loadHTML($view->file_get_contents($path)); } else { if ('application/msword' === $mimetype) { // FIXME uses ZipArchive ... make compatible with OC\Files\Filesystem //$doc = Zend_Search_Lucene_Document_Docx::loadDocxFile(OC\Files\Filesystem::file_get_contents($path)); //no special treatment yet $doc = new \Zend_Search_Lucene_Document(); } else { $doc = new \Zend_Search_Lucene_Document(); } } // store fscacheid as unique id to lookup by when deleting $doc->addField(\Zend_Search_Lucene_Field::Keyword('pk', $pk)); // Store document URL to identify it in the search results $doc->addField(\Zend_Search_Lucene_Field::Text('path', $path)); $doc->addField(\Zend_Search_Lucene_Field::unIndexed('size', $data['size'])); $doc->addField(\Zend_Search_Lucene_Field::unIndexed('mimetype', $mimetype)); self::extractMetadata($doc, $path, $view, $mimetype); Lucene::updateFile($doc, $path, $user); return true; } else { Util::writeLog('search_lucene', 'need mimetype for content extraction', Util::ERROR); return false; } }
/** * Retrieves the contents of a trash bin directory. * * @param string $dir path to the directory inside the trashbin * or empty to retrieve the root of the trashbin * @param string $user * @param string $sortAttribute attribute to sort on or empty to disable sorting * @param bool $sortDescending true for descending sort, false otherwise * @return \OCP\Files\FileInfo[] */ public static function getTrashFiles($dir, $user, $sortAttribute = '', $sortDescending = false) { $result = array(); $timestamp = null; $view = new \OC\Files\View('/' . $user . '/files_trashbin/files'); if (ltrim($dir, '/') !== '' && !$view->is_dir($dir)) { throw new \Exception('Directory does not exists'); } $dirContent = $view->opendir($dir); if ($dirContent === false) { return $result; } $mount = $view->getMount($dir); $storage = $mount->getStorage(); $absoluteDir = $view->getAbsolutePath($dir); $internalPath = $mount->getInternalPath($absoluteDir); if (is_resource($dirContent)) { $originalLocations = \OCA\Files_Trashbin\Trashbin::getLocations($user); while (($entryName = readdir($dirContent)) !== false) { if (!\OC\Files\Filesystem::isIgnoredDir($entryName)) { $id = $entryName; if ($dir === '' || $dir === '/') { $size = $view->filesize($id); $pathparts = pathinfo($entryName); $timestamp = substr($pathparts['extension'], 1); $id = $pathparts['filename']; } else { if ($timestamp === null) { // for subfolders we need to calculate the timestamp only once $size = $view->filesize($dir . '/' . $id); $parts = explode('/', ltrim($dir, '/')); $timestamp = substr(pathinfo($parts[0], PATHINFO_EXTENSION), 1); } } $originalPath = ''; if (isset($originalLocations[$id][$timestamp])) { $originalPath = $originalLocations[$id][$timestamp]; if (substr($originalPath, -1) === '/') { $originalPath = substr($originalPath, 0, -1); } } $i = array('name' => $id, 'mtime' => $timestamp, 'mimetype' => $view->is_dir($dir . '/' . $entryName) ? 'httpd/unix-directory' : \OC_Helper::getFileNameMimeType($id), 'type' => $view->is_dir($dir . '/' . $entryName) ? 'dir' : 'file', 'directory' => $dir === '/' ? '' : $dir, 'size' => $size); if ($originalPath) { $i['extraData'] = $originalPath . '/' . $id; } $result[] = new FileInfo($absoluteDir . '/' . $i['name'], $storage, $internalPath . '/' . $i['name'], $i, $mount); } } closedir($dirContent); } if ($sortAttribute !== '') { return \OCA\Files\Helper::sortFiles($result, $sortAttribute, $sortDescending); } return $result; }
public static function postAvatar($args) { \OC_JSON::checkLoggedIn(); \OC_JSON::callCheck(); $user = \OC_User::getUser(); if (isset($_POST['path'])) { $path = stripslashes($_POST['path']); $view = new \OC\Files\View('/' . $user . '/files'); $fileInfo = $view->getFileInfo($path); if ($fileInfo['encrypted'] === true) { $fileName = $view->toTmpFile($path); } else { $fileName = $view->getLocalFile($path); } } elseif (!empty($_FILES)) { $files = $_FILES['files']; if ($files['error'][0] === 0 && is_uploaded_file($files['tmp_name'][0]) && !\OC\Files\Filesystem::isFileBlacklisted($files['tmp_name'][0])) { \OC\Cache::set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200); $view = new \OC\Files\View('/' . $user . '/cache'); $fileName = $view->getLocalFile('avatar_upload'); unlink($files['tmp_name'][0]); } } else { $l = new \OC_L10n('core'); \OC_JSON::error(array("data" => array("message" => $l->t("No image or file provided")))); return; } try { $image = new \OC_Image(); $image->loadFromFile($fileName); $image->fixOrientation(); if ($image->valid()) { \OC\Cache::set('tmpavatar', $image->data(), 7200); \OC_JSON::error(array("data" => "notsquare")); } else { $l = new \OC_L10n('core'); $mimeType = $image->mimeType(); if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') { \OC_JSON::error(array("data" => array("message" => $l->t("Unknown filetype")))); } if (!$image->valid()) { \OC_JSON::error(array("data" => array("message" => $l->t("Invalid image")))); } } } catch (\Exception $e) { \OC_JSON::error(array("data" => array("message" => $e->getMessage()))); } }
/** * test moving a shared file out of the Shared folder */ function testRename() { // login as admin \Test_Encryption_Util::loginHelper(\Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER1); // save file with content $cryptedFile = file_put_contents('crypt:///' . \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER1 . '/files/' . $this->filename, $this->dataShort); // test that data was successfully written $this->assertTrue(is_int($cryptedFile)); // get the file info from previous created file $fileInfo = $this->view->getFileInfo('/' . \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER1 . '/files/' . $this->filename); // check if we have a valid file info $this->assertTrue($fileInfo instanceof \OC\Files\FileInfo); // share the file \OCP\Share::shareItem('file', $fileInfo['fileid'], \OCP\Share::SHARE_TYPE_USER, \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER2, OCP\PERMISSION_ALL); // check if share key for user2 exists $this->assertTrue($this->view->file_exists('/' . \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER1 . '/files_encryption/share-keys/' . $this->filename . '.' . \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER2 . '.shareKey')); // login as user2 \Test_Encryption_Util::loginHelper(\Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER2); $this->assertTrue($this->view->file_exists('/' . \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER2 . '/files/' . $this->filename)); // get file contents $retrievedCryptedFile = $this->view->file_get_contents('/' . \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER2 . '/files/' . $this->filename); // check if data is the same as we previously written $this->assertEquals($this->dataShort, $retrievedCryptedFile); // move the file to a subfolder $this->view->rename('/' . \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER2 . '/files/' . $this->filename, '/' . \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER2 . '/files/' . $this->folder1 . $this->filename); // check if we can read the moved file $retrievedRenamedFile = $this->view->file_get_contents('/' . \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER2 . '/files/' . $this->folder1 . $this->filename); // check if data is the same as we previously written $this->assertEquals($this->dataShort, $retrievedRenamedFile); // cleanup \Test_Encryption_Util::loginHelper(\Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER1); $this->view->unlink('/' . \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER1 . '/files/' . $this->filename); }
/** * Retrieves the contents of a trash bin directory. * * @param string $dir path to the directory inside the trashbin * or empty to retrieve the root of the trashbin * @param string $user * @param string $sortAttribute attribute to sort on or empty to disable sorting * @param bool $sortDescending true for descending sort, false otherwise * @return \OCP\Files\FileInfo[] */ public static function getTrashFiles($dir, $user, $sortAttribute = '', $sortDescending = false) { $result = array(); $timestamp = null; $view = new \OC\Files\View('/' . $user . '/files_trashbin/files'); if (ltrim($dir, '/') !== '' && !$view->is_dir($dir)) { throw new \Exception('Directory does not exists'); } $mount = $view->getMount($dir); $storage = $mount->getStorage(); $absoluteDir = $view->getAbsolutePath($dir); $internalPath = $mount->getInternalPath($absoluteDir); $originalLocations = \OCA\Files_Trashbin\Trashbin::getLocations($user); $dirContent = $storage->getCache()->getFolderContents($mount->getInternalPath($view->getAbsolutePath($dir))); foreach ($dirContent as $entry) { $entryName = $entry->getName(); $id = $entry->getId(); $name = $entryName; if ($dir === '' || $dir === '/') { $pathparts = pathinfo($entryName); $timestamp = substr($pathparts['extension'], 1); $name = $pathparts['filename']; } else { if ($timestamp === null) { // for subfolders we need to calculate the timestamp only once $parts = explode('/', ltrim($dir, '/')); $timestamp = substr(pathinfo($parts[0], PATHINFO_EXTENSION), 1); } } $originalPath = ''; if (isset($originalLocations[$id][$timestamp])) { $originalPath = $originalLocations[$id][$timestamp]; if (substr($originalPath, -1) === '/') { $originalPath = substr($originalPath, 0, -1); } } $i = array('name' => $name, 'mtime' => $timestamp, 'mimetype' => $entry->getMimeType(), 'type' => $entry->getMimeType() === ICacheEntry::DIRECTORY_MIMETYPE ? 'dir' : 'file', 'directory' => $dir === '/' ? '' : $dir, 'size' => $entry->getSize(), 'etag' => '', 'permissions' => Constants::PERMISSION_ALL - Constants::PERMISSION_SHARE); if ($originalPath) { $i['extraData'] = $originalPath . '/' . $id; } $result[] = new FileInfo($absoluteDir . '/' . $i['name'], $storage, $internalPath . '/' . $i['name'], $i, $mount); } if ($sortAttribute !== '') { return \OCA\Files\Helper::sortFiles($result, $sortAttribute, $sortDescending); } return $result; }
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]); }
/** * walk up the users file tree and update the etags * @param string $user * @param string $path */ private static function correctUsersFolder($user, $path) { // $path points to the mount point which is a virtual folder, so we start with // the parent $path = '/files' . dirname($path); \OC\Files\Filesystem::initMountPoints($user); $view = new \OC\Files\View('/' . $user); if ($view->file_exists($path)) { while ($path !== dirname($path)) { $etag = $view->getETag($path); $view->putFileInfo($path, array('etag' => $etag)); $path = dirname($path); } } else { \OCP\Util::writeLog('files_sharing', 'can not update etags on ' . $path . ' for user ' . $user . '. Path does not exists', \OCP\Util::DEBUG); } }
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; } }
/** * get the free space in the path's owner home folder * @param path * @return int */ private function getFreeSpace($path) { /** * @var \OC\Files\Storage\Storage $storage * @var string $internalPath */ list($storage, $internalPath) = \OC\Files\Filesystem::resolvePath($path); $owner = $storage->getOwner($internalPath); if (!$owner) { return -1; } $totalSpace = $this->getQuota($owner); if ($totalSpace == -1) { return -1; } $view = new \OC\Files\View("/" . $owner . "/files"); $rootInfo = $view->getFileInfo('/'); $usedSpace = isset($rootInfo['size']) ? $rootInfo['size'] : 0; return $totalSpace - $usedSpace; }
protected function setUp() { parent::setUp(); self::loginHelper(self::TEST_FILES_SHARING_API_USER1); // prepare user1's dir structure $this->view->mkdir('container'); $this->view->mkdir('container/shareddir'); $this->view->mkdir('container/shareddir/subdir'); list($this->ownerStorage, $internalPath) = $this->view->resolvePath(''); $this->ownerCache = $this->ownerStorage->getCache(); $this->ownerStorage->getScanner()->scan(''); // share "shareddir" with user2 $this->_share = $this->share(\OCP\Share::SHARE_TYPE_USER, 'container/shareddir', self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2, \OCP\Constants::PERMISSION_ALL); // login as user2 self::loginHelper(self::TEST_FILES_SHARING_API_USER2); // retrieve the shared storage $secondView = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2); list($this->sharedStorage, $internalPath) = $secondView->resolvePath('files/shareddir'); $this->sharedCache = $this->sharedStorage->getCache(); }
/** * 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); $dirContent = $rootView->getDirectoryContent('files_trashbin/files'); $this->assertSame(1, count($dirContent)); $firstElement = reset($dirContent); $ext = pathinfo($firstElement['path'], PATHINFO_EXTENSION); $this->assertTrue($rootView->file_exists('files_trashbin/files/localFolder.' . $ext . '/localFile.txt')); $this->assertFalse($rootView->file_exists('files_trashbin/files/localFolder.' . $ext . '/' . $this->folder)); //cleanup $rootView->deleteAll('files_trashin'); if ($status === false) { \OC_App::disable('files_trashbin'); } }
function testKeySetPreperation() { $basePath = '/' . Test_Encryption_Keymanager::TEST_USER . '/files'; $path = '/folder1/subfolder/subsubfolder/file.txt'; $this->assertFalse($this->view->is_dir($basePath . '/testKeySetPreperation')); $result = TestProtectedKeymanagerMethods::testKeySetPreperation($this->view, $path, $basePath); // return path without leading slash $this->assertSame('folder1/subfolder/subsubfolder/file.txt', $result); // check if directory structure was created $this->assertTrue($this->view->is_dir($basePath . '/folder1/subfolder/subsubfolder')); // cleanup $this->view->deleteAll($basePath . '/folder1'); }
function setUp() { parent::setUp(); self::loginHelper(self::TEST_FILES_SHARING_API_USER1); // prepare user1's dir structure $textData = "dummy file data\n"; $this->view->mkdir('container'); $this->view->mkdir('container/shareddir'); $this->view->mkdir('container/shareddir/subdir'); list($this->ownerStorage, $internalPath) = $this->view->resolvePath(''); $this->ownerCache = $this->ownerStorage->getCache(); $this->ownerStorage->getScanner()->scan(''); // share "shareddir" with user2 $fileinfo = $this->view->getFileInfo('container/shareddir'); \OCP\Share::shareItem('folder', $fileinfo['fileid'], \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2, 31); // login as user2 self::loginHelper(self::TEST_FILES_SHARING_API_USER2); // retrieve the shared storage $secondView = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2); list($this->sharedStorage, $internalPath) = $secondView->resolvePath('files/shareddir'); $this->sharedCache = $this->sharedStorage->getCache(); }
/** * Update the cache for changes to $path * * @param string $path * @param array $cachedData */ public function update($path, $cachedData) { parent::update($path, $cachedData); // since parent::update() has already updated the size of the subdirs, // only apply the update to the owner's parent dirs // find last parent before reaching the shared storage root, // which is the actual shared dir from the owner $sepPos = strpos($path, '/'); if ($sepPos > 0) { $baseDir = substr($path, 0, $sepPos); } else { $baseDir = $path; } // find the path relative to the data dir $file = $this->storage->getFile($baseDir); $view = new \OC\Files\View('/' . $file['fileOwner']); // find the owner's storage and path /** @var \OC\Files\Storage\Storage $storage */ list($storage, $internalPath) = $view->resolvePath($file['path']); // update the parent dirs' sizes in the owner's cache $storage->getCache()->correctFolderSize(dirname($internalPath)); }
function testDescryptAllWithBrokenFiles() { $file1 = "/decryptAll1" . uniqid() . ".txt"; $file2 = "/decryptAll2" . uniqid() . ".txt"; $util = new Encryption\Util($this->view, $this->userId); $this->view->file_put_contents($this->userId . '/files/' . $file1, $this->dataShort); $this->view->file_put_contents($this->userId . '/files/' . $file2, $this->dataShort); $fileInfoEncrypted1 = $this->view->getFileInfo($this->userId . '/files/' . $file1); $fileInfoEncrypted2 = $this->view->getFileInfo($this->userId . '/files/' . $file2); $this->assertTrue($fileInfoEncrypted1 instanceof \OC\Files\FileInfo); $this->assertTrue($fileInfoEncrypted2 instanceof \OC\Files\FileInfo); $this->assertEquals($fileInfoEncrypted1['encrypted'], 1); $this->assertEquals($fileInfoEncrypted2['encrypted'], 1); // rename keyfile for file1 so that the decryption for file1 fails // Expected behaviour: decryptAll() returns false, file2 gets decrypted anyway $this->view->rename($this->userId . '/files_encryption/keyfiles/' . $file1 . '.key', $this->userId . '/files_encryption/keyfiles/' . $file1 . '.key.moved'); // decrypt all encrypted files $result = $util->decryptAll(); $this->assertFalse($result); $fileInfoUnencrypted1 = $this->view->getFileInfo($this->userId . '/files/' . $file1); $fileInfoUnencrypted2 = $this->view->getFileInfo($this->userId . '/files/' . $file2); $this->assertTrue($fileInfoUnencrypted1 instanceof \OC\Files\FileInfo); $this->assertTrue($fileInfoUnencrypted2 instanceof \OC\Files\FileInfo); // file1 should be still encrypted; file2 should be decrypted $this->assertEquals(1, $fileInfoUnencrypted1['encrypted']); $this->assertEquals(0, $fileInfoUnencrypted2['encrypted']); // keyfiles and share keys should still exist $this->assertTrue($this->view->is_dir($this->userId . '/files_encryption/keyfiles/')); $this->assertTrue($this->view->is_dir($this->userId . '/files_encryption/share-keys/')); // rename the keyfile for file1 back $this->view->rename($this->userId . '/files_encryption/keyfiles/' . $file1 . '.key.moved', $this->userId . '/files_encryption/keyfiles/' . $file1 . '.key'); // try again to decrypt all encrypted files $result = $util->decryptAll(); $this->assertTrue($result); $fileInfoUnencrypted1 = $this->view->getFileInfo($this->userId . '/files/' . $file1); $fileInfoUnencrypted2 = $this->view->getFileInfo($this->userId . '/files/' . $file2); $this->assertTrue($fileInfoUnencrypted1 instanceof \OC\Files\FileInfo); $this->assertTrue($fileInfoUnencrypted2 instanceof \OC\Files\FileInfo); // now both files should be decrypted $this->assertEquals(0, $fileInfoUnencrypted1['encrypted']); $this->assertEquals(0, $fileInfoUnencrypted2['encrypted']); // keyfiles and share keys should be deleted $this->assertFalse($this->view->is_dir($this->userId . '/files_encryption/keyfiles/')); $this->assertFalse($this->view->is_dir($this->userId . '/files_encryption/share-keys/')); //cleanup $this->view->unlink($this->userId . '/files/' . $file1); $this->view->unlink($this->userId . '/files/' . $file2); $this->view->deleteAll($this->userId . '/files_encryption/keyfiles.backup'); $this->view->deleteAll($this->userId . '/files_encryption/share-keys.backup'); }