status, array( 'draft', 'validated' ), true ) ) { return new \WP_Error( 'invalid_job', __( 'Only draft jobs can be validated.', 'slugh' ) ); } $duplicates = JobRepository::duplicate_keys( $job_id ); $items = JobRepository::get_items( $job_id, array( 'kind' => 'direct', 'limit' => self::VALIDATE_BATCH, 'offset' => $offset, ) ); foreach ( $items as $item ) { self::validate_item( $item, $duplicates ); } $total = JobRepository::count_items( $job_id ); $next = $offset + count( $items ); $done = count( $items ) < self::VALIDATE_BATCH || $next >= $total; if ( $done ) { JobRepository::update( $job_id, array( 'status' => 'validated', 'counts' => self::summarize( $job_id ), ) ); } return array( 'done' => $done, 'offset' => $next, 'total' => $total, 'counts' => self::summarize( $job_id ), ); } /** * Validate one direct item and store the result. * * @param object $item Item. * @param array $duplicates In-job duplicate keys. * @return array Validation result. */ private static function validate_item( $item, array $duplicates ) { $key = JobRepository::duplicate_key( $item->post_type, $item->parent_id, $item->requested_post_name ); $validation = SlugValidator::validate( $item->post_id, $item->requested_post_name, array( 'expected_old_slug' => $item->old_post_name, 'expected_post_type' => $item->post_type, 'in_job_duplicate' => isset( $duplicates[ $key ] ), ) ); $state = $validation['state']; $result = ! empty( $item->message['user_excluded'] ) ? 'excluded' : 'pending'; if ( $validation['predicted_slug'] === $validation['old_slug'] && $validation['is_valid'] ) { $state = 'unchanged'; } JobRepository::merge_item_message( $item, array( 'validation' => self::compact_validation( $validation ) ), array( 'validation_state' => $state, 'expected_permalink' => $validation['predicted_permalink'], 'result' => $result, ) ); return $validation; } /** * Keep the parts of a validation result worth storing. * * @param array $validation Result. * @return array */ private static function compact_validation( array $validation ) { return array_intersect_key( $validation, array_flip( array( 'state', 'messages', 'sanitized_decoded', 'predicted_slug', 'predicted_decoded', 'old_permalink', 'predicted_permalink', 'url_changes', 'creates_redirect', 'descendants', 'descendant_samples', 'conflicts', 'needs_confirmation' ) ) ); } /** * Store an administrator's choice for a draft item: exclude it, or resolve its conflict. * * @param int $job_id Job ID. * @param int $item_id Item ID. * @param array $choice excluded (bool) and/or resolution (replace|keep|skip|''). * @return object|\WP_Error Updated item. */ public static function set_item_choice( $job_id, $item_id, array $choice ) { $job = JobRepository::get( $job_id ); $item = JobRepository::get_item( $item_id ); if ( ! $job || ! $item || (int) $item->job_id !== (int) $job_id || ! in_array( $job->status, array( 'draft', 'validated' ), true ) ) { return new \WP_Error( 'invalid_item', __( 'Choices can only be changed before the job is confirmed.', 'slugh' ) ); } $values = array(); $columns = array(); if ( array_key_exists( 'excluded', $choice ) ) { $values['user_excluded'] = (bool) $choice['excluded']; $columns['result'] = $values['user_excluded'] ? 'excluded' : 'pending'; } if ( array_key_exists( 'resolution', $choice ) ) { $resolution = sanitize_key( (string) $choice['resolution'] ); $values['resolution'] = in_array( $resolution, array( 'replace', 'keep', 'skip' ), true ) ? $resolution : ''; } JobRepository::merge_item_message( $item, $values, $columns ); return JobRepository::get_item( $item_id ); } /** * Count items per validation state and result. * * @param int $job_id Job ID. * @return array */ public static function summarize( $job_id ) { return array( 'total' => JobRepository::count_items( $job_id ), 'validation' => JobRepository::count_by( $job_id, 'validation_state' ), 'results' => JobRepository::count_by( $job_id, 'result' ), 'kinds' => JobRepository::count_by( $job_id, 'kind' ), ); } /** * Confirm a validated job: resolve conflicts, take snapshots, add descendant items. * * @param int $job_id Job ID. * @param array $args { * Confirmation choices. * * @type array $resolutions Item ID => replace|keep|skip for conflict items. * @type int[] $leave_out Item IDs to leave out. * @type int[]|null $only When set, apply only these item IDs ("apply selected"). * @type bool $confirmed The explicit confirmation checkbox. * } * @return array|\WP_Error Summary on success. */ public static function confirm( $job_id, array $args ) { if ( ! SlugUpdater::user_can_change_slugs() ) { return new \WP_Error( 'unfiltered_html_required', SlugUpdater::unfiltered_html_message() ); } $job = JobRepository::get( $job_id ); if ( ! $job || 'validated' !== $job->status ) { return new \WP_Error( 'invalid_job', __( 'Validate the job (preview) before confirming it.', 'slugh' ) ); } $resolutions = isset( $args['resolutions'] ) ? (array) $args['resolutions'] : array(); $exclude = array_map( 'absint', isset( $args['leave_out'] ) ? (array) $args['leave_out'] : array() ); $only = isset( $args['only'] ) && is_array( $args['only'] ) ? array_map( 'absint', $args['only'] ) : null; $confirmed = ! empty( $args['confirmed'] ); $items = JobRepository::get_items( $job_id, array( 'kind' => 'direct' ) ); $duplicates = JobRepository::duplicate_keys( $job_id ); $problems = array(); $included = array(); $needs_check = false; // Validate again immediately before confirmation. foreach ( $items as $item ) { $validation = self::validate_item( $item, $duplicates ); $item = JobRepository::get_item( $item->id ); $is_selected = null === $only || in_array( $item->id, $only, true ); if ( in_array( $item->id, $exclude, true ) || ! $is_selected || ! empty( $item->message['user_excluded'] ) ) { JobRepository::update_item( $item->id, array( 'result' => 'excluded' ) ); continue; } if ( 'unchanged' === $item->validation_state ) { JobRepository::update_item( $item->id, array( 'result' => 'unchanged' ) ); continue; } if ( ! $validation['is_valid'] ) { // Errors and stale items never apply. JobRepository::merge_item_message( $item, array( 'reason' => 'stale' === $validation['state'] ? 'stale' : 'validation_error' ), array( 'result' => 'excluded' ) ); continue; } if ( ! empty( $validation['conflicts'] ) ) { $resolution = isset( $resolutions[ $item->id ] ) ? sanitize_key( $resolutions[ $item->id ] ) : ( isset( $item->message['resolution'] ) ? $item->message['resolution'] : '' ); $has_loop = false; foreach ( $validation['conflicts'] as $conflict ) { $has_loop = $has_loop || ! empty( $conflict['loop'] ); } if ( ! in_array( $resolution, array( 'replace', 'keep', 'skip' ), true ) ) { /* translators: %d: post ID */ $problems[] = sprintf( __( 'Resolve or exclude the redirect conflict for record #%d.', 'slugh' ), $item->post_id ); continue; } if ( 'keep' === $resolution && $has_loop ) { /* translators: %d: post ID */ $problems[] = sprintf( __( 'Record #%d: keeping the existing redirect would create a loop; choose replace or skip.', 'slugh' ), $item->post_id ); continue; } if ( 'skip' === $resolution ) { JobRepository::merge_item_message( $item, array( 'resolution' => 'skip' ), array( 'result' => 'excluded' ) ); continue; } JobRepository::merge_item_message( $item, array( 'resolution' => $resolution ) ); $item = JobRepository::get_item( $item->id ); } if ( ! empty( $validation['needs_confirmation'] ) ) { $needs_check = true; } $included[] = $item; } if ( $needs_check && ! $confirmed ) { $problems[] = __( 'Some items have conflicts, slug suffixes or descendant URL changes. Tick the confirmation box to continue.', 'slugh' ); } if ( ! empty( $problems ) ) { // Nothing is confirmed; the next validation resets automatic exclusions. return new \WP_Error( 'confirmation_incomplete', implode( ' ', $problems ), array( 'problems' => $problems ) ); } if ( empty( $included ) ) { return new \WP_Error( 'nothing_to_apply', __( 'No item passed validation, so there is nothing to apply.', 'slugh' ) ); } $direct_ids = array(); foreach ( $included as $item ) { $direct_ids[ $item->post_id ] = true; } $descendant_count = 0; foreach ( $included as $item ) { $post = get_post( $item->post_id ); // Snapshot: ID, type, status, parent, raw post_name, permalink, post_modified, integrity hash. $components = IntegrityChecker::compute_components( $post->ID ); JobRepository::merge_item_message( $item, array( 'snapshot' => array( 'post_status' => $post->post_status, 'post_parent' => (int) $post->post_parent, 'post_modified' => $post->post_modified, 'components' => $components, ), ), array( 'old_post_name' => $post->post_name, 'old_permalink' => (string) get_permalink( $post ), 'post_type' => $post->post_type, 'parent_id' => (int) $post->post_parent, 'hash_before' => IntegrityChecker::combine( $components ), 'sort_order' => DescendantPropagator::depth( $post->ID ), ) ); $validation = isset( $item->message['validation'] ) ? $item->message['validation'] : array(); if ( empty( $validation['url_changes'] ) || ! is_post_type_hierarchical( $post->post_type ) ) { continue; } // Descendant snapshots; a descendant that is itself a direct item handles its own URL. foreach ( DescendantPropagator::get_descendants( $post->ID ) as $descendant_id ) { if ( isset( $direct_ids[ $descendant_id ] ) || self::has_descendant_item( $job_id, $descendant_id ) ) { continue; } $descendant = get_post( $descendant_id ); JobRepository::add_item( $job_id, array( 'post_id' => $descendant_id, 'kind' => 'descendant', 'post_type' => $descendant->post_type, 'parent_id' => (int) $descendant->post_parent, 'old_post_name' => $descendant->post_name, 'requested_post_name' => $descendant->post_name, 'old_permalink' => (string) get_permalink( $descendant ), 'validation_state' => 'ok', 'result' => 'pending', 'sort_order' => self::DESCENDANT_ORDER + DescendantPropagator::depth( $descendant_id ), 'message' => array( 'parent_item' => $item->id, 'snapshot' => array( 'post_status' => $descendant->post_status ), ), ) ); ++$descendant_count; } } $settings = array_merge( $job->settings, array( 'ownership_mode' => Settings::get( 'redirect_ownership_mode' ), 'trial_mode' => (bool) Settings::get( 'trial_mode', false ), 'phase' => 'apply', 'verify_offset' => 0, 'report' => array(), ) ); JobRepository::update( $job_id, array( 'status' => 'confirmed', 'confirmed_at' => current_time( 'mysql', true ), 'settings' => $settings, 'counts' => self::summarize( $job_id ), 'cursor' => 0, ) ); DraftManager::detach_editor_draft( $job_id ); AuditLogger::log( 'job_confirm', 'job', $job_id, null, array( 'items' => count( $included ), 'descendants' => $descendant_count, ), $job_id ); return array( 'job_id' => $job_id, 'items' => count( $included ), 'descendants' => $descendant_count, ); } /** * Whether a job already has a descendant item for a post. * * @param int $job_id Job ID. * @param int $post_id Post ID. * @return bool */ private static function has_descendant_item( $job_id, $post_id ) { global $wpdb; $table = \SlugH\Database\Schema::get_table_name( 'slugh_job_items' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return (bool) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM %i WHERE job_id = %d AND post_id = %d AND kind = 'descendant' LIMIT 1", $table, $job_id, $post_id ) ); } /** * Run the next batch of a confirmed or running job. Driven repeatedly by the admin page. * * @param int $job_id Job ID. * @return array|\WP_Error Progress. */ public static function run_batch( $job_id ) { $job = JobRepository::get( $job_id ); if ( ! $job || ! in_array( $job->status, array( 'confirmed', 'running' ), true ) ) { return new \WP_Error( 'invalid_job', __( 'This job is not ready to run.', 'slugh' ) ); } if ( 'scan' !== $job->type && ! SlugUpdater::user_can_change_slugs() ) { return new \WP_Error( 'unfiltered_html_required', SlugUpdater::unfiltered_html_message() ); } if ( ! JobRepository::acquire_lock( $job_id ) ) { return new \WP_Error( 'locked', __( 'Another request is already running this job. It will continue shortly.', 'slugh' ), array( 'status' => 409 ) ); } try { if ( 'confirmed' === $job->status ) { JobRepository::update( $job_id, array( 'status' => 'running', 'started_at' => current_time( 'mysql', true ), ) ); AuditLogger::log( 'job_start', 'job', $job_id, null, array( 'type' => $job->type ), $job_id ); $job = JobRepository::get( $job_id ); } $phase = isset( $job->settings['phase'] ) ? $job->settings['phase'] : 'apply'; if ( 'apply' === $phase ) { $progress = self::apply_batch( $job ); } else { $progress = self::verify_batch( $job ); } } finally { JobRepository::release_lock( $job_id ); } return $progress; } /** * Apply the next batch of pending items. * * @param object $job Job. * @return array Progress. */ private static function apply_batch( $job ) { $batch_size = (int) Settings::get( 'job_batch_size', 25 ); $items = JobRepository::get_items( $job->id, array( 'result' => 'pending', 'limit' => $batch_size, ) ); $failed = 0; $pause = ''; $applied = 0; foreach ( $items as $item ) { if ( 'rollback' === $job->type ) { $outcome = RollbackManager::process_item( $job, $item ); } elseif ( 'descendant' === $item->kind ) { $outcome = self::process_descendant( $job, $item ); } else { $outcome = self::process_direct( $job, $item ); } if ( 'failed' === $outcome ) { ++$failed; } elseif ( 'applied' === $outcome ) { ++$applied; } elseif ( 'integrity_changed' === $outcome ) { $pause = 'integrity_changed'; break; } } $processed = $job->cursor + count( $items ); $update = array( 'cursor' => $processed, 'counts' => self::summarize( $job->id ), ); if ( '' === $pause && count( $items ) > 0 && ( $failed / count( $items ) ) > self::FAILURE_THRESHOLD ) { $pause = 'failure_threshold'; } if ( '' !== $pause ) { $update['status'] = 'paused'; $update['settings'] = array_merge( $job->settings, array( 'pause_reason' => $pause ) ); JobRepository::update( $job->id, $update ); AuditLogger::log( 'job_pause', 'job', $job->id, null, array( 'reason' => $pause ), $job->id ); return self::progress( $job->id ); } if ( count( $items ) < $batch_size || 0 === count( JobRepository::get_items( $job->id, array( 'result' => 'pending', 'limit' => 1, ) ) ) ) { $update['settings'] = array_merge( $job->settings, array( 'phase' => 'verify' ) ); } JobRepository::update( $job->id, $update ); return self::progress( $job->id ); } /** * Apply one direct item. * * @param object $job Job. * @param object $item Item. * @return string Result. */ private static function process_direct( $job, $item ) { $validation = SlugValidator::validate( $item->post_id, $item->requested_post_name, array( 'expected_old_slug' => $item->old_post_name, 'expected_post_type' => $item->post_type, ) ); if ( 'stale' === $validation['state'] ) { return self::finish_item( $item, 'skipped', array( 'reason' => 'stale', 'detail' => implode( ' ', $validation['errors'] ), ) ); } if ( ! $validation['is_valid'] ) { return self::finish_item( $item, 'skipped', array( 'reason' => 'validation_error', 'detail' => implode( ' ', $validation['errors'] ), ) ); } $resolution = isset( $item->message['resolution'] ) ? $item->message['resolution'] : ''; if ( ! empty( $validation['conflicts'] ) && ! in_array( $resolution, array( 'replace', 'keep' ), true ) ) { return self::finish_item( $item, 'skipped', array( 'reason' => 'unresolved_conflict', 'detail' => implode( ' ', $validation['warnings'] ), ) ); } $post = get_post( $item->post_id ); $old_status = $post->post_status; $redirect = array( 'ids' => array(), 'actions' => array(), 'flattened' => array(), 'previous' => array(), 'disabled' => array(), ); $mode = isset( $job->settings['ownership_mode'] ) ? $job->settings['ownership_mode'] : Settings::MODE_SLUGH; // "Replace" on a redirect sitting at the new path: disable it, logged, so the live page is not shadowed. foreach ( $validation['conflicts'] as $conflict ) { if ( 'new_path' === $conflict['type'] && 'replace' === $resolution ) { RedirectRepository::set_enabled( $conflict['redirect_id'], false, $job->id ); $redirect['disabled'][] = (int) $conflict['redirect_id']; } } $update = SlugUpdater::update( $item->post_id, $item->requested_post_name, $job->id ); if ( is_wp_error( $update ) ) { return self::finish_item( $item, 'failed', array( 'reason' => $update->get_error_code(), 'detail' => $update->get_error_message(), ), array( 'redirect_ids' => $redirect['disabled'] ) ); } $columns = array( 'actual_post_name' => $update['actual_slug'], 'actual_permalink' => $update['actual_permalink'], 'hash_after' => $update['hash_after'], ); $notes = array(); if ( $update['actual_slug'] !== $validation['predicted_slug'] || Normalizer::normalize_path( $update['actual_permalink'] ) !== Normalizer::normalize_path( $validation['predicted_permalink'] ) ) { $notes['prediction_mismatch'] = array( 'predicted_slug' => $validation['predicted_slug'], 'predicted_permalink' => $validation['predicted_permalink'], ); } if ( $update['revision_created'] ) { $notes['revision_created'] = true; } if ( ! empty( $update['changed_fields'] ) ) { $notes['changed_fields'] = $update['changed_fields']; self::finish_item( $item, 'integrity_changed', $notes, $columns ); AuditLogger::log( 'integrity_changed', 'post', $item->post_id, null, array( 'fields' => $update['changed_fields'] ), $job->id ); return 'integrity_changed'; } $public_statuses = Settings::get( 'redirect_private_posts', false ) ? array( 'publish', 'private' ) : array( 'publish' ); $old_path = Normalizer::normalize_path( $item->old_permalink ); $new_path = Normalizer::normalize_path( $update['actual_permalink'] ); if ( Settings::MODE_SLUGH === $mode && in_array( $old_status, $public_statuses, true ) && $old_path !== $new_path ) { $created = RedirectRepository::create( array( 'source' => $item->old_permalink, 'destination' => $update['actual_permalink'], 'status_code' => ! empty( $job->settings['trial_mode'] ) ? 302 : 301, 'origin' => 'job', 'post_id' => $item->post_id, 'job_id' => $job->id, 'on_conflict' => 'keep' === $resolution ? 'keep' : ( 'replace' === $resolution ? 'replace' : 'error' ), ) ); if ( is_wp_error( $created ) ) { $notes['redirect_error'] = $created->get_error_message(); } else { self::record_redirect( $redirect, $created ); } } CacheManager::purge_urls( array( $item->old_permalink, $update['actual_permalink'] ), $item->post_id ); AuditLogger::log( 'slug_apply', 'post', $item->post_id, array( 'slug' => $item->old_post_name, 'permalink' => $item->old_permalink, ), array( 'slug' => $update['actual_slug'], 'permalink' => $update['actual_permalink'], 'redirects' => $redirect['ids'], ), $job->id ); $notes['redirects'] = $redirect; $columns['redirect_ids'] = array_values( array_unique( array_merge( $redirect['ids'], $redirect['disabled'] ) ) ); return self::finish_item( $item, 'applied', $notes, $columns ); } /** * Process a descendant: recompute its final permalink once, after every parent in the job ran. * * @param object $job Job. * @param object $item Item. * @return string Result. */ private static function process_descendant( $job, $item ) { clean_post_cache( $item->post_id ); $post = get_post( $item->post_id ); if ( ! $post ) { return self::finish_item( $item, 'skipped', array( 'reason' => 'not_found' ) ); } $new_permalink = (string) get_permalink( $post ); $old_path = Normalizer::normalize_path( $item->old_permalink ); $new_path = Normalizer::normalize_path( $new_permalink ); $columns = array( 'actual_post_name' => $post->post_name, 'actual_permalink' => $new_permalink, ); if ( $old_path === $new_path ) { return self::finish_item( $item, 'unchanged', array(), $columns ); } $redirect = array( 'ids' => array(), 'actions' => array(), 'flattened' => array(), 'previous' => array(), 'disabled' => array(), ); $notes = array(); $mode = isset( $job->settings['ownership_mode'] ) ? $job->settings['ownership_mode'] : Settings::MODE_SLUGH; $public_statuses = Settings::get( 'redirect_private_posts', false ) ? array( 'publish', 'private' ) : array( 'publish' ); if ( Settings::MODE_SLUGH === $mode && in_array( $post->post_status, $public_statuses, true ) ) { $created = RedirectRepository::create( array( 'source' => $item->old_permalink, 'destination' => $new_permalink, 'status_code' => ! empty( $job->settings['trial_mode'] ) ? 302 : 301, 'origin' => 'descendant', 'post_id' => $item->post_id, 'job_id' => $job->id, 'on_conflict' => 'replace', ) ); if ( is_wp_error( $created ) ) { $notes['redirect_error'] = $created->get_error_message(); } else { self::record_redirect( $redirect, $created ); } } CacheManager::purge_urls( array( $item->old_permalink, $new_permalink ), $item->post_id ); $notes['redirects'] = $redirect; $columns['redirect_ids'] = $redirect['ids']; return self::finish_item( $item, 'applied', $notes, $columns ); } /** * Collect a create() result into an item's redirect record. * * @param array $redirect Record (by reference). * @param array $created RedirectRepository::create() result. * @return void */ public static function record_redirect( array &$redirect, array $created ) { if ( empty( $created['id'] ) ) { $redirect['actions'][] = array( 'id' => 0, 'action' => $created['action'], ); return; } $redirect['ids'][] = (int) $created['id']; $redirect['actions'][] = array( 'id' => (int) $created['id'], 'action' => $created['action'], ); $redirect['flattened'] = array_merge( $redirect['flattened'], $created['flattened'] ); if ( ! empty( $created['previous'] ) ) { $prev = $created['previous']; $redirect['previous'][] = array( 'id' => (int) $prev->id, 'destination' => $prev->destination, 'status_code' => (int) $prev->status_code, 'match_mode' => $prev->match_mode, 'enabled' => (int) $prev->enabled, ); } } /** * Store an item's result. * * @param object $item Item. * @param string $result Result. * @param array $notes Message data. * @param array $columns Extra columns. * @return string Result. */ public static function finish_item( $item, $result, array $notes = array(), array $columns = array() ) { JobRepository::merge_item_message( $item, $notes, array_merge( $columns, array( 'result' => $result ) ) ); return $result; } /** * Verify the job's URLs over HTTP, then finish the job. * * Mode 1 tests every redirect the job created; mode 2 tests every changed URL and reports those that do * not reach the new URL in one hop; mode 3 reports old URLs that now return 404. * * @param object $job Job. * @return array Progress. */ private static function verify_batch( $job ) { $offset = isset( $job->settings['verify_offset'] ) ? (int) $job->settings['verify_offset'] : 0; $items = JobRepository::get_items( $job->id, array( 'result' => 'applied', 'limit' => self::VERIFY_BATCH, 'offset' => $offset, ) ); $mode = isset( $job->settings['ownership_mode'] ) ? $job->settings['ownership_mode'] : Settings::MODE_SLUGH; $report = isset( $job->settings['report'] ) ? (array) $job->settings['report'] : array(); foreach ( $items as $item ) { if ( empty( $item->actual_permalink ) || Normalizer::normalize_path( $item->old_permalink ) === Normalizer::normalize_path( $item->actual_permalink ) ) { continue; } $status_before = isset( $item->message['snapshot']['post_status'] ) ? $item->message['snapshot']['post_status'] : 'publish'; if ( ! in_array( $status_before, array( 'publish', 'private' ), true ) ) { continue; } if ( 'rollback' !== $job->type && Settings::MODE_SLUGH === $mode && empty( $item->redirect_ids ) && empty( $item->message['redirect_error'] ) ) { continue; } $trace = RedirectTester::test_url( $item->old_permalink ); $one_hop = RedirectTester::reaches_in_one_hop( $trace, $item->actual_permalink ); $status = isset( $trace['hops'][0]['status'] ) ? (int) $trace['hops'][0]['status'] : 0; $summary = array( 'item_id' => $item->id, 'post_id' => $item->post_id, 'kind' => $item->kind, 'old_url' => $item->old_permalink, 'new_url' => $item->actual_permalink, 'status' => $status, 'location' => isset( $trace['hops'][0]['location'] ) ? $trace['hops'][0]['location'] : null, 'one_hop' => $one_hop, 'by' => isset( $trace['hops'][0]['by'] ) ? $trace['hops'][0]['by'] : '', 'simulated' => ! empty( $trace['simulated'] ), ); JobRepository::merge_item_message( $item, array( 'test' => $summary ) ); if ( Settings::MODE_SLUG_ONLY === $mode ) { if ( 404 === (int) $trace['final_status'] || 404 === $status ) { $report[] = $summary; } } elseif ( ! $one_hop ) { $report[] = $summary; } } $done = count( $items ) < self::VERIFY_BATCH; $settings = array_merge( $job->settings, array( 'verify_offset' => $offset + count( $items ), 'report' => array_slice( $report, 0, 2000 ), ) ); if ( ! $done ) { JobRepository::update( $job->id, array( 'settings' => $settings ) ); return self::progress( $job->id ); } $settings['phase'] = 'done'; $results = JobRepository::count_by( $job->id, 'result' ); $has_errors = ! empty( $results['failed'] ) || ! empty( $results['integrity_changed'] ); JobRepository::update( $job->id, array( 'status' => $has_errors ? 'completed_with_errors' : 'completed', 'finished_at' => current_time( 'mysql', true ), 'settings' => $settings, 'counts' => self::summarize( $job->id ), ) ); if ( 'rollback' === $job->type && $job->parent_job_id ) { RollbackManager::update_target_status( (int) $job->parent_job_id ); } AuditLogger::log( 'job_complete', 'job', $job->id, null, array( 'results' => $results ), $job->id ); return self::progress( $job->id ); } /** * Progress report for the admin page. * * @param int $job_id Job ID. * @return array */ public static function progress( $job_id ) { $job = JobRepository::get( $job_id ); $results = JobRepository::count_by( $job_id, 'result' ); $total = JobRepository::count_items( $job_id ) - ( isset( $results['excluded'] ) ? $results['excluded'] : 0 ) - ( isset( $results['unchanged'] ) && 'draft' === $job->status ? $results['unchanged'] : 0 ); $pending = isset( $results['pending'] ) ? $results['pending'] : 0; return array( 'job_id' => $job_id, 'status' => $job->status, 'phase' => isset( $job->settings['phase'] ) ? $job->settings['phase'] : '', 'pause_reason' => isset( $job->settings['pause_reason'] ) ? $job->settings['pause_reason'] : '', 'total' => max( 0, $total ), 'processed' => max( 0, $total - $pending ), 'results' => $results, 'done' => in_array( $job->status, array( 'completed', 'completed_with_errors', 'cancelled', 'paused', 'rolled_back', 'partially_rolled_back' ), true ), ); } /** * Resume a paused job after review. * * @param int $job_id Job ID. * @return true|\WP_Error */ public static function resume( $job_id ) { $job = JobRepository::get( $job_id ); if ( ! $job || 'paused' !== $job->status ) { return new \WP_Error( 'invalid_job', __( 'Only paused jobs can be resumed.', 'slugh' ) ); } $settings = $job->settings; unset( $settings['pause_reason'] ); JobRepository::update( $job_id, array( 'status' => 'running', 'settings' => $settings, ) ); AuditLogger::log( 'job_resume', 'job', $job_id, array( 'status' => 'paused' ), array( 'status' => 'running' ), $job_id ); return true; } /** * Cancel a job that has not finished. Applied items stay applied and can be rolled back. * * @param int $job_id Job ID. * @return true|\WP_Error */ public static function cancel( $job_id ) { $job = JobRepository::get( $job_id ); if ( ! $job || ! in_array( $job->status, array( 'draft', 'validated', 'confirmed', 'running', 'paused' ), true ) ) { return new \WP_Error( 'invalid_job', __( 'This job cannot be cancelled.', 'slugh' ) ); } foreach ( JobRepository::get_items( $job_id, array( 'result' => 'pending' ) ) as $item ) { JobRepository::update_item( $item->id, array( 'result' => 'cancelled' ) ); } $results = JobRepository::count_by( $job_id, 'result' ); JobRepository::update( $job_id, array( 'status' => empty( $results['applied'] ) ? 'cancelled' : 'completed_with_errors', 'finished_at' => current_time( 'mysql', true ), 'counts' => self::summarize( $job_id ), ) ); DraftManager::detach_editor_draft( $job_id ); AuditLogger::log( 'job_cancel', 'job', $job_id, array( 'status' => $job->status ), null, $job_id ); return true; } /** * Hand-off mode: create the missing redirects reported after a job. * * @param int $job_id Job ID. * @return array{created: int, errors: string[]}|\WP_Error */ public static function create_missing_redirects( $job_id ) { $job = JobRepository::get( $job_id ); if ( ! $job || empty( $job->settings['report'] ) ) { return new \WP_Error( 'nothing_missing', __( 'This job has no missing redirects to create.', 'slugh' ) ); } $created = 0; $errors = array(); foreach ( $job->settings['report'] as $entry ) { $result = RedirectRepository::create( array( 'source' => $entry['old_url'], 'destination' => $entry['new_url'], 'status_code' => ! empty( $job->settings['trial_mode'] ) ? 302 : 301, 'origin' => 'descendant' === $entry['kind'] ? 'descendant' : 'job', 'post_id' => $entry['post_id'], 'job_id' => $job_id, 'on_conflict' => 'keep', ) ); if ( is_wp_error( $result ) ) { $errors[] = $entry['old_url'] . ': ' . $result->get_error_message(); continue; } $item = JobRepository::get_item( $entry['item_id'] ); if ( $item && ! empty( $result['id'] ) ) { $redirect = isset( $item->message['redirects'] ) ? $item->message['redirects'] : array( 'ids' => array(), 'actions' => array(), 'flattened' => array(), 'previous' => array(), 'disabled' => array(), ); self::record_redirect( $redirect, $result ); JobRepository::merge_item_message( $item, array( 'redirects' => $redirect ), array( 'redirect_ids' => array_values( array_unique( array_merge( $item->redirect_ids, $redirect['ids'] ) ) ) ) ); ++$created; } } JobRepository::merge_settings( $job_id, array( 'report' => array(), 'missing_resolved' => $created, ) ); return array( 'created' => $created, 'errors' => $errors, ); } }