Set HTTP status codes with http_​response_​code()

This commit is contained in:
Alexei Sorokin
2020-08-04 14:12:17 +03:00
committed by Diogo Peralta Cordeiro
parent 3429a3644d
commit 1667d727b4
14 changed files with 526 additions and 525 deletions

View File

@@ -1,53 +1,44 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2011, StatusNet, Inc.
*
* An action that requires an API key
*
* PHP version 5
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category DomainStatusNetwork
* @package StatusNet
* @package GNUsocial
* @author Evan Prodromou <evan@status.net>
* @copyright 2011 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
* @link http://status.net/
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
if (!defined('STATUSNET')) {
// This check helps protect against security problems;
// your code file can't be executed directly from the web.
exit(1);
}
defined('GNUSOCIAL') || die();
/**
* An action that requires an API key
*
* @category General
* @package StatusNet
* @package GNUsocial
* @author Evan Prodromou <evan@status.net>
* @copyright 2011 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
* @link http://status.net/
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class GlobalApiAction extends Action
{
var $email;
public $email;
/**
* Check for an API key, and throw an exception if it's not set
@@ -57,7 +48,7 @@ class GlobalApiAction extends Action
* @return boolean continuation flag
*/
function prepare(array $args = array())
public function prepare(array $args = [])
{
GNUsocial::setApi(true); // reduce exception reports to aid in debugging
@@ -96,12 +87,12 @@ class GlobalApiAction extends Action
return true;
}
function showError($message, $code=400)
public function showError($message, $code = 400)
{
$this->showOutput(array('error' => $message), $code);
}
function showSuccess($values=null, $code=200)
public function showSuccess($values = null, $code = 200)
{
if (empty($values)) {
$values = array();
@@ -110,19 +101,17 @@ class GlobalApiAction extends Action
$this->showOutput($values, $code);
}
function showOutput($values, $code)
public function showOutput($values, $code)
{
if (array_key_exists($code, ClientErrorAction::$status)) {
$status_string = ClientErrorAction::$status[$code];
} else if (array_key_exists($code, ServerErrorAction::$status)) {
$status_string = ServerErrorAction::$status[$code];
} else {
if (
!array_key_exists($code, ClientErrorAction::$status)
&& !array_key_exists($code, ServerErrorAction::$status)
) {
// bad code!
$code = 500;
$status_string = ServerErrorAction::$status[$code];
}
header('HTTP/1.1 '.$code.' '.$status_string);
http_response_code($code);
header('Content-Type: application/json; charset=utf-8');
print(json_encode($values));

View File

@@ -1,31 +1,28 @@
<?php
/*
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2010, StatusNet, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* Integrated WebSub hub; lets us only ping them what need it.
* @package Hub
* @maintainer Brion Vibber <brion@status.net>
* @package Hub
* @author Brion Vibber <brion@status.net>
* @copyright 2010 StatusNet, Inc.
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
if (!defined('STATUSNET')) {
exit(1);
}
defined('GNUSOCIAL') || die();
/**
* Things to consider...
@@ -38,7 +35,7 @@ if (!defined('STATUSNET')) {
*/
class PushHubAction extends Action
{
function arg($arg, $def=null)
public function arg($arg, $def = null)
{
// PHP converts '.'s in incoming var names to '_'s.
// It also merges multiple values, which'll break hub.verify and hub.topic for publishing
@@ -47,7 +44,7 @@ class PushHubAction extends Action
return parent::arg($arg, $def);
}
protected function prepare(array $args=array())
protected function prepare(array $args = [])
{
GNUsocial::setApi(true); // reduce exception reports to aid in debugging
return parent::prepare($args);
@@ -62,11 +59,17 @@ class PushHubAction extends Action
$this->subunsub($mode);
break;
case "publish":
// TRANS: Client exception.
throw new ClientException(_m('Publishing outside feeds not supported.'), 400);
throw new ClientException(
// TRANS: Client exception.
_m('Publishing outside feeds not supported.'),
400
);
default:
// TRANS: Client exception. %s is a mode.
throw new ClientException(sprintf(_m('Unrecognized mode "%s".'),$mode), 400);
throw new ClientException(sprintf(
// TRANS: Client exception. %s is a mode.
_m('Unrecognized mode "%s".'), $mode),
400
);
}
}
@@ -79,7 +82,7 @@ class PushHubAction extends Action
* 204 No Content - already subscribed
* 400 Bad Request - rejecting this (not specifically spec'd)
*/
function subunsub($mode)
public function subunsub($mode)
{
$callback = $this->argUrl('hub.callback');
@@ -87,22 +90,31 @@ class PushHubAction extends Action
$topic = $this->argUrl('hub.topic');
if (!$this->recognizedFeed($topic)) {
common_debug('WebSub hub request had unrecognized feed topic=='._ve($topic));
// TRANS: Client exception. %s is a topic.
throw new ClientException(sprintf(_m('Unsupported hub.topic %s this hub only serves local user and group Atom feeds.'),$topic));
throw new ClientException(sprintf(
// TRANS: Client exception. %s is a topic.
_m('Unsupported hub.topic %s this hub only serves local user and group Atom feeds.'),
$topic
));
}
$lease = $this->arg('hub.lease_seconds', null);
if ($mode == 'subscribe' && $lease != '' && !preg_match('/^\d+$/', $lease)) {
common_debug('WebSub hub request had invalid lease_seconds=='._ve($lease));
// TRANS: Client exception. %s is the invalid lease value.
throw new ClientException(sprintf(_m('Invalid hub.lease "%s". It must be empty or positive integer.'),$lease));
throw new ClientException(sprintf(
_m('Invalid hub.lease "%s". It must be empty or positive integer.'),
$lease
));
}
$secret = $this->arg('hub.secret', null);
if ($secret != '' && strlen($secret) >= 200) {
common_debug('WebSub hub request had invalid secret=='._ve($secret));
// TRANS: Client exception. %s is the invalid hub secret.
throw new ClientException(sprintf(_m('Invalid hub.secret "%s". It must be under 200 bytes.'),$secret));
throw new ClientException(sprintf(
// TRANS: Client exception. %s is the invalid hub secret.
_m('Invalid hub.secret "%s". It must be under 200 bytes.'),
$secret
));
}
$sub = HubSub::getByHashkey($topic, $callback);
@@ -126,10 +138,10 @@ class PushHubAction extends Action
$token = $this->arg('hub.verify_token', null); // TODO: deprecated
if ($verify == 'sync') { // pre-0.4 PuSH
$sub->verify($mode, $token);
header('HTTP/1.1 204 No Content');
http_response_code(204);
} else { // If $verify is not "sync", we might be using WebSub or PuSH 0.4
$sub->scheduleVerify($mode, $token); // If we were certain it's WebSub or PuSH 0.4, token could be removed
header('HTTP/1.1 202 Accepted');
http_response_code(202);
}
}
@@ -154,16 +166,22 @@ class PushHubAction extends Action
case common_local_url('ApiTimelineUser', $params):
$user = User::getKV('id', $id);
if (!$user instanceof User) {
// TRANS: Client exception. %s is a feed URL.
throw new ClientException(sprintf(_m('Invalid hub.topic "%s". User does not exist.'),$feed));
throw new ClientException(sprintf(
// TRANS: Client exception. %s is a feed URL.
_m('Invalid hub.topic "%s". User does not exist.'),
$feed
));
}
return true;
case common_local_url('ApiTimelineGroup', $params):
$group = Local_group::getKV('group_id', $id);
if (!$group instanceof Local_group) {
// TRANS: Client exception. %s is a feed URL.
throw new ClientException(sprintf(_m('Invalid hub.topic "%s". Local_group does not exist.'),$feed));
throw new ClientException(sprintf(
// TRANS: Client exception. %s is a feed URL.
_m('Invalid hub.topic "%s". Local_group does not exist.'),
$feed
));
}
return true;
}
@@ -183,8 +201,11 @@ class PushHubAction extends Action
$list = Profile_list::getKV('id', $id);
$user = User::getKV('id', $user);
if (!$list instanceof Profile_list || !$user instanceof User || $list->tagger != $user->id) {
// TRANS: Client exception. %s is a feed URL.
throw new ClientException(sprintf(_m('Invalid hub.topic %s; list does not exist.'),$feed));
throw new ClientException(sprintf(
// TRANS: Client exception. %s is a feed URL.
_m('Invalid hub.topic %s; list does not exist.'),
$feed
));
}
return true;
}
@@ -207,9 +228,13 @@ class PushHubAction extends Action
'allowed_schemes' => array('http', 'https'));
$validate = new Validate();
if (!$validate->uri($url, $params)) {
// TRANS: Client exception.
// TRANS: %1$s is this argument to the method this exception occurs in, %2$s is a URL.
throw new ClientException(sprintf(_m('Invalid URL passed for %1$s: "%2$s"'),$arg,$url));
throw new ClientException(sprintf(
// TRANS: Client exception.
// TRANS: %1$s is this argument to the method this exception occurs in, %2$s is a URL.
_m('Invalid URL passed for %1$s: "%2$s"'),
$arg,
$url
));
}
Event::handle('UrlBlacklistTest', array($url));

View File

@@ -1,73 +1,67 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* StatusNet, the distributed open-source microblogging tool
*
* Settings for OpenID
*
* PHP version 5
*
* LICENCE: This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category Settings
* @package StatusNet
* @author Craig Andrews <candrews@integralblue.com>
* @package GNUsocial
* @author Craig Andrews <candrews@integralblue.com>
* @copyright 2008-2009 StatusNet, Inc.
* @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
if (!defined('STATUSNET')) {
exit(1);
}
defined('GNUSOCIAL') || die();
require_once INSTALLDIR.'/plugins/OpenID/openid.php';
require_once INSTALLDIR . '/plugins/OpenID/openid.php';
/**
* Settings for OpenID
*
* Lets users add, edit and delete OpenIDs from their account
*
* @category Settings
* @package StatusNet
* @author Craig Andrews <candrews@integralblue.com>
* @category Settings
* @package GNUsocial
* @author Craig Andrews <candrews@integralblue.com>
* @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class OpenidserverAction extends Action
{
var $oserver;
public $oserver;
function prepare(array $args = array())
public function prepare(array $args = [])
{
parent::prepare($args);
$this->oserver = oid_server();
return true;
}
function handle()
public function handle()
{
parent::handle();
$request = $this->oserver->decodeRequest();
if (in_array($request->mode, array('checkid_immediate',
'checkid_setup'))) {
if (!$this->scoped instanceof Profile) {
if($request->immediate){
if ($request->immediate) {
//cannot prompt the user to login in immediate mode, so answer false
$response = $this->generateDenyResponse($request);
}else{
} else {
// Go log in, and then come back.
//
// Note: 303 redirect rather than 307 to avoid
@@ -76,14 +70,19 @@ class OpenidserverAction extends Action
common_set_returnto($_SERVER['REQUEST_URI']);
common_redirect(common_local_url('login'), 303);
}
} elseif (in_array($request->identity, $this->scoped->getAliases()) || $request->idSelect()) {
$user_openid_trustroot = User_openid_trustroot::pkeyGet(
array('user_id'=>$this->scoped->getID(), 'trustroot'=>$request->trust_root));
if(empty($user_openid_trustroot)){
if($request->immediate){
} elseif (
in_array($request->identity, $this->scoped->getAliases())
|| $request->idSelect()
) {
$user_openid_trustroot = User_openid_trustroot::pkeyGet([
'user_id' => $this->scoped->getID(),
'trustroot' => $request->trust_root,
]);
if (empty($user_openid_trustroot)) {
if ($request->immediate) {
//cannot prompt the user to trust this trust root in immediate mode, so answer false
$response = $this->generateDenyResponse($request);
}else{
} else {
common_ensure_session();
$_SESSION['openid_trust_root'] = $request->trust_root;
$allowResponse = $this->generateAllowResponse($request, $this->scoped);
@@ -108,51 +107,61 @@ class OpenidserverAction extends Action
$response = $this->generateDenyResponse($request);
} else {
//invalid
// TRANS: OpenID plugin client error given trying to add an unauthorised OpenID to a user (403).
// TRANS: %s is a request identity.
$this->clientError(sprintf(_m('You are not authorized to use the identity %s.'),$request->identity),$code=403);
$this->clientError(sprintf(
// TRANS: OpenID plugin client error given trying to add an unauthorised OpenID to a user (403).
// TRANS: %s is a request identity.
_m('You are not authorized to use the identity %s.'),
$request->identity
), 403);
}
} else {
$response = $this->oserver->handleRequest($request);
}
if($response){
if ($response) {
$response = $this->oserver->encodeResponse($response);
if ($response->code != AUTH_OPENID_HTTP_OK) {
header(sprintf("HTTP/1.1 %d ", $response->code),
true, $response->code);
http_response_code($response->code);
}
if($response->headers){
if ($response->headers) {
foreach ($response->headers as $k => $v) {
header("$k: $v");
}
}
$this->raw($response->body);
}else{
// TRANS: OpenID plugin client error given when not getting a response for a given OpenID provider (500).
$this->clientError(_m('Just an OpenID provider. Nothing to see here, move along...'),$code=500);
} else {
$this->clientError(
// TRANS: OpenID plugin client error given when not getting a response for a given OpenID provider (500).
_m('Just an OpenID provider. Nothing to see here, move along...'),
500
);
}
}
function generateAllowResponse($request, Profile $profile){
public function generateAllowResponse($request, Profile $profile)
{
$response = $request->answer(true, null, $profile->getUrl());
$user = $profile->getUser();
$sreg_data = array(
$sreg_data = [
'fullname' => $profile->getFullname(),
'nickname' => $profile->getNickname(),
'email' => $user->email, // FIXME: Should we make the email optional?
'language' => $user->language,
'timezone' => $user->timezone);
'timezone' => $user->timezone,
];
$sreg_request = Auth_OpenID_SRegRequest::fromOpenIDRequest($request);
$sreg_response = Auth_OpenID_SRegResponse::extractResponse(
$sreg_request, $sreg_data);
$sreg_request,
$sreg_data
);
$sreg_response->toMessage($response->fields);
return $response;
}
function generateDenyResponse($request){
public function generateDenyResponse($request)
{
$response = $request->answer(false);
return $response;
}

View File

@@ -1,36 +1,31 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* This test class pretends to be an RSS aggregator. It logs notifications
* from the cloud.
*
* PHP version 5
*
* @category Plugin
* @package StatusNet
* @author Zach Copley <zach@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
* @link http://status.net/
*
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2009, StatusNet, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* @category Plugin
* @package GNUsocial
* @author Zach Copley <zach@status.net>
* @copyright 2009 StatusNet, Inc.
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
if (!defined('STATUSNET')) {
exit(1);
}
defined('GNUSOCIAL') || die();
/**
* Dummy aggregator that acts as a proper notification handler. It
@@ -39,16 +34,15 @@ if (!defined('STATUSNET')) {
* and easily test things end-to-end. I'm leaving it in here as it
* may be useful for developing the plugin further.
*
* @category Plugin
* @package StatusNet
* @author Zach Copley <zach@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
* @category Plugin
* @package GNUsocial
* @author Zach Copley <zach@status.net>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class LoggingAggregatorAction extends Action
{
var $challenge = null;
var $url = null;
public $challenge = null;
public $url = null;
/**
* Initialization.
@@ -57,7 +51,7 @@ class LoggingAggregatorAction extends Action
*
* @return boolean false if user doesn't exist
*/
function prepare(array $args = array())
public function prepare(array $args = [])
{
parent::prepare($args);
@@ -77,7 +71,7 @@ class LoggingAggregatorAction extends Action
*
* @return void
*/
function handle()
public function handle()
{
parent::handle();
@@ -106,7 +100,7 @@ class LoggingAggregatorAction extends Action
}
header('Content-Type: text/xml');
Echo "<notifyResult success='true' msg='Thanks for the update.' />\n";
echo "<notifyResult success='true' msg='Thanks for the update.' />\n";
}
$this->ip = $_SERVER['REMOTE_ADDR'];
@@ -123,9 +117,9 @@ class LoggingAggregatorAction extends Action
*
* @return void
*/
function showError($msg)
public function showError($msg)
{
header('HTTP/1.1 400 Bad Request');
http_response_code(400);
header('Content-Type: text/xml');
echo "<?xml version='1.0'?>\n";
echo "<notifyResult success='false' msg='$msg' />\n";