ApiRoute.php
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * ====================================================================== |
| 5 | * LICENSE: This file is subject to the terms and conditions defined in * |
| 6 | * file 'license.txt', which is part of this source code package. * |
| 7 | * ====================================================================== |
| 8 | */ |
| 9 | |
| 10 | /** |
| 11 | * API Route service |
| 12 | * |
| 13 | * @package AAM |
| 14 | * @version 7.0.0 |
| 15 | */ |
| 16 | class AAM_Service_ApiRoute |
| 17 | { |
| 18 | use AAM_Service_BaseTrait; |
| 19 | |
| 20 | /** |
| 21 | * Constructor |
| 22 | * |
| 23 | * @return void |
| 24 | * @access protected |
| 25 | * |
| 26 | * @version 7.0.4 |
| 27 | */ |
| 28 | protected function __construct() |
| 29 | { |
| 30 | // Register RESTful API endpoints |
| 31 | AAM_Restful_ApiRoute::bootstrap(); |
| 32 | |
| 33 | add_action('init', function() { |
| 34 | $this->initialize_hooks(); |
| 35 | }, PHP_INT_MAX); |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Initialize API Route hooks |
| 40 | * |
| 41 | * @return void |
| 42 | * @access protected |
| 43 | * |
| 44 | * @version 7.0.4 |
| 45 | */ |
| 46 | protected function initialize_hooks() |
| 47 | { |
| 48 | if (is_admin()) { |
| 49 | // Hook that initialize the AAM UI part of the service |
| 50 | add_action('aam_initialize_ui_action', function () { |
| 51 | AAM_Backend_Feature_Main_ApiRoute::register(); |
| 52 | }); |
| 53 | } |
| 54 | |
| 55 | // Register API manager is applicable |
| 56 | add_filter('rest_pre_dispatch', function($result, $_, $request) { |
| 57 | return $this->_rest_pre_dispatch($result, $request); |
| 58 | }, PHP_INT_MAX, 3); |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * Authorize REST request |
| 63 | * |
| 64 | * Based on the matched route, check if it is disabled for current user |
| 65 | * |
| 66 | * @param WP_Error|null $response |
| 67 | * @param WP_REST_Request $request |
| 68 | * |
| 69 | * @return WP_Error|null |
| 70 | * @access public |
| 71 | * |
| 72 | * @version 7.0.0 |
| 73 | */ |
| 74 | private function _rest_pre_dispatch($response, $request) |
| 75 | { |
| 76 | if (!is_wp_error($response)) { |
| 77 | if (AAM::api()->api_routes()->is_denied($request)) { |
| 78 | $response = new WP_Error( |
| 79 | 'rest_access_denied', |
| 80 | __('Access Denied', 'advanced-access-manager'), |
| 81 | array('status' => 401) |
| 82 | ); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | return $response; |
| 87 | } |
| 88 | |
| 89 | } |