to_url; if ( 0 !== strpos( $to_url, 'http' ) ) { $to_url = home_url( $to_url ); } // Preserve the query string from the original request (e.g. UTM params). $query_string = isset( $_SERVER['QUERY_STRING'] ) ? sanitize_text_field( wp_unslash( $_SERVER['QUERY_STRING'] ) ) : ''; if ( ! empty( $query_string ) && false === strpos( $to_url, '?' ) ) { $to_url .= '?' . $query_string; } // Determine redirect type (301 by default). $status = isset( $redirect->redirect_type ) ? (int) $redirect->redirect_type : 301; if ( ! in_array( $status, array( 301, 302, 307, 308 ), true ) ) { $status = 301; } return array( 'url' => esc_url_raw( $to_url ), 'status' => $status, 'id' => (int) $redirect->id, ); } /** * Check the current request against the redirect table and 301 if matched. * * @param WP $wp The WP environment object (passed by reference). * @return void */ public static function maybe_redirect( $wp ) { $decision = self::resolve_redirect( $wp ); if ( ! $decision ) { return; } // Register the hit (deferred to shutdown — does not delay the response). AILM_URL_Redirect_DB::register_hit( $decision['id'] ); self::$redirected = true; wp_safe_redirect( $decision['url'], $decision['status'] ); exit; } /** * Resolve the current request path (relative to home_url, with leading /). * * @param WP $wp The WP environment object. * @return string Normalized path, or '' if it cannot be determined. */ private static function get_request_path( $wp ) { // Prefer REQUEST_URI — it contains the raw path the client requested. if ( isset( $_SERVER['REQUEST_URI'] ) ) { $request_uri = sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ); $path = wp_parse_url( $request_uri, PHP_URL_PATH ); if ( false !== $path && null !== $path ) { return AILM_URL_Redirect_DB::normalize_url( $path ); } } // Fallback: reconstruct from matched query vars. if ( ! empty( $wp->query_vars['pagename'] ) ) { return AILM_URL_Redirect_DB::normalize_url( '/' . $wp->query_vars['pagename'] ); } if ( ! empty( $wp->query_vars['name'] ) ) { return AILM_URL_Redirect_DB::normalize_url( '/' . $wp->query_vars['name'] ); } return ''; } /** * Look up a redirect for the given path using the 3-layer cache. * * @param string $path Request path (will be normalized). * @return object|null Redirect row or null. */ private static function lookup( $path ) { $path = AILM_URL_Redirect_DB::normalize_url( $path ); // L1: static cache. if ( array_key_exists( $path, self::$static_cache ) ) { return self::$static_cache[ $path ]; } // L2 + L3: handled by AILM_URL_Redirect_DB::get_redirect() which does // wp_cache_get → DB → wp_cache_set. $redirect = AILM_URL_Redirect_DB::get_redirect( $path ); self::$static_cache[ $path ] = $redirect; return $redirect; } /** * Reset the static caches (used by tests). * * @return void */ public static function reset_cache() { self::$static_cache = array(); self::$redirected = false; } }