RestAPI.php
1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/**
* Frontend Rest API query restrictions.
*
* @copyright (c) 2023, Code Atlantic LLC.
* @package ContentControl
*/
namespace ContentControl\Controllers\Frontend\Restrictions;
use ContentControl\Base\Controller;
use function ContentControl\content_is_restricted;
use function ContentControl\protection_is_disabled;
use function ContentControl\get_applicable_restriction;
defined( 'ABSPATH' ) || exit;
/**
* Class for handling global restrictions of the Rest API.
*
* @package ContentControl
*/
class RestAPI extends Controller {
/**
* Initiate functionality.
*
* @return void
*/
public function init() {
add_filter( 'rest_pre_dispatch', [ $this, 'pre_dispatch' ], 1, 3 );
}
/**
* Handle a restriction on the rest api via pre_dispatch.
*
* @param mixed $result Response to replace the requested resource with. Can be anything a normal endpoint can return, or null to not hijack the request.
* @param mixed $server Server instance.
* @param mixed $request Request used to generate the response.
*
* @return mixed
*/
public function pre_dispatch( $result, $server, $request ) { // phpcs:ignore
if ( protection_is_disabled() ) {
return $result;
}
if ( content_is_restricted() ) {
$restriction = get_applicable_restriction();
/**
* Fires when a post is restricted, but before the restriction is handled.
*
* @param \ContentControl\Models\Restriction $restriction Restriction object.
*/
do_action( 'content_control/restrict_rest_query', $restriction );
$method = $restriction->get_setting( 'restApiQueryHandling', 'forbidden' );
switch ( $method ) {
// If we got here, the default is to return a rest_forbidden response.
case 'forbidden':
// Mimic a rest_forbidden response.
return new \WP_Error(
'rest_forbidden',
$restriction->get_setting( 'restApiQueryMessage', __( 'You do not have permission to do this.', 'content-control' ), ),
[ 'status' => 403 ]
);
}
}
return $result;
}
}