Esempio 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);
         }
     }
 }
Esempio n. 2
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);
 }
Esempio n. 3
0
 /**
  * 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;
     }
 }
Esempio n. 4
0
 /**
  * Returns the matching file info
  *
  * @return FileInfo
  * @throws InvalidPathException
  * @throws NotFoundException
  */
 public function getFileInfo()
 {
     if (!Filesystem::isValidPath($this->path)) {
         throw new InvalidPathException();
     }
     if (!$this->fileInfo) {
         $fileInfo = $this->view->getFileInfo($this->path);
         if ($fileInfo instanceof FileInfo) {
             $this->fileInfo = $fileInfo;
         } else {
             throw new NotFoundException();
         }
     }
     return $this->fileInfo;
 }
Esempio n. 5
0
 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;
     }
     $galleryDir = \OC_User::getHome($this->user) . '/gallery/' . $this->user . '/';
     $this->path = $galleryDir . $imagePath . '.png';
     if (!file_exists($this->path)) {
         self::create($imagePath, $square);
     }
 }
Esempio n. 6
0
 /**
  * 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;
     }
     if (!$view->file_exists($path)) {
         Util::writeLog('search_lucene', 'file vanished, ignoring', Util::DEBUG);
         return true;
     }
     $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'];
         // initialize plain lucene document
         $doc = new \Zend_Search_Lucene_Document();
         // index content for local files only
         $localFile = $view->getLocalFile($path);
         if ($localFile) {
             //try to use special lucene document types
             if ('text/plain' === $mimeType) {
                 $body = $view->file_get_contents($path);
                 if ($body != '') {
                     $doc->addField(\Zend_Search_Lucene_Field::UnStored('body', $body));
                 }
             } else {
                 if ('text/html' === $mimeType) {
                     //TODO could be indexed, even if not local
                     $doc = \Zend_Search_Lucene_Document_Html::loadHTML($view->file_get_contents($path));
                 } else {
                     if ('application/pdf' === $mimeType) {
                         $doc = Pdf::loadPdf($view->file_get_contents($path));
                         // commented the mimetype checks, as the zend classes only understand docx and not doc files.
                         // FIXME distinguish doc and docx, xls and xlsx, ppt and pptx, in oc core mimetype helper ...
                         //} else if ('application/msword' === $mimeType) {
                     } else {
                         if (strtolower(substr($data['name'], -5)) === '.docx') {
                             $doc = \Zend_Search_Lucene_Document_Docx::loadDocxFile($localFile);
                             //} else if ('application/msexcel' === $mimeType) {
                         } else {
                             if (strtolower(substr($data['name'], -5)) === '.xlsx') {
                                 $doc = \Zend_Search_Lucene_Document_Xlsx::loadXlsxFile($localFile);
                                 //} else if ('application/mspowerpoint' === $mimeType) {
                             } else {
                                 if (strtolower(substr($data['name'], -5)) === '.pptx') {
                                     $doc = \Zend_Search_Lucene_Document_Pptx::loadPptxFile($localFile);
                                 } else {
                                     if (strtolower(substr($data['name'], -4)) === '.odt') {
                                         $doc = Odt::loadOdtFile($localFile);
                                     } else {
                                         if (strtolower(substr($data['name'], -4)) === '.ods') {
                                             $doc = Ods::loadOdsFile($localFile);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         // Store filecache id as unique id to lookup by when deleting
         $doc->addField(\Zend_Search_Lucene_Field::Keyword('pk', $pk));
         // Store filename
         $doc->addField(\Zend_Search_Lucene_Field::Text('filename', $data['name'], 'UTF-8'));
         // Store document path to identify it in the search results
         $doc->addField(\Zend_Search_Lucene_Field::Text('path', $path, 'UTF-8'));
         $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;
     }
 }
Esempio n. 7
0
 /**
  * @dataProvider isValidPathData
  */
 public function testIsValidPath($path, $expected)
 {
     $this->assertSame($expected, \OC\Files\Filesystem::isValidPath($path));
 }
Esempio n. 8
0
 /**
  * get the content of a directory
  *
  * @param string $directory path under datadirectory
  * @param string $mimetype_filter limit returned content to this mimetype or mimepart
  * @return FileInfo[]
  */
 public function getDirectoryContent($directory, $mimetype_filter = '')
 {
     $this->assertPathLength($directory);
     $result = array();
     if (!Filesystem::isValidPath($directory)) {
         return $result;
     }
     $path = Filesystem::normalizePath($this->fakeRoot . '/' . $directory);
     list($storage, $internalPath) = Filesystem::resolvePath($path);
     if ($storage) {
         $cache = $storage->getCache($internalPath);
         $user = \OC_User::getUser();
         if ($cache->getStatus($internalPath) < Cache\Cache::COMPLETE) {
             $scanner = $storage->getScanner($internalPath);
             $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
         } else {
             $watcher = $storage->getWatcher($internalPath);
             $watcher->checkUpdate($internalPath);
         }
         $folderId = $cache->getId($internalPath);
         /**
          * @var \OC\Files\FileInfo[] $files
          */
         $files = array();
         $contents = $cache->getFolderContents($internalPath, $folderId);
         //TODO: mimetype_filter
         foreach ($contents as $content) {
             if ($content['permissions'] === 0) {
                 $content['permissions'] = $storage->getPermissions($content['path']);
                 $cache->update($content['fileid'], array('permissions' => $content['permissions']));
             }
             $files[] = new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content);
         }
         //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
         $mounts = Filesystem::getMountManager()->findIn($path);
         $dirLength = strlen($path);
         foreach ($mounts as $mount) {
             $mountPoint = $mount->getMountPoint();
             $subStorage = Filesystem::getStorage($mountPoint);
             if ($subStorage) {
                 $subCache = $subStorage->getCache('');
                 if ($subCache->getStatus('') === Cache\Cache::NOT_FOUND) {
                     $subScanner = $subStorage->getScanner('');
                     $subScanner->scanFile('');
                 }
                 $rootEntry = $subCache->get('');
                 if ($rootEntry) {
                     $relativePath = trim(substr($mountPoint, $dirLength), '/');
                     if ($pos = strpos($relativePath, '/')) {
                         //mountpoint inside subfolder add size to the correct folder
                         $entryName = substr($relativePath, 0, $pos);
                         foreach ($files as &$entry) {
                             if ($entry['name'] === $entryName) {
                                 $entry['size'] += $rootEntry['size'];
                             }
                         }
                     } else {
                         //mountpoint in this folder, add an entry for it
                         $rootEntry['name'] = $relativePath;
                         $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
                         $permissions = $rootEntry['permissions'];
                         // do not allow renaming/deleting the mount point if they are not shared files/folders
                         // for shared files/folders we use the permissions given by the owner
                         if ($mount instanceof MoveableMount) {
                             $rootEntry['permissions'] = $permissions | \OCP\PERMISSION_UPDATE | \OCP\PERMISSION_DELETE;
                         } else {
                             $rootEntry['permissions'] = $permissions & \OCP\PERMISSION_ALL - (\OCP\PERMISSION_UPDATE | \OCP\PERMISSION_DELETE);
                         }
                         //remove any existing entry with the same name
                         foreach ($files as $i => $file) {
                             if ($file['name'] === $rootEntry['name']) {
                                 unset($files[$i]);
                                 break;
                             }
                         }
                         $rootEntry['path'] = substr($path . '/' . $rootEntry['name'], strlen($user) + 2);
                         // full path without /$user/
                         $files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry);
                     }
                 }
             }
         }
         if ($mimetype_filter) {
             foreach ($files as $file) {
                 if (strpos($mimetype_filter, '/')) {
                     if ($file['mimetype'] === $mimetype_filter) {
                         $result[] = $file;
                     }
                 } else {
                     if ($file['mimepart'] === $mimetype_filter) {
                         $result[] = $file;
                     }
                 }
             }
         } else {
             $result = $files;
         }
     }
     return $result;
 }
 /**
  * Remove the certificate and re-generate the certificate bundle
  *
  * @param string $name
  * @return bool
  */
 public function removeCertificate($name)
 {
     if (!Filesystem::isValidPath($name)) {
         return false;
     }
     $path = $this->getPathToCertificates() . 'uploads/';
     if ($this->view->file_exists($path . $name)) {
         $this->view->unlink($path . $name);
         $this->createCertificateBundle();
     }
     return true;
 }
Esempio n. 10
0
 /**
  * get the content of a directory
  *
  * @param string $directory path under datadirectory
  * @param string $mimetype_filter limit returned content to this mimetype or mimepart
  * @return FileInfo[]
  */
 public function getDirectoryContent($directory, $mimetype_filter = '')
 {
     $this->assertPathLength($directory);
     $result = array();
     if (!Filesystem::isValidPath($directory)) {
         return $result;
     }
     $path = $this->getAbsolutePath($directory);
     $path = Filesystem::normalizePath($path);
     $mount = $this->getMount($directory);
     $storage = $mount->getStorage();
     $internalPath = $mount->getInternalPath($path);
     if ($storage) {
         $cache = $storage->getCache($internalPath);
         $user = \OC_User::getUser();
         $data = $cache->get($internalPath);
         $watcher = $storage->getWatcher($internalPath);
         if (!$data or $data['size'] === -1) {
             if (!$storage->file_exists($internalPath)) {
                 return array();
             }
             $scanner = $storage->getScanner($internalPath);
             $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
             $data = $cache->get($internalPath);
         } else {
             if ($watcher->checkUpdate($internalPath, $data)) {
                 $this->updater->propagate($path);
                 $data = $cache->get($internalPath);
             }
         }
         $folderId = $data['fileid'];
         /**
          * @var \OC\Files\FileInfo[] $files
          */
         $files = array();
         $contents = $cache->getFolderContentsById($folderId);
         //TODO: mimetype_filter
         foreach ($contents as $content) {
             if ($content['permissions'] === 0) {
                 $content['permissions'] = $storage->getPermissions($content['path']);
                 $cache->update($content['fileid'], array('permissions' => $content['permissions']));
             }
             // if sharing was disabled for the user we remove the share permissions
             if (\OCP\Util::isSharingDisabledForUser()) {
                 $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
             }
             $files[] = new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount);
         }
         //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
         $mounts = Filesystem::getMountManager()->findIn($path);
         $dirLength = strlen($path);
         foreach ($mounts as $mount) {
             $mountPoint = $mount->getMountPoint();
             $subStorage = $mount->getStorage();
             if ($subStorage) {
                 $subCache = $subStorage->getCache('');
                 if ($subCache->getStatus('') === Cache\Cache::NOT_FOUND) {
                     $subScanner = $subStorage->getScanner('');
                     try {
                         $subScanner->scanFile('');
                     } catch (\OCP\Files\StorageNotAvailableException $e) {
                         continue;
                     } catch (\OCP\Files\StorageInvalidException $e) {
                         continue;
                     } catch (\Exception $e) {
                         // sometimes when the storage is not available it can be any exception
                         \OCP\Util::writeLog('core', 'Exception while scanning storage "' . $subStorage->getId() . '": ' . get_class($e) . ': ' . $e->getMessage(), \OCP\Util::ERROR);
                         continue;
                     }
                 }
                 $rootEntry = $subCache->get('');
                 if ($rootEntry) {
                     $relativePath = trim(substr($mountPoint, $dirLength), '/');
                     if ($pos = strpos($relativePath, '/')) {
                         //mountpoint inside subfolder add size to the correct folder
                         $entryName = substr($relativePath, 0, $pos);
                         foreach ($files as &$entry) {
                             if ($entry['name'] === $entryName) {
                                 $entry['size'] += $rootEntry['size'];
                             }
                         }
                     } else {
                         //mountpoint in this folder, add an entry for it
                         $rootEntry['name'] = $relativePath;
                         $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
                         $permissions = $rootEntry['permissions'];
                         // do not allow renaming/deleting the mount point if they are not shared files/folders
                         // for shared files/folders we use the permissions given by the owner
                         if ($mount instanceof MoveableMount) {
                             $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
                         } else {
                             $rootEntry['permissions'] = $permissions & \OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE);
                         }
                         //remove any existing entry with the same name
                         foreach ($files as $i => $file) {
                             if ($file['name'] === $rootEntry['name']) {
                                 unset($files[$i]);
                                 break;
                             }
                         }
                         $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2);
                         // full path without /$user/
                         // if sharing was disabled for the user we remove the share permissions
                         if (\OCP\Util::isSharingDisabledForUser()) {
                             $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
                         }
                         $files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount);
                     }
                 }
             }
         }
         if ($mimetype_filter) {
             foreach ($files as $file) {
                 if (strpos($mimetype_filter, '/')) {
                     if ($file['mimetype'] === $mimetype_filter) {
                         $result[] = $file;
                     }
                 } else {
                     if ($file['mimepart'] === $mimetype_filter) {
                         $result[] = $file;
                     }
                 }
             }
         } else {
             $result = $files;
         }
     }
     return $result;
 }
Esempio n. 11
0
 /**
  * @param string $dir
  * @throws \OC\ForbiddenException
  */
 public function scan($dir = '')
 {
     if (!Filesystem::isValidPath($dir)) {
         throw new \InvalidArgumentException('Invalid path to scan');
     }
     $mounts = $this->getMounts($dir);
     foreach ($mounts as $mount) {
         if (is_null($mount->getStorage())) {
             continue;
         }
         $storage = $mount->getStorage();
         // if the home storage isn't writable then the scanner is run as the wrong user
         if ($storage->instanceOfStorage('\\OC\\Files\\Storage\\Home') and (!$storage->isCreatable('') or !$storage->isCreatable('files'))) {
             throw new ForbiddenException();
         }
         $relativePath = $mount->getInternalPath($dir);
         $scanner = $storage->getScanner();
         $scanner->setUseTransactions(false);
         $this->attachListener($mount);
         $this->db->beginTransaction();
         $scanner->scan($relativePath, \OC\Files\Cache\Scanner::SCAN_RECURSIVE, \OC\Files\Cache\Scanner::REUSE_ETAG | \OC\Files\Cache\Scanner::REUSE_SIZE);
         $this->db->commit();
     }
     $this->propagator->propagateChanges(time());
 }
Esempio n. 12
0
    }
}
$files = $_FILES['files'];
$error = false;
$maxUploadFileSize = $storageStats['uploadMaxFilesize'];
$maxHumanFileSize = OCP\Util::humanFileSize($maxUploadFileSize);
$totalSize = 0;
foreach ($files['size'] as $size) {
    $totalSize += $size;
}
if ($maxUploadFileSize >= 0 and $totalSize > $maxUploadFileSize) {
    OCP\JSON::error(array('data' => array('message' => $l->t('Not enough storage available'), 'uploadMaxFilesize' => $maxUploadFileSize, 'maxHumanFilesize' => $maxHumanFileSize)));
    exit;
}
$result = array();
if (\OC\Files\Filesystem::isValidPath($dir) === true) {
    $fileCount = count($files['name']);
    for ($i = 0; $i < $fileCount; $i++) {
        if (isset($_POST['resolution'])) {
            $resolution = $_POST['resolution'];
        } else {
            $resolution = null;
        }
        // target directory for when uploading folders
        $relativePath = '';
        if (!empty($_POST['file_directory'])) {
            $relativePath = '/' . $_POST['file_directory'];
        }
        // $path needs to be normalized - this failed within drag'n'drop upload to a sub-folder
        if ($resolution === 'autorename') {
            // append a number in brackets like 'filename (2).ext'
Esempio n. 13
0
 /**
  * check if the requested path is valid
  *
  * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem
  * @param string $path
  * @return bool
  */
 public static function isValidPath($path)
 {
     return \OC\Files\Filesystem::isValidPath($path);
 }
Esempio n. 14
0
 /**
  * Remove the certificate and re-generate the certificate bundle
  *
  * @param string $name
  * @return bool
  */
 public function removeCertificate($name)
 {
     if (!Filesystem::isValidPath($name)) {
         return false;
     }
     $path = $this->user->getHome() . '/files_external/uploads/';
     if (file_exists($path . $name)) {
         unlink($path . $name);
         $this->createCertificateBundle();
     }
     return true;
 }
Esempio n. 15
0
 /**
  * Assembles the chunks into the file specified by the path.
  * Also triggers the relevant hooks and proxies.
  *
  * @param \OC\Files\Storage\Storage $storage storage
  * @param string $path target path relative to the storage
  * @return bool true on success or false if file could not be created
  *
  * @throws \OC\ServerNotAvailableException
  */
 public function file_assemble($storage, $path)
 {
     // use file_put_contents as method because that best matches what this function does
     if (\OC\Files\Filesystem::isValidPath($path)) {
         $target = $storage->fopen($path, 'w');
         if ($target) {
             $count = $this->assemble($target);
             fclose($target);
             return $count > 0;
         } else {
             return false;
         }
     }
     return false;
 }
Esempio n. 16
0
 public function file_assemble($path)
 {
     $absolutePath = \OC\Files\Filesystem::normalizePath(\OC\Files\Filesystem::getView()->getAbsolutePath($path));
     $data = '';
     // use file_put_contents as method because that best matches what this function does
     if (OC_FileProxy::runPreProxies('file_put_contents', $absolutePath, $data) && \OC\Files\Filesystem::isValidPath($path)) {
         $path = \OC\Files\Filesystem::getView()->getRelativePath($absolutePath);
         $exists = \OC\Files\Filesystem::file_exists($path);
         $run = true;
         if (!$exists) {
             OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, array(\OC\Files\Filesystem::signal_param_path => $path, \OC\Files\Filesystem::signal_param_run => &$run));
         }
         OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, array(\OC\Files\Filesystem::signal_param_path => $path, \OC\Files\Filesystem::signal_param_run => &$run));
         if (!$run) {
             return false;
         }
         $target = \OC\Files\Filesystem::fopen($path, 'w');
         if ($target) {
             $count = $this->assemble($target);
             fclose($target);
             if (!$exists) {
                 OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, array(\OC\Files\Filesystem::signal_param_path => $path));
             }
             OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, array(\OC\Files\Filesystem::signal_param_path => $path));
             OC_FileProxy::runPostProxies('file_put_contents', $absolutePath, $count);
             return $count > 0;
         } else {
             return false;
         }
     }
 }
Esempio n. 17
0
 /**
  * Assembles the chunks into the file specified by the path.
  * Also triggers the relevant hooks and proxies.
  *
  * @param \OC\Files\Storage\Storage $storage
  * @param string $path target path relative to the storage
  * @param string $absolutePath
  * @return bool assembled file size or false if file could not be created
  *
  * @throws \OC\ServerNotAvailableException
  */
 public function file_assemble($storage, $path, $absolutePath)
 {
     $data = '';
     // use file_put_contents as method because that best matches what this function does
     if (\OC\Files\Filesystem::isValidPath($path)) {
         $exists = $storage->file_exists($path);
         $run = true;
         $hookPath = \OC\Files\Filesystem::getView()->getRelativePath($absolutePath);
         if (!$exists) {
             OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, array(\OC\Files\Filesystem::signal_param_path => $hookPath, \OC\Files\Filesystem::signal_param_run => &$run));
         }
         OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, array(\OC\Files\Filesystem::signal_param_path => $hookPath, \OC\Files\Filesystem::signal_param_run => &$run));
         if (!$run) {
             return false;
         }
         $target = $storage->fopen($path, 'w');
         if ($target) {
             $count = $this->assemble($target);
             fclose($target);
             if (!$exists) {
                 OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, array(\OC\Files\Filesystem::signal_param_path => $hookPath));
             }
             OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, array(\OC\Files\Filesystem::signal_param_path => $hookPath));
             return $count > 0;
         } else {
             return false;
         }
     }
     return false;
 }
Esempio n. 18
0
 /**
  * @param string $dir
  * @throws \OC\ForbiddenException
  */
 public function scan($dir = '')
 {
     if (!Filesystem::isValidPath($dir)) {
         throw new \InvalidArgumentException('Invalid path to scan');
     }
     $mounts = $this->getMounts($dir);
     foreach ($mounts as $mount) {
         if (is_null($mount->getStorage())) {
             continue;
         }
         $storage = $mount->getStorage();
         // if the home storage isn't writable then the scanner is run as the wrong user
         if ($storage->instanceOfStorage('\\OC\\Files\\Storage\\Home') and (!$storage->isCreatable('') or !$storage->isCreatable('files'))) {
             throw new ForbiddenException();
         }
         $relativePath = $mount->getInternalPath($dir);
         $scanner = $storage->getScanner();
         $scanner->setUseTransactions(false);
         $this->attachListener($mount);
         $isDbLocking = \OC::$server->getLockingProvider() instanceof DBLockingProvider;
         if (!$isDbLocking) {
             $this->db->beginTransaction();
         }
         try {
             $scanner->scan($relativePath, \OC\Files\Cache\Scanner::SCAN_RECURSIVE, \OC\Files\Cache\Scanner::REUSE_ETAG | \OC\Files\Cache\Scanner::REUSE_SIZE);
         } catch (StorageNotAvailableException $e) {
             $this->logger->error('Storage ' . $storage->getId() . ' not available');
             $this->logger->logException($e);
             $this->emit('\\OC\\Files\\Utils\\Scanner', 'StorageNotAvailable', [$e]);
         }
         if (!$isDbLocking) {
             $this->db->commit();
         }
     }
 }
Esempio n. 19
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $user = $input->getOption('user');
     $mountPoint = $input->getArgument('mount_point');
     $storageIdentifier = $input->getArgument('storage_backend');
     $authIdentifier = $input->getArgument('authentication_backend');
     $configInput = $input->getOption('config');
     $storageBackend = $this->backendService->getBackend($storageIdentifier);
     $authBackend = $this->backendService->getAuthMechanism($authIdentifier);
     if (!Filesystem::isValidPath($mountPoint)) {
         $output->writeln('<error>Invalid mountpoint "' . $mountPoint . '"</error>');
         return 1;
     }
     if (is_null($storageBackend)) {
         $output->writeln('<error>Storage backend with identifier "' . $storageIdentifier . '" not found (see `occ files_external:backends` for possible values)</error>');
         return 404;
     }
     if (is_null($authBackend)) {
         $output->writeln('<error>Authentication backend with identifier "' . $authIdentifier . '" not found (see `occ files_external:backends` for possible values)</error>');
         return 404;
     }
     $supportedSchemes = array_keys($storageBackend->getAuthSchemes());
     if (!in_array($authBackend->getScheme(), $supportedSchemes)) {
         $output->writeln('<error>Authentication backend "' . $authIdentifier . '" not valid for storage backend "' . $storageIdentifier . '" (see `occ files_external:backends storage ' . $storageIdentifier . '` for possible values)</error>');
         return 1;
     }
     $config = [];
     foreach ($configInput as $configOption) {
         if (!strpos($configOption, '=')) {
             $output->writeln('<error>Invalid mount configuration option "' . $configOption . '"</error>');
             return 1;
         }
         list($key, $value) = explode('=', $configOption, 2);
         if (!$this->validateParam($key, $value, $storageBackend, $authBackend)) {
             $output->writeln('<error>Unknown configuration for backends "' . $key . '"</error>');
             return 1;
         }
         $config[$key] = $value;
     }
     $mount = new StorageConfig();
     $mount->setMountPoint($mountPoint);
     $mount->setBackend($storageBackend);
     $mount->setAuthMechanism($authBackend);
     $mount->setBackendOptions($config);
     if ($user) {
         if (!$this->userManager->userExists($user)) {
             $output->writeln('<error>User "' . $user . '" not found</error>');
             return 1;
         }
         $mount->setApplicableUsers([$user]);
     }
     if ($input->getOption('dry')) {
         $this->showMount($user, $mount, $input, $output);
     } else {
         $this->getStorageService($user)->addStorage($mount);
         if ($input->getOption('output') === self::OUTPUT_FORMAT_PLAIN) {
             $output->writeln('<info>Storage created with id ' . $mount->getId() . '</info>');
         } else {
             $output->writeln($mount->getId());
         }
     }
     return 0;
 }
Esempio n. 20
0
$userId = $rootLinkItem['uid_owner'];
OCP\JSON::checkUserExists($rootLinkItem['uid_owner']);
\OC_Util::setupFS($userId);
\OC\Files\Filesystem::initMountPoints($userId);
$view = new \OC\Files\View('/' . $userId . '/files');
$pathId = $linkedItem['file_source'];
$path = $view->getPath($pathId);
if ($path === null) {
    \OC_Response::setStatus(\OC_Response::STATUS_NOT_FOUND);
    \OCP\Util::writeLog('core-preview', 'Could not resolve file for shared item', \OCP\Util::WARN);
    exit;
}
$pathInfo = $view->getFileInfo($path);
$sharedFile = null;
if ($linkedItem['item_type'] === 'folder') {
    $isValid = \OC\Files\Filesystem::isValidPath($file);
    if (!$isValid) {
        \OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
        \OCP\Util::writeLog('core-preview', 'Passed filename is not valid, might be malicious (file:"' . $file . '";ip:"' . \OC::$server->getRequest()->getRemoteAddress() . '")', \OCP\Util::WARN);
        exit;
    }
    $sharedFile = \OC\Files\Filesystem::normalizePath($file);
}
if ($linkedItem['item_type'] === 'file') {
    $parent = $pathInfo['parent'];
    $path = $view->getPath($parent);
    $sharedFile = $pathInfo['name'];
}
$path = \OC\Files\Filesystem::normalizePath($path, false);
if (substr($path, 0, 1) === '/') {
    $path = substr($path, 1);
Esempio n. 21
0
 /**
  * @param string $dir
  * @throws \OC\ForbiddenException
  */
 public function scan($dir = '')
 {
     if (!Filesystem::isValidPath($dir)) {
         throw new \InvalidArgumentException('Invalid path to scan');
     }
     $mounts = $this->getMounts($dir);
     foreach ($mounts as $mount) {
         if (is_null($mount->getStorage())) {
             continue;
         }
         $storage = $mount->getStorage();
         // if the home storage isn't writable then the scanner is run as the wrong user
         if ($storage->instanceOfStorage('\\OC\\Files\\Storage\\Home') and (!$storage->isCreatable('') or !$storage->isCreatable('files'))) {
             if ($storage->file_exists('') or $storage->getCache()->inCache('')) {
                 throw new ForbiddenException();
             } else {
                 // if the root exists in neither the cache nor the storage the user isn't setup yet
                 break;
             }
         }
         $relativePath = $mount->getInternalPath($dir);
         $scanner = $storage->getScanner();
         $scanner->setUseTransactions(false);
         $this->attachListener($mount);
         $isDbLocking = \OC::$server->getLockingProvider() instanceof DBLockingProvider;
         $scanner->listen('\\OC\\Files\\Cache\\Scanner', 'removeFromCache', function ($path) use($storage) {
             $this->triggerPropagator($storage, $path);
         });
         $scanner->listen('\\OC\\Files\\Cache\\Scanner', 'updateCache', function ($path) use($storage) {
             $this->triggerPropagator($storage, $path);
         });
         $scanner->listen('\\OC\\Files\\Cache\\Scanner', 'addToCache', function ($path) use($storage) {
             $this->triggerPropagator($storage, $path);
         });
         if (!$isDbLocking) {
             $this->db->beginTransaction();
         }
         try {
             $storage->getPropagator()->beginBatch();
             $scanner->scan($relativePath, \OC\Files\Cache\Scanner::SCAN_RECURSIVE, \OC\Files\Cache\Scanner::REUSE_ETAG | \OC\Files\Cache\Scanner::REUSE_SIZE);
             $cache = $storage->getCache();
             if ($cache instanceof Cache) {
                 // only re-calculate for the root folder we scanned, anything below that is taken care of by the scanner
                 $cache->correctFolderSize($relativePath);
             }
             $storage->getPropagator()->commitBatch();
         } catch (StorageNotAvailableException $e) {
             $this->logger->error('Storage ' . $storage->getId() . ' not available');
             $this->logger->logException($e);
             $this->emit('\\OC\\Files\\Utils\\Scanner', 'StorageNotAvailable', [$e]);
         }
         if (!$isDbLocking) {
             $this->db->commit();
         }
     }
 }