/** * Updates the data * * The data argument is a readable stream resource. * * After a succesful put operation, you may choose to return an ETag. The * etag must always be surrounded by double-quotes. These quotes must * appear in the actual string you're returning. * * Clients may use the ETag from a PUT request to later on make sure that * when they update the file, the contents haven't changed in the mean * time. * * If you don't plan to store the file byte-by-byte, and you return a * different object on a subsequent GET you are strongly recommended to not * return an ETag, and just return null. * * @param resource $data * @throws Sabre_DAV_Exception_Forbidden * @return string|null */ public function put($data) { if (!\OC\Files\Filesystem::isUpdatable($this->path)) { throw new \Sabre_DAV_Exception_Forbidden(); } // mark file as partial while uploading (ignored by the scanner) $partpath = $this->path . '.part'; \OC\Files\Filesystem::file_put_contents($partpath, $data); //detect aborted upload if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PUT') { if (isset($_SERVER['CONTENT_LENGTH'])) { $expected = $_SERVER['CONTENT_LENGTH']; $actual = \OC\Files\Filesystem::filesize($partpath); if ($actual != $expected) { \OC\Files\Filesystem::unlink($partpath); throw new Sabre_DAV_Exception_BadRequest('expected filesize ' . $expected . ' got ' . $actual); } } } // rename to correct path \OC\Files\Filesystem::rename($partpath, $this->path); //allow sync clients to send the mtime along in a header $mtime = OC_Request::hasModificationTime(); if ($mtime !== false) { if (\OC\Files\Filesystem::touch($this->path, $mtime)) { header('X-OC-MTime: accepted'); } } return OC_Connector_Sabre_Node::getETagPropertyForPath($this->path); }
public static function getPresentations() { $presentations = array(); $list = \OC\Files\Filesystem::searchByMime('text/impress'); foreach ($list as $l) { $info = pathinfo($l); $size = \OC\Files\Filesystem::filesize($l); $mtime = \OC\Files\Filesystem::filemtime($l); $entry = array('url' => $l, 'name' => $info['filename'], 'size' => $size, 'mtime' => $mtime); $presentations[] = $entry; } return $presentations; }
/** * @param string $filename * @param string $name * @param bool $zip */ private static function sendHeaders($filename, $name, $zip = false) { OC_Response::setContentDispositionHeader($name, 'attachment'); header('Content-Transfer-Encoding: binary'); OC_Response::disableCaching(); if ($zip) { header('Content-Type: application/zip'); } else { $filesize = \OC\Files\Filesystem::filesize($filename); header('Content-Type: '.\OC_Helper::getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename))); if ($filesize > -1) { OC_Response::setContentLengthHeader($filesize); } } }
/** * Creates a new file in the directory * * Data will either be supplied as a stream resource, or in certain cases * as a string. Keep in mind that you may have to support either. * * After succesful creation of the file, you may choose to return the ETag * of the new file here. * * The returned ETag must be surrounded by double-quotes (The quotes should * be part of the actual string). * * If you cannot accurately determine the ETag, you should not return it. * If you don't store the file exactly as-is (you're transforming it * somehow) you should also not return an ETag. * * This means that if a subsequent GET to this new file does not exactly * return the same contents of what was submitted here, you are strongly * recommended to omit the ETag. * * @param string $name Name of the file * @param resource|string $data Initial payload * @throws Sabre_DAV_Exception_Forbidden * @return null|string */ public function createFile($name, $data = null) { if (!\OC\Files\Filesystem::isCreatable($this->path)) { throw new \Sabre_DAV_Exception_Forbidden(); } if (isset($_SERVER['HTTP_OC_CHUNKED'])) { $info = OC_FileChunking::decodeName($name); if (empty($info)) { throw new Sabre_DAV_Exception_NotImplemented(); } $chunk_handler = new OC_FileChunking($info); $chunk_handler->store($info['index'], $data); if ($chunk_handler->isComplete()) { $newPath = $this->path . '/' . $info['name']; $chunk_handler->file_assemble($newPath); return OC_Connector_Sabre_Node::getETagPropertyForPath($newPath); } } else { $newPath = $this->path . '/' . $name; // mark file as partial while uploading (ignored by the scanner) $partpath = $newPath . '.part'; \OC\Files\Filesystem::file_put_contents($partpath, $data); //detect aborted upload if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PUT') { if (isset($_SERVER['CONTENT_LENGTH'])) { $expected = $_SERVER['CONTENT_LENGTH']; $actual = \OC\Files\Filesystem::filesize($partpath); if ($actual != $expected) { \OC\Files\Filesystem::unlink($partpath); throw new Sabre_DAV_Exception_BadRequest('expected filesize ' . $expected . ' got ' . $actual); } } } // rename to correct path \OC\Files\Filesystem::rename($partpath, $newPath); // allow sync clients to send the mtime along in a header $mtime = OC_Request::hasModificationTime(); if ($mtime !== false) { if (\OC\Files\Filesystem::touch($newPath, $mtime)) { header('X-OC-MTime: accepted'); } } return OC_Connector_Sabre_Node::getETagPropertyForPath($newPath); } return null; }
/** * Stream directory recursively * @param string $dir * @param string $internalDir */ public function addDirRecursive($dir, $internalDir = '') { $dirname = basename($dir); $rootDir = $internalDir . $dirname; if (!empty($rootDir)) { $this->streamerInstance->addEmptyDir($rootDir); } $internalDir .= $dirname . '/'; // prevent absolute dirs $internalDir = ltrim($internalDir, '/'); $files = \OC\Files\Filesystem::getDirectoryContent($dir); foreach ($files as $file) { $filename = $file['name']; $file = $dir . '/' . $filename; if (\OC\Files\Filesystem::is_file($file)) { $filesize = \OC\Files\Filesystem::filesize($file); $fh = \OC\Files\Filesystem::fopen($file, 'r'); $this->addFileFromStream($fh, $internalDir . $filename, $filesize); fclose($fh); } elseif (\OC\Files\Filesystem::is_dir($file)) { $this->addDirRecursive($file, $internalDir); } } }
* * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ // Check if we are a user OCP\User::checkLoggedIn(); $filename = $_GET["file"]; if (!\OC\Files\Filesystem::file_exists($filename)) { header("HTTP/1.0 404 Not Found"); $tmpl = new OCP\Template('', '404', 'guest'); $tmpl->assign('file', $filename); $tmpl->printPage(); exit; } $ftype = \OC\Files\Filesystem::getMimeType($filename); header('Content-Type:' . $ftype); if (preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"])) { header('Content-Disposition: attachment; filename="' . rawurlencode(basename($filename)) . '"'); } else { header('Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode(basename($filename)) . '; filename="' . rawurlencode(basename($filename)) . '"'); } OCP\Response::disableCaching(); header('Content-Length: ' . \OC\Files\Filesystem::filesize($filename)); OC_Util::obEnd(); \OC\Files\Filesystem::readfile($filename);
/** * @PublicPage * @NoCSRFRequired * * @param string $token * @param string $path * @return TemplateResponse|RedirectResponse */ public function showShare($token, $path = '') { \OC_User::setIncognitoMode(true); // Check whether share exists $linkItem = Share::getShareByToken($token, false); if ($linkItem === false) { return new NotFoundResponse(); } $shareOwner = $linkItem['uid_owner']; $originalSharePath = $this->getPath($token); // Share is password protected - check whether the user is permitted to access the share if (isset($linkItem['share_with']) && !Helper::authenticate($linkItem)) { return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate', array('token' => $token))); } if (Filesystem::isReadable($originalSharePath . $path)) { $getPath = Filesystem::normalizePath($path); $originalSharePath .= $path; } else { throw new OCP\Files\NotFoundException(); } $file = basename($originalSharePath); $shareTmpl = []; $shareTmpl['displayName'] = User::getDisplayName($shareOwner); $shareTmpl['filename'] = $file; $shareTmpl['directory_path'] = $linkItem['file_target']; $shareTmpl['mimetype'] = Filesystem::getMimeType($originalSharePath); $shareTmpl['previewSupported'] = \OC::$server->getPreviewManager()->isMimeSupported($shareTmpl['mimetype']); $shareTmpl['dirToken'] = $linkItem['token']; $shareTmpl['sharingToken'] = $token; $shareTmpl['server2serversharing'] = Helper::isOutgoingServer2serverShareEnabled(); $shareTmpl['protected'] = isset($linkItem['share_with']) ? 'true' : 'false'; $shareTmpl['dir'] = ''; $nonHumanFileSize = \OC\Files\Filesystem::filesize($originalSharePath); $shareTmpl['nonHumanFileSize'] = $nonHumanFileSize; $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($nonHumanFileSize); // Show file list if (Filesystem::is_dir($originalSharePath)) { $shareTmpl['dir'] = $getPath; $maxUploadFilesize = Util::maxUploadFilesize($originalSharePath); $freeSpace = Util::freeSpace($originalSharePath); $uploadLimit = Util::uploadLimit(); $folder = new Template('files', 'list', ''); $folder->assign('dir', $getPath); $folder->assign('dirToken', $linkItem['token']); $folder->assign('permissions', \OCP\Constants::PERMISSION_READ); $folder->assign('isPublic', true); $folder->assign('publicUploadEnabled', 'no'); $folder->assign('uploadMaxFilesize', $maxUploadFilesize); $folder->assign('uploadMaxHumanFilesize', OCP\Util::humanFileSize($maxUploadFilesize)); $folder->assign('freeSpace', $freeSpace); $folder->assign('uploadLimit', $uploadLimit); // PHP upload limit $folder->assign('usedSpacePercent', 0); $folder->assign('trash', false); $shareTmpl['folder'] = $folder->fetchPage(); } $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', array('token' => $token)); $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10); $csp = new OCP\AppFramework\Http\ContentSecurityPolicy(); $csp->addAllowedFrameDomain('\'self\''); $response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base'); $response->setContentSecurityPolicy($csp); return $response; }
/** * checks if the selected files are within the size constraint. If not, outputs an error page. * * @param dir $dir * @param files $files */ static function validateZipDownload($dir, $files) { if (!OC_Config::getValue('allowZipDownload', true)) { $l = OC_L10N::get('lib'); header("HTTP/1.0 409 Conflict"); OC_Template::printErrorPage($l->t('ZIP download is turned off.'), $l->t('Files need to be downloaded one by one.') . '<br/><a href="javascript:history.back()">' . $l->t('Back to Files') . '</a>'); exit; } $zipLimit = OC_Config::getValue('maxZipInputSize', OC_Helper::computerFileSize('800 MB')); if ($zipLimit > 0) { $totalsize = 0; if (!is_array($files)) { $files = array($files); } foreach ($files as $file) { $path = $dir . '/' . $file; if (\OC\Files\Filesystem::is_dir($path)) { foreach (\OC\Files\Filesystem::getDirectoryContent($path) as $i) { $totalsize += $i['size']; } } else { $totalsize += \OC\Files\Filesystem::filesize($path); } } if ($totalsize > $zipLimit) { $l = OC_L10N::get('lib'); header("HTTP/1.0 409 Conflict"); OC_Template::printErrorPage($l->t('Selected files too large to generate zip file.'), $l->t('Please download the files separately in smaller chunks or kindly ask your administrator.') . '<br/><a href="javascript:history.back()">' . $l->t('Back to Files') . '</a>'); exit; } } }
public function testFilesize() { $folderSize = $this->view->filesize($this->folder); $file1Size = $this->view->filesize($this->folder . $this->filename); $file2Size = $this->view->filesize($this->filename); $share1 = $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); $share2 = $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 | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE); self::loginHelper(self::TEST_FILES_SHARING_API_USER2); // compare file size between user1 and user2, should always be the same $this->assertSame($folderSize, \OC\Files\Filesystem::filesize($this->folder)); $this->assertSame($file1Size, \OC\Files\Filesystem::filesize($this->folder . $this->filename)); $this->assertSame($file2Size, \OC\Files\Filesystem::filesize($this->filename)); //cleanup $this->shareManager->deleteShare($share1); $this->shareManager->deleteShare($share2); }
public function testFilesize() { $fileinfoFolder = $this->view->getFileInfo($this->folder); $fileinfoFile = $this->view->getFileInfo($this->filename); $folderSize = $this->view->filesize($this->folder); $file1Size = $this->view->filesize($this->folder . $this->filename); $file2Size = $this->view->filesize($this->filename); $result = \OCP\Share::shareItem('folder', $fileinfoFolder['fileid'], \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2, 31); $this->assertTrue($result); $result = \OCP\Share::shareItem('file', $fileinfoFile['fileid'], \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2, 31); $this->assertTrue($result); self::loginHelper(self::TEST_FILES_SHARING_API_USER2); // compare file size between user1 and user2, should always be the same $this->assertSame($folderSize, \OC\Files\Filesystem::filesize($this->folder)); $this->assertSame($file1Size, \OC\Files\Filesystem::filesize($this->folder . $this->filename)); $this->assertSame($file2Size, \OC\Files\Filesystem::filesize($this->filename)); //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); $result = \OCP\Share::unshare('file', $fileinfoFile['fileid'], \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2); $this->assertTrue($result); }
* * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ // Check if we are a user OCP\User::checkLoggedIn(); $filename = $_GET["file"]; if (!\OC\Files\Filesystem::file_exists($filename)) { header("HTTP/1.0 404 Not Found"); $tmpl = new OCP\Template('', '404', 'guest'); $tmpl->assign('file', $filename); $tmpl->printPage(); exit; } $ftype = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename)); header('Content-Type:' . $ftype); OCP\Response::setContentDispositionHeader(basename($filename), 'attachment'); OCP\Response::disableCaching(); OCP\Response::setContentLengthHeader(\OC\Files\Filesystem::filesize($filename)); OC_Util::obEnd(); \OC\Files\Filesystem::readfile($filename);
// Get file mtime $filemtime = \OC\Files\Filesystem::filemtime($path); if ($mtime != $filemtime) { // Then the file has changed since opening OCP\JSON::error(array('data' => array('message' => $l->t('Cannot save file as it has been modified since opening')))); OCP\Util::writeLog('files_texteditor', "File: " . $path . " modified since opening.", OCP\Util::ERROR); } else { // File same as when opened, save file if (\OC\Files\Filesystem::isUpdatable($path)) { $filecontents = iconv(mb_detect_encoding($filecontents), "UTF-8", $filecontents); \OC\Files\Filesystem::file_put_contents($path, $filecontents); // Clear statcache clearstatcache(); // Get new mtime $newmtime = \OC\Files\Filesystem::filemtime($path); $newsize = \OC\Files\Filesystem::filesize($path); OCP\JSON::success(array('data' => array('mtime' => $newmtime, 'size' => $newsize))); } else { // Not writeable! OCP\JSON::error(array('data' => array('message' => $l->t('Insufficient permissions')))); OCP\Util::writeLog('files_texteditor', "User does not have permission to write to file: " . $path, OCP\Util::ERROR); } } } else { if ($path == '') { OCP\JSON::error(array('data' => array('message' => $l->t('File path not supplied')))); OCP\Util::writeLog('files_texteditor', 'No file path supplied', OCP\Util::ERROR); } else { if ($mtime == '') { OCP\JSON::error(array('data' => array('message' => $l->t('File mtime not supplied')))); OCP\Util::writeLog('files_texteditor', 'No file mtime supplied', OCP\Util::ERROR);
} } break; case 'play': $ftype = \OC\Files\Filesystem::getMimeType($arguments['path']); if (substr($ftype, 0, 5) != 'audio' and $ftype != 'application/ogg') { echo 'Not an audio file'; exit; } $songId = $collection->getSongByPath($arguments['path']); $collection->registerPlay($songId); header('Content-Type:' . $ftype); \OCP\Response::enableCaching(3600 * 24); // 24 hour header('Accept-Ranges: bytes'); header('Content-Length: ' . \OC\Files\Filesystem::filesize($arguments['path'])); $mtime = \OC\Files\Filesystem::filemtime($arguments['path']); \OCP\Response::setLastModifiedHeader($mtime); \OC\Files\Filesystem::readfile($arguments['path']); exit; case 'find_music': $scanner = new Scanner($collection); $music = $scanner->getMusic(); \OCP\JSON::encodedPrint($music); exit; } } class ScanWatcher { /** * @var \OC_EventSource $eventSource;
/** * @param View $view * @param string $name * @param string $dir * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header */ private static function getSingleFile($view, $dir, $name, $params) { $filename = $dir . '/' . $name; OC_Util::obEnd(); $view->lockFile($filename, ILockingProvider::LOCK_SHARED); $rangeArray = array(); if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') { $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), \OC\Files\Filesystem::filesize($filename)); } if (\OC\Files\Filesystem::isReadable($filename)) { self::sendHeaders($filename, $name, $rangeArray); } elseif (!\OC\Files\Filesystem::file_exists($filename)) { header("HTTP/1.0 404 Not Found"); $tmpl = new OC_Template('', '404', 'guest'); $tmpl->printPage(); exit; } else { header("HTTP/1.0 403 Forbidden"); die('403 Forbidden'); } if (isset($params['head']) && $params['head']) { return; } if (!empty($rangeArray)) { try { if (count($rangeArray) == 1) { $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']); } else { // check if file is seekable (if not throw UnseekableException) // we have to check it before body contents $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']); $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename)); foreach ($rangeArray as $range) { echo "\r\n--" . self::getBoundary() . "\r\n" . "Content-type: " . $type . "\r\n" . "Content-range: bytes " . $range['from'] . "-" . $range['to'] . "/" . $range['size'] . "\r\n\r\n"; $view->readfilePart($filename, $range['from'], $range['to']); } echo "\r\n--" . self::getBoundary() . "--\r\n"; } } catch (\OCP\Files\UnseekableException $ex) { // file is unseekable header_remove('Accept-Ranges'); header_remove('Content-Range'); header("HTTP/1.1 200 OK"); self::sendHeaders($filename, $name, array()); $view->readfile($filename); } } else { $view->readfile($filename); } }
$humanDelta = OCP\Util::humanFileSize($delta); $eventSource->send('error', (string) $l10n->t('The file exceeds your quota by %s', array($humanDelta))); $eventSource->close(); fclose($sourceStream); exit; } } } } $result = \OC\Files\Filesystem::file_put_contents($target, $sourceStream); } if ($result) { $meta = \OC\Files\Filesystem::getFileInfo($target); $mime = $meta['mimetype']; $id = $meta['fileid']; $eventSource->send('success', array('mime' => $mime, 'size' => \OC\Files\Filesystem::filesize($target), 'id' => $id, 'etag' => $meta['etag'])); } else { $eventSource->send('error', $l10n->t('Error while downloading %s to %s', array($source, $target))); } if (is_resource($sourceStream)) { fclose($sourceStream); } $eventSource->close(); exit; } else { $success = false; if (!$content) { $templateManager = OC_Helper::getFileTemplateManager(); $mimeType = OC_Helper::getMimetypeDetector()->detectPath($target); $content = $templateManager->getTemplate($mimeType); }
/** * return the content of a file or return a zip file containing multiple files * * @param string $dir * @param string $files ; separated list of files to download * @param boolean $onlyHeader ; boolean to only send header of the request */ public static function get($dir, $files, $onlyHeader = false) { $view = \OC\Files\Filesystem::getView(); $getType = self::FILE; $filename = $dir; try { if (is_array($files) && count($files) === 1) { $files = $files[0]; } if (!is_array($files)) { $filename = $dir . '/' . $files; if (!$view->is_dir($filename)) { self::getSingleFile($view, $dir, $files, $onlyHeader); return; } } $name = 'download'; if (is_array($files)) { $getType = self::ZIP_FILES; $basename = basename($dir); if ($basename) { $name = $basename; } $filename = $dir . '/' . $name; } else { $filename = $dir . '/' . $files; $getType = self::ZIP_DIR; // downloading root ? if ($files !== '') { $name = $files; } } $streamer = new Streamer(); OC_Util::obEnd(); self::lockFiles($view, $dir, $files); $streamer->sendHeaders($name); $executionTime = intval(OC::$server->getIniWrapper()->getNumeric('max_execution_time')); set_time_limit(0); if ($getType === self::ZIP_FILES) { foreach ($files as $file) { $file = $dir . '/' . $file; if (\OC\Files\Filesystem::is_file($file)) { $fileSize = \OC\Files\Filesystem::filesize($file); $fh = \OC\Files\Filesystem::fopen($file, 'r'); $streamer->addFileFromStream($fh, basename($file), $fileSize); fclose($fh); } elseif (\OC\Files\Filesystem::is_dir($file)) { $streamer->addDirRecursive($file); } } } elseif ($getType === self::ZIP_DIR) { $file = $dir . '/' . $files; $streamer->addDirRecursive($file); } $streamer->finalize(); set_time_limit($executionTime); self::unlockAllTheFiles($dir, $files, $getType, $view, $filename); } catch (\OCP\Lock\LockedException $ex) { self::unlockAllTheFiles($dir, $files, $getType, $view, $filename); OC::$server->getLogger()->logException($ex); $l = \OC::$server->getL10N('core'); $hint = method_exists($ex, 'getHint') ? $ex->getHint() : ''; \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint); } catch (\OCP\Files\ForbiddenException $ex) { self::unlockAllTheFiles($dir, $files, $getType, $view, $filename); OC::$server->getLogger()->logException($ex); $l = \OC::$server->getL10N('core'); \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage()); } catch (\Exception $ex) { self::unlockAllTheFiles($dir, $files, $getType, $view, $filename); OC::$server->getLogger()->logException($ex); $l = \OC::$server->getL10N('core'); $hint = method_exists($ex, 'getHint') ? $ex->getHint() : ''; \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint); } }
/** * return the content of a file or return a zip file containing multiple files * * @param string $dir * @param string $files ; separated list of files to download * @param boolean $onlyHeader ; boolean to only send header of the request */ public static function get($dir, $files, $onlyHeader = false) { $view = \OC\Files\Filesystem::getView(); if (is_array($files) && count($files) === 1) { $files = $files[0]; } if (is_array($files)) { $getType = self::ZIP_FILES; $basename = basename($dir); if ($basename) { $name = $basename; } else { $name = 'download'; } $filename = $dir . '/' . $name; } else { $filename = $dir . '/' . $files; if (\OC\Files\Filesystem::is_dir($dir . '/' . $files)) { $getType = self::ZIP_DIR; // downloading root ? if ($files === '') { $name = 'download'; } else { $name = $files; } } else { $getType = self::FILE; $name = $files; } } if ($getType === self::FILE) { $streamer = false; } else { $streamer = new Streamer(); } OC_Util::obEnd(); try { if ($getType === self::FILE) { $view->lockFile($filename, ILockingProvider::LOCK_SHARED); } if ($streamer) { $streamer->sendHeaders($name); } elseif (\OC\Files\Filesystem::isReadable($filename)) { self::sendHeaders($filename, $name); } elseif (!\OC\Files\Filesystem::file_exists($filename)) { header("HTTP/1.0 404 Not Found"); $tmpl = new OC_Template('', '404', 'guest'); $tmpl->printPage(); exit; } else { header("HTTP/1.0 403 Forbidden"); die('403 Forbidden'); } if ($onlyHeader) { return; } if ($streamer) { $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); if ($getType === self::ZIP_FILES) { foreach ($files as $file) { $file = $dir . '/' . $file; if (\OC\Files\Filesystem::is_file($file)) { $fileSize = \OC\Files\Filesystem::filesize($file); $fh = \OC\Files\Filesystem::fopen($file, 'r'); $streamer->addFileFromStream($fh, basename($file), $fileSize); fclose($fh); } elseif (\OC\Files\Filesystem::is_dir($file)) { $streamer->addDirRecursive($file); } } } elseif ($getType === self::ZIP_DIR) { $file = $dir . '/' . $files; $streamer->addDirRecursive($file); } $streamer->finalize(); set_time_limit($executionTime); } else { \OC\Files\Filesystem::readfile($filename); } if ($getType === self::FILE) { $view->unlockFile($filename, ILockingProvider::LOCK_SHARED); } } catch (\OCP\Lock\LockedException $ex) { $l = \OC::$server->getL10N('core'); $hint = method_exists($ex, 'getHint') ? $ex->getHint() : ''; \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint); } catch (\Exception $ex) { $l = \OC::$server->getL10N('core'); $hint = method_exists($ex, 'getHint') ? $ex->getHint() : ''; \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint); } }
/** * @PublicPage * @NoCSRFRequired * * @param string $token * @param string $path * @return TemplateResponse */ public function showShare($token, $path = '') { \OC_User::setIncognitoMode(true); // Check whether share exists $linkItem = Share::getShareByToken($token, false); if ($linkItem === false) { return new TemplateResponse('core', '404', array(), 'guest'); } $linkItem = OCP\Share::getShareByToken($token, false); $shareOwner = $linkItem['uid_owner']; $originalSharePath = null; $rootLinkItem = OCP\Share::resolveReShare($linkItem); if (isset($rootLinkItem['uid_owner'])) { OCP\JSON::checkUserExists($rootLinkItem['uid_owner']); OC_Util::tearDownFS(); OC_Util::setupFS($rootLinkItem['uid_owner']); $originalSharePath = Filesystem::getPath($linkItem['file_source']); } // Share is password protected - check whether the user is permitted to access the share if (isset($linkItem['share_with']) && !Helper::authenticate($linkItem)) { return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate', array('token' => $token))); } if (Filesystem::isReadable($originalSharePath . $path)) { $getPath = Filesystem::normalizePath($path); $originalSharePath .= $path; } $file = basename($originalSharePath); $shareTmpl = array(); $shareTmpl['displayName'] = User::getDisplayName($shareOwner); $shareTmpl['filename'] = $file; $shareTmpl['directory_path'] = $linkItem['file_target']; $shareTmpl['mimetype'] = Filesystem::getMimeType($originalSharePath); $shareTmpl['dirToken'] = $linkItem['token']; $shareTmpl['sharingToken'] = $token; $shareTmpl['server2serversharing'] = Helper::isOutgoingServer2serverShareEnabled(); $shareTmpl['protected'] = isset($linkItem['share_with']) ? 'true' : 'false'; $shareTmpl['dir'] = ''; $shareTmpl['fileSize'] = \OCP\Util::humanFileSize(\OC\Files\Filesystem::filesize($originalSharePath)); // Show file list if (Filesystem::is_dir($originalSharePath)) { $shareTmpl['dir'] = $getPath; $files = array(); $maxUploadFilesize = Util::maxUploadFilesize($originalSharePath); $freeSpace = Util::freeSpace($originalSharePath); $uploadLimit = Util::uploadLimit(); $folder = new Template('files', 'list', ''); $folder->assign('dir', $getPath); $folder->assign('dirToken', $linkItem['token']); $folder->assign('permissions', \OCP\Constants::PERMISSION_READ); $folder->assign('isPublic', true); $folder->assign('publicUploadEnabled', 'no'); $folder->assign('files', $files); $folder->assign('uploadMaxFilesize', $maxUploadFilesize); $folder->assign('uploadMaxHumanFilesize', OCP\Util::humanFileSize($maxUploadFilesize)); $folder->assign('freeSpace', $freeSpace); $folder->assign('uploadLimit', $uploadLimit); // PHP upload limit $folder->assign('usedSpacePercent', 0); $folder->assign('trash', false); $shareTmpl['folder'] = $folder->fetchPage(); } $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', array('token' => $token)); return new TemplateResponse($this->appName, 'public', $shareTmpl, 'base'); }
/** * @deprecated OC_Filesystem is replaced by \OC\Files\Filesystem */ public static function filesize($path) { return \OC\Files\Filesystem::filesize($path); }