Example #1
0
 /**
  * Correct the parent folders' ETags for all users shared the file at $target
  *
  * @param string $target
  */
 public static function correctFolders($target)
 {
     $uid = \OCP\User::getUser();
     $uidOwner = \OC\Files\Filesystem::getOwner($target);
     $info = \OC\Files\Filesystem::getFileInfo($target);
     // Correct Shared folders of other users shared with
     $users = \OCP\Share::getUsersItemShared('file', $info['fileid'], $uidOwner, true);
     if (!empty($users)) {
         while (!empty($users)) {
             $reshareUsers = array();
             foreach ($users as $user) {
                 if ($user !== $uidOwner) {
                     $etag = \OC\Files\Filesystem::getETag('');
                     \OCP\Config::setUserValue($user, 'files_sharing', 'etag', $etag);
                     // Look for reshares
                     $reshareUsers = array_merge($reshareUsers, \OCP\Share::getUsersItemShared('file', $info['fileid'], $user, true));
                 }
             }
             $users = $reshareUsers;
         }
         // Correct folders of shared file owner
         $target = substr($target, 8);
         if ($uidOwner !== $uid && ($source = \OC_Share_Backend_File::getSource($target))) {
             \OC\Files\Filesystem::initMountPoints($uidOwner);
             $source = '/' . $uidOwner . '/' . $source['path'];
             \OC\Files\Cache\Updater::correctFolder($source, $info['mtime']);
         }
     }
 }
Example #2
0
 /**
  * get the UID of the owner of the file and the path to the file relative to
  * owners files folder
  *
  * @param string $filename
  * @return array
  * @throws \OC\User\NoUserException
  */
 public static function getUidAndFilename($filename)
 {
     $uid = Filesystem::getOwner($filename);
     $userManager = \OC::$server->getUserManager();
     // if the user with the UID doesn't exists, e.g. because the UID points
     // to a remote user with a federated cloud ID we use the current logged-in
     // user. We need a valid local user to create the versions
     if (!$userManager->userExists($uid)) {
         $uid = User::getUser();
     }
     Filesystem::initMountPoints($uid);
     if ($uid != User::getUser()) {
         $info = Filesystem::getFileInfo($filename);
         $ownerView = new View('/' . $uid . '/files');
         try {
             $filename = $ownerView->getPath($info['fileid']);
             // make sure that the file name doesn't end with a trailing slash
             // can for example happen single files shared across servers
             $filename = rtrim($filename, '/');
         } catch (NotFoundException $e) {
             $filename = null;
         }
     }
     return [$uid, $filename];
 }
 protected function setUp()
 {
     $app = new Application();
     $this->container = $app->getContainer();
     $this->container['Config'] = $this->getMockBuilder('\\OCP\\IConfig')->disableOriginalConstructor()->getMock();
     $this->container['AppName'] = 'files_sharing';
     $this->container['UserSession'] = $this->getMockBuilder('\\OC\\User\\Session')->disableOriginalConstructor()->getMock();
     $this->container['URLGenerator'] = $this->getMockBuilder('\\OC\\URLGenerator')->disableOriginalConstructor()->getMock();
     $this->urlGenerator = $this->container['URLGenerator'];
     $this->shareController = $this->container['ShareController'];
     // Store current user
     $this->oldUser = \OC_User::getUser();
     // Create a dummy user
     $this->user = \OC::$server->getSecureRandom()->getLowStrengthGenerator()->generate(12, ISecureRandom::CHAR_LOWER);
     \OC_User::createUser($this->user, $this->user);
     \OC_Util::tearDownFS();
     \OC_User::setUserId('');
     Filesystem::tearDown();
     \OC_User::setUserId($this->user);
     \OC_Util::setupFS($this->user);
     // Create a dummy shared file
     $view = new View('/' . $this->user . '/files');
     $view->file_put_contents('file1.txt', 'I am such an awesome shared file!');
     $this->token = \OCP\Share::shareItem(Filesystem::getFileInfo('file1.txt')->getType(), Filesystem::getFileInfo('file1.txt')->getId(), \OCP\Share::SHARE_TYPE_LINK, 'IAmPasswordProtected!', 1);
 }
Example #4
0
	/**
	 * @param string[] $files
	 */
	private function getEtags($files) {
		$etags = array();
		foreach ($files as $file) {
			$info = Filesystem::getFileInfo($file);
			$etags[$file] = $info['etag'];
		}
		return $etags;
	}
Example #5
0
 public static function getUidAndFilename($filename)
 {
     $uid = \OC\Files\Filesystem::getOwner($filename);
     \OC\Files\Filesystem::initMountPoints($uid);
     if ($uid != \OCP\User::getUser()) {
         $info = \OC\Files\Filesystem::getFileInfo($filename);
         $ownerView = new \OC\Files\View('/' . $uid . '/files');
         $filename = $ownerView->getPath($info['fileid']);
     }
     return array($uid, $filename);
 }
Example #6
0
 /**
  * @brief list bookshelf contents
  *
  * @return array of FileInfo[], sorted by time added
  */
 public static function get()
 {
     $files = array();
     if ($bookshelf = json_decode(Config::get('bookshelf', ''), true)) {
         arsort($bookshelf);
         while (list($id, $time) = each($bookshelf)) {
             array_push($files, \OC\Files\Filesystem::getFileInfo(\OC\Files\Filesystem::normalizePath(\OC\Files\Filesystem::getPath($id))));
         }
     }
     return $files;
 }
Example #7
0
 /**
  * Remove thumbnails and db entries for deleted files
  * @param array $params All parameters passed by hook
  */
 public static function cleanupForDelete($params)
 {
     // Get full thumbnail path
     $path = $params['path'];
     \OCA\OCLife\utilities::deleteThumb($path);
     // Now remove all entry in DB for this file
     // -- Verificare che qui esista l'entry del file nel DB!!! :-///
     $fileInfos = \OC\Files\Filesystem::getFileInfo($path);
     if ($fileInfos['fileid']) {
         $result = \OCA\OCLife\hTags::removeAllTagsForFile($fileInfos['fileid']);
     }
     return $result;
 }
Example #8
0
 /**
  * @brief Cleanup session data on removing the document
  * @param array
  *
  * This function is connected to the delete signal of OC_Filesystem
  * to delete the related info from database
  */
 public static function onDelete($params)
 {
     $info = \OC\Files\Filesystem::getFileInfo($params['path']);
     $fileId = @$info['fileid'];
     if (!$fileId) {
         return;
     }
     $sessionObj = new Db_Session();
     $session = $sessionObj->loadBy('file_id', $fileId)->getData();
     if (!is_array($session) || !isset($session['es_id'])) {
         return;
     }
     Db_Session::cleanUp($session['es_id']);
 }
Example #9
0
 /**
  * @param string $filename
  * @return array
  * @throws \OC\User\NoUserException
  */
 public static function getUidAndFilename($filename)
 {
     $uid = \OC\Files\Filesystem::getOwner($filename);
     \OC\Files\Filesystem::initMountPoints($uid);
     if ($uid != \OCP\User::getUser()) {
         $info = \OC\Files\Filesystem::getFileInfo($filename);
         $ownerView = new \OC\Files\View('/' . $uid . '/files');
         try {
             $filename = $ownerView->getPath($info['fileid']);
         } catch (NotFoundException $e) {
             $filename = null;
         }
     }
     return [$uid, $filename];
 }
Example #10
0
 public function setUp()
 {
     parent::setUp();
     $this->userBackend = new \Test\Util\User\Dummy();
     \OC::$server->getUserManager()->registerBackend($this->userBackend);
     $this->ownerUid = $this->getUniqueID('owner_');
     $this->recipientUid = $this->getUniqueID('recipient_');
     $this->userBackend->createUser($this->ownerUid, '');
     $this->userBackend->createUser($this->recipientUid, '');
     $this->loginAsUser($this->ownerUid);
     Filesystem::mkdir('/foo');
     Filesystem::file_put_contents('/foo/bar.txt', 'asd');
     $fileId = Filesystem::getFileInfo('/foo/bar.txt')->getId();
     \OCP\Share::shareItem('file', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->recipientUid, 31);
     $this->loginAsUser($this->recipientUid);
     $this->assertTrue(Filesystem::file_exists('bar.txt'));
 }
Example #11
0
 /**
  * @brief Cleanup session data on removing the document
  * @param array
  *
  * This function is connected to the delete signal of OC_Filesystem
  * to delete the related info from database
  */
 public static function onDelete($params)
 {
     $info = \OC\Files\Filesystem::getFileInfo($params['path']);
     $fileId = @$info['fileid'];
     if (!$fileId) {
         return;
     }
     $session = new Db\Session();
     $session->loadBy('file_id', $fileId);
     if (!$session->getEsId()) {
         return;
     }
     $member = new Db\Member();
     $sessionMembers = $member->getCollectionBy('es_id', $session->getEsId());
     foreach ($sessionMembers as $memberData) {
         if (intval($memberData['status']) === Db\Member::MEMBER_STATUS_ACTIVE) {
             return;
         }
     }
     Db\Session::cleanUp($session->getEsId());
 }
Example #12
0
 /**
  * @medium
  */
 function testUnshareChildren()
 {
     $fileInfo2 = \OC\Files\Filesystem::getFileInfo($this->folder);
     $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);
     // one folder should be shared with the user
     $shares = $this->shareManager->getSharedWith(self::TEST_FILES_SHARING_API_USER2, \OCP\Share::SHARE_TYPE_USER);
     $this->assertCount(1, $shares);
     // move shared folder to 'localDir'
     \OC\Files\Filesystem::mkdir('localDir');
     $result = \OC\Files\Filesystem::rename($this->folder, '/localDir/' . $this->folder);
     $this->assertTrue($result);
     \OC\Files\Filesystem::unlink('localDir');
     self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
     // after the parent directory was deleted the share should be unshared
     $shares = $this->shareManager->getSharedWith(self::TEST_FILES_SHARING_API_USER2, \OCP\Share::SHARE_TYPE_USER);
     $this->assertEmpty($shares);
     self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
     // the folder for the owner should still exists
     $this->assertTrue(\OC\Files\Filesystem::file_exists($this->folder));
 }
Example #13
0
 /**
  * @medium
  */
 function testpreUnlink()
 {
     $fileInfo2 = \OC\Files\Filesystem::getFileInfo($this->folder);
     $result = \OCP\Share::shareItem('folder', $fileInfo2->getId(), \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2, 31);
     $this->assertTrue($result);
     self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
     // one folder should be shared with the user
     $sharedFolders = \OCP\Share::getItemsSharedWith('folder');
     $this->assertSame(1, count($sharedFolders));
     // move shared folder to 'localDir'
     \OC\Files\Filesystem::mkdir('localDir');
     $result = \OC\Files\Filesystem::rename($this->folder, '/localDir/' . $this->folder);
     $this->assertTrue($result);
     \OC\Files\Filesystem::unlink('localDir');
     self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
     // after the parent directory was deleted the share should be unshared
     $sharedFolders = \OCP\Share::getItemsSharedWith('folder');
     $this->assertTrue(empty($sharedFolders));
     self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
     // the folder for the owner should still exists
     $this->assertTrue(\OC\Files\Filesystem::file_exists($this->folder));
 }
Example #14
0
 /**
  * update keyfiles and share keys recursively
  *
  * @param int $fileSource file source id
  */
 private function update($fileSource)
 {
     $path = \OC\Files\Filesystem::getPath($fileSource);
     $info = \OC\Files\Filesystem::getFileInfo($path);
     $owner = \OC\Files\Filesystem::getOwner($path);
     $view = new \OC\Files\View('/' . $owner . '/files');
     $ownerPath = $view->getPath($info->getId());
     $absPath = '/' . $owner . '/files' . $ownerPath;
     $mount = $this->mountManager->find($path);
     $mountPoint = $mount->getMountPoint();
     // if a folder was shared, get a list of all (sub-)folders
     if ($this->view->is_dir($absPath)) {
         $allFiles = $this->util->getAllFiles($absPath, $mountPoint);
     } else {
         $allFiles = array($absPath);
     }
     $encryptionModule = $this->encryptionManager->getDefaultEncryptionModule();
     foreach ($allFiles as $path) {
         $usersSharing = $this->file->getAccessList($path);
         $encryptionModule->update($path, $this->uid, $usersSharing);
     }
 }
Example #15
0
File: api.php Project: evanjt/core
 /**
  * @expectedException \Exception
  */
 public function testShareNotOwner()
 {
     \Test_Files_Sharing_Api::loginHelper(\Test_Files_Sharing_Api::TEST_FILES_SHARING_API_USER2);
     \OC\Files\Filesystem::file_put_contents('foo.txt', 'bar');
     $info = \OC\Files\Filesystem::getFileInfo('foo.txt');
     \Test_Files_Sharing_Api::loginHelper(\Test_Files_Sharing_Api::TEST_FILES_SHARING_API_USER1);
     \OCP\Share::shareItem('file', $info->getId(), \OCP\Share::SHARE_TYPE_LINK, \Test_Files_Sharing_Api::TEST_FILES_SHARING_API_USER2, 31);
 }
Example #16
0
 function testGetPermissions()
 {
     $fileinfoFolder = $this->view->getFileInfo($this->folder);
     $result = \OCP\Share::shareItem('folder', $fileinfoFolder['fileid'], \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2, 1);
     $this->assertTrue($result);
     self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
     $this->assertTrue(\OC\Files\Filesystem::is_dir($this->folder));
     // for the share root we expect:
     // the shared permissions (1)
     // the delete permission (8), to enable unshare
     // the update permission (2), to allow renaming of the mount point
     $rootInfo = \OC\Files\Filesystem::getFileInfo($this->folder);
     $this->assertSame(11, $rootInfo->getPermissions());
     // for the file within the shared folder we expect:
     // the shared permissions (1)
     $subfileInfo = \OC\Files\Filesystem::getFileInfo($this->folder . $this->filename);
     $this->assertSame(1, $subfileInfo->getPermissions());
     //cleanup
     self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
     $result = \OCP\Share::unshare('folder', $fileinfoFolder['fileid'], \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
     $this->assertTrue($result);
 }
Example #17
0
// if IE8 and "?dir=path&view=someview" was specified, reformat the URL to use a hash like "#?dir=path&view=someview"
if ($isIE8 && (isset($_GET['dir']) || isset($_GET['view']))) {
    $hash = '#?';
    $dir = isset($_GET['dir']) ? $_GET['dir'] : '/';
    $view = isset($_GET['view']) ? $_GET['view'] : 'files';
    $hash = '#?dir=' . \OCP\Util::encodePath($dir);
    if ($view !== 'files') {
        $hash .= '&view=' . urlencode($view);
    }
    header('Location: ' . OCP\Util::linkTo('files', 'index.php') . $hash);
    exit;
}
$user = OC_User::getUser();
$config = \OC::$server->getConfig();
// mostly for the home storage's free space
$dirInfo = \OC\Files\Filesystem::getFileInfo('/', false);
$storageInfo = OC_Helper::getStorageInfo('/', $dirInfo);
$nav = new OCP\Template('files', 'appnavigation', '');
function sortNavigationItems($item1, $item2)
{
    return $item1['order'] - $item2['order'];
}
\OCA\Files\App::getNavigationManager()->add(array('id' => 'favorites', 'appname' => 'files', 'script' => 'simplelist.php', 'order' => 5, 'name' => $l->t('Favorites')));
$navItems = \OCA\Files\App::getNavigationManager()->getAll();
usort($navItems, 'sortNavigationItems');
$nav->assign('navigationItems', $navItems);
$contentItems = array();
function renderScript($appName, $scriptName)
{
    $content = '';
    $appPath = OC_App::getAppPath($appName);
Example #18
0
 /**
  * Get storage info including all mount points and quota
  *
  * @return array
  */
 private static function getGlobalStorageInfo()
 {
     $quota = OC_Util::getUserQuota(\OCP\User::getUser());
     $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
     $used = $rootInfo['size'];
     if ($used < 0) {
         $used = 0;
     }
     $total = $quota;
     $free = $quota - $used;
     if ($total > 0) {
         if ($quota > 0 && $total > $quota) {
             $total = $quota;
         }
         // prevent division by zero or error codes (negative values)
         $relative = round($used / $total * 10000) / 100;
     } else {
         $relative = 0;
     }
     return array('free' => $free, 'used' => $used, 'total' => $total, 'relative' => $relative);
 }
Example #19
0
$keepAspect = array_key_exists('a', $_GET) ? true : false;
$always = array_key_exists('forceIcon', $_GET) ? (bool) $_GET['forceIcon'] : true;
if ($file === '') {
    //400 Bad Request
    \OC_Response::setStatus(400);
    \OC_Log::write('core-preview', 'No file parameter was passed', \OC_Log::DEBUG);
    exit;
}
if ($maxX === 0 || $maxY === 0) {
    //400 Bad Request
    \OC_Response::setStatus(400);
    \OC_Log::write('core-preview', 'x and/or y set to 0', \OC_Log::DEBUG);
    exit;
}
try {
    $preview = new \OC\Preview(\OC_User::getUser(), 'files');
    $info = \OC\Files\Filesystem::getFileInfo($file);
    if (!$always and !$preview->isAvailable($info)) {
        \OC_Response::setStatus(404);
    } else {
        $preview->setFile($file);
        $preview->setMaxX($maxX);
        $preview->setMaxY($maxY);
        $preview->setScalingUp($scalingUp);
        $preview->setKeepAspect($keepAspect);
    }
    $preview->showPreview();
} catch (\Exception $e) {
    \OC_Response::setStatus(500);
    \OC_Log::write('core', $e->getmessage(), \OC_Log::DEBUG);
}
Example #20
0
 public function testFileOwner()
 {
     $this->share(\OCP\Share::SHARE_TYPE_USER, $this->filename, self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2, \OCP\Constants::PERMISSION_READ);
     $this->loginHelper(self::TEST_FILES_SHARING_API_USER2);
     $info = \OC\Files\Filesystem::getFileInfo($this->filename);
     $this->assertSame(self::TEST_FILES_SHARING_API_USER1, $info->getOwner()->getUID());
 }
Example #21
0
}
$relativePath = null;
if (isset($_GET['dir'])) {
    $relativePath = $_GET['dir'];
}
$data = \OCA\Files_Sharing\Helper::setupFromToken($token, $relativePath, $password);
$linkItem = $data['linkItem'];
// Load the files
$path = $data['realPath'];
$isWritable = $linkItem['permissions'] & (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_CREATE);
if (!$isWritable) {
    \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, $storage) {
        return new \OCA\Files_Sharing\ReadOnlyWrapper(array('storage' => $storage));
    });
}
$rootInfo = \OC\Files\Filesystem::getFileInfo($path);
$rootView = new \OC\Files\View('');
/**
 * @param \OCP\Files\FileInfo $dir
 * @param \OC\Files\View $view
 * @return array
 */
function getChildInfo($dir, $view)
{
    $children = $view->getDirectoryContent($dir->getPath());
    $result = array();
    foreach ($children as $child) {
        $formated = \OCA\Files\Helper::formatFileInfo($child);
        if ($child->getType() === 'dir') {
            $formated['children'] = getChildInfo($child, $view);
        }
Example #22
0
 public function testGetPathByIdShareSubFolder()
 {
     self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
     \OC\Files\Filesystem::mkdir('foo');
     \OC\Files\Filesystem::mkdir('foo/bar');
     \OC\Files\Filesystem::touch('foo/bar/test.txt', 'bar');
     $folderInfo = \OC\Files\Filesystem::getFileInfo('foo');
     $fileInfo = \OC\Files\Filesystem::getFileInfo('foo/bar/test.txt');
     \OCP\Share::shareItem('folder', $folderInfo->getId(), \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2, \OCP\PERMISSION_ALL);
     \OC_Util::tearDownFS();
     self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
     $this->assertTrue(\OC\Files\Filesystem::file_exists('/foo'));
     list($sharedStorage) = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/foo');
     /**
      * @var \OC\Files\Storage\Shared $sharedStorage
      */
     $sharedCache = $sharedStorage->getCache();
     $this->assertEquals('', $sharedCache->getPathById($folderInfo->getId()));
     $this->assertEquals('bar/test.txt', $sharedCache->getPathById($fileInfo->getId()));
 }
Example #23
0
 private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate)
 {
     $backend = self::getBackend($itemType);
     $l = \OC::$server->getL10N('lib');
     $result = array();
     $column = $itemType === 'file' || $itemType === 'folder' ? 'file_source' : 'item_source';
     $checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
     if ($checkReshare) {
         // Check if attempting to share back to owner
         if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
             $message = 'Sharing %s failed, because the user %s is the original sharer';
             $message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
             \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
             throw new \Exception($message_t);
         }
     }
     if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
         // Check if share permissions is granted
         if (self::isResharingAllowed() && (int) $checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
             if (~(int) $checkReshare['permissions'] & $permissions) {
                 $message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
                 $message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
                 \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $uidOwner), \OCP\Util::DEBUG);
                 throw new \Exception($message_t);
             } else {
                 // TODO Don't check if inside folder
                 $result['parent'] = $checkReshare['id'];
                 $result['expirationDate'] = $expirationDate;
                 // $checkReshare['expiration'] could be null and then is always less than any value
                 if (isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
                     $result['expirationDate'] = $checkReshare['expiration'];
                 }
                 // only suggest the same name as new target if it is a reshare of the
                 // same file/folder and not the reshare of a child
                 if ($checkReshare[$column] === $itemSource) {
                     $result['filePath'] = $checkReshare['file_target'];
                     $result['itemSource'] = $checkReshare['item_source'];
                     $result['fileSource'] = $checkReshare['file_source'];
                     $result['suggestedItemTarget'] = $checkReshare['item_target'];
                     $result['suggestedFileTarget'] = $checkReshare['file_target'];
                 } else {
                     $result['filePath'] = $backend instanceof \OCP\Share_Backend_File_Dependent ? $backend->getFilePath($itemSource, $uidOwner) : null;
                     $result['suggestedItemTarget'] = null;
                     $result['suggestedFileTarget'] = null;
                     $result['itemSource'] = $itemSource;
                     $result['fileSource'] = $backend instanceof \OCP\Share_Backend_File_Dependent ? $itemSource : null;
                 }
             }
         } else {
             $message = 'Sharing %s failed, because resharing is not allowed';
             $message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
             \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
             throw new \Exception($message_t);
         }
     } else {
         $result['parent'] = null;
         $result['suggestedItemTarget'] = null;
         $result['suggestedFileTarget'] = null;
         $result['itemSource'] = $itemSource;
         $result['expirationDate'] = $expirationDate;
         if (!$backend->isValidSource($itemSource, $uidOwner)) {
             $message = 'Sharing %s failed, because the sharing backend for ' . '%s could not find its source';
             $message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
             \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSource, $itemType), \OCP\Util::DEBUG);
             throw new \Exception($message_t);
         }
         if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
             $result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
             if ($itemType == 'file' || $itemType == 'folder') {
                 $result['fileSource'] = $itemSource;
             } else {
                 $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
                 $result['fileSource'] = $meta['fileid'];
             }
             if ($result['fileSource'] == -1) {
                 $message = 'Sharing %s failed, because the file could not be found in the file cache';
                 $message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
                 \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
                 throw new \Exception($message_t);
             }
         } else {
             $result['filePath'] = null;
             $result['fileSource'] = null;
         }
     }
     return $result;
 }
Example #24
0
    $result['data'] = array('message' => (string) $l10n->t('The target folder has been moved or deleted.'), 'code' => 'targetnotfound');
    OCP\JSON::error($result);
    exit;
}
$target = $dir . '/' . $fileName;
if (\OC\Files\Filesystem::file_exists($target)) {
    $result['data'] = array('message' => (string) $l10n->t('The name %s is already used in the folder %s. Please choose a different name.', array($fileName, $dir)));
    OCP\JSON::error($result);
    exit;
}
$success = false;
$templateManager = OC_Helper::getFileTemplateManager();
$mimeType = OC_Helper::getMimetypeDetector()->detectPath($target);
$content = $templateManager->getTemplate($mimeType);
try {
    if ($content) {
        $success = \OC\Files\Filesystem::file_put_contents($target, $content);
    } else {
        $success = \OC\Files\Filesystem::touch($target);
    }
} catch (\Exception $e) {
    $result = ['success' => false, 'data' => ['message' => $e->getMessage()]];
    OCP\JSON::error($result);
    exit;
}
if ($success) {
    $meta = \OC\Files\Filesystem::getFileInfo($target);
    OCP\JSON::success(array('data' => \OCA\Files\Helper::formatFileInfo($meta)));
    return;
}
OCP\JSON::error(array('data' => array('message' => $l10n->t('Error when creating the file'))));
Example #25
0
 /**
  * test expiration of files older then the max storage time defined for the trash
  * in this test we delete a shared file and check if both trash bins, the one from
  * the owner of the file and the one from the user who deleted the file get expired
  * correctly
  */
 public function testExpireOldFilesShared()
 {
     $currentTime = time();
     $folder = "trashTest-" . $currentTime . '/';
     $expiredDate = $currentTime - 3 * 24 * 60 * 60;
     // create some files
     \OC\Files\Filesystem::mkdir($folder);
     \OC\Files\Filesystem::file_put_contents($folder . 'user1-1.txt', 'file1');
     \OC\Files\Filesystem::file_put_contents($folder . 'user1-2.txt', 'file2');
     \OC\Files\Filesystem::file_put_contents($folder . 'user1-3.txt', 'file3');
     \OC\Files\Filesystem::file_put_contents($folder . 'user1-4.txt', 'file4');
     //share user1-4.txt with user2
     $fileInfo = \OC\Files\Filesystem::getFileInfo($folder);
     $result = \OCP\Share::shareItem('folder', $fileInfo->getId(), \OCP\Share::SHARE_TYPE_USER, self::TEST_TRASHBIN_USER2, 31);
     $this->assertTrue($result);
     // delete them so that they end up in the trash bin
     \OC\Files\Filesystem::unlink($folder . 'user1-1.txt');
     \OC\Files\Filesystem::unlink($folder . 'user1-2.txt');
     \OC\Files\Filesystem::unlink($folder . 'user1-3.txt');
     $filesInTrash = OCA\Files_Trashbin\Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'name');
     $this->assertSame(3, count($filesInTrash));
     // every second file will get a date in the past so that it will get expired
     $this->manipulateDeleteTime($filesInTrash, $this->trashRoot1, $expiredDate);
     // login as user2
     self::loginHelper(self::TEST_TRASHBIN_USER2);
     $this->assertTrue(\OC\Files\Filesystem::file_exists($folder . "user1-4.txt"));
     // create some files
     \OC\Files\Filesystem::file_put_contents('user2-1.txt', 'file1');
     \OC\Files\Filesystem::file_put_contents('user2-2.txt', 'file2');
     // delete them so that they end up in the trash bin
     \OC\Files\Filesystem::unlink('user2-1.txt');
     \OC\Files\Filesystem::unlink('user2-2.txt');
     $filesInTrashUser2 = OCA\Files_Trashbin\Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER2, 'name');
     $this->assertSame(2, count($filesInTrashUser2));
     // every second file will get a date in the past so that it will get expired
     $this->manipulateDeleteTime($filesInTrashUser2, $this->trashRoot2, $expiredDate);
     \OC\Files\Filesystem::unlink($folder . 'user1-4.txt');
     $this->runCommands();
     $filesInTrashUser2AfterDelete = OCA\Files_Trashbin\Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER2);
     // user2-1.txt should have been expired
     $this->verifyArray($filesInTrashUser2AfterDelete, array('user2-2.txt', 'user1-4.txt'));
     self::loginHelper(self::TEST_TRASHBIN_USER1);
     // user1-1.txt and user1-3.txt should have been expired
     $filesInTrashUser1AfterDelete = OCA\Files_Trashbin\Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1);
     $this->verifyArray($filesInTrashUser1AfterDelete, array('user1-2.txt', 'user1-4.txt'));
 }
Example #26
0
 /**
  * Return the source
  *
  * @param string $path
  * @return array
  */
 protected function getSourcePathAndOwner($path)
 {
     $uidOwner = Filesystem::getOwner($path);
     if ($uidOwner !== $this->currentUser) {
         Filesystem::initMountPoints($uidOwner);
         $info = Filesystem::getFileInfo($path);
         if ($info !== false) {
             $ownerView = new View('/' . $uidOwner . '/files');
             $path = $ownerView->getPath((int) $info['fileid']);
         }
     }
     return array($path, $uidOwner);
 }
Example #27
0
 /**
  * Check if a file is encrypted according to database file cache
  * @param string $path
  * @return bool
  */
 public static function isEncryptedMeta($path)
 {
     // TODO: Use DI to get \OC\Files\Filesystem out of here
     // Fetch all file metadata from DB
     $metadata = \OC\Files\Filesystem::getFileInfo($path);
     // Return encryption status
     return isset($metadata['encrypted']) && (bool) $metadata['encrypted'];
 }
Example #28
0
 public function testFileOwner()
 {
     $fileinfo = $this->view->getFileInfo($this->filename);
     $result = \OCP\Share::shareItem('file', $fileinfo['fileid'], \OCP\Share::SHARE_TYPE_USER, \Test_Files_Sharing::TEST_FILES_SHARING_API_USER2, \OCP\Constants::PERMISSION_ALL);
     $this->assertTrue($result);
     $this->loginHelper(\Test_Files_Sharing::TEST_FILES_SHARING_API_USER2);
     $info = \OC\Files\Filesystem::getFileInfo($this->filename);
     $this->assertSame(\Test_Files_Sharing::TEST_FILES_SHARING_API_USER1, $info->getOwner()->getUID());
 }
Example #29
0
 /**
  * Encrypt all files in a directory
  * @param string $dirPath the directory whose files will be encrypted
  * @return bool
  * @note Encryption is recursive
  */
 public function encryptAll($dirPath)
 {
     $result = true;
     $found = $this->findEncFiles($dirPath);
     // Disable proxy to prevent file being encrypted twice
     \OC_FileProxy::$enabled = false;
     $versionStatus = \OCP\App::isEnabled('files_versions');
     \OC_App::disable('files_versions');
     $encryptedFiles = array();
     // Encrypt unencrypted files
     foreach ($found['plain'] as $plainFile) {
         //get file info
         $fileInfo = \OC\Files\Filesystem::getFileInfo($plainFile['path']);
         //relative to data/<user>/file
         $relPath = $plainFile['path'];
         //relative to /data
         $rawPath = '/' . $this->userId . '/files/' . $plainFile['path'];
         // keep timestamp
         $timestamp = $fileInfo['mtime'];
         // Open plain file handle for binary reading
         $plainHandle = $this->view->fopen($rawPath, 'rb');
         // Open enc file handle for binary writing, with same filename as original plain file
         $encHandle = fopen('crypt://' . $rawPath . '.part', 'wb');
         if (is_resource($encHandle) && is_resource($plainHandle)) {
             // Move plain file to a temporary location
             $size = stream_copy_to_stream($plainHandle, $encHandle);
             fclose($encHandle);
             fclose($plainHandle);
             $fakeRoot = $this->view->getRoot();
             $this->view->chroot('/' . $this->userId . '/files');
             $this->view->rename($relPath . '.part', $relPath);
             // set timestamp
             $this->view->touch($relPath, $timestamp);
             $encSize = $this->view->filesize($relPath);
             $this->view->chroot($fakeRoot);
             // Add the file to the cache
             \OC\Files\Filesystem::putFileInfo($relPath, array('encrypted' => true, 'size' => $encSize, 'unencrypted_size' => $size, 'etag' => $fileInfo['etag']));
             $encryptedFiles[] = $relPath;
         } else {
             \OCP\Util::writeLog('files_encryption', 'initial encryption: could not encrypt ' . $rawPath, \OCP\Util::FATAL);
             $result = false;
         }
     }
     \OC_FileProxy::$enabled = true;
     if ($versionStatus) {
         \OC_App::enable('files_versions');
     }
     $result = $result && $this->encryptVersions($encryptedFiles);
     return $result;
 }
Example #30
0
 /**
  * Test whether versions are created when overwriting as share recipient
  */
 public function testStoreVersionAsRecipient()
 {
     $this->loginAsUser(self::TEST_VERSIONS_USER);
     \OC\Files\Filesystem::mkdir('folder');
     \OC\Files\Filesystem::file_put_contents('folder/test.txt', 'test file');
     $fileInfo = \OC\Files\Filesystem::getFileInfo('folder');
     \OCP\Share::shareItem('folder', $fileInfo['fileid'], \OCP\Share::SHARE_TYPE_USER, self::TEST_VERSIONS_USER2, \OCP\Constants::PERMISSION_ALL);
     $this->loginAsUser(self::TEST_VERSIONS_USER2);
     $this->createAndCheckVersions(\OC\Files\Filesystem::getView(), 'folder/test.txt');
 }