check_academy_course_action( $request, __FUNCTION__, true ); if ( true !== $allowed || current_user_can( 'manage_options' ) ) { return $allowed; } // Outside administrators only published templates and the user's own // drafts are readable: an instructor's role includes edit_others, which // would otherwise expose another instructor's draft or private template. $post = get_post( (int) $request['id'] ); if ( $post && 'publish' !== $post->post_status && (int) $post->post_author !== get_current_user_id() ) { return new WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to view this certificate template.', 'academy' ), [ 'status' => rest_authorization_required_code() ] ); } return $allowed; } public function get_items_permissions_check( $request ) { return $this->check_academy_course_action( $request, __FUNCTION__, true ); } /** * Limit a collection query for non-administrators to published templates * and their own drafts or private templates. * * @param array $args WP_Query arguments. * @return array */ public static function restrict_collection_query( $args ) { if ( ! current_user_can( 'manage_options' ) ) { // The filter runs just before the REST query and removes itself. add_filter( 'posts_where', array( __CLASS__, 'own_unpublished_where' ) ); } return $args; } /** * Adds "published, or authored by the current user" to the collection query. * * @param string $where SQL WHERE. * @return string */ public static function own_unpublished_where( $where ) { global $wpdb; remove_filter( 'posts_where', array( __CLASS__, 'own_unpublished_where' ) ); return $where . $wpdb->prepare( " AND ( {$wpdb->posts}.post_status = 'publish' OR {$wpdb->posts}.post_author = %d )", get_current_user_id() ); } public function create_item_permissions_check( $request ) { return $this->check_academy_course_action( $request, __FUNCTION__ ); } public function update_item_permissions_check( $request ) { return $this->check_academy_course_action( $request, __FUNCTION__ ); } public function delete_item_permissions_check( $request ) { return $this->check_academy_course_action( $request, __FUNCTION__ ); } private function check_academy_course_action( $request, $perm_method, bool $pass = false ) { if ( ! is_user_logged_in() ) { return new WP_Error( 'unauthorized', __( 'Unauthorized.', 'academy' ), [ 'status' => 401 ] ); } if ( current_user_can( 'manage_options' ) ) { return true; } // The parent check returns true or a WP_Error. A WP_Error is an object and // therefore truthy, so it has to be tested explicitly: otherwise a denied // read (a draft or private template) would be treated as allowed. $allowed = parent::{$perm_method}( $request ); if ( is_wp_error( $allowed ) ) { return $allowed; } if ( ! $allowed ) { return new WP_Error( 'unauthorized', __( 'Unauthorized.', 'academy' ), [ 'status' => rest_authorization_required_code() ] ); } return $pass; } }