Merge pull request #10009 from nextcloud/techdebt/noid/replace-headers-with-http_response_code-calls

Replace hard coded HTTP status codes with proper calls to http_response_code
pull/10020/head
Morris Jobke 6 years ago committed by GitHub
commit e4e3387417
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -38,7 +38,7 @@ $dir = \OC\Files\Filesystem::normalizePath($dir);
try { try {
$dirInfo = \OC\Files\Filesystem::getFileInfo($dir); $dirInfo = \OC\Files\Filesystem::getFileInfo($dir);
if (!$dirInfo || !$dirInfo->getType() === 'dir') { if (!$dirInfo || !$dirInfo->getType() === 'dir') {
header("HTTP/1.0 404 Not Found"); http_response_code(404);
exit(); exit();
} }

@ -30,14 +30,13 @@ $route = isset($_GET['download']) ? 'files_sharing.sharecontroller.downloadShare
if($token !== '') { if($token !== '') {
$protocol = \OC::$server->getRequest()->getHttpProtocol(); $protocol = \OC::$server->getRequest()->getHttpProtocol();
if ($protocol == 'HTTP/1.0') { if ($protocol == 'HTTP/1.0') {
$status = '302 Found'; http_response_code(302);
} else { } else {
$status = '307 Temporary Redirect'; http_response_code(307);
} }
header($protocol.' ' . $status);
header('Location: ' . $urlGenerator->linkToRoute($route, array('token' => $token))); header('Location: ' . $urlGenerator->linkToRoute($route, array('token' => $token)));
} else { } else {
header('HTTP/1.0 404 Not Found'); http_response_code(404);
$tmpl = new OCP\Template('', '404', 'guest'); $tmpl = new OCP\Template('', '404', 'guest');
print_unescaped($tmpl->fetchPage()); print_unescaped($tmpl->fetchPage());
} }

@ -34,7 +34,7 @@ $data = array();
try { try {
$files = \OCA\Files_Trashbin\Helper::getTrashFiles($dir, \OCP\User::getUser(), $sortAttribute, $sortDirection); $files = \OCA\Files_Trashbin\Helper::getTrashFiles($dir, \OCP\User::getUser(), $sortAttribute, $sortDirection);
} catch (Exception $e) { } catch (Exception $e) {
header("HTTP/1.0 404 Not Found"); http_response_code(404);
exit(); exit();
} }

@ -34,7 +34,7 @@ $revision=(int)$_GET['revision'];
try { try {
list($uid, $filename) = OCA\Files_Versions\Storage::getUidAndFilename($file); list($uid, $filename) = OCA\Files_Versions\Storage::getUidAndFilename($file);
} catch(\OCP\Files\NotFoundException $e) { } catch(\OCP\Files\NotFoundException $e) {
header("HTTP/1.1 404 Not Found"); http_response_code(404);
$tmpl = new OCP\Template('', '404', 'guest'); $tmpl = new OCP\Template('', '404', 'guest');
$tmpl->assign('file', ''); $tmpl->assign('file', '');
$tmpl->printPage(); $tmpl->printPage();

@ -45,41 +45,29 @@ try {
\OC::$server->getLogger()->logException($ex, array('app' => 'index')); \OC::$server->getLogger()->logException($ex, array('app' => 'index'));
//show the user a detailed error page //show the user a detailed error page
OC_Template::printExceptionErrorPage($ex, \OC_Response::STATUS_SERVICE_UNAVAILABLE); OC_Template::printExceptionErrorPage($ex, 503);
} catch (\OC\HintException $ex) { } catch (\OC\HintException $ex) {
try { try {
OC_Template::printErrorPage($ex->getMessage(), $ex->getHint(), OC_Response::STATUS_SERVICE_UNAVAILABLE); OC_Template::printErrorPage($ex->getMessage(), $ex->getHint(), 503);
} catch (Exception $ex2) { } catch (Exception $ex2) {
\OC::$server->getLogger()->logException($ex, array('app' => 'index')); \OC::$server->getLogger()->logException($ex, array('app' => 'index'));
\OC::$server->getLogger()->logException($ex2, array('app' => 'index')); \OC::$server->getLogger()->logException($ex2, array('app' => 'index'));
//show the user a detailed error page //show the user a detailed error page
OC_Template::printExceptionErrorPage($ex, \OC_Response::STATUS_INTERNAL_SERVER_ERROR); OC_Template::printExceptionErrorPage($ex, 500);
} }
} catch (\OC\User\LoginException $ex) { } catch (\OC\User\LoginException $ex) {
OC_Template::printErrorPage($ex->getMessage(), $ex->getMessage(), OC_Response::STATUS_FORBIDDEN); OC_Template::printErrorPage($ex->getMessage(), $ex->getMessage(), 403);
} catch (Exception $ex) { } catch (Exception $ex) {
\OC::$server->getLogger()->logException($ex, array('app' => 'index')); \OC::$server->getLogger()->logException($ex, array('app' => 'index'));
//show the user a detailed error page //show the user a detailed error page
OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR); OC_Template::printExceptionErrorPage($ex, 500);
OC_Template::printExceptionErrorPage($ex);
} catch (Error $ex) { } catch (Error $ex) {
try { try {
\OC::$server->getLogger()->logException($ex, array('app' => 'index')); \OC::$server->getLogger()->logException($ex, array('app' => 'index'));
} catch (Error $e) { } catch (Error $e) {
http_response_code(500);
$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
$validProtocols = [
'HTTP/1.0',
'HTTP/1.1',
'HTTP/2',
];
$protocol = 'HTTP/1.1';
if(in_array($claimedProtocol, $validProtocols, true)) {
$protocol = $claimedProtocol;
}
header($protocol . ' 500 Internal Server Error');
header('Content-Type: text/plain; charset=utf-8'); header('Content-Type: text/plain; charset=utf-8');
print("Internal Server Error\n\n"); print("Internal Server Error\n\n");
print("The server encountered an internal error and was unable to complete your request.\n"); print("The server encountered an internal error and was unable to complete your request.\n");
@ -88,5 +76,5 @@ try {
throw $e; throw $e;
} }
OC_Template::printExceptionErrorPage($ex, \OC_Response::STATUS_INTERNAL_SERVER_ERROR); OC_Template::printExceptionErrorPage($ex, 500);
} }

@ -287,8 +287,7 @@ class OC {
// Allow ajax update script to execute without being stopped // Allow ajax update script to execute without being stopped
if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') { if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
// send http status 503 // send http status 503
header('HTTP/1.1 503 Service Temporarily Unavailable'); http_response_code(503);
header('Status: 503 Service Temporarily Unavailable');
header('Retry-After: 120'); header('Retry-After: 120');
// render error page // render error page
@ -344,8 +343,7 @@ class OC {
if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) { if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
// send http status 503 // send http status 503
header('HTTP/1.1 503 Service Temporarily Unavailable'); http_response_code(503);
header('Status: 503 Service Temporarily Unavailable');
header('Retry-After: 120'); header('Retry-After: 120');
// render error page // render error page
@ -434,7 +432,7 @@ class OC {
} catch (Exception $e) { } catch (Exception $e) {
\OC::$server->getLogger()->logException($e, ['app' => 'base']); \OC::$server->getLogger()->logException($e, ['app' => 'base']);
//show the user a detailed error page //show the user a detailed error page
OC_Template::printExceptionErrorPage($e, \OC_Response::STATUS_INTERNAL_SERVER_ERROR); OC_Template::printExceptionErrorPage($e, 500);
die(); die();
} }
@ -600,9 +598,7 @@ class OC {
} catch (\RuntimeException $e) { } catch (\RuntimeException $e) {
if (!self::$CLI) { if (!self::$CLI) {
$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']); http_response_code(503);
$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
} }
// we can't use the template error page here, because this needs the // we can't use the template error page here, because this needs the
// DI container which isn't available yet // DI container which isn't available yet
@ -689,7 +685,7 @@ class OC {
} }
exit(1); exit(1);
} else { } else {
OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE); http_response_code(503);
OC_Util::addStyle('guest'); OC_Util::addStyle('guest');
OC_Template::printGuestPage('', 'error', array('errors' => $errors)); OC_Template::printGuestPage('', 'error', array('errors' => $errors));
exit; exit;
@ -778,16 +774,14 @@ class OC {
} }
if(substr($request->getRequestUri(), -11) === '/status.php') { if(substr($request->getRequestUri(), -11) === '/status.php') {
OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST); http_response_code(400);
header('Status: 400 Bad Request');
header('Content-Type: application/json'); header('Content-Type: application/json');
echo '{"error": "Trusted domain error.", "code": 15}'; echo '{"error": "Trusted domain error.", "code": 15}';
exit(); exit();
} }
if (!$isScssRequest) { if (!$isScssRequest) {
OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST); http_response_code(400);
header('Status: 400 Bad Request');
\OC::$server->getLogger()->info( \OC::$server->getLogger()->info(
'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.', 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
@ -997,7 +991,7 @@ class OC {
} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
//header('HTTP/1.0 404 Not Found'); //header('HTTP/1.0 404 Not Found');
} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
OC_Response::setStatus(405); http_response_code(405);
return; return;
} }
} }
@ -1007,8 +1001,7 @@ class OC {
// not allowed any more to prevent people // not allowed any more to prevent people
// mounting this root directly. // mounting this root directly.
// Users need to mount remote.php/webdav instead. // Users need to mount remote.php/webdav instead.
header('HTTP/1.1 405 Method Not Allowed'); http_response_code(405);
header('Status: 405 Method Not Allowed');
return; return;
} }

@ -88,7 +88,7 @@ class OC_API {
} else { } else {
header('WWW-Authenticate: Basic realm="Authorisation Required"'); header('WWW-Authenticate: Basic realm="Authorisation Required"');
} }
header('HTTP/1.0 401 Unauthorized'); http_response_code(401);
} }
foreach($result->getHeaders() as $name => $value) { foreach($result->getHeaders() as $name => $value) {
@ -101,7 +101,7 @@ class OC_API {
$statusCode = self::mapStatusCodes($result->getStatusCode()); $statusCode = self::mapStatusCodes($result->getStatusCode());
if (!is_null($statusCode)) { if (!is_null($statusCode)) {
$meta['statuscode'] = $statusCode; $meta['statuscode'] = $statusCode;
OC_Response::setStatus($statusCode); http_response_code($statusCode);
} }
} }

@ -83,7 +83,7 @@ class OC_Files {
$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename)); $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
if ($fileSize > -1) { if ($fileSize > -1) {
if (!empty($rangeArray)) { if (!empty($rangeArray)) {
header('HTTP/1.1 206 Partial Content', true); http_response_code(206);
header('Accept-Ranges: bytes', true); header('Accept-Ranges: bytes', true);
if (count($rangeArray) > 1) { if (count($rangeArray) > 1) {
$type = 'multipart/byteranges; boundary='.self::getBoundary(); $type = 'multipart/byteranges; boundary='.self::getBoundary();
@ -286,12 +286,12 @@ class OC_Files {
if (\OC\Files\Filesystem::isReadable($filename)) { if (\OC\Files\Filesystem::isReadable($filename)) {
self::sendHeaders($filename, $name, $rangeArray); self::sendHeaders($filename, $name, $rangeArray);
} elseif (!\OC\Files\Filesystem::file_exists($filename)) { } elseif (!\OC\Files\Filesystem::file_exists($filename)) {
header("HTTP/1.1 404 Not Found"); http_response_code(404);
$tmpl = new OC_Template('', '404', 'guest'); $tmpl = new OC_Template('', '404', 'guest');
$tmpl->printPage(); $tmpl->printPage();
exit(); exit();
} else { } else {
header("HTTP/1.1 403 Forbidden"); http_response_code(403);
die('403 Forbidden'); die('403 Forbidden');
} }
if (isset($params['head']) && $params['head']) { if (isset($params['head']) && $params['head']) {
@ -321,7 +321,7 @@ class OC_Files {
// file is unseekable // file is unseekable
header_remove('Accept-Ranges'); header_remove('Accept-Ranges');
header_remove('Content-Range'); header_remove('Content-Range');
header("HTTP/1.1 200 OK"); http_response_code(200);
self::sendHeaders($filename, $name, array()); self::sendHeaders($filename, $name, array());
$view->readfile($filename); $view->readfile($filename);
} }

@ -31,49 +31,6 @@
*/ */
class OC_Response { class OC_Response {
const STATUS_FOUND = 302;
const STATUS_NOT_MODIFIED = 304;
const STATUS_TEMPORARY_REDIRECT = 307;
const STATUS_BAD_REQUEST = 400;
const STATUS_FORBIDDEN = 403;
const STATUS_NOT_FOUND = 404;
const STATUS_INTERNAL_SERVER_ERROR = 500;
const STATUS_SERVICE_UNAVAILABLE = 503;
/**
* Set response status
* @param int $status a HTTP status code, see also the STATUS constants
*/
static public function setStatus($status) {
$protocol = \OC::$server->getRequest()->getHttpProtocol();
switch($status) {
case self::STATUS_NOT_MODIFIED:
$status = $status . ' Not Modified';
break;
case self::STATUS_TEMPORARY_REDIRECT:
if ($protocol == 'HTTP/1.0') {
$status = self::STATUS_FOUND;
// fallthrough
} else {
$status = $status . ' Temporary Redirect';
break;
}
case self::STATUS_FOUND;
$status = $status . ' Found';
break;
case self::STATUS_NOT_FOUND;
$status = $status . ' Not Found';
break;
case self::STATUS_INTERNAL_SERVER_ERROR;
$status = $status . ' Internal Server Error';
break;
case self::STATUS_SERVICE_UNAVAILABLE;
$status = $status . ' Service Unavailable';
break;
}
header($protocol.' '.$status);
}
/** /**
* Sets the content disposition header (with possible workarounds) * Sets the content disposition header (with possible workarounds)
* @param string $filename file name * @param string $filename file name

@ -36,7 +36,7 @@ if (\OCP\Util::needUpgrade()
|| \OC::$server->getSystemConfig()->getValue('maintenance', false)) { || \OC::$server->getSystemConfig()->getValue('maintenance', false)) {
// since the behavior of apps or remotes are unpredictable during // since the behavior of apps or remotes are unpredictable during
// an upgrade, return a 503 directly // an upgrade, return a 503 directly
OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE); http_response_code(503);
$response = new \OC\OCS\Result(null, OC_Response::STATUS_SERVICE_UNAVAILABLE, 'Service unavailable'); $response = new \OC\OCS\Result(null, OC_Response::STATUS_SERVICE_UNAVAILABLE, 'Service unavailable');
OC_API::respond($response, OC_API::requestedFormat()); OC_API::respond($response, OC_API::requestedFormat());
exit; exit;
@ -65,7 +65,7 @@ try {
// Fall through the not found // Fall through the not found
} catch (MethodNotAllowedException $e) { } catch (MethodNotAllowedException $e) {
OC_API::setContentType(); OC_API::setContentType();
OC_Response::setStatus(405); http_response_code(405);
exit(); exit();
} catch (Exception $ex) { } catch (Exception $ex) {
OC_API::respond($ex->getResult(), OC_API::requestedFormat()); OC_API::respond($ex->getResult(), OC_API::requestedFormat());
@ -89,7 +89,7 @@ try {
OC_API::respond(new \OC\OCS\Result(null, \OCP\API::RESPOND_NOT_FOUND, $txt), $format); OC_API::respond(new \OC\OCS\Result(null, \OCP\API::RESPOND_NOT_FOUND, $txt), $format);
} catch (MethodNotAllowedException $e) { } catch (MethodNotAllowedException $e) {
OC_API::setContentType(); OC_API::setContentType();
OC_Response::setStatus(405); http_response_code(405);
} catch (\OC\OCS\Exception $ex) { } catch (\OC\OCS\Exception $ex) {
OC_API::respond($ex->getResult(), OC_API::requestedFormat()); OC_API::respond($ex->getResult(), OC_API::requestedFormat());
} catch (\OC\User\LoginException $e) { } catch (\OC\User\LoginException $e) {

@ -36,7 +36,7 @@ try {
if (\OCP\Util::needUpgrade()) { if (\OCP\Util::needUpgrade()) {
// since the behavior of apps or remotes are unpredictable during // since the behavior of apps or remotes are unpredictable during
// an upgrade, return a 503 directly // an upgrade, return a 503 directly
OC_Template::printErrorPage('Service unavailable', '', OC_Response::STATUS_SERVICE_UNAVAILABLE); OC_Template::printErrorPage('Service unavailable', '', 503);
exit; exit;
} }
@ -45,7 +45,7 @@ try {
$pathInfo = $request->getPathInfo(); $pathInfo = $request->getPathInfo();
if (!$pathInfo && $request->getParam('service', '') === '') { if (!$pathInfo && $request->getParam('service', '') === '') {
header('HTTP/1.0 404 Not Found'); http_response_code(404);
exit; exit;
} elseif ($request->getParam('service', '')) { } elseif ($request->getParam('service', '')) {
$service = $request->getParam('service', ''); $service = $request->getParam('service', '');
@ -55,7 +55,7 @@ try {
} }
$file = \OC::$server->getConfig()->getAppValue('core', 'public_' . strip_tags($service)); $file = \OC::$server->getConfig()->getAppValue('core', 'public_' . strip_tags($service));
if ($file === null) { if ($file === null) {
header('HTTP/1.0 404 Not Found'); http_response_code(404);
exit; exit;
} }
@ -78,10 +78,9 @@ try {
require_once OC_App::getAppPath($app) . '/' . $parts[1]; require_once OC_App::getAppPath($app) . '/' . $parts[1];
} catch (Exception $ex) { } catch (Exception $ex) {
$status = 500;
if ($ex instanceof \OC\ServiceUnavailableException) { if ($ex instanceof \OC\ServiceUnavailableException) {
$status = OC_Response::STATUS_SERVICE_UNAVAILABLE; $status = 503;
} else {
$status = OC_Response::STATUS_INTERNAL_SERVER_ERROR;
} }
//show the user a detailed error page //show the user a detailed error page
\OC::$server->getLogger()->logException($ex, ['app' => 'public']); \OC::$server->getLogger()->logException($ex, ['app' => 'public']);
@ -89,5 +88,5 @@ try {
} catch (Error $ex) { } catch (Error $ex) {
//show the user a detailed error page //show the user a detailed error page
\OC::$server->getLogger()->logException($ex, ['app' => 'public']); \OC::$server->getLogger()->logException($ex, ['app' => 'public']);
OC_Template::printExceptionErrorPage($ex, OC_Response::STATUS_INTERNAL_SERVER_ERROR); OC_Template::printExceptionErrorPage($ex, 500);
} }

@ -59,9 +59,9 @@ function handleException($e) {
$server->on('beforeMethod', function () use ($e) { $server->on('beforeMethod', function () use ($e) {
if ($e instanceof RemoteException) { if ($e instanceof RemoteException) {
switch ($e->getCode()) { switch ($e->getCode()) {
case OC_Response::STATUS_SERVICE_UNAVAILABLE: case 503:
throw new ServiceUnavailable($e->getMessage()); throw new ServiceUnavailable($e->getMessage());
case OC_Response::STATUS_NOT_FOUND: case 404:
throw new \Sabre\DAV\Exception\NotFound($e->getMessage()); throw new \Sabre\DAV\Exception\NotFound($e->getMessage());
} }
} }
@ -71,9 +71,9 @@ function handleException($e) {
}); });
$server->exec(); $server->exec();
} else { } else {
$statusCode = OC_Response::STATUS_INTERNAL_SERVER_ERROR; $statusCode = 500;
if ($e instanceof \OC\ServiceUnavailableException ) { if ($e instanceof \OC\ServiceUnavailableException ) {
$statusCode = OC_Response::STATUS_SERVICE_UNAVAILABLE; $statusCode = 503;
} }
if ($e instanceof RemoteException) { if ($e instanceof RemoteException) {
// we shall not log on RemoteException // we shall not log on RemoteException
@ -118,13 +118,13 @@ try {
if (\OCP\Util::needUpgrade()) { if (\OCP\Util::needUpgrade()) {
// since the behavior of apps or remotes are unpredictable during // since the behavior of apps or remotes are unpredictable during
// an upgrade, return a 503 directly // an upgrade, return a 503 directly
throw new RemoteException('Service unavailable', OC_Response::STATUS_SERVICE_UNAVAILABLE); throw new RemoteException('Service unavailable', 503);
} }
$request = \OC::$server->getRequest(); $request = \OC::$server->getRequest();
$pathInfo = $request->getPathInfo(); $pathInfo = $request->getPathInfo();
if ($pathInfo === false || $pathInfo === '') { if ($pathInfo === false || $pathInfo === '') {
throw new RemoteException('Path not found', OC_Response::STATUS_NOT_FOUND); throw new RemoteException('Path not found', 404);
} }
if (!$pos = strpos($pathInfo, '/', 1)) { if (!$pos = strpos($pathInfo, '/', 1)) {
$pos = strlen($pathInfo); $pos = strlen($pathInfo);
@ -134,7 +134,7 @@ try {
$file = resolveService($service); $file = resolveService($service);
if(is_null($file)) { if(is_null($file)) {
throw new RemoteException('Path not found', OC_Response::STATUS_NOT_FOUND); throw new RemoteException('Path not found', 404);
} }
$file=ltrim($file, '/'); $file=ltrim($file, '/');

@ -59,6 +59,6 @@ try {
} }
} catch (Exception $ex) { } catch (Exception $ex) {
OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR); http_response_code(500);
\OC::$server->getLogger()->logException($ex, ['app' => 'remote']); \OC::$server->getLogger()->logException($ex, ['app' => 'remote']);
} }

Loading…
Cancel
Save