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