status, array( 'draft', 'validated' ), true ) && (int) $job->created_by === $user_id ) { return $job_id; } } if ( ! $create ) { return 0; } $job_id = JobRepository::create( 'edit', 'draft', array( 'source' => 'editor' ) ); update_user_meta( $user_id, self::EDITOR_META_KEY, $job_id ); AuditLogger::log( 'job_create', 'job', $job_id, null, array( 'type' => 'edit' ), $job_id ); return $job_id; } /** * Forget the editor draft for the current user (after it is confirmed or discarded). * * @param int $job_id Job ID. * @return void */ public static function detach_editor_draft( $job_id ) { $user_id = get_current_user_id(); if ( (int) get_user_meta( $user_id, self::EDITOR_META_KEY, true ) === (int) $job_id ) { delete_user_meta( $user_id, self::EDITOR_META_KEY ); } } /** * Discard a draft job: it is cancelled (kept for history) and detached from the editor. * * @param int $job_id Job ID. * @return bool */ public static function discard( $job_id ) { $job = JobRepository::get( $job_id ); if ( ! $job || ! in_array( $job->status, array( 'draft', 'validated' ), true ) ) { return false; } JobRepository::update( $job_id, array( 'status' => 'cancelled', 'finished_at' => current_time( 'mysql', true ), ) ); self::detach_editor_draft( $job_id ); AuditLogger::log( 'job_discard', 'job', $job_id, array( 'status' => $job->status ), array( 'status' => 'cancelled' ), $job_id ); return true; } /** * Add or update one draft change, matched by content ID only. * * @param int $job_id Draft job ID. * @param int $post_id Content ID. * @param string $new_slug Proposed slug (decoded or percent-encoded). * @param string|null $expected_old_slug Old slug safeguard (null = current slug). * @param string|null $expected_post_type Post type safeguard (null = current type). * @param array $extra Extra message data (e.g. CSV line). * @return array{status: string, item_id?: int, message?: string} */ public static function upsert_item( $job_id, $post_id, $new_slug, $expected_old_slug = null, $expected_post_type = null, array $extra = array() ) { $job = JobRepository::get( $job_id ); if ( ! $job || ! in_array( $job->status, array( 'draft', 'validated' ), true ) ) { return array( 'status' => 'error', 'message' => __( 'This job is no longer a draft.', 'slugh' ), ); } $post = get_post( absint( $post_id ) ); if ( ! $post ) { return array( 'status' => 'error', 'message' => __( 'No record with this content ID.', 'slugh' ), ); } if ( ! PostTypes::is_supported( $post->post_type ) ) { return array( 'status' => 'error', /* translators: %s: post type */ 'message' => sprintf( __( 'Post type "%s" is not managed by slugH.', 'slugh' ), $post->post_type ), ); } if ( ! in_array( $post->post_status, PostTypes::SUPPORTED_STATUSES, true ) ) { return array( 'status' => 'error', /* translators: %s: post status */ 'message' => sprintf( __( 'Status "%s" is not supported.', 'slugh' ), $post->post_status ), ); } if ( ! current_user_can( 'edit_post', $post->ID ) ) { return array( 'status' => 'error', 'message' => __( 'You cannot edit this record.', 'slugh' ), ); } $requested = self::sanitize_candidate( $new_slug ); if ( '' === $requested ) { return array( 'status' => 'error', 'message' => __( 'The new slug is empty after sanitization.', 'slugh' ), ); } $existing = JobRepository::find_item( $job_id, $post->ID ); $expected = null === $expected_old_slug ? ( $existing ? $existing->old_post_name : $post->post_name ) : (string) $expected_old_slug; $type = null === $expected_post_type || '' === $expected_post_type ? ( $existing ? $existing->post_type : $post->post_type ) : sanitize_key( $expected_post_type ); // A change back to the current slug removes the draft change instead. if ( SlugValidator::compare_form( $requested ) === SlugValidator::compare_form( $post->post_name ) && SlugValidator::compare_form( $expected ) === SlugValidator::compare_form( $post->post_name ) ) { if ( $existing ) { JobRepository::delete_draft_item( $existing->id ); } self::mark_dirty( $job_id ); return array( 'status' => 'unchanged', 'message' => __( 'Same as the current slug; nothing to change.', 'slugh' ), ); } $data = array( 'post_id' => $post->ID, 'kind' => 'direct', 'post_type' => $type, 'parent_id' => (int) $post->post_parent, 'old_post_name' => $expected, 'requested_post_name' => $requested, 'old_permalink' => (string) get_permalink( $post ), 'validation_state' => 'pending', 'result' => 'pending', 'message' => array_merge( array( 'input' => (string) $new_slug ), $extra ), ); if ( $existing ) { JobRepository::update_item( $existing->id, $data ); $item_id = $existing->id; } else { $item_id = JobRepository::add_item( $job_id, $data ); } self::mark_dirty( $job_id ); return array( 'status' => $existing ? 'updated' : 'added', 'item_id' => $item_id, ); } /** * Remove a post's change from a draft. * * @param int $job_id Job ID. * @param int $post_id Post ID. * @return bool */ public static function remove_item( $job_id, $post_id ) { $item = JobRepository::find_item( $job_id, $post_id ); if ( ! $item ) { return false; } JobRepository::delete_draft_item( $item->id ); self::mark_dirty( $job_id ); return true; } /** * Any draft change invalidates an earlier validation. * * @param int $job_id Job ID. * @return void */ private static function mark_dirty( $job_id ) { $job = JobRepository::get( $job_id ); if ( $job && 'validated' === $job->status ) { JobRepository::update( $job_id, array( 'status' => 'draft' ) ); } } /** * Sanitize a candidate the same way WordPress stores it (NFC, then sanitize_title()). * * @param string $slug Candidate. * @return string */ public static function sanitize_candidate( $slug ) { $slug = trim( rawurldecode( (string) $slug ) ); if ( class_exists( '\Normalizer' ) ) { $nfc = \Normalizer::normalize( $slug, \Normalizer::FORM_C ); $slug = false === $nfc ? $slug : $nfc; } return '' === $slug ? '' : sanitize_title( $slug ); } /** * Parse "content_id,new_slug" lines (comma or tab separated) into the draft. * * @param int $job_id Draft job ID. * @param string $text Pasted text. * @return array{added: int, updated: int, unchanged: int, errors: array} */ public static function apply_bulk_paste( $job_id, $text ) { $report = array( 'added' => 0, 'updated' => 0, 'unchanged' => 0, 'errors' => array(), ); $lines = preg_split( '/\r\n|\r|\n/', (string) $text ); $seen = array(); foreach ( $lines as $index => $line ) { $line_number = $index + 1; if ( '' === trim( $line ) ) { continue; } $parts = false !== strpos( $line, "\t" ) ? explode( "\t", $line, 2 ) : str_getcsv( $line, ',', '"', '\\' ); if ( count( $parts ) < 2 ) { $report['errors'][] = array( 'line' => $line_number, 'text' => $line, 'reason' => __( 'Expected "content_id,new_slug" (comma or tab separated).', 'slugh' ), ); continue; } $id = trim( (string) $parts[0] ); $slug = trim( (string) $parts[1] ); if ( ! preg_match( '/^[0-9]+$/D', $id ) ) { if ( 1 === $line_number && preg_match( '/id/i', $id ) ) { continue; // Header row. } $report['errors'][] = array( 'line' => $line_number, 'text' => $line, 'reason' => __( 'The content ID must be a number.', 'slugh' ), ); continue; } if ( isset( $seen[ $id ] ) ) { $report['errors'][] = array( 'line' => $line_number, 'text' => $line, /* translators: %d: earlier line number */ 'reason' => sprintf( __( 'Duplicate content ID; line %d already sets it.', 'slugh' ), $seen[ $id ] ), ); continue; } $seen[ $id ] = $line_number; $res = self::upsert_item( $job_id, (int) $id, $slug, null, null, array( 'source' => 'paste' ) ); if ( 'error' === $res['status'] ) { $report['errors'][] = array( 'line' => $line_number, 'text' => $line, 'reason' => $res['message'], ); } else { ++$report[ $res['status'] ]; } } return $report; } /** * Create an import job from a parsed slug CSV. * * @param array $parsed Output of CsvHandler::parse_file(). * @param string $filename Original file name. * @return array{job_id: int, added: int, skipped_empty: int, unchanged: int, errors: array}|\WP_Error */ public static function import_csv( array $parsed, $filename = '' ) { $required = array( 'content_id', 'post_type', 'old_slug', 'new_slug' ); $missing = array_diff( $required, $parsed['headers'] ); if ( ! empty( $missing ) ) { return new \WP_Error( 'missing_columns', sprintf( /* translators: %s: column names */ __( 'The file is missing required columns: %s. Nothing was imported.', 'slugh' ), implode( ', ', $missing ) ) ); } $job_id = JobRepository::create( 'import', 'draft', array( 'source' => 'csv', 'filename' => sanitize_file_name( $filename ), ) ); $report = array( 'job_id' => $job_id, 'added' => 0, 'skipped_empty' => 0, 'unchanged' => 0, 'errors' => array(), ); $seen = array(); foreach ( $parsed['rows'] as $row ) { $line = $row['line']; $data = $row['data']; $id = trim( (string) $data['content_id'] ); if ( '' === trim( (string) $data['new_slug'] ) ) { ++$report['skipped_empty']; continue; } if ( ! preg_match( '/^[0-9]+$/D', $id ) ) { $report['errors'][] = array( 'line' => $line, 'reason' => __( 'content_id must be a number.', 'slugh' ), ); continue; } if ( isset( $seen[ $id ] ) ) { $report['errors'][] = array( 'line' => $line, /* translators: %d: earlier line number */ 'reason' => sprintf( __( 'Duplicate content_id; line %d already sets it.', 'slugh' ), $seen[ $id ] ), ); continue; } $seen[ $id ] = $line; $res = self::upsert_item( $job_id, (int) $id, (string) $data['new_slug'], (string) $data['old_slug'], (string) $data['post_type'], array( 'source' => 'csv', 'line' => $line, ) ); if ( 'error' === $res['status'] ) { $report['errors'][] = array( 'line' => $line, 'reason' => $res['message'], ); } elseif ( 'unchanged' === $res['status'] ) { ++$report['unchanged']; } else { ++$report['added']; } } JobRepository::merge_settings( $job_id, array( 'import_errors' => array_slice( $report['errors'], 0, 1000 ), 'import_report' => array( 'rows' => count( $parsed['rows'] ), 'added' => $report['added'], 'skipped_empty' => $report['skipped_empty'], 'unchanged' => $report['unchanged'], 'invalid' => count( $report['errors'] ), ), ) ); AuditLogger::log( 'import', 'job', $job_id, array( 'filename' => $filename ), $report['added'] ? array_diff_key( $report, array( 'errors' => 1 ) ) : array( 'invalid' => count( $report['errors'] ) ), $job_id ); return $report; } }