*/ public static function defaults(): array { return array( 'enabled' => true, 'monitor_404' => true, 'auto_redirect'=> true, // Redirect when a post slug changes. ); } public function register( Container $container ): void {} public function boot( Container $container ): void { add_action( 'rest_api_init', array( $this, 'routes' ) ); Guard::action( 'template_redirect', array( $this, 'handle' ), 1 ); add_action( 'post_updated', array( $this, 'slug_changed' ), 10, 3 ); } /** * Current request path, normalized (no host, no query, leading slash, no trailing slash). */ private function current_path(): string { $uri = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : ''; return self::normalize( (string) wp_parse_url( $uri, PHP_URL_PATH ) ); } public static function normalize( string $path ): string { $path = '/' . trim( (string) wp_parse_url( $path, PHP_URL_PATH ), '/' ); return '/' === $path ? '/' : rtrim( $path, '/' ); } /** * Perform a matching redirect, else log a 404. */ public function handle(): void { global $wpdb; $settings = $this->settings(); if ( empty( $settings['enabled'] ) ) { return; } $path = $this->current_path(); if ( '' === $path || str_starts_with( $path, '/wp-admin' ) ) { return; } // What is actually in the table, cached. Almost every site runs this // hook on every page view and almost every site has no redirects at // all, so the default case used to be two database queries to learn // nothing. Now it is a cache read, and a site with only exact redirects // never pays for the regex scan. $shape = $this->shape(); if ( 0 === $shape['exact'] && array() === $shape['regex'] ) { if ( is_404() && ! empty( $settings['monitor_404'] ) ) { $this->log_404( $path ); } return; } $table = Database::redirects(); $row = null; if ( $shape['exact'] > 0 ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $row = $wpdb->get_row( $wpdb->prepare( "SELECT id, target, type FROM {$table} WHERE source = %s AND status = 'active' LIMIT 1", $path ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared } if ( ! $row ) { $row = $this->match_regex( $path, $shape['regex'] ); } if ( $row ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET hits = hits + 1, last_hit = %s WHERE id = %d", current_time( 'mysql', true ), $row->id ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared if ( 410 === (int) $row->type ) { status_header( 410 ); exit; } $target = (string) $row->target; $url = str_starts_with( $target, 'http' ) ? $target : home_url( $target ); wp_safe_redirect( $url, (int) $row->type ); exit; } if ( is_404() && ! empty( $settings['monitor_404'] ) ) { $this->log_404( $path ); } } private const SHAPE = 'airanksuite_redirect_shape'; /** * How many exact rules exist, and every regex rule, in one cached read. * * The regex rules travel with the shape because there are at most 200 of * them, they are tiny, and every one has to be tested against the path * anyway — caching the count without the rows would save nothing. The exact * rules do not, because there can be tens of thousands of them and the * lookup is a single indexed hit; all the front end needs to know is * whether it is worth making. * * Invalidated on every write, so a redirect works the moment it is saved * rather than within the hour. A stale cache here would mean a customer * adding a redirect, testing it, seeing a 404 and filing a bug. * * @return array{exact:int, regex:array} */ private function shape(): array { $cached = get_transient( self::SHAPE ); if ( is_array( $cached ) && isset( $cached['exact'], $cached['regex'] ) ) { return $cached; } global $wpdb; $table = Database::redirects(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $exact = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE status = 'active'", $table ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $regex = (array) $wpdb->get_results( $wpdb->prepare( "SELECT id, source, target, type FROM %i WHERE status = 'regex' LIMIT 200", $table ) ); $shape = array( 'exact' => $exact, 'regex' => $regex, ); set_transient( self::SHAPE, $shape, DAY_IN_SECONDS ); return $shape; } /** Forget the cached rule set. Called after every write. */ public static function forget(): void { delete_transient( self::SHAPE ); } /** * Try regex redirects (stored with type flag 'regex' in the status column * so no schema change is needed). * * @param string $path The request path. * @param array $rows The cached regex rules. * @return object|null */ private function match_regex( string $path, array $rows ) { foreach ( $rows as $row ) { // The cached row is shared; rewriting its target below would // poison every later request in this process. $row = clone $row; $pattern = '#' . str_replace( '#', '\#', (string) $row->source ) . '#i'; // A malformed pattern must never fatal the front end. $matched = @preg_match( $pattern, $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged if ( 1 === $matched ) { $row->target = (string) @preg_replace( $pattern, (string) $row->target, $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged return $row; } } return null; } private function log_404( string $path ): void { global $wpdb; $table = Database::not_found(); $now = current_time( 'mysql', true ); $referrer = isset( $_SERVER['HTTP_REFERER'] ) ? esc_url_raw( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : ''; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $existing = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$table} WHERE path = %s", $path ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared if ( $existing ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET hits = hits + 1, last_hit = %s WHERE id = %d", $now, $existing ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared return; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->insert( $table, array( 'path' => mb_substr( $path, 0, 191 ), 'hits' => 1, 'referrer' => mb_substr( $referrer, 0, 191 ), 'last_hit' => $now, 'created_at' => $now, ), array( '%s', '%d', '%s', '%s', '%s' ) ); } /** * Create an automatic redirect when a published post's slug changes. * * @param int $post_id Post ID. * @param \WP_Post $post_after Post after update. * @param \WP_Post $post_before Post before update. */ public function slug_changed( int $post_id, $post_after, $post_before ): void { $settings = $this->settings(); if ( empty( $settings['auto_redirect'] ) ) { return; } if ( 'publish' !== $post_before->post_status || 'publish' !== $post_after->post_status ) { return; } if ( $post_before->post_name === $post_after->post_name || '' === $post_before->post_name ) { return; } $old = self::normalize( (string) wp_parse_url( get_permalink( $post_before ), PHP_URL_PATH ) ); $new = self::normalize( (string) wp_parse_url( get_permalink( $post_after ), PHP_URL_PATH ) ); if ( $old === $new || '/' === $old ) { return; } $this->create( $old, $new, 301 ); } /** * Insert (or revive) a redirect. */ private function create( string $source, string $target, int $type, bool $regex = false ): bool { global $wpdb; $now = current_time( 'mysql', true ); self::forget(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return false !== $wpdb->replace( Database::redirects(), array( 'source' => mb_substr( $regex ? $source : self::normalize( $source ), 0, 191 ), 'target' => $target, 'type' => $type, 'status' => $regex ? 'regex' : 'active', 'created_at' => $now, ), array( '%s', '%s', '%d', '%s', '%s' ) ); } /** @return array */ private function settings(): array { return \AiRankSuite\Kernel::service( \AiRankSuite\Support\Options::class )->get( 'redirects', self::defaults() ); } public function routes(): void { register_rest_route( self::NAMESPACE, '/redirects', array( array( 'methods' => 'GET', 'callback' => array( $this, 'index' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), ), array( 'methods' => 'POST', 'callback' => array( $this, 'store' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), 'args' => array( 'source' => array( 'type' => 'string', 'required' => true, // A path, not prose. sanitize_text_field strips %XX, so // /caf%C3%A9-menu became /caf-menu and the redirect then // never matched the raw REQUEST_URI it is compared against. 'sanitize_callback' => static fn( $v ): string => trim( wp_strip_all_tags( (string) $v ) ), ), 'target' => array( 'type' => 'string', 'required' => true, 'sanitize_callback' => static fn( $v ): string => trim( wp_strip_all_tags( (string) $v ) ), ), 'type' => array( 'type' => 'integer', 'default' => 301, 'enum' => array( 301, 302, 307, 410 ), ), ), ), ) ); register_rest_route( self::NAMESPACE, '/redirects/(?P\d+)', array( 'methods' => 'DELETE', 'callback' => array( $this, 'destroy' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), ) ); register_rest_route( self::NAMESPACE, '/404s', array( 'methods' => 'GET', 'callback' => array( $this, 'not_found' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), ) ); register_rest_route( self::NAMESPACE, '/404s/(?P\d+)', array( 'methods' => 'DELETE', 'callback' => array( $this, 'delete_404' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), ) ); // A migration arrives as a spreadsheet; so does the handover at the end. register_rest_route( self::NAMESPACE, '/redirects/import', array( 'methods' => 'POST', 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), 'callback' => static function ( WP_REST_Request $request ) { $result = Services\RedirectFile::import( (string) $request['content'], (string) $request['format'], array( 'dry_run' => (bool) $request['dry_run'], 'overwrite' => (bool) $request['overwrite'], // A large file is applied a slice per request; the // response says where the next one starts. 'offset' => (int) $request['offset'], ) ); return new WP_REST_Response( $result ); }, 'args' => array( 'content' => array( 'type' => 'string', 'required' => true ), 'format' => array( 'type' => 'string', 'default' => 'csv', 'enum' => array( 'csv', 'json' ) ), 'dry_run' => array( 'type' => 'boolean', 'default' => false ), 'overwrite' => array( 'type' => 'boolean', 'default' => false ), 'offset' => array( 'type' => 'integer', 'default' => 0, 'minimum' => 0 ), ), ) ); register_rest_route( self::NAMESPACE, '/redirects/export', array( 'methods' => 'GET', 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), 'callback' => static fn() => new WP_REST_Response( array( 'csv' => Services\RedirectFile::export() ) ), ) ); register_rest_route( self::NAMESPACE, '/settings/redirects', array( array( 'methods' => 'GET', 'callback' => fn() => new WP_REST_Response( $this->settings() ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), ), array( 'methods' => 'PUT', 'callback' => array( $this, 'update_settings' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), 'args' => array( 'enabled' => array( 'type' => 'boolean' ), 'monitor_404' => array( 'type' => 'boolean' ), 'auto_redirect' => array( 'type' => 'boolean' ), ), ), ) ); } public function index( WP_REST_Request $request ): WP_REST_Response|WP_Error { global $wpdb; $table = Database::redirects(); // Legacy shape when no pagination is asked for: existing callers (and // any third-party consumer) keep getting the bare array they always got. if ( null === $request->get_param( 'page' ) && null === $request->get_param( 'per_page' ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE status IN ('active','regex') ORDER BY created_at DESC LIMIT 200", $table ) ); return new WP_REST_Response( array_map( array( $this, 'shape_redirect' ), (array) $rows ) ); } // Paginated mode: the shared list contract. Server does the searching, // sorting and counting so ten thousand redirects never reach the browser. $query = \AiRankSuite\Support\ListQuery::from_request( $request, array( 'orderby' => array( 'created_at', 'hits', 'source', 'last_hit' ), 'default_orderby' => 'created_at', 'status' => array( 'active', 'regex' ), ) ); if ( $query instanceof WP_Error ) { return $query; } // The statement is a constant: nothing is assembled into it. A filter // that is not in use is switched off by its own flag rather than left // out of the text, the sort column travels as an identifier (%i), and // the direction picks one of two literals. $any_status = '' === $query->status ? 1 : 0; $any_text = '' === $query->search ? 1 : 0; $like = '%' . $wpdb->esc_like( $query->search ) . '%'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $total = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE ( ( %d = 1 AND status IN ('active','regex') ) OR ( %d = 0 AND status = %s ) ) AND ( %d = 1 OR source LIKE %s OR target LIKE %s )", $table, $any_status, $any_status, $query->status, $any_text, $like, $like ) ); if ( 'ASC' === $query->order ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE ( ( %d = 1 AND status IN ('active','regex') ) OR ( %d = 0 AND status = %s ) ) AND ( %d = 1 OR source LIKE %s OR target LIKE %s ) ORDER BY %i ASC LIMIT %d OFFSET %d", $table, $any_status, $any_status, $query->status, $any_text, $like, $like, $query->orderby, $query->per_page, $query->offset() ) ); } else { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE ( ( %d = 1 AND status IN ('active','regex') ) OR ( %d = 0 AND status = %s ) ) AND ( %d = 1 OR source LIKE %s OR target LIKE %s ) ORDER BY %i DESC LIMIT %d OFFSET %d", $table, $any_status, $any_status, $query->status, $any_text, $like, $like, $query->orderby, $query->per_page, $query->offset() ) ); } return \AiRankSuite\Support\Paginated::response( array_map( array( $this, 'shape_redirect' ), (array) $rows ), $total, $query ); } public function store( WP_REST_Request $request ): WP_REST_Response|WP_Error { $regex = (bool) $request['regex']; $target = (string) $request['target']; if ( $regex ) { $pattern = (string) $request['source']; // Reject a pattern that PHP cannot compile before it reaches the front end. if ( false === @preg_match( '#' . str_replace( '#', '\#', $pattern ) . '#i', '' ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged return new WP_Error( 'airanksuite_redirect_bad_regex', __( 'That is not a valid regular expression.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } if ( ! $this->create( $pattern, $target, (int) $request['type'], true ) ) { return new WP_Error( 'airanksuite_redirect_failed', __( 'Could not save the redirect.', 'ai-rank-suite' ), array( 'status' => 500 ) ); } return $this->index( $request ); } $source = self::normalize( (string) $request['source'] ); if ( '/' === $source || '' === trim( $target ) ) { return new WP_Error( 'airanksuite_redirect_invalid', __( 'Source and target are required, and the source cannot be the home page.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } if ( $source === self::normalize( $target ) ) { return new WP_Error( 'airanksuite_redirect_loop', __( 'Source and target are identical — that would loop.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } if ( ! $this->create( $source, $target, (int) $request['type'] ) ) { return new WP_Error( 'airanksuite_redirect_failed', __( 'Could not save the redirect.', 'ai-rank-suite' ), array( 'status' => 500 ) ); } return $this->index( $request ); } public function destroy( WP_REST_Request $request ): WP_REST_Response { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->delete( Database::redirects(), array( 'id' => (int) $request['id'] ), array( '%d' ) ); self::forget(); return $this->index( $request ); } public function not_found(): WP_REST_Response { global $wpdb; $table = Database::not_found(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i ORDER BY hits DESC, last_hit DESC LIMIT 200", $table ) ); $out = array(); foreach ( (array) $rows as $row ) { $out[] = array( 'id' => (int) $row->id, 'path' => (string) $row->path, 'hits' => (int) $row->hits, 'referrer' => (string) $row->referrer, 'last_hit' => (string) $row->last_hit, ); } return new WP_REST_Response( $out ); } public function delete_404( WP_REST_Request $request ): WP_REST_Response { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->delete( Database::not_found(), array( 'id' => (int) $request['id'] ), array( '%d' ) ); return $this->not_found(); } public function update_settings( WP_REST_Request $request ): WP_REST_Response { $defaults = self::defaults(); $values = array(); foreach ( array_keys( $defaults ) as $key ) { if ( $request->has_param( $key ) ) { $values[ $key ] = (bool) $request->get_param( $key ); } } \AiRankSuite\Kernel::service( \AiRankSuite\Support\Options::class )->set( 'redirects', $values, $defaults ); return new WP_REST_Response( $this->settings() ); } /** * @param object $row DB row. * @return array */ private function shape_redirect( $row ): array { return array( 'id' => (int) $row->id, 'source' => (string) $row->source, 'target' => (string) $row->target, 'type' => (int) $row->type, 'hits' => (int) $row->hits, 'last_hit' => (string) $row->last_hit, 'regex' => 'regex' === (string) $row->status, ); } }