get_row( $wpdb->prepare( 'SELECT id, source_path, source_hash, destination, destination_type, status_code, match_mode, enabled FROM %i WHERE source_hash = %s AND enabled = 1 LIMIT 1', $table, $source_hash ) ); // phpcs:enable wp_cache_set( $source_hash, $row ? $row : 'none', self::CACHE_GROUP, HOUR_IN_SECONDS ); } if ( ! $row || 'none' === $row ) { return false; } if ( null !== $canonical_path && $row->source_path !== $canonical_path ) { return false; } return $row; } /** * Get a redirect by ID. * * @param int $id Redirect ID. * @return object|null */ public static function get( $id ) { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, absint( $id ) ) ); } /** * Find any redirect (enabled or not) with the given canonical source. * * @param string $canonical_path Canonical source path. * @return object|null */ public static function find_by_source( $canonical_path ) { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE source_hash = %s AND source_path = %s', $table, Normalizer::compute_hash( $canonical_path ), $canonical_path ) ); } /** * Validate and normalize a redirect destination. * * Same-site destinations are stored home-relative. External destinations need the * "allow external destinations" setting and a valid http(s) URL. * * @param string $destination Raw destination. * @param int $status_code Status code (410 needs no destination). * @return array{destination: string, type: string, hash: string}|\WP_Error */ public static function prepare_destination( $destination, $status_code = 301 ) { $destination = trim( (string) $destination ); if ( 410 === (int) $status_code ) { return array( 'destination' => '', 'type' => 'internal', 'hash' => '', ); } if ( '' === $destination ) { return new \WP_Error( 'invalid_destination', __( 'A redirect destination is required.', 'slugh' ) ); } if ( Normalizer::is_same_site( $destination ) ) { if ( preg_match( '#^[a-z][a-z0-9+.-]*:#i', $destination ) && ! preg_match( '#^https?://#i', $destination ) ) { return new \WP_Error( 'invalid_destination', __( 'Destinations must be a path or an http(s) URL.', 'slugh' ) ); } $relative = Normalizer::to_home_relative( $destination ); return array( 'destination' => $relative, 'type' => 'internal', 'hash' => Normalizer::compute_hash( Normalizer::normalize_path( $relative ) ), ); } if ( ! Settings::get( 'allow_external_destinations', false ) ) { return new \WP_Error( 'external_not_allowed', __( 'External destinations are disabled. Enable them in slugH Settings to redirect to another site.', 'slugh' ) ); } if ( ! preg_match( '#^https?://#i', $destination ) || ! wp_http_validate_url( $destination ) ) { return new \WP_Error( 'invalid_destination', __( 'External destinations must be a valid http or https URL.', 'slugh' ) ); } return array( 'destination' => esc_url_raw( $destination, array( 'http', 'https' ) ), 'type' => 'external', 'hash' => '', ); } /** * Validate and normalize a redirect source (always a same-site path). * * @param string $source Raw source path or URL. * @return array{path: string, hash: string, raw: string}|\WP_Error */ public static function prepare_source( $source ) { $raw = trim( (string) $source ); if ( '' === $raw ) { return new \WP_Error( 'invalid_source', __( 'Redirect source path cannot be empty.', 'slugh' ) ); } if ( ! Normalizer::is_same_site( $raw ) ) { return new \WP_Error( 'invalid_source', __( 'Redirect sources must be paths on this site.', 'slugh' ) ); } $path = Normalizer::normalize_path( $raw ); if ( '/' === $path ) { return new \WP_Error( 'invalid_source', __( 'The home page cannot be a redirect source.', 'slugh' ) ); } return array( 'path' => $path, 'hash' => Normalizer::compute_hash( $path ), 'raw' => $raw, ); } /** * Create a redirect under the conflict, loop and chain rules of spec section 10. * * @param array $data { * Redirect fields. * * @type string $source Source path or URL. * @type string $destination Destination path or URL. * @type int $status_code 301, 302, 307, 308 or 410. * @type string $match_mode 404_only or always. * @type string $origin job, descendant, manual, import or rollback. * @type int $post_id Related post ID. * @type int $job_id Related job ID. * @type bool $enabled Whether enabled. * @type string $on_conflict What to do when an enabled redirect owns the source: * error (default), replace, keep or skip. * } * @return array{id: int, action: string, flattened: array, previous: ?object}|\WP_Error */ public static function create( array $data ) { global $wpdb; $source_input = isset( $data['source'] ) ? $data['source'] : ( isset( $data['source_path'] ) ? $data['source_path'] : '' ); $source = self::prepare_source( $source_input ); if ( is_wp_error( $source ) ) { return $source; } $status_code = isset( $data['status_code'] ) ? absint( $data['status_code'] ) : 301; if ( ! in_array( $status_code, self::STATUS_CODES, true ) ) { return new \WP_Error( 'invalid_status', __( 'Unsupported redirect status code.', 'slugh' ) ); } $dest = self::prepare_destination( isset( $data['destination'] ) ? $data['destination'] : '', $status_code ); if ( is_wp_error( $dest ) ) { return $dest; } $match_mode = isset( $data['match_mode'] ) && in_array( $data['match_mode'], self::MATCH_MODES, true ) ? $data['match_mode'] : '404_only'; $origin = isset( $data['origin'] ) && in_array( $data['origin'], self::ORIGINS, true ) ? $data['origin'] : 'manual'; $post_id = ! empty( $data['post_id'] ) ? absint( $data['post_id'] ) : null; $job_id = ! empty( $data['job_id'] ) ? absint( $data['job_id'] ) : null; $enabled = isset( $data['enabled'] ) ? (int) (bool) $data['enabled'] : 1; $on_conflict = isset( $data['on_conflict'] ) ? sanitize_key( $data['on_conflict'] ) : 'error'; if ( 'internal' === $dest['type'] && 410 !== $status_code ) { if ( Normalizer::normalize_path( $dest['destination'] ) === $source['path'] ) { return new \WP_Error( 'redirect_self', __( 'A path cannot redirect to itself.', 'slugh' ) ); } if ( $enabled ) { $loop = LoopDetector::check_loop( $source['path'], $dest['destination'] ); if ( $loop['is_loop'] ) { return new \WP_Error( 'redirect_loop_detected', sprintf( /* translators: %s: redirect path chain */ __( 'Blocked: this redirect would create a loop: %s', 'slugh' ), implode( ' → ', $loop['path'] ) ), array( 'path' => $loop['path'] ) ); } } } $existing = self::find_by_source( $source['path'] ); $action = 'created'; if ( $existing && (int) $existing->enabled ) { switch ( $on_conflict ) { case 'keep': return array( 'id' => (int) $existing->id, 'action' => 'kept', 'flattened' => array(), 'previous' => null, ); case 'skip': return array( 'id' => 0, 'action' => 'skipped', 'flattened' => array(), 'previous' => null, ); case 'replace': $action = 'replaced'; break; default: return new \WP_Error( 'redirect_conflict', sprintf( /* translators: 1: source path, 2: existing redirect ID, 3: existing destination */ __( 'An enabled redirect (#%2$d) already sends %1$s to %3$s.', 'slugh' ), $source['path'], (int) $existing->id, $existing->destination ), array( 'existing_id' => (int) $existing->id ) ); } } elseif ( $existing ) { $action = 'reenabled'; } $now = current_time( 'mysql', true ); $fields = array( 'source_path' => $source['path'], 'source_hash' => $source['hash'], 'source_raw' => $source['raw'], 'destination' => $dest['destination'], 'destination_type' => $dest['type'], 'destination_hash' => $dest['hash'], 'status_code' => $status_code, 'match_mode' => $match_mode, 'post_id' => $post_id, 'job_id' => $job_id, 'origin' => $origin, 'enabled' => $enabled, 'updated_at' => $now, ); $formats = array( '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%d', '%s' ); if ( $existing ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $result = $wpdb->update( self::table(), $fields, array( 'id' => $existing->id ), $formats, array( '%d' ) ); $redirect_id = (int) $existing->id; } else { $fields['hits'] = 0; $fields['created_by'] = get_current_user_id(); $fields['created_at'] = $now; $formats[] = '%d'; $formats[] = '%d'; $formats[] = '%s'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $result = $wpdb->insert( self::table(), $fields, $formats ); $redirect_id = (int) $wpdb->insert_id; } if ( false === $result ) { return new \WP_Error( 'db_error', __( 'Failed to save redirect record in database.', 'slugh' ) ); } self::clear_cache( $source['hash'] ); $flattened = array(); if ( $enabled && 'internal' === $dest['type'] && 410 !== $status_code ) { $flattened = LoopDetector::flatten_chains( $source['path'], $dest['destination'], $redirect_id, $job_id ); } AuditLogger::log( 'created' === $action ? 'redirect_create' : 'redirect_update', 'redirect', $redirect_id, $existing ? self::audit_fields( $existing ) : null, array_merge( self::audit_fields( (object) $fields ), array( 'action' => $action ) ), $job_id ); if ( 'created' === $action ) { /** * Fires after a redirect is created. * * @param int $redirect_id Redirect ID. * @param string $source_path Canonical source path. * @param string $destination Stored destination. */ do_action( 'slugh_redirect_created', $redirect_id, $source['path'], $dest['destination'] ); } return array( 'id' => $redirect_id, 'action' => $action, 'flattened' => $flattened, 'previous' => $existing ? $existing : null, ); } /** * Edit a redirect. * * @param int $id Redirect ID. * @param array $data Fields: source, destination, status_code, match_mode, enabled. * @param int|null $job_id Job ID for the audit log. * @return true|\WP_Error */ public static function update( $id, array $data, $job_id = null ) { global $wpdb; $existing = self::get( $id ); if ( ! $existing ) { return new \WP_Error( 'not_found', __( 'Redirect not found.', 'slugh' ) ); } $source = self::prepare_source( isset( $data['source'] ) ? $data['source'] : $existing->source_raw ); if ( is_wp_error( $source ) ) { return $source; } $status_code = isset( $data['status_code'] ) ? absint( $data['status_code'] ) : (int) $existing->status_code; if ( ! in_array( $status_code, self::STATUS_CODES, true ) ) { return new \WP_Error( 'invalid_status', __( 'Unsupported redirect status code.', 'slugh' ) ); } $dest = self::prepare_destination( isset( $data['destination'] ) ? $data['destination'] : $existing->destination, $status_code ); if ( is_wp_error( $dest ) ) { return $dest; } $match_mode = isset( $data['match_mode'] ) && in_array( $data['match_mode'], self::MATCH_MODES, true ) ? $data['match_mode'] : $existing->match_mode; $enabled = isset( $data['enabled'] ) ? (int) (bool) $data['enabled'] : (int) $existing->enabled; $other = self::find_by_source( $source['path'] ); if ( $other && (int) $other->id !== (int) $existing->id ) { return new \WP_Error( 'redirect_conflict', /* translators: %d: redirect ID */ sprintf( __( 'Redirect #%d already uses this source path.', 'slugh' ), (int) $other->id ) ); } if ( 'internal' === $dest['type'] && 410 !== $status_code ) { if ( Normalizer::normalize_path( $dest['destination'] ) === $source['path'] ) { return new \WP_Error( 'redirect_self', __( 'A path cannot redirect to itself.', 'slugh' ) ); } if ( $enabled ) { $loop = LoopDetector::check_loop( $source['path'], $dest['destination'] ); if ( $loop['is_loop'] ) { return new \WP_Error( 'redirect_loop_detected', /* translators: %s: redirect path chain */ sprintf( __( 'Blocked: this redirect would create a loop: %s', 'slugh' ), implode( ' → ', $loop['path'] ) ) ); } } } $fields = array( 'source_path' => $source['path'], 'source_hash' => $source['hash'], 'source_raw' => $source['raw'], 'destination' => $dest['destination'], 'destination_type' => $dest['type'], 'destination_hash' => $dest['hash'], 'status_code' => $status_code, 'match_mode' => $match_mode, 'enabled' => $enabled, 'updated_at' => current_time( 'mysql', true ), ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $result = $wpdb->update( self::table(), $fields, array( 'id' => $existing->id ), array( '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%d', '%s' ), array( '%d' ) ); if ( false === $result ) { return new \WP_Error( 'db_error', __( 'Failed to update redirect.', 'slugh' ) ); } self::clear_cache( $existing->source_hash ); self::clear_cache( $source['hash'] ); if ( $enabled && 'internal' === $dest['type'] && 410 !== $status_code ) { LoopDetector::flatten_chains( $source['path'], $dest['destination'], (int) $existing->id, $job_id ); } $event = 'redirect_update'; if ( (int) $existing->enabled !== $enabled && count( array_diff_assoc( self::audit_fields( (object) $fields ), self::audit_fields( $existing ) ) ) === 1 ) { $event = $enabled ? 'redirect_enable' : 'redirect_disable'; } AuditLogger::log( $event, 'redirect', (int) $existing->id, self::audit_fields( $existing ), self::audit_fields( (object) $fields ), $job_id ); return true; } /** * Enable or disable a redirect. * * @param int $id Redirect ID. * @param bool $enabled New state. * @param int|null $job_id Job ID for the audit log. * @return true|\WP_Error */ public static function set_enabled( $id, $enabled, $job_id = null ) { return self::update( $id, array( 'enabled' => (bool) $enabled ), $job_id ); } /** * Restore a redirect's destination (used by rollback for flattened chains). * * @param int $id Redirect ID. * @param string $destination Previous destination. * @param int|null $job_id Job ID for the audit log. * @return true|\WP_Error */ public static function restore_destination( $id, $destination, $job_id = null ) { return self::update( $id, array( 'destination' => $destination ), $job_id ); } /** * Delete a redirect (explicit administrator action only; jobs never delete). * * @param int $id Redirect ID. * @return bool */ public static function delete( $id ) { global $wpdb; $existing = self::get( $id ); if ( ! $existing ) { return false; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $deleted = $wpdb->delete( self::table(), array( 'id' => $existing->id ), array( '%d' ) ); self::clear_cache( $existing->source_hash ); if ( $deleted ) { AuditLogger::log( 'redirect_delete', 'redirect', (int) $existing->id, self::audit_fields( $existing ), null ); } return (bool) $deleted; } /** * Fields recorded in the audit log for a redirect. * * @param object $row Redirect row. * @return array */ private static function audit_fields( $row ) { return array( 'source' => isset( $row->source_path ) ? $row->source_path : '', 'destination' => isset( $row->destination ) ? $row->destination : '', 'status_code' => isset( $row->status_code ) ? (int) $row->status_code : 0, 'match_mode' => isset( $row->match_mode ) ? $row->match_mode : '', 'enabled' => isset( $row->enabled ) ? (int) $row->enabled : 0, ); } /** * Clear the cached lookup for a source hash and the cached "always" set. * * @param string $source_hash Source hash. * @return void */ public static function clear_cache( $source_hash ) { wp_cache_delete( $source_hash, self::CACHE_GROUP ); wp_cache_delete( 'always_hashes', self::CACHE_GROUP ); self::rebuild_always_hashes(); } /** * Store the set of "always" hashes in an autoloaded option, so normal page views need no query * even without a persistent object cache. Written only when the set changes. * * @return string[] */ public static function rebuild_always_hashes() { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $hashes = $wpdb->get_col( $wpdb->prepare( "SELECT source_hash FROM %i WHERE match_mode = 'always' AND enabled = 1 ORDER BY source_hash", $table ) ); $hashes = is_array( $hashes ) ? $hashes : array(); if ( get_option( self::ALWAYS_OPTION ) !== $hashes ) { update_option( self::ALWAYS_OPTION, $hashes, true ); } return $hashes; } /** * Record a hit, written at most once a minute per redirect. * * @param int $id Redirect ID. * @return void */ public static function record_hit( $id ) { $id = absint( $id ); if ( ! wp_cache_add( 'hit_' . $id, 1, self::CACHE_GROUP, MINUTE_IN_SECONDS ) ) { return; } global $wpdb; $table = self::table(); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $wpdb->query( $wpdb->prepare( 'UPDATE %i SET hits = hits + 1, last_hit_at = %s WHERE id = %d AND ( last_hit_at IS NULL OR last_hit_at < %s )', $table, current_time( 'mysql', true ), $id, gmdate( 'Y-m-d H:i:s', time() - MINUTE_IN_SECONDS ) ) ); // phpcs:enable } /** * Get the cached set of source hashes for enabled redirects in "always" match mode. * * @return string[] */ public static function get_always_hashes() { $cached = wp_cache_get( 'always_hashes', self::CACHE_GROUP ); if ( is_array( $cached ) ) { return $cached; } // Autoloaded, so reading it costs no query on a normal page view. $hashes = get_option( self::ALWAYS_OPTION, null ); if ( ! is_array( $hashes ) ) { $hashes = self::rebuild_always_hashes(); } wp_cache_set( 'always_hashes', $hashes, self::CACHE_GROUP, HOUR_IN_SECONDS ); return $hashes; } /** * Convert a job's trial (302) redirects to 301 once verified. * * @param int $job_id Job ID. * @return int Number of converted redirects. */ public static function promote_job_redirects( $job_id ) { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id FROM %i WHERE job_id = %d AND status_code = 302 AND origin IN ('job','descendant')", $table, absint( $job_id ) ) ); $count = 0; foreach ( (array) $rows as $row ) { if ( true === self::update( (int) $row->id, array( 'status_code' => 301 ), $job_id ) ) { ++$count; } } return $count; } /** * Query redirects for list screens. * * @param array $args search, enabled ('' | '1' | '0'), origin, job_id, orderby, order, per_page, page. * @return array{items: array, total: int} */ public static function query( array $args = array() ) { global $wpdb; $table = self::table(); $where = array( '1=1' ); $binds = array(); $per_page = isset( $args['per_page'] ) ? min( 500, max( 1, absint( $args['per_page'] ) ) ) : 50; $page = isset( $args['page'] ) ? max( 1, absint( $args['page'] ) ) : 1; if ( ! empty( $args['search'] ) ) { $like = '%' . $wpdb->esc_like( (string) $args['search'] ) . '%'; $norm = '%' . $wpdb->esc_like( Normalizer::normalize_path( (string) $args['search'] ) ) . '%'; $where[] = '(source_path LIKE %s OR source_path LIKE %s OR destination LIKE %s)'; array_push( $binds, $like, $norm, $like ); } if ( isset( $args['enabled'] ) && '' !== $args['enabled'] && null !== $args['enabled'] ) { $where[] = 'enabled = %d'; $binds[] = (int) (bool) $args['enabled']; } if ( ! empty( $args['origin'] ) && in_array( $args['origin'], self::ORIGINS, true ) ) { $where[] = 'origin = %s'; $binds[] = $args['origin']; } if ( ! empty( $args['job_id'] ) ) { $where[] = 'job_id = %d'; $binds[] = absint( $args['job_id'] ); } $orderby_map = array( 'id' => 'id', 'source' => 'source_path', 'status_code' => 'status_code', 'hits' => 'hits', 'last_hit_at' => 'last_hit_at', 'created_at' => 'created_at', ); $orderby = isset( $args['orderby'], $orderby_map[ $args['orderby'] ] ) ? $orderby_map[ $args['orderby'] ] : 'id'; $order = isset( $args['order'] ) && 'asc' === strtolower( $args['order'] ) ? 'ASC' : 'DESC'; $where_sql = implode( ' AND ', $where ); // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter -- The WHERE clause is built from fixed SQL fragments; every value is bound by prepare(). $total = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE {$where_sql}", array_merge( array( $table ), $binds ) ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter -- The WHERE clause is built from fixed SQL fragments; every value is bound by prepare(). $items = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- Values are passed as one array. "SELECT * FROM %i WHERE {$where_sql} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d", array_merge( array( $table ), $binds, array( $per_page, ( $page - 1 ) * $per_page ) ) ) ); // phpcs:enable return array( 'items' => $items, 'total' => $total, ); } /** * Totals for the Overview screen. * * @return array{total: int, enabled: int, disabled: int, origins: array} */ public static function totals() { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT origin, enabled, COUNT(*) AS n FROM %i GROUP BY origin, enabled', $table ) ); $totals = array( 'total' => 0, 'enabled' => 0, 'disabled' => 0, 'origins' => array_fill_keys( self::ORIGINS, 0 ), ); foreach ( (array) $rows as $row ) { $n = (int) $row->n; $totals['total'] += $n; $key = (int) $row->enabled ? 'enabled' : 'disabled'; $totals[ $key ] += $n; $origin = in_array( $row->origin, self::ORIGINS, true ) ? $row->origin : 'manual'; $totals['origins'][ $origin ] += $n; } return $totals; } /** * All redirects for CSV export, optionally limited to a job. * * @param int $job_id Optional job ID. * @return array */ public static function export_rows( $job_id = 0 ) { global $wpdb; $table = self::table(); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared if ( $job_id ) { return $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE job_id = %d ORDER BY id ASC', $table, absint( $job_id ) ) ); } return $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i ORDER BY id ASC', $table ) ); // phpcs:enable } }