true, 'ignore_bots' => true, 'max_logs' => 1000, ); } /** * Settings fields. * * @return array */ public function get_fields() { return array( 'log_404' => array( 'type' => 'checkbox', 'label' => __( '404 logging', 'toolvane' ), 'checkbox_label' => __( 'Log URLs that return "Not Found"', 'toolvane' ), ), 'ignore_bots' => array( 'type' => 'checkbox', 'label' => __( 'Bots', 'toolvane' ), 'checkbox_label' => __( 'Ignore search engine bots, crawlers and vulnerability scanners', 'toolvane' ), ), 'max_logs' => array( 'type' => 'number', 'label' => __( 'Keep at most', 'toolvane' ), 'unit' => __( 'entries', 'toolvane' ), 'min' => 100, 'max' => 50000, 'description' => __( 'Older 404 entries are removed daily.', 'toolvane' ), ), ); } /** * Registers hooks. */ public function init() { add_action( 'template_redirect', array( $this, 'maybe_redirect' ), 1 ); if ( $this->get( 'log_404' ) ) { add_action( 'template_redirect', array( $this, 'log_404' ), 999 ); } add_action( Installer::CRON_HOOK, array( $this, 'prune' ) ); foreach ( array( 'add_redirect', 'delete_redirect', 'delete_404', 'clear_404', 'export_redirects', 'import_redirects' ) as $action ) { add_action( 'admin_post_toolvane_' . $action, array( $this, 'handle_' . $action ) ); } } /* * Rules. */ /** * Saved rules keyed by md5(source). * * @return array */ private function rules() { $rules = get_option( self::RULES_OPTION, array() ); return is_array( $rules ) ? $rules : array(); } /** * Validates a list of rules, for example from an import file. * * @param mixed $rules Raw rules. * @return array Clean rules keyed by md5(source). */ public static function sanitize_rules( $rules ) { $clean = array(); if ( ! is_array( $rules ) ) { return $clean; } $self = new self(); foreach ( $rules as $rule ) { if ( ! is_array( $rule ) || count( $clean ) >= self::MAX_RULES ) { continue; } $rule = $self->build_rule( isset( $rule['source'] ) ? (string) $rule['source'] : '', isset( $rule['target'] ) ? (string) $rule['target'] : '', isset( $rule['code'] ) ? (int) $rule['code'] : 301 ); if ( $rule ) { $clean[ md5( $rule['source'] ) ] = $rule; } } return $clean; } /** * Builds a validated rule. * * @param string $source Source path. * @param string $target Target URL. * @param int $code HTTP status. * @return array|null */ private function build_rule( $source, $target, $code ) { $source = $this->clean_source( sanitize_text_field( $source ) ); $target = trim( $target ); $code = in_array( (int) $code, self::CODES, true ) ? (int) $code : 301; if ( 0 === strpos( $target, '/' ) && 0 !== strpos( $target, '//' ) ) { // Relative target on this site. $target = '/' . ltrim( str_replace( array( '"', "'", '<', '>', ' ' ), array( '', '', '', '', '%20' ), sanitize_text_field( $target ) ), '/' ); } elseif ( preg_match( '#^https?://#i', $target ) ) { $target = esc_url_raw( $target, array( 'http', 'https' ) ); $domain = (string) wp_parse_url( $target, PHP_URL_HOST ); if ( ! preg_match( '/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/i', $domain ) && ! filter_var( trim( $domain, '[]' ), FILTER_VALIDATE_IP ) ) { $target = ''; } } else { // Only full http(s) URLs and paths starting with "/" are accepted. $target = ''; } if ( 410 === $code ) { $target = ''; } if ( '' === $source || '/' === $source || ( 410 !== $code && '' === $target ) ) { return null; } // A rule that points to itself would loop forever. $host = wp_parse_url( $target, PHP_URL_HOST ); if ( '' !== $target && ( ! $host || wp_parse_url( home_url(), PHP_URL_HOST ) === $host ) && false === strpos( $source, '*' ) && $this->normalize( $target ) === $source ) { return null; } return array( 'source' => $source, 'target' => $target, 'code' => $code, 'created' => time(), ); } /** * Normalizes a path relative to the home URL: lowercase, leading slash, no trailing slash. * * @param string $path Path (may be a full URL). * @return string */ private function normalize( $path ) { $path = (string) wp_parse_url( $path, PHP_URL_PATH ); $path = strtolower( rawurldecode( $path ) ); $home_path = strtolower( untrailingslashit( (string) wp_parse_url( home_url(), PHP_URL_PATH ) ) ); if ( $home_path && 0 === strpos( $path, $home_path ) ) { $path = substr( $path, strlen( $home_path ) ); } return '/' . trim( $path, '/' ); } /** * Normalizes a user-entered source and keeps a trailing wildcard and query string. * * @param string $source Raw source. * @return string Empty string when invalid. */ private function clean_source( $source ) { $source = trim( $source ); if ( '' === $source ) { return ''; } $wild = '*' === substr( $source, -1 ); $source = rtrim( $source, '*' ); $query = (string) wp_parse_url( $source, PHP_URL_QUERY ); $path = $this->normalize( $source ); if ( $wild ) { return '/' === $path ? '' : $path . '/*'; // A bare "/*" would redirect the whole site. } return $query ? $path . '?' . strtolower( $query ) : $path; } /** * Current request: array( normalized path, raw query ). * * @return array */ private function current_request() { $uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '/'; return array( $this->normalize( $uri ), (string) wp_parse_url( $uri, PHP_URL_QUERY ) ); } /* * Front end. */ /** * Performs a redirect if a rule matches. */ public function maybe_redirect() { $rules = $this->rules(); if ( ! $rules || is_admin() ) { return; } list( $path, $query ) = $this->current_request(); $path_query = $query ? $path . '?' . strtolower( $query ) : $path; // Exact matches win over wildcards. $match = null; if ( isset( $rules[ md5( $path_query ) ] ) ) { $match = $rules[ md5( $path_query ) ]; } elseif ( isset( $rules[ md5( $path ) ] ) ) { $match = $rules[ md5( $path ) ]; } else { $best = -1; foreach ( $rules as $rule ) { if ( '/*' !== substr( $rule['source'], -2 ) ) { continue; } $prefix = substr( $rule['source'], 0, -2 ); if ( ( $path === $prefix || 0 === strpos( $path, $prefix . '/' ) ) && strlen( $prefix ) > $best ) { $match = $rule; $best = strlen( $prefix ); } } } if ( ! $match ) { return; } $source = $match['source']; $target = $match['target']; $code = (int) $match['code']; if ( '/*' === substr( $source, -2 ) && '/*' === substr( $target, -2 ) ) { $target = substr( $target, 0, -2 ) . substr( $path, strlen( substr( $source, 0, -2 ) ) ); } $this->count_hit( $source ); if ( 410 === $code ) { nocache_headers(); wp_die( esc_html__( 'This content has been permanently removed.', 'toolvane' ), esc_html__( 'Gone', 'toolvane' ), array( 'response' => 410 ) ); } if ( 0 === strpos( $target, '/' ) && 0 !== strpos( $target, '//' ) ) { $target = home_url( $target ); } // Keep UTM and tracking parameters for path-only rules. if ( $query && false === strpos( $source, '?' ) && false === strpos( $target, '?' ) ) { $target .= '?' . $query; } // Loop protection. $same_host = wp_parse_url( $target, PHP_URL_HOST ) === wp_parse_url( home_url(), PHP_URL_HOST ); if ( $same_host && $this->normalize( $target ) === $path ) { return; } nocache_headers(); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- Targets are set by administrators and may be external. wp_redirect( $target, $code, 'Toolvane' ); exit; } /** * Counts how often a rule is used. * * @param string $source Rule source. */ private function count_hit( $source ) { $hits = get_option( self::HITS_OPTION, array() ); $hits = is_array( $hits ) ? $hits : array(); $key = md5( $source ); $hits[ $key ] = array( 'count' => isset( $hits[ $key ]['count'] ) ? (int) $hits[ $key ]['count'] + 1 : 1, 'last' => time(), ); update_option( self::HITS_OPTION, $hits, false ); } /** * Logs 404 hits. */ public function log_404() { if ( ! is_404() ) { return; } $agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : ''; if ( $this->get( 'ignore_bots' ) && ( '' === $agent || preg_match( '/bot|crawl|spider|slurp|facebookexternalhit|bingpreview|curl|wget|python|scan|headless|httpclient|go-http|java\//i', $agent ) ) ) { return; } list( $path, $query ) = $this->current_request(); $url = substr( $query ? $path . '?' . $query : $path, 0, 2000 ); $referrer = isset( $_SERVER['HTTP_REFERER'] ) ? esc_url_raw( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : ''; $now = current_time( 'mysql', true ); global $wpdb; $table = Installer::table_404(); // phpcs:disable WordPress.DB.DirectDatabaseQuery -- Custom log table. $wpdb->query( $wpdb->prepare( "INSERT INTO %i (url, url_hash, referrer, user_agent, hits, first_seen, last_seen) VALUES (%s, %s, %s, %s, 1, %s, %s) ON DUPLICATE KEY UPDATE hits = hits + 1, last_seen = VALUES(last_seen), referrer = IF(VALUES(referrer) = '', referrer, VALUES(referrer))", $table, $url, md5( $url ), substr( $referrer, 0, 2000 ), substr( $agent, 0, 255 ), $now, $now ) ); // phpcs:enable } /** * Keeps the log table within the configured size (daily cron). */ public function prune() { global $wpdb; $table = Installer::table_404(); // phpcs:disable WordPress.DB.DirectDatabaseQuery -- Custom log table. $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE id NOT IN ( SELECT id FROM ( SELECT id FROM %i ORDER BY last_seen DESC LIMIT %d ) AS keep_rows )', $table, $table, absint( $this->get( 'max_logs', 1000 ) ) ) ); // phpcs:enable } /* * Admin actions. */ /** * Common permission and nonce check. * * @param string $nonce_action Nonce action. */ private function verify( $nonce_action ) { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You are not allowed to do this.', 'toolvane' ), '', array( 'response' => 403 ) ); } check_admin_referer( $nonce_action ); } /** * Redirects back to the tab with a message. * * @param string $msg Message key. * @param array $extra Extra query arguments. */ private function back( $msg, array $extra = array() ) { wp_safe_redirect( Admin::url( $this->get_id(), array_merge( array( 'tn_msg' => $msg ), $extra ) ) ); exit; } /** * Nonce-protected admin-post URL for a row action. * * @param string $action Action name, also used as the nonce action. * @param string|int $id Row ID. * @return string */ private function action_url( $action, $id ) { return wp_nonce_url( add_query_arg( array( 'action' => $action, 'id' => $id, ), admin_url( 'admin-post.php' ) ), $action ); } /** * Saves rules and purges page caches. * * @param array $rules Rules. */ private function save_rules( array $rules ) { update_option( self::RULES_OPTION, $rules, true ); Cache::purge_all(); } /** * Adds a redirect. */ public function handle_add_redirect() { $this->verify( 'toolvane_add_redirect' ); // phpcs:disable WordPress.Security.NonceVerification.Missing -- Verified above. $rule = $this->build_rule( isset( $_POST['source'] ) ? sanitize_text_field( wp_unslash( $_POST['source'] ) ) : '', isset( $_POST['target'] ) ? sanitize_text_field( wp_unslash( $_POST['target'] ) ) : '', isset( $_POST['code'] ) ? absint( $_POST['code'] ) : 301 ); // phpcs:enable if ( ! $rule ) { $this->back( 'error' ); } $rules = $this->rules(); if ( count( $rules ) >= self::MAX_RULES && ! isset( $rules[ md5( $rule['source'] ) ] ) ) { $this->back( 'limit' ); } $rules[ md5( $rule['source'] ) ] = $rule; $this->save_rules( $rules ); // The URL is fixed now, so remove it from the 404 log. global $wpdb; $wpdb->delete( Installer::table_404(), array( 'url_hash' => md5( $rule['source'] ) ), array( '%s' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery $this->back( 'added' ); } /** * Deletes a redirect. */ public function handle_delete_redirect() { $this->verify( 'toolvane_delete_redirect' ); $id = isset( $_GET['id'] ) ? sanitize_key( wp_unslash( $_GET['id'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce checked in verify(). $rules = $this->rules(); unset( $rules[ $id ] ); $this->save_rules( $rules ); $this->back( 'deleted' ); } /** * Deletes a 404 log entry. */ public function handle_delete_404() { $this->verify( 'toolvane_delete_404' ); global $wpdb; $id = isset( $_GET['id'] ) ? absint( $_GET['id'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce checked in verify(). $wpdb->delete( Installer::table_404(), array( 'id' => $id ), array( '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery $this->back( 'deleted' ); } /** * Empties the 404 log. */ public function handle_clear_404() { $this->verify( 'toolvane_clear_404' ); global $wpdb; $wpdb->query( $wpdb->prepare( 'TRUNCATE TABLE %i', Installer::table_404() ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Custom log table. $this->back( 'cleared' ); } /** * Escapes a CSV cell and neutralizes spreadsheet formulas. * * @param string $value Cell value. * @return string */ private function csv_cell( $value ) { $value = (string) $value; if ( '' !== $value && in_array( $value[0], array( '=', '+', '-', '@', "\t", "\r" ), true ) ) { $value = "'" . $value; } return '"' . str_replace( '"', '""', $value ) . '"'; } /** * Downloads all redirects as CSV. */ public function handle_export_redirects() { $this->verify( 'toolvane_export_redirects' ); $lines = array( 'source,target,code' ); foreach ( $this->rules() as $rule ) { $lines[] = $this->csv_cell( $rule['source'] ) . ',' . $this->csv_cell( $rule['target'] ) . ',' . (int) $rule['code']; } nocache_headers(); header( 'Content-Type: text/csv; charset=utf-8' ); header( 'Content-Disposition: attachment; filename="toolvane-redirects-' . gmdate( 'Y-m-d' ) . '.csv"' ); echo implode( "\r\n", $lines ) . "\r\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CSV download, every cell is escaped by csv_cell(). exit; } /** * Imports redirects from a CSV file (source, target, code). */ public function handle_import_redirects() { $this->verify( 'toolvane_import_redirects' ); $tmp = isset( $_FILES['toolvane_csv']['tmp_name'] ) ? (string) $_FILES['toolvane_csv']['tmp_name'] : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Nonce checked in verify(); the path is validated with is_uploaded_file() and must not be unslashed (Windows paths). if ( '' === $tmp || ! is_uploaded_file( $tmp ) || filesize( $tmp ) > MB_IN_BYTES * 5 ) { $this->back( 'import_error' ); } $lines = file( $tmp, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ); $rules = $this->rules(); $added = 0; foreach ( (array) $lines as $i => $line ) { if ( 0 === $i ) { $line = preg_replace( '/^\xEF\xBB\xBF/', '', $line ); // Strip a UTF-8 byte order mark. } $cells = str_getcsv( $line, ',', '"', '\\' ); if ( count( $cells ) < 2 || 'source' === strtolower( trim( $cells[0] ) ) ) { continue; } $source = ltrim( trim( $cells[0] ), "'" ); $target = ltrim( trim( $cells[1] ), "'" ); $code = isset( $cells[2] ) ? (int) $cells[2] : 301; $rule = $this->build_rule( $source, $target, $code ); if ( ! $rule || ( count( $rules ) >= self::MAX_RULES && ! isset( $rules[ md5( $rule['source'] ) ] ) ) ) { continue; } $rules[ md5( $rule['source'] ) ] = $rule; ++$added; } $this->save_rules( $rules ); $this->back( 'imported', array( 'tn_count' => $added ) ); } /* * Admin page. */ /** * Renders the module page. */ public function render_custom_page() { global $wpdb; // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Display only. $msg = isset( $_GET['tn_msg'] ) ? sanitize_key( wp_unslash( $_GET['tn_msg'] ) ) : ''; $count = isset( $_GET['tn_count'] ) ? absint( $_GET['tn_count'] ) : 0; $prefill = isset( $_GET['source'] ) ? sanitize_text_field( wp_unslash( $_GET['source'] ) ) : ''; // phpcs:enable $messages = array( 'added' => array( 'success', __( 'Redirect saved.', 'toolvane' ) ), 'deleted' => array( 'success', __( 'Deleted.', 'toolvane' ) ), 'cleared' => array( 'success', __( '404 log cleared.', 'toolvane' ) ), /* translators: %d: number of redirects */ 'imported' => array( 'success', sprintf( _n( '%d redirect imported.', '%d redirects imported.', $count, 'toolvane' ), $count ) ), 'error' => array( 'error', __( 'Please enter a valid source path and target URL.', 'toolvane' ) ), 'import_error' => array( 'error', __( 'Please upload a valid CSV file.', 'toolvane' ) ), /* translators: %d: maximum number of redirects */ 'limit' => array( 'error', sprintf( __( 'You reached the limit of %d redirects.', 'toolvane' ), self::MAX_RULES ) ), ); if ( isset( $messages[ $msg ] ) ) { printf( '

%2$s

', esc_attr( $messages[ $msg ][0] ), esc_html( $messages[ $msg ][1] ) ); } if ( class_exists( 'Red_Item' ) || defined( 'RANK_MATH_VERSION' ) || defined( 'WPSEO_PREMIUM_FILE' ) || defined( 'AIOSEO_PRO' ) ) { echo '

' . esc_html__( 'Another redirect manager (Redirection, Rank Math, Yoast SEO Premium or All in One SEO Pro) is active. Both work side by side, but avoid creating the same rule in two places. Toolvane rules run first.', 'toolvane' ) . '

'; } $post_url = admin_url( 'admin-post.php' ); $rules = $this->rules(); $hits = get_option( self::HITS_OPTION, array() ); $hits = is_array( $hits ) ? $hits : array(); $table = Installer::table_404(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Custom log table, admin screen only. $logs = $wpdb->get_results( $wpdb->prepare( 'SELECT id, url, referrer, hits, last_seen FROM %i ORDER BY hits DESC, last_seen DESC LIMIT 100', $table ) ); $fmt = get_option( 'date_format' ) . ' ' . get_option( 'time_format' ); ?>

/blog/* → /news/* to move a whole section. Query strings such as UTM tags are passed along automatically.', 'toolvane' ) ); ?>

$rule ) : ?>
' . esc_html( sprintf( __( '%s ago', 'toolvane' ), human_time_diff( (int) $hit['last'] ) ) ) . ''; } else { echo '0'; } ?>

get( 'log_404' ) ) : ?>

url ); ?> hits ) ); ?> last_seen, $fmt ) ); ?> referrer ? esc_html( $row->referrer ) : '—'; ?> |