Exemplo n.º 1
2
 public function __construct($imagePath, $user = null, $square = false)
 {
     if (!Filesystem::isValidPath($imagePath)) {
         return;
     }
     if (is_null($user)) {
         $this->view = Filesystem::getView();
         $this->user = \OCP\User::getUser();
     } else {
         $this->view = new View('/' . $user . '/files');
         $this->user = $user;
     }
     $this->useOriginal = (substr($imagePath, -4) === '.svg' or substr($imagePath, -5) === '.svgz');
     if ($this->useOriginal) {
         $this->path = $imagePath;
     } else {
         $galleryDir = \OC_User::getHome($this->user) . '/gallery/' . $this->user . '/';
         if (strrpos($imagePath, '.')) {
             $extension = substr($imagePath, strrpos($imagePath, '.') + 1);
             $image = substr($imagePath, 0, strrpos($imagePath, '.'));
         } else {
             $extension = '';
             $image = $imagePath;
         }
         if ($square) {
             $extension = 'square.' . $extension;
         }
         $this->path = $galleryDir . $image . '.' . $extension;
         if (!file_exists($this->path)) {
             $this->create($imagePath, $square);
         }
     }
 }
Exemplo n.º 2
0
    public static function listdir($dir, $dirs_stat)
    {
        $list = \OC\Files\Filesystem::getdirectorycontent($dir);
        if (sizeof($list) > 0) {
            $ret = '';
            //$d=explode('/',$dir);
            foreach ($list as $i) {
                if ($i['type'] == 'dir' && $i['name'] != '.') {
                    if (!isset($i['directory'])) {
                        $i['directory'] = '';
                    }
                    $ret .= '<li class="ui-droppable">
					 	<a href="./?app=files&dir=' . $i['directory'] . '/' . $i['name'] . '" data-pathname="' . $i['directory'] . '/' . $i['name'] . '">' . $i['name'] . '</a>' . listdir($dir . '/' . $i['name'], $dirs_stat) . '
						</li>
					';
                }
            }
            if ($ret != '') {
                $class = 'class="collapsed"';
                if ($dir == '' || isset($dirs_stat[$dir]) && $dirs_stat[$dir] == 'expanded') {
                    $class = 'class="expanded"';
                }
                $ret = '<ul ' . $class . ' data-path="' . $dir . '"><li></li>' . $ret . '</ul>';
            }
            return $ret;
        }
    }
Exemplo n.º 3
0
 public function tearDown()
 {
     foreach ($this->storages as $storage) {
         $storage->getCache()->clear();
     }
     \OC\Files\Filesystem::clearMounts();
 }
Exemplo n.º 4
0
 public static function getFiles($dir, $sortAttribute = 'name', $sortDescending = false, $mimetypeFilter = '')
 {
     $contents = \OC\Files\Filesystem::getDirectoryContent($dir, $mimetypeFilter);
     if (isset($_SESSION['targetType']) && $_SESSION['targetType'] == TargetType::PROJECT) {
         /** @var FileInfo[] $subContents */
         $subContents = [];
         foreach ($contents as $content) {
             /** @var FileInfo $content */
             if ($content && $content->getMimetype() === 'httpd/unix-directory') {
                 $subDir = $dir . "/" . $content->getName();
                 $subContents = array_merge($subContents, \OC\Files\Filesystem::getDirectoryContent($subDir, $mimetypeFilter));
             }
         }
     }
     if (isset($subContents) && count($subContents) != 0) {
         $contents = array_merge($contents, $subContents);
     }
     $excludeFolder = [];
     foreach ($contents as $content) {
         /** @var FileInfo $content */
         if ($content && $content->getMimetype() === 'httpd/unix-directory') {
             continue;
         }
         array_push($excludeFolder, $content);
     }
     return self::sortFiles($excludeFolder, $sortAttribute, $sortDescending);
 }
Exemplo n.º 5
0
 /**
  * @param string $internalPath
  * @param int $time
  * @return array[] all propagated entries
  */
 public function propagateChange($internalPath, $time)
 {
     $source = $this->storage->getSourcePath($internalPath);
     /** @var \OC\Files\Storage\Storage $storage */
     list($storage, $sourceInternalPath) = \OC\Files\Filesystem::resolvePath($source);
     return $storage->getPropagator()->propagateChange($sourceInternalPath, $time);
 }
Exemplo n.º 6
0
 protected function setUp()
 {
     parent::setUp();
     $this->user = $this->getUniqueID();
     $storage = new \OC\Files\Storage\Temporary(array());
     \OC\Files\Filesystem::mount($storage, array(), '/' . $this->user . '/');
 }
Exemplo n.º 7
0
 /**
  * Make sure your configuration file doesn't contain any additional providers
  */
 protected function setUp()
 {
     parent::setUp();
     $userManager = \OC::$server->getUserManager();
     $userManager->clearBackends();
     $backend = new \Test\Util\User\Dummy();
     $userManager->registerBackend($backend);
     $backend->createUser(self::TEST_PREVIEW_USER1, self::TEST_PREVIEW_USER1);
     $this->loginAsUser(self::TEST_PREVIEW_USER1);
     $storage = new \OC\Files\Storage\Temporary([]);
     \OC\Files\Filesystem::mount($storage, [], '/' . self::TEST_PREVIEW_USER1 . '/');
     $this->rootView = new \OC\Files\View('');
     $this->rootView->mkdir('/' . self::TEST_PREVIEW_USER1);
     $this->rootView->mkdir('/' . self::TEST_PREVIEW_USER1 . '/files');
     // We simulate the max dimension set in the config
     \OC::$server->getConfig()->setSystemValue('preview_max_x', $this->configMaxWidth);
     \OC::$server->getConfig()->setSystemValue('preview_max_y', $this->configMaxHeight);
     // Used to test upscaling
     $this->maxScaleFactor = 2;
     \OC::$server->getConfig()->setSystemValue('preview_max_scale_factor', $this->maxScaleFactor);
     // We need to enable the providers we're going to use in the tests
     $providers = ['OC\\Preview\\JPEG', 'OC\\Preview\\PNG', 'OC\\Preview\\GIF', 'OC\\Preview\\TXT', 'OC\\Preview\\Postscript'];
     \OC::$server->getConfig()->setSystemValue('enabledPreviewProviders', $providers);
     // Sample is 1680x1050 JPEG
     $this->prepareSample('testimage.jpg', 1680, 1050);
     // Sample is 2400x1707 EPS
     $this->prepareSample('testimage.eps', 2400, 1707);
     // Sample is 1200x450 PNG
     $this->prepareSample('testimage-wide.png', 1200, 450);
     // Sample is 64x64 GIF
     $this->prepareSample('testimage.gif', 64, 64);
 }
Exemplo n.º 8
0
 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;
 }
 private static function checkUpdate($id)
 {
     $cacheItem = Cache::getById($id);
     if (is_null($cacheItem)) {
         return;
     }
     list($storageId, $internalPath) = $cacheItem;
     $mounts = Filesystem::getMountByStorageId($storageId);
     if (count($mounts) === 0) {
         //if the storage we need isn't mounted on default, try to find a user that has access to the storage
         $permissionsCache = new Permissions($storageId);
         $users = $permissionsCache->getUsers($id);
         if (count($users) === 0) {
             return;
         }
         Filesystem::initMountPoints($users[0]);
         $mounts = Filesystem::getMountByStorageId($storageId);
         if (count($mounts) === 0) {
             return;
         }
     }
     $storage = $mounts[0]->getStorage();
     $watcher = new Watcher($storage);
     $watcher->checkUpdate($internalPath);
 }
Exemplo n.º 10
0
 /**
  * @NoAdminRequired
  * @NoCSRFRequired
  */
 public function Add()
 {
     \OCP\JSON::setContentTypeHeader('application/json');
     if (isset($_POST['FILE']) && strlen($_POST['FILE']) > 0 && Tools::CheckURL($_POST['FILE']) && isset($_POST['OPTIONS'])) {
         try {
             $Target = Tools::CleanString(substr($_POST['FILE'], strrpos($_POST['FILE'], '/') + 1));
             // If target file exists, create a new one
             if (\OC\Files\Filesystem::file_exists($this->DownloadsFolder . '/' . $Target)) {
                 $Target = time() . '_' . $Target;
             }
             // Create the target file if the downloader is Aria2
             if ($this->WhichDownloader == 0) {
                 \OC\Files\Filesystem::touch($this->DownloadsFolder . '/' . $Target);
             } else {
                 if (!\OC\Files\Filesystem::is_dir($this->DownloadsFolder)) {
                     \OC\Files\Filesystem::mkdir($this->DownloadsFolder);
                 }
             }
             // Build OPTIONS array
             $OPTIONS = array('dir' => $this->AbsoluteDownloadsFolder, 'out' => $Target, 'follow-torrent' => false);
             if (isset($_POST['OPTIONS']['FTPUser']) && strlen(trim($_POST['OPTIONS']['FTPUser'])) > 0 && isset($_POST['OPTIONS']['FTPPasswd']) && strlen(trim($_POST['OPTIONS']['FTPPasswd'])) > 0) {
                 $OPTIONS['ftp-user'] = $_POST['OPTIONS']['FTPUser'];
                 $OPTIONS['ftp-passwd'] = $_POST['OPTIONS']['FTPPasswd'];
             }
             if (isset($_POST['OPTIONS']['FTPPasv']) && strlen(trim($_POST['OPTIONS']['FTPPasv'])) > 0) {
                 $OPTIONS['ftp-pasv'] = strcmp($_POST['OPTIONS']['FTPPasv'], "true") == 0 ? true : false;
             }
             if (!$this->ProxyOnlyWithYTDL && !is_null($this->ProxyAddress) && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) {
                 $OPTIONS['all-proxy'] = rtrim($this->ProxyAddress, '/') . ':' . $this->ProxyPort;
                 if (!is_null($this->ProxyUser) && !is_null($this->ProxyPasswd)) {
                     $OPTIONS['all-proxy-user'] = $this->ProxyUser;
                     $OPTIONS['all-proxy-passwd'] = $this->ProxyPasswd;
                 }
             }
             $AddURI = $this->WhichDownloader == 0 ? Aria2::AddUri(array($_POST['FILE']), array('Params' => $OPTIONS)) : CURL::AddUri($_POST['FILE'], $OPTIONS);
             if (isset($AddURI['result']) && !is_null($AddURI['result'])) {
                 $SQL = 'INSERT INTO `*PREFIX*ocdownloader_queue` (`UID`, `GID`, `FILENAME`, `PROTOCOL`, `STATUS`, `TIMESTAMP`) VALUES (?, ?, ?, ?, ?, ?)';
                 if ($this->DbType == 1) {
                     $SQL = 'INSERT INTO *PREFIX*ocdownloader_queue ("UID", "GID", "FILENAME", "PROTOCOL", "STATUS", "TIMESTAMP") VALUES (?, ?, ?, ?, ?, ?)';
                 }
                 $Query = \OCP\DB::prepare($SQL);
                 $Result = $Query->execute(array($this->CurrentUID, $AddURI['result'], $Target, strtoupper(substr($_POST['FILE'], 0, strpos($_POST['FILE'], ':'))), 1, time()));
                 sleep(1);
                 $Status = $this->WhichDownloader == 0 ? Aria2::TellStatus($AddURI['result']) : CURL::TellStatus($AddURI['result']);
                 $Progress = 0;
                 if ($Status['result']['totalLength'] > 0) {
                     $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength'];
                 }
                 $ProgressString = Tools::GetProgressString($Status['result']['completedLength'], $Status['result']['totalLength'], $Progress);
                 return new JSONResponse(array('ERROR' => false, 'MESSAGE' => (string) $this->L10N->t('Download started'), 'GID' => $AddURI['result'], 'PROGRESSVAL' => round($Progress * 100, 2) . '%', 'PROGRESS' => is_null($ProgressString) ? (string) $this->L10N->t('N/A') : $ProgressString, 'STATUS' => isset($Status['result']['status']) ? (string) $this->L10N->t(ucfirst($Status['result']['status'])) : (string) $this->L10N->t('N/A'), 'STATUSID' => Tools::GetDownloadStatusID($Status['result']['status']), 'SPEED' => isset($Status['result']['downloadSpeed']) ? Tools::FormatSizeUnits($Status['result']['downloadSpeed']) . '/s' : (string) $this->L10N->t('N/A'), 'FILENAME' => strlen($Target) > 40 ? substr($Target, 0, 40) . '...' : $Target, 'PROTO' => strtoupper(substr($_POST['FILE'], 0, strpos($_POST['FILE'], ':'))), 'ISTORRENT' => false));
             } else {
                 return new JSONResponse(array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t($this->WhichDownloader == 0 ? 'Returned GID is null ! Is Aria2c running as a daemon ?' : 'An error occurred while running the CURL download')));
             }
         } catch (Exception $E) {
             return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage()));
         }
     } else {
         return new JSONResponse(array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t('Please check the URL you\'ve just provided')));
     }
 }
Exemplo n.º 11
0
 protected function setUp()
 {
     parent::setUp();
     if (!getenv('RUN_OBJECTSTORE_TESTS')) {
         $this->markTestSkipped('objectstore tests are unreliable in some environments');
     }
     // reset backend
     \OC_User::clearBackends();
     \OC_User::useBackend('database');
     // create users
     $users = array('test');
     foreach ($users as $userName) {
         \OC_User::deleteUser($userName);
         \OC_User::createUser($userName, $userName);
     }
     // main test user
     \OC_Util::tearDownFS();
     \OC_User::setUserId('');
     \OC\Files\Filesystem::tearDown();
     \OC_User::setUserId('test');
     $config = \OC::$server->getConfig()->getSystemValue('objectstore');
     $this->objectStorage = new ObjectStoreToTest($config['arguments']);
     $config['objectstore'] = $this->objectStorage;
     $this->instance = new ObjectStoreStorage($config);
 }
Exemplo n.º 12
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->sourceUser = $input->getArgument('source-user');
     $this->destinationUser = $input->getArgument('destination-user');
     if (!$this->userManager->userExists($this->sourceUser)) {
         $output->writeln("<error>Unknown source user {$this->sourceUser}</error>");
         return;
     }
     if (!$this->userManager->userExists($this->destinationUser)) {
         $output->writeln("<error>Unknown destination user {$this->destinationUser}</error>");
         return;
     }
     $date = date('c');
     $this->finalTarget = "{$this->destinationUser}/files/transferred from {$this->sourceUser} on {$date}";
     // setup filesystem
     Filesystem::initMountPoints($this->sourceUser);
     Filesystem::initMountPoints($this->destinationUser);
     // analyse source folder
     $this->analyse($output);
     // collect all the shares
     $this->collectUsersShares($output);
     // transfer the files
     $this->transfer($output);
     // restore the shares
     $this->restoreShares($output);
 }
Exemplo n.º 13
0
 /**
  * propagate the registered changes to their parent folders
  *
  * @param int $time (optional) the mtime to set for the folders, if not set the current time is used
  */
 public function propagateChanges($time = null)
 {
     $changes = $this->getChanges();
     $this->changedFiles = [];
     if (!$time) {
         $time = time();
     }
     foreach ($changes as $change) {
         /**
          * @var \OC\Files\Storage\Storage $storage
          * @var string $internalPath
          */
         $absolutePath = $this->view->getAbsolutePath($change);
         $mount = $this->view->getMount($change);
         $storage = $mount->getStorage();
         $internalPath = $mount->getInternalPath($absolutePath);
         if ($storage) {
             $propagator = $storage->getPropagator();
             $propagatedEntries = $propagator->propagateChange($internalPath, $time);
             foreach ($propagatedEntries as $entry) {
                 $absolutePath = Filesystem::normalizePath($mount->getMountPoint() . '/' . $entry['path']);
                 $relativePath = $this->view->getRelativePath($absolutePath);
                 $this->emit('\\OC\\Files', 'propagate', [$relativePath, $entry]);
             }
         }
     }
 }
Exemplo n.º 14
0
 public static function CheckFilepath($FP)
 {
     if (\OC\Files\Filesystem::file_exists($FP)) {
         return true;
     }
     return false;
 }
Exemplo n.º 15
0
 /**
  * rename a file
  *
  * @param string $dir
  * @param string $oldname
  * @param string $newname
  * @return array
  */
 public function rename($dir, $oldname, $newname)
 {
     $result = array('success' => false, 'data' => NULL);
     $normalizedOldPath = \OC\Files\Filesystem::normalizePath($dir . '/' . $oldname);
     $normalizedNewPath = \OC\Files\Filesystem::normalizePath($dir . '/' . $newname);
     // rename to non-existing folder is denied
     if (!$this->view->file_exists($normalizedOldPath)) {
         $result['data'] = array('message' => $this->l10n->t('%s could not be renamed as it has been deleted', array($oldname)), 'code' => 'sourcenotfound', 'oldname' => $oldname, 'newname' => $newname);
     } else {
         if (!$this->view->file_exists($dir)) {
             $result['data'] = array('message' => (string) $this->l10n->t('The target folder has been moved or deleted.', array($dir)), 'code' => 'targetnotfound');
             // rename to existing file is denied
         } else {
             if ($this->view->file_exists($normalizedNewPath)) {
                 $result['data'] = array('message' => $this->l10n->t("The name %s is already used in the folder %s. Please choose a different name.", array($newname, $dir)));
             } else {
                 if ($newname !== '.' and $this->view->rename($normalizedOldPath, $normalizedNewPath)) {
                     // successful rename
                     $meta = $this->view->getFileInfo($normalizedNewPath);
                     $meta = \OCA\Files\Helper::populateTags(array($meta));
                     $fileInfo = \OCA\Files\Helper::formatFileInfo(current($meta));
                     $fileInfo['path'] = dirname($normalizedNewPath);
                     $result['success'] = true;
                     $result['data'] = $fileInfo;
                 } else {
                     // rename failed
                     $result['data'] = array('message' => $this->l10n->t('%s could not be renamed', array($oldname)));
                 }
             }
         }
     }
     return $result;
 }
Exemplo n.º 16
0
 public function setUp()
 {
     if (!getenv('RUN_OBJECTSTORE_TESTS')) {
         $this->markTestSkipped('objectstore tests are unreliable on travis');
     }
     \OC_App::disable('files_sharing');
     \OC_App::disable('files_versions');
     // reset backend
     \OC_User::clearBackends();
     \OC_User::useBackend('database');
     // create users
     $users = array('test');
     foreach ($users as $userName) {
         \OC_User::deleteUser($userName);
         \OC_User::createUser($userName, $userName);
     }
     // main test user
     $userName = '******';
     \OC_Util::tearDownFS();
     \OC_User::setUserId('');
     \OC\Files\Filesystem::tearDown();
     \OC_User::setUserId('test');
     $testContainer = 'oc-test-container-' . substr(md5(rand()), 0, 7);
     $params = array('username' => 'facebook100000330192569', 'password' => 'Dbdj1sXnRSHxIGc4', 'container' => $testContainer, 'autocreate' => true, 'region' => 'RegionOne', 'url' => 'http://8.21.28.222:5000/v2.0', 'tenantName' => 'facebook100000330192569', 'serviceName' => 'swift', 'user' => \OC_User::getManager()->get($userName));
     $this->objectStorage = new ObjectStoreToTest($params);
     $params['objectstore'] = $this->objectStorage;
     $this->instance = new ObjectStoreStorage($params);
 }
Exemplo n.º 17
0
 public function __construct(array $urlParams = array())
 {
     parent::__construct('files_sharing', $urlParams);
     $container = $this->getContainer();
     $server = $container->getServer();
     /**
      * Controllers
      */
     $container->registerService('ShareController', function (SimpleContainer $c) use($server) {
         return new ShareController($c->query('AppName'), $c->query('Request'), $c->query('UserSession'), $server->getAppConfig(), $server->getConfig(), $c->query('URLGenerator'), $c->query('UserManager'), $server->getLogger(), $server->getActivityManager());
     });
     $container->registerService('ExternalSharesController', function (SimpleContainer $c) {
         return new ExternalSharesController($c->query('AppName'), $c->query('Request'), $c->query('IsIncomingShareEnabled'), $c->query('ExternalManager'), $c->query('HttpClientService'));
     });
     /**
      * Core class wrappers
      */
     $container->registerService('UserSession', function (SimpleContainer $c) use($server) {
         return $server->getUserSession();
     });
     $container->registerService('URLGenerator', function (SimpleContainer $c) use($server) {
         return $server->getUrlGenerator();
     });
     $container->registerService('UserManager', function (SimpleContainer $c) use($server) {
         return $server->getUserManager();
     });
     $container->registerService('HttpClientService', function (SimpleContainer $c) use($server) {
         return $server->getHTTPClientService();
     });
     $container->registerService('IsIncomingShareEnabled', function (SimpleContainer $c) {
         return Helper::isIncomingServer2serverShareEnabled();
     });
     $container->registerService('ExternalManager', function (SimpleContainer $c) use($server) {
         $user = $server->getUserSession()->getUser();
         $uid = $user ? $user->getUID() : null;
         return new \OCA\Files_Sharing\External\Manager($server->getDatabaseConnection(), \OC\Files\Filesystem::getMountManager(), \OC\Files\Filesystem::getLoader(), $server->getHTTPHelper(), $server->getNotificationManager(), $uid);
     });
     /**
      * Middleware
      */
     $container->registerService('SharingCheckMiddleware', function (SimpleContainer $c) use($server) {
         return new SharingCheckMiddleware($c->query('AppName'), $server->getConfig(), $server->getAppManager());
     });
     // Execute middlewares
     $container->registerMiddleware('SharingCheckMiddleware');
     $container->registerService('MountProvider', function (IContainer $c) {
         /** @var \OCP\IServerContainer $server */
         $server = $c->query('ServerContainer');
         return new MountProvider($server->getConfig(), $c->query('PropagationManager'));
     });
     $container->registerService('PropagationManager', function (IContainer $c) {
         /** @var \OCP\IServerContainer $server */
         $server = $c->query('ServerContainer');
         return new PropagationManager($server->getUserSession(), $server->getConfig());
     });
     /*
      * Register capabilities
      */
     $container->registerCapability('OCA\\Files_Sharing\\Capabilities');
 }
Exemplo n.º 18
0
 /**
  * Get the source cache of a shared file or folder
  *
  * @param string $target Shared target file path
  * @return \OC\Files\Cache\Cache
  */
 private function getSourceCache($target)
 {
     if ($target === false || $target === $this->storage->getMountPoint()) {
         $target = '';
     }
     $source = \OC_Share_Backend_File::getSource($target, $this->storage->getMountPoint(), $this->storage->getItemType());
     if (isset($source['path']) && isset($source['fileOwner'])) {
         try {
             \OC\Files\Filesystem::initMountPoints($source['fileOwner']);
         } catch (NoUserException $e) {
             \OC::$server->getLogger()->warning('The user \'' . $source['uid_owner'] . '\' of a share can\'t be retrieved.', array('app' => 'files_sharing'));
             return false;
         }
         $mounts = \OC\Files\Filesystem::getMountByNumericId($source['storage']);
         if (is_array($mounts) and !empty($mounts)) {
             $fullPath = $mounts[0]->getMountPoint() . $source['path'];
             list($storage, $internalPath) = \OC\Files\Filesystem::resolvePath($fullPath);
             if ($storage) {
                 $this->files[$target] = $internalPath;
                 $cache = $storage->getCache();
                 $this->storageId = $storage->getId();
                 $this->numericId = $cache->getNumericStorageId();
                 return $cache;
             }
         }
     }
     return false;
 }
Exemplo n.º 19
0
 public function testOC()
 {
     \OC\Files\Filesystem::clearMounts();
     $storage = new \OC\Files\Storage\Temporary(array());
     $storage->file_put_contents('foo.txt', 'asd');
     \OC\Files\Filesystem::mount($storage, array(), '/');
     $this->assertTrue(file_exists('oc:///foo.txt'));
     $this->assertEquals('asd', file_get_contents('oc:///foo.txt'));
     $this->assertEquals(array('.', '..', 'foo.txt'), scandir('oc:///'));
     file_put_contents('oc:///bar.txt', 'qwerty');
     $this->assertEquals('qwerty', $storage->file_get_contents('bar.txt'));
     $this->assertEquals(array('.', '..', 'bar.txt', 'foo.txt'), scandir('oc:///'));
     $this->assertEquals('qwerty', file_get_contents('oc:///bar.txt'));
     $fh = fopen('oc:///bar.txt', 'rb');
     $this->assertSame(0, ftell($fh));
     $content = fread($fh, 4);
     $this->assertSame(4, ftell($fh));
     $this->assertSame('qwer', $content);
     $content = fread($fh, 1);
     $this->assertSame(5, ftell($fh));
     $this->assertSame(0, fseek($fh, 0));
     $this->assertSame(0, ftell($fh));
     unlink('oc:///foo.txt');
     $this->assertEquals(array('.', '..', 'bar.txt'), scandir('oc:///'));
 }
Exemplo n.º 20
0
 /**
  * Hook that mounts the given user's visible mount points
  * @param array $data
  */
 public static function initMountPointsHook($data)
 {
     $mountPoints = self::getAbsoluteMountPoints($data['user']);
     foreach ($mountPoints as $mountPoint => $options) {
         \OC\Files\Filesystem::mount($options['class'], $options['options'], $mountPoint);
     }
 }
Exemplo n.º 21
0
 /**
  * constructor
  * @param string $user user to do avatar-management with
  * @throws \Exception In case the username is potentially dangerous
  */
 public function __construct($user)
 {
     if (!Filesystem::isValidPath($user)) {
         throw new \Exception('Username may not contain slashes');
     }
     $this->view = new \OC\Files\View('/' . $user);
 }
Exemplo n.º 22
0
 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();
 }
Exemplo n.º 23
0
 /**
  * Search for files and folders matching the given query
  * @param string $query
  * @return \OCP\Search\Result
  */
 function search($query)
 {
     $files = Filesystem::search($query);
     $results = array();
     // edit results
     foreach ($files as $fileData) {
         // skip versions
         if (strpos($fileData['path'], '_versions') === 0) {
             continue;
         }
         // skip top-level folder
         if ($fileData['name'] === 'files' && $fileData['parent'] === -1) {
             continue;
         }
         // create audio result
         if ($fileData['mimepart'] === 'audio') {
             $result = new \OC\Search\Result\Audio($fileData);
         } elseif ($fileData['mimepart'] === 'image') {
             $result = new \OC\Search\Result\Image($fileData);
         } elseif ($fileData['mimetype'] === 'httpd/unix-directory') {
             $result = new \OC\Search\Result\Folder($fileData);
         } else {
             $result = new \OC\Search\Result\File($fileData);
         }
         // add to results
         $results[] = $result;
     }
     // return
     return $results;
 }
 public static function setUpBeforeClass()
 {
     $appManager = \OC::$server->getAppManager();
     self::$trashBinStatus = $appManager->isEnabledForUser('files_trashbin');
     $appManager->disableApp('files_trashbin');
     // just in case...
     \OC\Files\Filesystem::getLoader()->removeStorageWrapper('oc_trashbin');
 }
Exemplo n.º 25
0
 /**
  * Returns metadata from the shared storage, but
  * with permissions from the source storage.
  *
  * @param string $path path of the file for which to retrieve metadata
  *
  * @return array an array of metadata of the file
  */
 protected function getData($path)
 {
     $data = parent::getData($path);
     $sourcePath = $this->storage->getSourcePath($path);
     list($sourceStorage, $internalPath) = \OC\Files\Filesystem::resolvePath($sourcePath);
     $data['permissions'] = $sourceStorage->getPermissions($internalPath);
     return $data;
 }
Exemplo n.º 26
0
 public function setUp()
 {
     $storage = new Temporary(array());
     $root = '/' . uniqid();
     Filesystem::mount($storage, array(), $root);
     $this->view = new View($root);
     $this->propagator = new \OC\Files\Cache\ChangePropagator($this->view);
 }
Exemplo n.º 27
0
	/**
	 * @param string[] $files
	 */
	private function getEtags($files) {
		$etags = array();
		foreach ($files as $file) {
			$info = Filesystem::getFileInfo($file);
			$etags[$file] = $info['etag'];
		}
		return $etags;
	}
 /**
  * @NoAdminRequired
  *
  * @param string $path
  * @param string $pass
  */
 public function validatePath($path, $pass)
 {
     if (\OC\Files\Filesystem::file_exists($path)) {
         return "true";
     } else {
         return $path;
     }
 }
Exemplo n.º 29
0
 public function checkScanWarning($fullPath, OutputInterface $output)
 {
     $normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
     $path = basename($fullPath);
     if ($normalizedPath !== $path) {
         $output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
     }
 }
Exemplo n.º 30
0
 protected function tearDown()
 {
     $result = \OC_User::deleteUser(self::$user);
     $this->assertTrue($result);
     \OC\Files\Filesystem::tearDown();
     \OC\Files\Filesystem::mount($this->originalStorage, array(), '/');
     parent::tearDown();
 }