$types, 'statuses' => $statuses, 'last_id' => 0, ) ); JobRepository::update( $scan_id, array( 'started_at' => current_time( 'mysql', true ) ) ); AuditLogger::log( 'scan_start', 'job', $scan_id, null, array( 'post_types' => $types, 'statuses' => $statuses, ), $scan_id ); return $scan_id; } /** * Process the next ID-ordered batch of a scan job. * * @param int $scan_id Scan job ID. * @return array{scan_id: int, processed: int, scanned: int, last_id: int, done: bool}|\WP_Error */ public static function run_batch( $scan_id ) { global $wpdb; $job = JobRepository::get( $scan_id ); if ( ! $job || 'scan' !== $job->type || 'running' !== $job->status ) { return new \WP_Error( 'invalid_scan', __( 'This scan is not running.', 'slugh' ) ); } if ( ! JobRepository::acquire_lock( $scan_id ) ) { return new \WP_Error( 'locked', __( 'This scan batch is already running.', 'slugh' ), array( 'status' => 409 ) ); } $types = (array) $job->settings['post_types']; $statuses = (array) $job->settings['statuses']; $last_id = isset( $job->settings['last_id'] ) ? (int) $job->settings['last_id'] : 0; $batch_size = (int) Settings::get( 'scan_batch_size', 500 ); $scanned = isset( $job->settings['scanned'] ) ? (int) $job->settings['scanned'] : 0; $type_in = implode( ',', array_fill( 0, count( $types ), '%s' ) ); $status_in = implode( ',', array_fill( 0, count( $statuses ), '%s' ) ); // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $rows = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- Values are passed as one array. "SELECT ID, post_author, post_date, post_date_gmt, post_name, post_type, post_status, post_parent, post_title, post_modified, post_modified_gmt, menu_order FROM {$wpdb->posts} WHERE ID > %d AND post_type IN ({$type_in}) AND post_status IN ({$status_in}) ORDER BY ID ASC LIMIT %d", array_merge( array( $last_id ), $types, $statuses, array( $batch_size ) ) ) ); // phpcs:enable $table = Schema::get_table_name( 'slugh_scan_items' ); $now = current_time( 'mysql', true ); $pretty = (bool) get_option( 'permalink_structure' ); $front_page = (int) get_option( 'page_on_front' ); $processed = 0; $posts = array(); $ids_by_type = array(); foreach ( (array) $rows as $row ) { $post = new \WP_Post( $row ); $posts[] = $post; $ids_by_type[ $post->post_type ][] = $post->ID; } foreach ( $ids_by_type as $type => $ids ) { update_object_term_cache( $ids, $type ); } foreach ( $posts as $post ) { $last_id = max( $last_id, $post->ID ); ++$processed; if ( ! current_user_can( 'edit_post', $post->ID ) ) { continue; } $analysis = DetectorRegistry::analyze( $post ); $flags = $analysis['flags']; $permalink = (string) get_permalink( $post ); $perm_hash = ''; if ( 'publish' === $post->post_status ) { $perm_hash = Normalizer::compute_hash( Normalizer::normalize_path( $permalink ) ); if ( $pretty && $post->ID !== $front_page && DetectorRegistry::has_permalink_problem( $post, $permalink ) ) { $flags |= Flags::PERMALINK_ISSUE; } if ( '' !== $post->post_name ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $duplicate = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND post_status = 'publish' AND post_parent = %d AND post_name = %s AND ID != %d LIMIT 1", $post->post_type, $post->post_parent, $post->post_name, $post->ID ) ); if ( $duplicate ) { $flags |= Flags::DUPLICATE; } } } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->replace( $table, array( 'scan_id' => $scan_id, 'post_id' => $post->ID, 'post_type' => $post->post_type, 'post_status' => $post->post_status, 'decoded_slug' => mb_substr( $analysis['decoded_slug'], 0, 500 ), 'flags' => $flags, 'scripts' => $analysis['scripts'], 'permalink_hash' => $perm_hash, 'scanned_at' => $now, ), array( '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%s', '%s' ) ); ++$scanned; } $done = count( (array) $rows ) < $batch_size; JobRepository::update( $scan_id, array( 'cursor' => $last_id, 'settings' => array_merge( $job->settings, array( 'last_id' => $last_id, 'scanned' => $scanned, ) ), ) ); if ( $done ) { self::finish( $scan_id ); } JobRepository::release_lock( $scan_id ); return array( 'scan_id' => $scan_id, 'processed' => $processed, 'scanned' => $scanned, 'last_id' => $last_id, 'done' => $done, ); } /** * Finish a scan: flag cross-type permalink collisions, store counts, prune old scans. * * @param int $scan_id Scan ID. * @return void */ private static function finish( $scan_id ) { global $wpdb; $table = Schema::get_table_name( 'slugh_scan_items' ); // Records published at the same canonical path (e.g. a page and a post at the same root path). // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $wpdb->query( $wpdb->prepare( "UPDATE %i s JOIN ( SELECT permalink_hash FROM %i WHERE scan_id = %d AND permalink_hash != '' GROUP BY permalink_hash HAVING COUNT(*) > 1 ) d ON d.permalink_hash = s.permalink_hash SET s.flags = s.flags | %d WHERE s.scan_id = %d", $table, $table, $scan_id, Flags::DUPLICATE, $scan_id ) ); // phpcs:enable JobRepository::update( $scan_id, array( 'status' => 'completed', 'finished_at' => current_time( 'mysql', true ), 'counts' => self::get_scan_counts( $scan_id ), ) ); self::prune_old_scans(); } /** * Scan data is derived and is the only data cleanup deletes: keep the latest 5 scans' items. * * @return void */ public static function prune_old_scans() { global $wpdb; $table = Schema::get_table_name( 'slugh_scan_items' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $scan_ids = array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( 'SELECT DISTINCT scan_id FROM %i ORDER BY scan_id DESC', $table ) ) ); if ( count( $scan_ids ) <= self::KEEP_SCANS ) { return; } $keep = array_slice( $scan_ids, 0, self::KEEP_SCANS ); $in = implode( ',', array_fill( 0, count( $keep ), '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE scan_id NOT IN ({$in})", array_merge( array( $table ), $keep ) ) ); } /** * Latest completed scan ID. * * @return int|null */ public static function get_latest_scan_id() { $jobs = JobRepository::query( array( 'type' => 'scan', 'status' => 'completed', 'per_page' => 1, ) ); return empty( $jobs['items'] ) ? null : (int) $jobs['items'][0]->id; } /** * Counts per detection category for a scan. * * @param int $scan_id Scan ID. * @return array */ public static function get_scan_counts( $scan_id ) { global $wpdb; $table = Schema::get_table_name( 'slugh_scan_items' ); $labels = Flags::get_keys(); $select = array( 'COUNT(*) AS total', 'SUM(flags = 0) AS clean' ); foreach ( $labels as $flag => $key ) { $select[] = sprintf( 'SUM((flags & %d) > 0) AS %s', (int) $flag, $key ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $select is built from integer flag constants only. $row = $wpdb->get_row( $wpdb->prepare( 'SELECT ' . implode( ', ', $select ) . ' FROM %i WHERE scan_id = %d', $table, absint( $scan_id ) ), ARRAY_A ); return array_map( 'intval', (array) $row ); } /** * Page through a scan's results with filters. Joins wp_posts for title, modified date and staleness. * * @param int $scan_id Scan ID. * @param array $args post_type, post_status, flags (int[] all must match), search, modified_from, modified_to, orderby, order, per_page, page. * @return array{items: array, total: int} */ public static function query_results( $scan_id, array $args = array() ) { global $wpdb; $table = Schema::get_table_name( 'slugh_scan_items' ); $where = array( 's.scan_id = %d' ); $binds = array( absint( $scan_id ) ); $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['post_type'] ) ) { $where[] = 's.post_type = %s'; $binds[] = sanitize_key( $args['post_type'] ); } if ( ! empty( $args['post_status'] ) ) { $where[] = 's.post_status = %s'; $binds[] = sanitize_key( $args['post_status'] ); } if ( ! empty( $args['flags'] ) ) { $mask = 0; foreach ( (array) $args['flags'] as $flag ) { $mask |= absint( $flag ); } if ( $mask ) { $where[] = '(s.flags & %d) = %d'; $binds[] = $mask; $binds[] = $mask; } } if ( ! empty( $args['issues_only'] ) ) { $where[] = 's.flags != 0'; } if ( isset( $args['search'] ) && '' !== $args['search'] ) { $like = '%' . $wpdb->esc_like( (string) $args['search'] ) . '%'; $where[] = '(p.post_title LIKE %s OR s.decoded_slug LIKE %s)'; $binds[] = $like; $binds[] = $like; } if ( ! empty( $args['modified_from'] ) ) { $where[] = 'p.post_modified >= %s'; $binds[] = sanitize_text_field( $args['modified_from'] ) . ' 00:00:00'; } if ( ! empty( $args['modified_to'] ) ) { $where[] = 'p.post_modified <= %s'; $binds[] = sanitize_text_field( $args['modified_to'] ) . ' 23:59:59'; } $orderby_map = array( 'id' => 's.post_id', 'title' => 'p.post_title', 'type' => 's.post_type', 'modified' => 'p.post_modified', 'slug' => 's.decoded_slug', ); $orderby = isset( $args['orderby'], $orderby_map[ $args['orderby'] ] ) ? $orderby_map[ $args['orderby'] ] : 's.post_id'; $order = isset( $args['order'] ) && 'desc' === strtolower( $args['order'] ) ? 'DESC' : 'ASC'; $where_sql = implode( ' AND ', $where ); $from = "%i s LEFT JOIN {$wpdb->posts} p ON p.ID = s.post_id"; $binds = array_merge( array( $table ), $binds ); // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching // 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 {$from} WHERE {$where_sql}", $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 s.*, p.post_title, p.post_name AS current_post_name, p.post_modified, p.post_modified_gmt FROM {$from} WHERE {$where_sql} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d", array_merge( $binds, array( $per_page, ( $page - 1 ) * $per_page ) ) ) ); // phpcs:enable foreach ( (array) $items as $item ) { $item->is_stale = null === $item->current_post_name || rawurldecode( (string) $item->current_post_name ) !== $item->decoded_slug || ( $item->post_modified_gmt && $item->post_modified_gmt > $item->scanned_at ); } return array( 'items' => (array) $items, 'total' => $total, ); } }