public function output($files, $cache_key) { header('Content-Type: ' . $this->contentType); OC_Response::enableCaching(); $etag = $this->generateETag($files); $cache_key .= '-' . $etag; $gzout = false; $cache = OC_Cache::getGlobalCache(); if (!OC_Request::isNoCache() && (!defined('DEBUG') || !DEBUG)) { OC_Response::setETagHeader($etag); $gzout = $cache->get($cache_key . '.gz'); } if (!$gzout) { $out = $this->minimizeFiles($files); $gzout = gzencode($out); $cache->set($cache_key . '.gz', $gzout); OC_Response::setETagHeader($etag); } if ($encoding = OC_Request::acceptGZip()) { header('Content-Encoding: ' . $encoding); $out = $gzout; } else { $out = gzdecode($gzout); } header('Content-Length: ' . strlen($out)); echo $out; }
/** * @param string $filename * @param string $name */ private static function sendHeaders($filename, $name) { OC_Response::setContentDispositionHeader($name, 'attachment'); header('Content-Transfer-Encoding: binary'); OC_Response::disableCaching(); $filesize = \OC\Files\Filesystem::filesize($filename); header('Content-Type: ' . \OC_Helper::getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename))); if ($filesize > -1) { OC_Response::setContentLengthHeader($filesize); } }
public function renderContent() { if ($this->isEditable()) { list($app, $filename) = explode('/templates/', $this->path, 2); $name = substr($filename, 0, -4); list(, $template) = $this->findTemplate($this->theme, $app, $name, ''); \OC_Response::sendFile($template); } else { throw new SecurityException('Template not editable.', 403); } }
/** * @param string $filename * @param string $name * @param boolean $isAttachment ; enforce download of file */ private static function sendHeaders($filename, $name, $isAttachment = true) { if ($isAttachment) { OC_Response::setContentDispositionHeader($name, 'attachment'); } header('Content-Transfer-Encoding: binary'); OC_Response::disableCaching(); $fileSize = \OC\Files\Filesystem::filesize($filename); $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename)); header('Content-Type: ' . $type); if ($fileSize > -1) { OC_Response::setContentLengthHeader($fileSize); } }
/** * @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\Files\Filesystem::getMimeType($filename)); if ($filesize > -1) { header("Content-Length: " . $filesize); } } }
/** * Sets up the filesystem and user for public sharing * @param string $token string share token * @param string $relativePath optional path relative to the share * @param string $password optional password */ public static function setupFromToken($token, $relativePath = null, $password = null) { \OC_User::setIncognitoMode(true); $linkItem = \OCP\Share::getShareByToken($token, !$password); if ($linkItem === false || $linkItem['item_type'] !== 'file' && $linkItem['item_type'] !== 'folder') { \OC_Response::setStatus(404); \OC_Log::write('core-preview', 'Passed token parameter is not valid', \OC_Log::DEBUG); exit; } if (!isset($linkItem['uid_owner']) || !isset($linkItem['file_source'])) { \OC_Response::setStatus(500); \OC_Log::write('core-preview', 'Passed token seems to be valid, but it does not contain all necessary information . ("' . $token . '")', \OC_Log::WARN); exit; } $rootLinkItem = \OCP\Share::resolveReShare($linkItem); $path = null; if (isset($rootLinkItem['uid_owner'])) { \OCP\JSON::checkUserExists($rootLinkItem['uid_owner']); \OC_Util::tearDownFS(); \OC_Util::setupFS($rootLinkItem['uid_owner']); $path = \OC\Files\Filesystem::getPath($linkItem['file_source']); } if ($path === null) { \OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG); \OC_Response::setStatus(404); \OCP\JSON::error(array('success' => false)); exit; } if (!isset($linkItem['item_type'])) { \OCP\Util::writeLog('share', 'No item type set for share id: ' . $linkItem['id'], \OCP\Util::ERROR); \OC_Response::setStatus(404); \OCP\JSON::error(array('success' => false)); exit; } if (isset($linkItem['share_with'])) { if (!self::authenticate($linkItem, $password)) { \OC_Response::setStatus(403); \OCP\JSON::error(array('success' => false)); exit; } } $basePath = $path; if ($relativePath !== null && \OC\Files\Filesystem::isReadable($basePath . $relativePath)) { $path .= \OC\Files\Filesystem::normalizePath($relativePath); } return array('linkItem' => $linkItem, 'basePath' => $basePath, 'realPath' => $path); }
/** * @param Exception $e */ function handleException(Exception $e) { $request = \OC::$server->getRequest(); // in case the request content type is text/xml - we assume it's a WebDAV request $isXmlContentType = strpos($request->getHeader('Content-Type'), 'text/xml'); if ($isXmlContentType === 0) { // fire up a simple server to properly process the exception $server = new Server(); if (!$e instanceof RemoteException) { // we shall not log on RemoteException $server->addPlugin(new ExceptionLoggerPlugin('webdav', \OC::$server->getLogger())); } $server->on('beforeMethod', function () use($e) { if ($e instanceof RemoteException) { switch ($e->getCode()) { case OC_Response::STATUS_SERVICE_UNAVAILABLE: throw new ServiceUnavailable($e->getMessage()); case OC_Response::STATUS_NOT_FOUND: throw new \Sabre\DAV\Exception\NotFound($e->getMessage()); } } $class = get_class($e); $msg = $e->getMessage(); throw new ServiceUnavailable("{$class}: {$msg}"); }); $server->exec(); } else { $statusCode = OC_Response::STATUS_INTERNAL_SERVER_ERROR; if ($e instanceof \OC\ServiceUnavailableException) { $statusCode = OC_Response::STATUS_SERVICE_UNAVAILABLE; } if ($e instanceof RemoteException) { // we shall not log on RemoteException OC_Response::setStatus($e->getCode()); OC_Template::printErrorPage($e->getMessage()); } else { \OCP\Util::writeLog('remote', $e->getMessage(), \OCP\Util::FATAL); OC_Response::setStatus($statusCode); OC_Template::printExceptionErrorPage($e); } } }
/** * Send redirect response * @param string $location to redirect to */ public static function redirect($location) { \OC_Response::redirect($location); }
/** * @NoAdminRequired * @PublicPage * Store the document content to its origin */ public function save() { try { $esId = $this->request->server['HTTP_WEBODF_SESSION_ID']; if (!$esId) { throw new \Exception('Session id can not be empty'); } $memberId = $this->request->server['HTTP_WEBODF_MEMBER_ID']; $currentMember = new Db\Member(); $currentMember->load($memberId); //check if member belongs to the session if ($esId != $currentMember->getEsId()) { throw new \Exception($memberId . ' does not belong to session ' . $esId); } // Extra info for future usage // $sessionRevision = $this->request->server['HTTP_WEBODF_SESSION_REVISION']; //NB ouch! New document content is passed as an input stream content $stream = fopen('php://input', 'r'); if (!$stream) { throw new \Exception('New content missing'); } $content = stream_get_contents($stream); $session = new Db\Session(); $session->load($esId); if (!$session->getEsId()) { throw new \Exception('Session does not exist'); } try { if ($currentMember->getIsGuest()) { $file = File::getByShareToken($currentMember->getToken()); } else { $file = new File($session->getFileId()); } list($view, $path) = $file->getOwnerViewAndPath(true); } catch (\Exception $e) { //File was deleted or unshared. We need to save content as new file anyway //Sorry, but for guests it would be lost :( if ($this->uid) { $view = new View('/' . $this->uid . '/files'); $dir = \OCP\Config::getUserValue($this->uid, 'documents', 'save_path', ''); $path = Helper::getNewFileName($view, $dir . 'New Document.odt'); } else { throw $e; } } $member = new Db\Member(); $members = $member->getActiveCollection($esId); $memberIds = array_map(function ($x) { return $x['member_id']; }, $members); // Active users except current user $memberCount = count($memberIds) - 1; if ($view->file_exists($path)) { $currentHash = sha1($view->file_get_contents($path)); if (!Helper::isVersionsEnabled() && $currentHash !== $session->getGenesisHash()) { // Original file was modified externally. Save to a new one $path = Helper::getNewFileName($view, $path, '-conflict'); } $mimetype = $view->getMimeType($path); } else { $mimetype = Storage::MIMETYPE_LIBREOFFICE_WORDPROCESSOR; } $data = Filter::write($content, $mimetype); if ($view->file_put_contents($path, $data['content'])) { // Not a last user if ($memberCount > 0) { // Update genesis hash to prevent conflicts $this->logger->debug('Update hash', array('app' => $this->appName)); $session->updateGenesisHash($esId, sha1($data['content'])); } else { // Last user. Kill session data Db\Session::cleanUp($esId); } $view->touch($path); } $response = array('status' => 'success'); } catch (\Exception $e) { $this->logger->warning('Saving failed. Reason:' . $e->getMessage(), array('app' => $this->appName)); \OC_Response::setStatus(500); $response = array(); } return $response; }
/** * @brief Handle the request */ public static function handleRequest() { // load all the classpaths from the enabled apps so they are available // in the routing files of each app OC::loadAppClassPaths(); // Check if ownCloud is installed or in maintenance (update) mode if (!OC_Config::getValue('installed', false)) { require_once 'core/setup.php'; exit; } $request = OC_Request::getPathInfo(); if (substr($request, -3) !== '.js') { // we need these files during the upgrade self::checkMaintenanceMode(); self::checkUpgrade(); } if (!self::$CLI) { try { if (!OC_Config::getValue('maintenance', false)) { OC_App::loadApps(); } OC::getRouter()->match(OC_Request::getRawPathInfo()); return; } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { //header('HTTP/1.0 404 Not Found'); } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { OC_Response::setStatus(405); return; } } $app = OC::$REQUESTEDAPP; $file = OC::$REQUESTEDFILE; $param = array('app' => $app, 'file' => $file); // Handle app css files if (substr($file, -3) == 'css') { self::loadCSSFile($param); return; } // Handle redirect URL for logged in users if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) { $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url'])); // Deny the redirect if the URL contains a @ // This prevents unvalidated redirects like ?redirect_url=:user@domain.com if (strpos($location, '@') === FALSE) { header('Location: ' . $location); return; } } // Handle WebDAV if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') { header('location: ' . OC_Helper::linkToRemote('webdav')); return; } // Someone is logged in : if (OC_User::isLoggedIn()) { OC_App::loadApps(); OC_User::setupBackends(); if (isset($_GET["logout"]) and $_GET["logout"]) { if (isset($_COOKIE['oc_token'])) { OC_Preferences::deleteKey(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']); } OC_User::logout(); header("Location: " . OC::$WEBROOT . '/'); } else { if (is_null($file)) { $param['file'] = 'index.php'; } $file_ext = substr($param['file'], -3); if ($file_ext != 'php' || !self::loadAppScriptFile($param)) { header('HTTP/1.0 404 Not Found'); } } return; } // Not handled and not logged in self::handleLogin(); }
/** * Generate JSON response for routing in javascript */ public static function JSRoutes() { $router = OC::getRouter(); $etag = $router->getCacheKey(); OC_Response::enableCaching(); OC_Response::setETagHeader($etag); $root = $router->getCollection('root'); $routes = array(); foreach ($root->all() as $name => $route) { $compiled_route = $route->compile(); $defaults = $route->getDefaults(); unset($defaults['action']); $routes[$name] = array('tokens' => $compiled_route->getTokens(), 'defaults' => $defaults); } OCP\JSON::success(array('data' => $routes)); }
<?php /** * @author Lukas Reschke * @copyright 2014 Lukas Reschke lukas@owncloud.com * * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ // This file is just used to redirect the legacy sharing URLs (< ownCloud 8) to the new ones $urlGenerator = new \OC\URLGenerator(\OC::$server->getConfig()); $token = isset($_GET['t']) ? $_GET['t'] : ''; $route = isset($_GET['download']) ? 'files_sharing.sharecontroller.downloadShare' : 'files_sharing.sharecontroller.showShare'; OC_Response::redirect($urlGenerator->linkToRoute($route, array('token' => $token)));
/** * return the content of a file or return a zip file containing multiple files * * @param string $dir * @param string $file ; separated list of files to download * @param boolean $only_header ; boolean to only send header of the request */ public static function get($dir, $files, $only_header = false) { $xsendfile = false; if (isset($_SERVER['MOD_X_SENDFILE_ENABLED']) || isset($_SERVER['MOD_X_ACCEL_REDIRECT_ENABLED'])) { $xsendfile = true; } if (is_array($files) && count($files) == 1) { $files = $files[0]; } if (is_array($files)) { self::validateZipDownload($dir, $files); $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); $zip = new ZipArchive(); if ($xsendfile) { $filename = OC_Helper::tmpFileNoClean('.zip'); } else { $filename = OC_Helper::tmpFile('.zip'); } if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) { exit("cannot open <{$filename}>\n"); } foreach ($files as $file) { $file = $dir . '/' . $file; if (\OC\Files\Filesystem::is_file($file)) { $tmpFile = \OC\Files\Filesystem::toTmpFile($file); self::$tmpFiles[] = $tmpFile; $zip->addFile($tmpFile, basename($file)); } elseif (\OC\Files\Filesystem::is_dir($file)) { self::zipAddDir($file, $zip); } } $zip->close(); $basename = basename($dir); if ($basename) { $name = $basename . '.zip'; } else { $name = 'owncloud.zip'; } set_time_limit($executionTime); } elseif (\OC\Files\Filesystem::is_dir($dir . '/' . $files)) { self::validateZipDownload($dir, $files); $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); $zip = new ZipArchive(); if ($xsendfile) { $filename = OC_Helper::tmpFileNoClean('.zip'); } else { $filename = OC_Helper::tmpFile('.zip'); } if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) { exit("cannot open <{$filename}>\n"); } $file = $dir . '/' . $files; self::zipAddDir($file, $zip); $zip->close(); $name = $files . '.zip'; set_time_limit($executionTime); } else { $zip = false; $filename = $dir . '/' . $files; $name = $files; } OC_Util::obEnd(); if ($zip or \OC\Files\Filesystem::isReadable($filename)) { if (preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"])) { header('Content-Disposition: attachment; filename="' . rawurlencode($name) . '"'); } else { header('Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode($name) . '; filename="' . rawurlencode($name) . '"'); } header('Content-Transfer-Encoding: binary'); OC_Response::disableCaching(); if ($zip) { ini_set('zlib.output_compression', 'off'); header('Content-Type: application/zip'); header('Content-Length: ' . filesize($filename)); self::addSendfileHeader($filename); } else { header('Content-Type: ' . \OC\Files\Filesystem::getMimeType($filename)); header("Content-Length: " . \OC\Files\Filesystem::filesize($filename)); list($storage) = \OC\Files\Filesystem::resolvePath($filename); if ($storage instanceof \OC\Files\Storage\Local) { self::addSendfileHeader(\OC\Files\Filesystem::getLocalFile($filename)); } } } elseif ($zip or !\OC\Files\Filesystem::file_exists($filename)) { header("HTTP/1.0 404 Not Found"); $tmpl = new OC_Template('', '404', 'guest'); $tmpl->assign('file', $name); $tmpl->printPage(); } else { header("HTTP/1.0 403 Forbidden"); die('403 Forbidden'); } if ($only_header) { return; } if ($zip) { $handle = fopen($filename, 'r'); if ($handle) { $chunkSize = 8 * 1024; // 1 MB chunks while (!feof($handle)) { echo fread($handle, $chunkSize); flush(); } } if (!$xsendfile) { unlink($filename); } } else { \OC\Files\Filesystem::readfile($filename); } foreach (self::$tmpFiles as $tmpFile) { if (file_exists($tmpFile) and is_file($tmpFile)) { unlink($tmpFile); } } }
if (isset($_POST['password'])) { $password = $_POST['password']; } $relativePath = null; if (isset($_GET['dir'])) { $relativePath = $_GET['dir']; } $sortAttribute = isset($_GET['sort']) ? $_GET['sort'] : 'name'; $sortDirection = isset($_GET['sortdirection']) ? $_GET['sortdirection'] === 'desc' : false; $data = \OCA\Files_Sharing\Helper::setupFromToken($token, $relativePath, $password); $linkItem = $data['linkItem']; // Load the files $dir = $data['realPath']; $dir = \OC\Files\Filesystem::normalizePath($dir); if (!\OC\Files\Filesystem::is_dir($dir . '/')) { \OC_Response::setStatus(\OC_Response::STATUS_NOT_FOUND); \OCP\JSON::error(array('success' => false)); exit; } $data = array(); // make filelist $files = \OCA\Files\Helper::getFiles($dir, $sortAttribute, $sortDirection); $formattedFiles = array(); foreach ($files as $file) { $entry = \OCA\Files\Helper::formatFileInfo($file); unset($entry['directory']); // for now $entry['permissions'] = \OCP\PERMISSION_READ; $formattedFiles[] = $entry; } $data['directory'] = $relativePath;
/** * @brief Handle the request */ public static function handleRequest() { // load all the classpaths from the enabled apps so they are available // in the routing files of each app OC::loadAppClassPaths(); // Check if ownCloud is installed or in maintenance (update) mode if (!OC_Config::getValue('installed', false)) { require_once 'core/setup.php'; exit; } $host = OC_Request::insecureServerHost(); // if the host passed in headers isn't trusted if (!OC::$CLI && OC_Request::getOverwriteHost() === null && !OC_Request::isTrustedDomain($host)) { header('HTTP/1.1 400 Bad Request'); header('Status: 400 Bad Request'); OC_Template::printErrorPage('You are accessing the server from an untrusted domain.', 'Please contact your administrator. If you are an administrator of this instance, configure the "trusted_domain" setting in config/config.php. An example configuration is provided in config/config.sample.php.'); return; } $request = OC_Request::getPathInfo(); if (substr($request, -3) !== '.js') { // we need these files during the upgrade self::checkMaintenanceMode(); self::checkUpgrade(); } // Test it the user is already authenticated using Apaches AuthType Basic... very usable in combination with LDAP OC::tryBasicAuthLogin(); if (!self::$CLI and (!isset($_GET["logout"]) or $_GET["logout"] !== 'true')) { try { if (!OC_Config::getValue('maintenance', false)) { OC_App::loadApps(); } self::checkSingleUserMode(); OC::getRouter()->match(OC_Request::getRawPathInfo()); return; } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { //header('HTTP/1.0 404 Not Found'); } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { OC_Response::setStatus(405); return; } } $app = OC::$REQUESTEDAPP; $file = OC::$REQUESTEDFILE; $param = array('app' => $app, 'file' => $file); // Handle app css files if (substr($file, -3) == 'css') { self::loadCSSFile($param); return; } // Handle redirect URL for logged in users if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) { $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url'])); // Deny the redirect if the URL contains a @ // This prevents unvalidated redirects like ?redirect_url=:user@domain.com if (strpos($location, '@') === false) { header('Location: ' . $location); return; } } // Handle WebDAV if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') { // not allowed any more to prevent people // mounting this root directly. // Users need to mount remote.php/webdav instead. header('HTTP/1.1 405 Method Not Allowed'); header('Status: 405 Method Not Allowed'); return; } // Someone is logged in : if (OC_User::isLoggedIn()) { OC_App::loadApps(); OC_User::setupBackends(); if (isset($_GET["logout"]) and $_GET["logout"]) { if (isset($_COOKIE['oc_token'])) { OC_Preferences::deleteKey(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']); } OC_User::logout(); header("Location: " . OC::$WEBROOT . '/'); } else { if (is_null($file)) { $param['file'] = 'index.php'; } $file_ext = substr($param['file'], -3); if ($file_ext != 'php' || !self::loadAppScriptFile($param)) { header('HTTP/1.0 404 Not Found'); } } return; } // Not handled and not logged in self::handleLogin(); }
public static function getTmpAvatar($args) { \OC_JSON::checkLoggedIn(); \OC_JSON::callCheck(); $tmpavatar = \OC_Cache::get('tmpavatar'); if (is_null($tmpavatar)) { $l = new \OC_L10n('core'); \OC_JSON::error(array("data" => array("message" => $l->t("No temporary profile picture available, try again")))); return; } $image = new \OC_Image($tmpavatar); \OC_Response::disableCaching(); \OC_Response::setLastModifiedHeader(time()); \OC_Response::setETagHeader(crc32($image->data())); $image->show(); }
/** * return the content of a file or return a zip file containning multiply files * * @param dir $dir * @param file $file ; seperated list of files to download * @param boolean $only_header ; boolean to only send header of the request */ public static function get($dir, $files, $only_header = false) { if (strpos($files, ';')) { $files = explode(';', $files); } if (is_array($files)) { self::validateZipDownload($dir, $files); $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); $zip = new ZipArchive(); $filename = OC_Helper::tmpFile('.zip'); if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE) { exit("cannot open <{$filename}>\n"); } foreach ($files as $file) { $file = $dir . '/' . $file; if (OC_Filesystem::is_file($file)) { $tmpFile = OC_Filesystem::toTmpFile($file); self::$tmpFiles[] = $tmpFile; $zip->addFile($tmpFile, basename($file)); } elseif (OC_Filesystem::is_dir($file)) { self::zipAddDir($file, $zip); } } $zip->close(); set_time_limit($executionTime); } elseif (OC_Filesystem::is_dir($dir . '/' . $files)) { self::validateZipDownload($dir, $files); $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); $zip = new ZipArchive(); $filename = OC_Helper::tmpFile('.zip'); if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE) { exit("cannot open <{$filename}>\n"); } $file = $dir . '/' . $files; self::zipAddDir($file, $zip); $zip->close(); set_time_limit($executionTime); } else { $zip = false; $filename = $dir . '/' . $files; } @ob_end_clean(); if ($zip or OC_Filesystem::is_readable($filename)) { header('Content-Disposition: attachment; filename="' . basename($filename) . '"'); header('Content-Transfer-Encoding: binary'); OC_Response::disableCaching(); if ($zip) { ini_set('zlib.output_compression', 'off'); header('Content-Type: application/zip'); header('Content-Length: ' . filesize($filename)); } else { $fileData = OC_FileCache::get($filename); header('Content-Type: ' . $fileData['mimetype']); } } elseif ($zip or !OC_Filesystem::file_exists($filename)) { header("HTTP/1.0 404 Not Found"); $tmpl = new OC_Template('', '404', 'guest'); $tmpl->assign('file', $filename); $tmpl->printPage(); } else { header("HTTP/1.0 403 Forbidden"); die('403 Forbidden'); } if ($only_header) { if (!$zip) { header("Content-Length: " . OC_Filesystem::filesize($filename)); } return; } if ($zip) { $handle = fopen($filename, 'r'); if ($handle) { $chunkSize = 8 * 1024; // 1 MB chunks while (!feof($handle)) { echo fread($handle, $chunkSize); flush(); } } unlink($filename); } else { OC_Filesystem::readfile($filename); } foreach (self::$tmpFiles as $tmpFile) { if (file_exists($tmpFile) and is_file($tmpFile)) { unlink($tmpFile); } } }
/** main function to handle the REST request **/ public static function handle() { // overwrite the 404 error page returncode header("HTTP/1.0 200 OK"); if ($_SERVER['REQUEST_METHOD'] == 'GET') { $method = 'get'; } elseif ($_SERVER['REQUEST_METHOD'] == 'PUT') { $method = 'put'; parse_str(file_get_contents("php://input"), $put_vars); } elseif ($_SERVER['REQUEST_METHOD'] == 'POST') { $method = 'post'; } else { echo 'internal server error: method not supported'; exit; } $format = self::readData($method, 'format', 'text', ''); $router = new OC_Router(); $router->useCollection('root'); // CONFIG $router->create('config', '/config.{format}')->defaults(array('format' => $format))->action('OC_OCS', 'apiConfig')->requirements(array('format' => 'xml|json')); // PERSON $router->create('person_check', '/person/check.{format}')->post()->defaults(array('format' => $format))->action(function ($parameters) { $format = $parameters['format']; $login = OC_OCS::readData('post', 'login', 'text'); $passwd = OC_OCS::readData('post', 'password', 'text'); OC_OCS::personCheck($format, $login, $passwd); })->requirements(array('format' => 'xml|json')); // ACTIVITY // activityget - GET ACTIVITY page,pagesize als urlparameter $router->create('activity_get', '/activity.{format}')->defaults(array('format' => $format))->action(function ($parameters) { $format = $parameters['format']; $page = OC_OCS::readData('get', 'page', 'int', 0); $pagesize = OC_OCS::readData('get', 'pagesize', 'int', 10); if ($pagesize < 1 or $pagesize > 100) { $pagesize = 10; } OC_OCS::activityGet($format, $page, $pagesize); })->requirements(array('format' => 'xml|json')); // activityput - POST ACTIVITY $router->create('activity_put', '/activity.{format}')->post()->defaults(array('format' => $format))->action(function ($parameters) { $format = $parameters['format']; $message = OC_OCS::readData('post', 'message', 'text'); OC_OCS::activityPut($format, $message); })->requirements(array('format' => 'xml|json')); // PRIVATEDATA // get - GET DATA $router->create('privatedata_get', '/privatedata/getattribute/{app}/{key}.{format}')->defaults(array('app' => '', 'key' => '', 'format' => $format))->action(function ($parameters) { $format = $parameters['format']; $app = addslashes(strip_tags($parameters['app'])); $key = addslashes(strip_tags($parameters['key'])); OC_OCS::privateDataGet($format, $app, $key); })->requirements(array('format' => 'xml|json')); // set - POST DATA $router->create('privatedata_set', '/privatedata/setattribute/{app}/{key}.{format}')->post()->defaults(array('format' => $format))->action(function ($parameters) { $format = $parameters['format']; $app = addslashes(strip_tags($parameters['app'])); $key = addslashes(strip_tags($parameters['key'])); $value = OC_OCS::readData('post', 'value', 'text'); OC_OCS::privateDataSet($format, $app, $key, $value); })->requirements(array('format' => 'xml|json')); // delete - POST DATA $router->create('privatedata_delete', '/privatedata/deleteattribute/{app}/{key}.{format}')->post()->defaults(array('format' => $format))->action(function ($parameters) { $format = $parameters['format']; $app = addslashes(strip_tags($parameters['app'])); $key = addslashes(strip_tags($parameters['key'])); OC_OCS::privateDataDelete($format, $app, $key); })->requirements(array('format' => 'xml|json')); // CLOUD // systemWebApps $router->create('system_webapps', '/cloud/system/webapps.{format}')->defaults(array('format' => $format))->action(function ($parameters) { $format = $parameters['format']; OC_OCS::systemwebapps($format); })->requirements(array('format' => 'xml|json')); // quotaget $router->create('quota_get', '/cloud/user/{user}.{format}')->defaults(array('format' => $format))->action(function ($parameters) { $format = $parameters['format']; $user = $parameters['user']; OC_OCS::quotaGet($format, $user); })->requirements(array('format' => 'xml|json')); // quotaset $router->create('quota_set', '/cloud/user/{user}.{format}')->post()->defaults(array('format' => $format))->action(function ($parameters) { $format = $parameters['format']; $user = $parameters['user']; $quota = self::readData('post', 'quota', 'int'); OC_OCS::quotaSet($format, $user, $quota); })->requirements(array('format' => 'xml|json')); // keygetpublic $router->create('keygetpublic', '/cloud/user/{user}/publickey.{format}')->defaults(array('format' => $format))->action(function ($parameters) { $format = $parameters['format']; $user = $parameters['user']; OC_OCS::publicKeyGet($format, $user); })->requirements(array('format' => 'xml|json')); // keygetprivate $router->create('keygetpublic', '/cloud/user/{user}/privatekey.{format}')->defaults(array('format' => $format))->action(function ($parameters) { $format = $parameters['format']; $user = $parameters['user']; OC_OCS::privateKeyGet($format, $user); })->requirements(array('format' => 'xml|json')); // add more calls here // please document all the call in the draft spec // http://www.freedesktop.org/wiki/Specifications/open-collaboration-services-1.7#CLOUD // TODO: // users // groups // bookmarks // sharing // versioning // news (rss) try { $router->match($_SERVER['PATH_INFO']); } catch (ResourceNotFoundException $e) { $txt = 'Invalid query, please check the syntax. ' . 'API specifications are here: ' . 'http://www.freedesktop.org/wiki/Specifications/open-collaboration-services.' . 'DEBUG OUTPUT:' . "\n"; $txt .= OC_OCS::getdebugoutput(); echo OC_OCS::generatexml($format, 'failed', 999, $txt); } catch (MethodNotAllowedException $e) { OC_Response::setStatus(405); } exit; }
/** * Store the document content to its origin */ public static function save() { try { $esId = @$_SERVER['HTTP_WEBODF_SESSION_ID']; if (!$esId) { throw new \Exception('Session id can not be empty'); } $memberId = @$_SERVER['HTTP_WEBODF_MEMBER_ID']; $currentMember = new Db\Member(); $currentMember->load($memberId); if (is_null($currentMember->getIsGuest()) || $currentMember->getIsGuest()) { self::preDispatchGuest(); } else { $uid = self::preDispatch(); } //check if member belongs to the session if ($esId != $currentMember->getEsId()) { throw new \Exception($memberId . ' does not belong to session ' . $esId); } // Extra info for future usage // $sessionRevision = Helper::getArrayValueByKey($_SERVER, 'HTTP_WEBODF_SESSION_REVISION'); $stream = fopen('php://input', 'r'); if (!$stream) { throw new \Exception('New content missing'); } $content = stream_get_contents($stream); $session = new Db\Session(); $session->load($esId); if (!$session->getEsId()) { throw new \Exception('Session does not exist'); } try { if ($currentMember->getIsGuest()) { $file = File::getByShareToken($currentMember->getToken()); } else { $file = new File($session->getFileId()); } list($view, $path) = $file->getOwnerViewAndPath(true); } catch (\Exception $e) { //File was deleted or unshared. We need to save content as new file anyway //Sorry, but for guests it would be lost :( if (isset($uid)) { $view = new \OC\Files\View('/' . $uid . '/files'); $dir = \OCP\Config::getUserValue(\OCP\User::getUser(), 'documents', 'save_path', ''); $path = Helper::getNewFileName($view, $dir . 'New Document.odt'); } } $member = new Db\Member(); $members = $member->getActiveCollection($esId); $memberIds = array_map(function ($x) { return $x['member_id']; }, $members); // Active users except current user $memberCount = count($memberIds) - 1; if ($view->file_exists($path)) { $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; $currentHash = sha1($view->file_get_contents($path)); \OC_FileProxy::$enabled = $proxyStatus; if (!Helper::isVersionsEnabled() && $currentHash !== $session->getGenesisHash()) { // Original file was modified externally. Save to a new one $path = Helper::getNewFileName($view, $path, '-conflict'); } $mimetype = $view->getMimeType($path); } else { $mimetype = Storage::MIMETYPE_LIBREOFFICE_WORDPROCESSOR; } $data = Filter::write($content, $mimetype); if ($view->file_put_contents($path, $data['content'])) { // Not a last user if ($memberCount > 0) { // Update genesis hash to prevent conflicts Helper::debugLog('Update hash'); $session->updateGenesisHash($esId, sha1($data['content'])); } else { // Last user. Kill session data Db\Session::cleanUp($esId); } $view->touch($path); } \OCP\JSON::success(); } catch (\Exception $e) { Helper::warnLog('Saving failed. Reason:' . $e->getMessage()); //\OCP\JSON::error(array('message'=>$e->getMessage())); \OC_Response::setStatus(500); } exit; }
/** * return the content of a file or return a zip file containing multiple files * * @param string $dir * @param string $file ; separated list of files to download * @param boolean $only_header ; boolean to only send header of the request */ public static function get($dir, $files, $only_header = false) { $xsendfile = false; if (isset($_SERVER['MOD_X_SENDFILE_ENABLED']) || isset($_SERVER['MOD_X_SENDFILE2_ENABLED']) || isset($_SERVER['MOD_X_ACCEL_REDIRECT_ENABLED'])) { $xsendfile = true; } if (is_array($files) && count($files) == 1) { $files = $files[0]; } if (is_array($files)) { self::validateZipDownload($dir, $files); $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); $zip = new ZipArchive(); $filename = OC_Helper::tmpFile('.zip'); if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) { $l = OC_L10N::get('lib'); throw new Exception($l->t('cannot open "%s"', array($filename))); } foreach ($files as $file) { $file = $dir . '/' . $file; if (\OC\Files\Filesystem::is_file($file)) { $tmpFile = \OC\Files\Filesystem::toTmpFile($file); self::$tmpFiles[] = $tmpFile; $zip->addFile($tmpFile, basename($file)); } elseif (\OC\Files\Filesystem::is_dir($file)) { self::zipAddDir($file, $zip); } } $zip->close(); if ($xsendfile) { $filename = OC_Helper::moveToNoClean($filename); } $basename = basename($dir); if ($basename) { $name = $basename . '.zip'; } else { $name = 'download.zip'; } set_time_limit($executionTime); } elseif (\OC\Files\Filesystem::is_dir($dir . '/' . $files)) { self::validateZipDownload($dir, $files); $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); $zip = new ZipArchive(); $filename = OC_Helper::tmpFile('.zip'); if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) { $l = OC_L10N::get('lib'); throw new Exception($l->t('cannot open "%s"', array($filename))); } $file = $dir . '/' . $files; self::zipAddDir($file, $zip); $zip->close(); if ($xsendfile) { $filename = OC_Helper::moveToNoClean($filename); } $name = $files . '.zip'; set_time_limit($executionTime); } else { $zip = false; $filename = $dir . '/' . $files; $name = $files; if ($xsendfile && OC_App::isEnabled('files_encryption')) { $xsendfile = false; } } OC_Util::obEnd(); if ($zip or \OC\Files\Filesystem::isReadable($filename)) { OC_Response::setContentDispositionHeader($name, 'attachment'); header('Content-Transfer-Encoding: binary'); OC_Response::disableCaching(); if ($zip) { ini_set('zlib.output_compression', 'off'); header('Content-Type: application/zip'); header('Content-Length: ' . filesize($filename)); self::addSendfileHeader($filename); } else { $filesize = \OC\Files\Filesystem::filesize($filename); header('Content-Type: ' . \OC\Files\Filesystem::getMimeType($filename)); if ($filesize > -1) { header("Content-Length: " . $filesize); } if ($xsendfile) { list($storage) = \OC\Files\Filesystem::resolvePath(\OC\Files\Filesystem::getView()->getAbsolutePath($filename)); /** * @var \OC\Files\Storage\Storage $storage */ if ($storage->instanceOfStorage('\\OC\\Files\\Storage\\Local')) { self::addSendfileHeader(\OC\Files\Filesystem::getLocalFile($filename)); } } } } elseif ($zip or !\OC\Files\Filesystem::file_exists($filename)) { header("HTTP/1.0 404 Not Found"); $tmpl = new OC_Template('', '404', 'guest'); $tmpl->assign('file', $name); $tmpl->printPage(); } else { header("HTTP/1.0 403 Forbidden"); die('403 Forbidden'); } if ($only_header) { return; } if ($zip) { $handle = fopen($filename, 'r'); if ($handle) { $chunkSize = 8 * 1024; // 1 MB chunks while (!feof($handle)) { echo fread($handle, $chunkSize); flush(); } } if (!$xsendfile) { unlink($filename); } } else { \OC\Files\Filesystem::readfile($filename); } foreach (self::$tmpFiles as $tmpFile) { if (file_exists($tmpFile) and is_file($tmpFile)) { unlink($tmpFile); } } }
/** * Handle the request */ public static function handleRequest() { \OC::$server->getEventLogger()->start('handle_request', 'Handle request'); $systemConfig = \OC::$server->getSystemConfig(); // load all the classpaths from the enabled apps so they are available // in the routing files of each app OC::loadAppClassPaths(); // Check if ownCloud is installed or in maintenance (update) mode if (!$systemConfig->getValue('installed', false)) { \OC::$server->getSession()->clear(); $setupHelper = new OC\Setup(\OC::$server->getConfig(), \OC::$server->getIniWrapper(), \OC::$server->getL10N('lib'), new \OC_Defaults(), \OC::$server->getLogger(), \OC::$server->getSecureRandom()); $controller = new OC\Core\Setup\Controller($setupHelper); $controller->run($_POST); exit; } $request = \OC::$server->getRequest()->getPathInfo(); if (substr($request, -3) !== '.js') { // we need these files during the upgrade self::checkMaintenanceMode(); self::checkUpgrade(); } // Always load authentication apps OC_App::loadApps(['authentication']); // Load minimum set of apps if (!self::checkUpgrade(false) && !$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) { // For logged-in users: Load everything if (OC_User::isLoggedIn()) { OC_App::loadApps(); } else { // For guests: Load only filesystem and logging OC_App::loadApps(array('filesystem', 'logging')); \OC_User::tryBasicAuthLogin(); } } if (!self::$CLI and (!isset($_GET["logout"]) or $_GET["logout"] !== 'true')) { try { if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) { OC_App::loadApps(array('filesystem', 'logging')); OC_App::loadApps(); } self::checkSingleUserMode(); OC_Util::setupFS(); OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo()); return; } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { //header('HTTP/1.0 404 Not Found'); } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { OC_Response::setStatus(405); return; } } // Handle redirect URL for logged in users if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) { $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url'])); // Deny the redirect if the URL contains a @ // This prevents unvalidated redirects like ?redirect_url=:user@domain.com if (strpos($location, '@') === false) { header('Location: ' . $location); return; } } // Handle WebDAV if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') { // not allowed any more to prevent people // mounting this root directly. // Users need to mount remote.php/webdav instead. header('HTTP/1.1 405 Method Not Allowed'); header('Status: 405 Method Not Allowed'); return; } // Redirect to index if the logout link is accessed without valid session // this is needed to prevent "Token expired" messages while login if a session is expired // @see https://github.com/owncloud/core/pull/8443#issuecomment-42425583 if (isset($_GET['logout']) && !OC_User::isLoggedIn()) { header("Location: " . OC::$WEBROOT . (empty(OC::$WEBROOT) ? '/' : '')); return; } // Someone is logged in if (OC_User::isLoggedIn()) { OC_App::loadApps(); OC_User::setupBackends(); OC_Util::setupFS(); if (isset($_GET["logout"]) and $_GET["logout"]) { OC_JSON::callCheck(); if (isset($_COOKIE['oc_token'])) { \OC::$server->getConfig()->deleteUserValue(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']); } OC_User::logout(); // redirect to webroot and add slash if webroot is empty header("Location: " . OC::$WEBROOT . (empty(OC::$WEBROOT) ? '/' : '')); } else { // Redirect to default application OC_Util::redirectToDefaultPage(); } } else { // Not handled and not logged in self::handleLogin(); } }
public static function loadfile() { if (file_exists(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE)) { if (substr(OC::$REQUESTEDFILE, -3) == 'css') { $appswebroot = (string) OC::$APPSWEBROOT; $webroot = (string) OC::$WEBROOT; $filepath = OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE; header('Content-Type: text/css'); OC_Response::enableCaching(); OC_Response::setLastModifiedHeader(filemtime($filepath)); $cssfile = file_get_contents($filepath); $cssfile = str_replace('%appswebroot%', $appswebroot, $cssfile); $cssfile = str_replace('%webroot%', $webroot, $cssfile); OC_Response::setETagHeader(md5($cssfile)); header('Content-Length: ' . strlen($cssfile)); echo $cssfile; exit; } elseif (substr(OC::$REQUESTEDFILE, -3) == 'php') { require_once OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE; } } else { header('HTTP/1.0 404 Not Found'); exit; } }
/** * respond to a call * @param OC_OCS_Result $result * @param string $format the format xml|json */ public static function respond($result, $format = 'xml') { // Send 401 headers if unauthorised if ($result->getStatusCode() === API::RESPOND_UNAUTHORISED) { header('WWW-Authenticate: Basic realm="Authorisation Required"'); header('HTTP/1.0 401 Unauthorized'); } foreach ($result->getHeaders() as $name => $value) { header($name . ': ' . $value); } $meta = $result->getMeta(); $data = $result->getData(); if (self::isV2(\OC::$server->getRequest())) { $statusCode = self::mapStatusCodes($result->getStatusCode()); if (!is_null($statusCode)) { $meta['statuscode'] = $statusCode; OC_Response::setStatus($statusCode); } } self::setContentType($format); $body = self::renderResult($format, $meta, $data); echo $body; }
/** * Handle the request */ public static function handleRequest() { $l = \OC_L10N::get('lib'); // load all the classpaths from the enabled apps so they are available // in the routing files of each app OC::loadAppClassPaths(); // Check if ownCloud is installed or in maintenance (update) mode if (!OC_Config::getValue('installed', false)) { $controller = new OC\Core\Setup\Controller(); $controller->run($_POST); exit; } $host = OC_Request::insecureServerHost(); // if the host passed in headers isn't trusted if (!OC::$CLI && OC_Request::getOverwriteHost() === null && !OC_Request::isTrustedDomain($host)) { header('HTTP/1.1 400 Bad Request'); header('Status: 400 Bad Request'); OC_Template::printErrorPage($l->t('You are accessing the server from an untrusted domain.'), $l->t('Please contact your administrator. If you are an administrator of this instance, configure the "trusted_domain" setting in config/config.php. An example configuration is provided in config/config.sample.php.')); return; } $request = OC_Request::getPathInfo(); if (substr($request, -3) !== '.js') { // we need these files during the upgrade self::checkMaintenanceMode(); self::checkUpgrade(); } if (!OC_User::isLoggedIn()) { // Test it the user is already authenticated using Apaches AuthType Basic... very usable in combination with LDAP OC::tryBasicAuthLogin(); } if (!self::$CLI and (!isset($_GET["logout"]) or $_GET["logout"] !== 'true')) { try { if (!OC_Config::getValue('maintenance', false) && !\OCP\Util::needUpgrade()) { OC_App::loadApps(array('authentication')); OC_App::loadApps(array('filesystem', 'logging')); OC_App::loadApps(); } self::checkSingleUserMode(); OC::$server->getRouter()->match(OC_Request::getRawPathInfo()); return; } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { //header('HTTP/1.0 404 Not Found'); } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { OC_Response::setStatus(405); return; } } // Load minimum set of apps if (!self::checkUpgrade(false)) { // For logged-in users: Load everything if (OC_User::isLoggedIn()) { OC_App::loadApps(); } else { // For guests: Load only authentication, filesystem and logging OC_App::loadApps(array('authentication')); OC_App::loadApps(array('filesystem', 'logging')); } } // Handle redirect URL for logged in users if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) { $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url'])); // Deny the redirect if the URL contains a @ // This prevents unvalidated redirects like ?redirect_url=:user@domain.com if (strpos($location, '@') === false) { header('Location: ' . $location); return; } } // Handle WebDAV if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') { // not allowed any more to prevent people // mounting this root directly. // Users need to mount remote.php/webdav instead. header('HTTP/1.1 405 Method Not Allowed'); header('Status: 405 Method Not Allowed'); return; } // Redirect to index if the logout link is accessed without valid session // this is needed to prevent "Token expired" messages while login if a session is expired // @see https://github.com/owncloud/core/pull/8443#issuecomment-42425583 if (isset($_GET['logout']) && !OC_User::isLoggedIn()) { header("Location: " . OC::$WEBROOT . (empty(OC::$WEBROOT) ? '/' : '')); return; } // Someone is logged in if (OC_User::isLoggedIn()) { OC_App::loadApps(); OC_User::setupBackends(); if (isset($_GET["logout"]) and $_GET["logout"]) { OC_JSON::callCheck(); if (isset($_COOKIE['oc_token'])) { OC_Preferences::deleteKey(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']); } if (isset($_SERVER['PHP_AUTH_USER'])) { if (isset($_COOKIE['oc_ignore_php_auth_user'])) { // Ignore HTTP Authentication for 5 more mintues. setcookie('oc_ignore_php_auth_user', $_SERVER['PHP_AUTH_USER'], time() + 300, OC::$WEBROOT . (empty(OC::$WEBROOT) ? '/' : '')); } elseif ($_SERVER['PHP_AUTH_USER'] === self::$session->get('loginname')) { // Ignore HTTP Authentication to allow a different user to log in. setcookie('oc_ignore_php_auth_user', $_SERVER['PHP_AUTH_USER'], 0, OC::$WEBROOT . (empty(OC::$WEBROOT) ? '/' : '')); } } OC_User::logout(); // redirect to webroot and add slash if webroot is empty header("Location: " . OC::$WEBROOT . (empty(OC::$WEBROOT) ? '/' : '')); } else { // Redirect to default application OC_Util::redirectToDefaultPage(); } } else { // Not handled and not logged in self::handleLogin(); } }
* 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/> * */ OCP\JSON::checkAppEnabled('files_sharing'); if (!isset($_GET['t'])) { \OC_Response::setStatus(400); //400 Bad Request exit; } if (OCA\Files_Sharing\Helper::isOutgoingServer2serverShareEnabled() === false) { \OC_Response::setStatus(404); // 404 not found exit; } $token = $_GET['t']; $password = null; if (isset($_POST['password'])) { $password = $_POST['password']; } $relativePath = null; if (isset($_GET['dir'])) { $relativePath = $_GET['dir']; } $data = \OCA\Files_Sharing\Helper::setupFromToken($token, $relativePath, $password); $linkItem = $data['linkItem']; // Load the files
public function show() { if ($this->useOriginal) { $fp = @$this->view->fopen($this->path, 'rb'); $mtime = $this->view->filemtime($this->path); $size = $this->view->filesize($this->path); $mime = $this->view->getMimetype($this->path); } else { $fp = @fopen($this->path, 'rb'); $mtime = filemtime($this->path); $size = filesize($this->path); $mime = \OC_Helper::getMimetype($this->path); } if ($fp) { \OCP\Response::enableCaching(); \OCP\Response::setLastModifiedHeader($mtime); header('Content-Length: ' . $size); header('Content-Type: ' . $mime); fpassthru($fp); } else { \OC_Response::setStatus(\OC_Response::STATUS_NOT_FOUND); } }
//400 Bad Request \OCP\Util::writeLog('core-preview', 'x and/or y set to 0', \OCP\Util::DEBUG); exit; } try { $preview = new \OC\Preview(\OC_User::getUser(), 'files_trashbin/files', $file); $view = new \OC\Files\View('/' . \OC_User::getUser() . '/files_trashbin/files'); if ($view->is_dir($file)) { $mimetype = 'httpd/unix-directory'; } else { $pathInfo = pathinfo(ltrim($file, '/')); $fileName = $pathInfo['basename']; // if in root dir if ($pathInfo['dirname'] === '.') { // cut off the .d* suffix $i = strrpos($fileName, '.'); if ($i !== false) { $fileName = substr($fileName, 0, $i); } } $mimetype = \OC::$server->getMimeTypeDetector()->detectPath($fileName); } $preview->setMimetype($mimetype); $preview->setMaxX($maxX); $preview->setMaxY($maxY); $preview->setScalingUp($scalingUp); $preview->showPreview(); } catch (\Exception $e) { \OC_Response::setStatus(500); \OCP\Util::writeLog('core', $e->getmessage(), \OCP\Util::DEBUG); }
/** * Handle the request */ public static function handleRequest() { \OC::$server->getEventLogger()->start('handle_request', 'Handle request'); $systemConfig = \OC::$server->getSystemConfig(); // load all the classpaths from the enabled apps so they are available // in the routing files of each app OC::loadAppClassPaths(); // Check if ownCloud is installed or in maintenance (update) mode if (!$systemConfig->getValue('installed', false)) { \OC::$server->getSession()->clear(); $setupHelper = new OC\Setup(\OC::$server->getConfig(), \OC::$server->getIniWrapper(), \OC::$server->getL10N('lib'), new \OC_Defaults(), \OC::$server->getLogger(), \OC::$server->getSecureRandom()); $controller = new OC\Core\Controller\SetupController($setupHelper); $controller->run($_POST); exit; } $request = \OC::$server->getRequest(); // Check if requested URL matches 'index.php/occ' $isOccControllerRequested = preg_match('|/index\\.php$|', $request->getScriptName()) === 1 && strpos($request->getPathInfo(), '/occ/') === 0; $requestPath = $request->getRawPathInfo(); if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade self::checkMaintenanceMode($request); $needUpgrade = self::checkUpgrade(!$isOccControllerRequested); } // emergency app disabling if ($requestPath === '/disableapp' && $request->getMethod() === 'POST' && (string) $request->getParam('appid') !== '') { \OCP\JSON::callCheck(); \OCP\JSON::checkAdminUser(); $appId = (string) $request->getParam('appid'); $appId = \OC_App::cleanAppId($appId); \OC_App::disable($appId); \OC_JSON::success(); exit; } try { // Always load authentication apps OC_App::loadApps(['authentication']); } catch (\OC\NeedsUpdateException $e) { if ($isOccControllerRequested && $needUpgrade) { OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo()); return; } throw $e; } // Load minimum set of apps if (!self::checkUpgrade(false) && !$systemConfig->getValue('maintenance', false)) { // For logged-in users: Load everything if (OC_User::isLoggedIn()) { OC_App::loadApps(); } else { // For guests: Load only filesystem and logging OC_App::loadApps(array('filesystem', 'logging')); self::handleLogin($request); } } if (!self::$CLI) { try { if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) { OC_App::loadApps(array('filesystem', 'logging')); OC_App::loadApps(); } self::checkSingleUserMode(); OC_Util::setupFS(); OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo()); return; } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { //header('HTTP/1.0 404 Not Found'); } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { OC_Response::setStatus(405); return; } } // Handle WebDAV if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') { // not allowed any more to prevent people // mounting this root directly. // Users need to mount remote.php/webdav instead. header('HTTP/1.1 405 Method Not Allowed'); header('Status: 405 Method Not Allowed'); return; } // Someone is logged in if (OC_User::isLoggedIn()) { OC_App::loadApps(); OC_User::setupBackends(); OC_Util::setupFS(); // FIXME // Redirect to default application OC_Util::redirectToDefaultPage(); } else { // Not handled and not logged in header('Location: ' . \OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm')); } }
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); } if ($maxX === 0 || $maxY === 0) { \OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST); \OCP\Util::writeLog('core-preview', 'x and/or y set to 0', \OCP\Util::DEBUG); exit; } $root = 'files/' . $path; try { $preview = new \OC\Preview($userId, $root); $preview->setFile($sharedFile); $preview->setMaxX($maxX); $preview->setMaxY($maxY); $preview->setScalingUp($scalingUp); $preview->setKeepAspect($keepAspect); $preview->showPreview(); } catch (\Exception $e) { \OC_Response::setStatus(\OC_Response::STATUS_INTERNAL_SERVER_ERROR); \OCP\Util::writeLog('core', $e->getmessage(), \OCP\Util::DEBUG); }
* ownCloud * * @author Frank Karlitschek * @copyright 2012 Frank Karlitschek frank@owncloud.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * 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/>. * */ require_once '../lib/base.php'; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\Exception\MethodNotAllowedException; try { OC::getRouter()->match('/ocs' . OC_Request::getRawPathInfo()); } catch (ResourceNotFoundException $e) { OC_API::setContentType(); OC_OCS::notFound(); } catch (MethodNotAllowedException $e) { OC_API::setContentType(); OC_Response::setStatus(405); }