route( '/scans', \WP_REST_Server::CREATABLE, array( $this, 'start' ), Capabilities::CAP_VIEW ); $this->route( '/scans/(?P\d+)/run', \WP_REST_Server::CREATABLE, array( $this, 'run' ), Capabilities::CAP_VIEW ); $this->route( '/scans/(?P\d+)', \WP_REST_Server::READABLE, array( $this, 'get' ), Capabilities::CAP_VIEW ); $this->route( '/lookup', \WP_REST_Server::READABLE, array( $this, 'lookup' ), Capabilities::CAP_VIEW ); } /** * Start a scan job. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response */ public function start( \WP_REST_Request $request ) { $scan_id = Scanner::start( $request->get_param( 'post_types' ), $request->get_param( 'statuses' ) ); return $this->respond( array( 'scan_id' => $scan_id ) ); } /** * Run the next batch. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function run( \WP_REST_Request $request ) { $result = Scanner::run_batch( absint( $request['id'] ) ); if ( ! is_wp_error( $result ) && $result['done'] ) { $result['counts'] = Scanner::get_scan_counts( $result['scan_id'] ); } return $this->respond( $result ); } /** * Scan status. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function get( \WP_REST_Request $request ) { $job = JobRepository::get( absint( $request['id'] ) ); if ( ! $job || 'scan' !== $job->type ) { return new \WP_Error( 'not_found', __( 'Scan not found.', 'slugh' ), array( 'status' => 404 ) ); } return $this->respond( $job ); } /** * URL lookup: normalize any URL (encoded or not) and show the matching record, redirect, or neither. * Query strings are never treated as part of the slug. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function lookup( \WP_REST_Request $request ) { $url = trim( $this->text_param( $request, 'url' ) ); if ( '' === $url ) { return new \WP_Error( 'missing_url', __( 'Enter a URL to look up.', 'slugh' ), array( 'status' => 400 ) ); } $canonical = Normalizer::normalize_path( $url ); $hash = Normalizer::compute_hash( $canonical ); $redirect = RedirectRepository::find_by_source( $canonical ); $record = null; $post_id = url_to_postid( home_url( $canonical ) ); if ( ! $post_id ) { $post_id = url_to_postid( home_url( user_trailingslashit( $canonical ) ) ); } if ( $post_id ) { $post = get_post( $post_id ); if ( $post && current_user_can( 'edit_post', $post->ID ) ) { $record = array( 'id' => $post->ID, 'title' => get_the_title( $post ), 'slug' => rawurldecode( $post->post_name ), 'type' => $post->post_type, 'status' => $post->post_status, 'permalink' => get_permalink( $post ), 'edit_link' => get_edit_post_link( $post->ID, 'raw' ), ); } } return $this->respond( array( 'queried_url' => $url, 'canonical_path' => $canonical, 'query_string' => Normalizer::extract_query( $url ), 'malformed' => Normalizer::is_malformed( $url ), 'source_hash' => $hash, 'redirect' => $redirect, 'record' => $record, ) ); } }