absint( $post_id ), 'candidate_slug' => (string) $candidate, 'sanitized_slug' => '', 'sanitized_decoded' => '', 'predicted_slug' => '', 'predicted_decoded' => '', 'old_slug' => '', 'old_permalink' => '', 'predicted_permalink' => '', 'old_path' => '', 'new_path' => '', 'url_changes' => false, 'creates_redirect' => false, 'descendants' => 0, 'descendant_samples' => array(), 'conflicts' => array(), 'messages' => array(), 'state' => self::STATE_OK, 'needs_confirmation' => false, 'is_valid' => true, 'errors' => array(), 'warnings' => array(), ); $post = get_post( $post_id ); if ( ! $post ) { return self::finish( self::add( $result, self::STATE_ERROR, 'not_found', __( 'Record not found.', 'slugh' ) ) ); } $result['old_slug'] = $post->post_name; $result['old_permalink'] = (string) get_permalink( $post ); $result['old_path'] = Normalizer::normalize_path( $result['old_permalink'] ); if ( ! PostTypes::is_supported( $post->post_type ) ) { $result = self::add( $result, self::STATE_ERROR, 'unsupported_type', __( 'This post type is not managed by slugH.', 'slugh' ) ); } if ( ! current_user_can( 'edit_post', $post->ID ) ) { $result = self::add( $result, self::STATE_ERROR, 'permission', __( 'You do not have permission to edit this record.', 'slugh' ) ); } // Stale check: the expected old slug and post type must still match the record. if ( isset( $context['expected_old_slug'] ) && null !== $context['expected_old_slug'] ) { if ( self::compare_form( $context['expected_old_slug'] ) !== self::compare_form( $post->post_name ) ) { $result = self::add( $result, self::STATE_STALE, 'stale_slug', sprintf( /* translators: 1: expected slug, 2: current slug */ __( 'Stale: the slug changed since this item was created (expected "%1$s", now "%2$s"). Review it before applying.', 'slugh' ), rawurldecode( (string) $context['expected_old_slug'] ), rawurldecode( $post->post_name ) ) ); } } if ( ! empty( $context['expected_post_type'] ) && $context['expected_post_type'] !== $post->post_type ) { $result = self::add( $result, self::STATE_STALE, 'stale_type', sprintf( /* translators: 1: expected post type, 2: actual post type */ __( 'Stale: expected post type "%1$s" but the record is "%2$s".', 'slugh' ), $context['expected_post_type'], $post->post_type ) ); } $input = trim( (string) $candidate ); if ( class_exists( '\Normalizer' ) ) { $nfc = \Normalizer::normalize( rawurldecode( $input ), \Normalizer::FORM_C ); $input = false === $nfc ? $input : $nfc; } $sanitized = '' === $input ? '' : sanitize_title( $input ); $result['sanitized_slug'] = $sanitized; $result['sanitized_decoded'] = rawurldecode( $sanitized ); if ( '' === $sanitized ) { return self::finish( self::add( $result, self::STATE_ERROR, 'empty', __( 'The slug is empty after sanitization.', 'slugh' ) ) ); } if ( rawurldecode( $input ) !== $result['sanitized_decoded'] ) { $result = self::add( $result, self::STATE_WARNING, 'sanitized', sprintf( /* translators: %s: sanitized slug */ __( 'WordPress will store this slug as "%s".', 'slugh' ), $result['sanitized_decoded'] ) ); } $encoded_length = self::full_encoded_length( $input ); if ( $encoded_length > self::MAX_LENGTH ) { $result = self::add( $result, self::STATE_ERROR, 'too_long', sprintf( /* translators: 1: encoded length, 2: limit */ __( 'The encoded slug is %1$d characters; WordPress would silently cut it at %2$d. Shorten it.', 'slugh' ), $encoded_length, self::MAX_LENGTH ) ); } if ( in_array( $result['sanitized_decoded'], self::reserved_slugs(), true ) ) { $result = self::add( $result, self::STATE_ERROR, 'reserved', /* translators: %s: slug */ sprintf( __( '"%s" is reserved by WordPress.', 'slugh' ), $result['sanitized_decoded'] ) ); } if ( ! empty( $context['in_job_duplicate'] ) ) { $result = self::add( $result, self::STATE_ERROR, 'job_duplicate', __( 'Another item in this job uses the same new slug for the same post type and parent.', 'slugh' ) ); } // Predict the final slug the way WordPress will. $predicted = wp_unique_post_slug( $sanitized, $post->ID, $post->post_status, $post->post_type, $post->post_parent ); $result['predicted_slug'] = $predicted; $result['predicted_decoded'] = rawurldecode( $predicted ); if ( $predicted !== $sanitized ) { $result = self::add( $result, self::STATE_WARNING, 'suffix', sprintf( /* translators: 1: requested slug, 2: predicted slug */ __( 'The slug is taken; WordPress will save "%2$s" instead of "%1$s".', 'slugh' ), $result['sanitized_decoded'], $result['predicted_decoded'] ), true ); } if ( in_array( $post->post_status, array( 'draft', 'pending' ), true ) ) { $published = self::find_published_with_slug( $post, $sanitized ); if ( $published ) { $result = self::add( $result, self::STATE_WARNING, 'draft_duplicate', sprintf( /* translators: %d: post ID */ __( 'Published record #%d already uses this slug. WordPress does not check drafts, so it may add a suffix such as -2 when this record is published.', 'slugh' ), $published ) ); } } if ( $predicted === $post->post_name ) { $result = self::add( $result, 'info', 'unchanged', __( 'The slug is unchanged.', 'slugh' ) ); return self::finish( $result ); } $result['predicted_permalink'] = self::predict_permalink( $post, $predicted ); $result['new_path'] = Normalizer::normalize_path( $result['predicted_permalink'] ); $result['url_changes'] = '' !== $result['new_path'] && $result['new_path'] !== $result['old_path']; if ( ! get_option( 'permalink_structure' ) ) { $result = self::add( $result, 'info', 'plain_permalinks', __( 'Plain permalinks are active, so the URL does not change and no redirect is needed.', 'slugh' ) ); } $result = self::check_path_collisions( $result, $post ); $public_statuses = Settings::get( 'redirect_private_posts', false ) ? array( 'publish', 'private' ) : array( 'publish' ); $result['creates_redirect'] = $result['url_changes'] && in_array( $post->post_status, $public_statuses, true ) && Settings::slugh_owns_redirects(); if ( $result['url_changes'] && ! in_array( $post->post_status, $public_statuses, true ) ) { $result = self::add( $result, 'info', 'no_redirect_status', __( 'No redirect will be created because this record has no public URL yet.', 'slugh' ) ); } if ( $result['url_changes'] ) { $result = self::check_redirect_conflicts( $result ); } if ( function_exists( 'wp_check_post_lock' ) || self::load_post_admin() ) { $lock_user = wp_check_post_lock( $post->ID ); if ( $lock_user ) { $user = get_userdata( $lock_user ); $result = self::add( $result, self::STATE_WARNING, 'edit_lock', sprintf( /* translators: %s: user display name */ __( '%s is editing this record right now.', 'slugh' ), $user ? $user->display_name : __( 'Another user', 'slugh' ) ) ); } } if ( $result['url_changes'] && is_post_type_hierarchical( $post->post_type ) ) { $descendants = DescendantPropagator::get_descendants( $post->ID ); if ( ! empty( $descendants ) ) { $result['descendants'] = count( $descendants ); $result['descendant_samples'] = DescendantPropagator::predict_samples( $descendants, $result['old_permalink'], $result['predicted_permalink'], 5 ); $result = self::add( $result, self::STATE_WARNING, 'descendants', sprintf( /* translators: %d: number of descendants */ _n( '%d descendant URL will change and get its own redirect.', '%d descendant URLs will change and get their own redirects.', count( $descendants ), 'slugh' ), count( $descendants ) ), true ); } } return self::finish( $result ); } /** * Encoded length of a slug before WordPress truncates it. * * WordPress: sanitize_title() cuts the percent-encoded result at 200 characters without telling anyone, so its * output can never be measured. Sanitizing short pieces and joining them gives the untruncated length. * * @param string $input Candidate (decoded). * @return int */ public static function full_encoded_length( $input ) { $parts = preg_split( '/[\s\-]+/u', (string) $input, -1, PREG_SPLIT_NO_EMPTY ); $encoded = array(); foreach ( (array) $parts as $part ) { $piece = ''; foreach ( Normalizer::split( $part, 20 ) as $chunk ) { $piece .= sanitize_title( $chunk ); } if ( '' !== $piece ) { $encoded[] = $piece; } } return strlen( preg_replace( '/-{2,}/', '-', implode( '-', $encoded ) ) ); } /** * Detect another record, term archive or author archive at the predicted path. * * @param array $result Result so far. * @param \WP_Post $post Post. * @return array */ private static function check_path_collisions( array $result, \WP_Post $post ) { global $wpdb; if ( ! $result['url_changes'] ) { return $result; } $slug = $result['predicted_slug']; // Drafts and pending posts have no public URL yet; WordPress may add a suffix when they are published. $level = in_array( $post->post_status, array( 'draft', 'pending' ), true ) ? self::STATE_WARNING : self::STATE_ERROR; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $others = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_name = %s AND ID != %d AND post_status = 'publish' AND post_type NOT IN ('revision','nav_menu_item','attachment') LIMIT 20", $slug, $post->ID ) ); foreach ( (array) $others as $other_id ) { if ( Normalizer::normalize_path( (string) get_permalink( (int) $other_id ) ) === $result['new_path'] ) { return self::add( $result, $level, 'path_collision', sprintf( /* translators: 1: post ID, 2: post type */ __( 'Record #%1$d (%2$s) is already published at this URL.', 'slugh' ), (int) $other_id, get_post_type( (int) $other_id ) ) ); } } $terms = get_terms( array( 'slug' => array( $slug ), 'hide_empty' => false, 'number' => 10, ) ); if ( ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { $link = get_term_link( $term ); if ( ! is_wp_error( $link ) && Normalizer::normalize_path( $link ) === $result['new_path'] ) { return self::add( $result, $level, 'term_collision', /* translators: %s: taxonomy */ sprintf( __( 'A "%s" term archive already uses this URL.', 'slugh' ), $term->taxonomy ) ); } } } $user = get_user_by( 'slug', $slug ); if ( $user && Normalizer::normalize_path( get_author_posts_url( $user->ID ) ) === $result['new_path'] ) { return self::add( $result, $level, 'author_collision', __( 'An author archive already uses this URL.', 'slugh' ) ); } return $result; } /** * Detect enabled redirects at the old or new path and loops through them. * * @param array $result Result so far. * @return array */ private static function check_redirect_conflicts( array $result ) { $at_new = RedirectRepository::find_by_source( $result['new_path'] ); if ( $at_new && (int) $at_new->enabled ) { $loop = LoopDetector::check_loop( $result['old_path'], $result['new_path'] ); $result['conflicts'][] = array( 'type' => 'new_path', 'redirect_id' => (int) $at_new->id, 'destination' => $at_new->destination, 'loop' => $loop['is_loop'], ); $result = self::add( $result, self::STATE_CONFLICT, 'redirect_at_new', sprintf( /* translators: 1: redirect ID, 2: destination */ __( 'Redirect #%1$d already sends the new URL to %2$s. Choose "replace" to disable it, "keep" to leave it, or skip this item.', 'slugh' ), (int) $at_new->id, $at_new->destination ) . ( $loop['is_loop'] ? ' ' . sprintf( /* translators: %s: loop path */ __( 'Keeping it would create a loop (%s), so only "replace" or "skip" can be used.', 'slugh' ), implode( ' → ', $loop['path'] ) ) : '' ) ); } if ( $result['creates_redirect'] ) { $at_old = RedirectRepository::find_by_source( $result['old_path'] ); if ( $at_old && (int) $at_old->enabled ) { $result['conflicts'][] = array( 'type' => 'old_path', 'redirect_id' => (int) $at_old->id, 'destination' => $at_old->destination, 'loop' => false, ); $result = self::add( $result, self::STATE_CONFLICT, 'redirect_at_old', sprintf( /* translators: 1: redirect ID, 2: destination */ __( 'Redirect #%1$d already sends the old URL to %2$s. Choose "replace" to point it at the new URL, "keep" to leave it, or skip this item.', 'slugh' ), (int) $at_old->id, $at_old->destination ) ); } } return $result; } /** * Predict the permalink a record will have with a new slug. * * @param \WP_Post $post Post. * @param string $slug Predicted stored slug. * @return string */ public static function predict_permalink( \WP_Post $post, $slug ) { $clone = clone $post; $clone->post_name = $slug; if ( in_array( $clone->post_status, array( 'draft', 'pending', 'auto-draft', 'future' ), true ) ) { $clone->filter = 'sample'; if ( '0000-00-00 00:00:00' === $clone->post_date_gmt ) { $clone->post_date = current_time( 'mysql' ); } } return (string) get_permalink( $clone ); } /** * Find a published record of the same type (and parent, if hierarchical) using a slug. * * @param \WP_Post $post Post. * @param string $slug Sanitized slug. * @return int Post ID or 0. */ private static function find_published_with_slug( \WP_Post $post, $slug ) { global $wpdb; if ( is_post_type_hierarchical( $post->post_type ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return (int) $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_name = %s AND post_type = %s AND post_parent = %d AND post_status = 'publish' AND ID != %d LIMIT 1", $slug, $post->post_type, $post->post_parent, $post->ID ) ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return (int) $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_name = %s AND post_type = %s AND post_status = 'publish' AND ID != %d LIMIT 1", $slug, $post->post_type, $post->ID ) ); } /** * Reserved slugs: the fixed list plus registered feed names. * * @return string[] */ public static function reserved_slugs() { global $wp_rewrite; $feeds = ( $wp_rewrite && is_array( $wp_rewrite->feeds ) ) ? $wp_rewrite->feeds : array(); return array_unique( array_merge( self::RESERVED_ENDPOINTS, $feeds ) ); } /** * Form used to compare slugs that may be decoded or percent-encoded. * * @param string $slug Slug. * @return string */ public static function compare_form( $slug ) { $decoded = rawurldecode( trim( (string) $slug ) ); if ( class_exists( '\Normalizer' ) ) { $nfc = \Normalizer::normalize( $decoded, \Normalizer::FORM_C ); $decoded = false === $nfc ? $decoded : $nfc; } return Normalizer::lower( $decoded ); } /** * Load wp-admin post helpers for wp_check_post_lock() outside the admin. * * @return bool */ private static function load_post_admin() { if ( ! function_exists( 'wp_check_post_lock' ) && file_exists( ABSPATH . 'wp-admin/includes/post.php' ) ) { require_once ABSPATH . 'wp-admin/includes/post.php'; } return function_exists( 'wp_check_post_lock' ); } /** * Add a message and raise the state. * * @param array $result Result. * @param string $level ok|info|warning|conflict|stale|error. * @param string $code Message code. * @param string $text Message. * @param bool $needs_confirmation Whether the item needs explicit confirmation. * @return array */ private static function add( array $result, $level, $code, $text, $needs_confirmation = false ) { $result['messages'][] = array( 'level' => $level, 'code' => $code, 'text' => $text, ); $rank = array( self::STATE_OK => 0, 'info' => 0, self::STATE_WARNING => 1, self::STATE_CONFLICT => 2, self::STATE_STALE => 3, self::STATE_ERROR => 4, ); if ( isset( $rank[ $level ] ) && $rank[ $level ] > $rank[ $result['state'] ] ) { $result['state'] = $level; } if ( $needs_confirmation || self::STATE_CONFLICT === $level ) { $result['needs_confirmation'] = true; } if ( self::STATE_ERROR === $level || self::STATE_STALE === $level ) { $result['errors'][] = $text; } elseif ( self::STATE_WARNING === $level || self::STATE_CONFLICT === $level ) { $result['warnings'][] = $text; } return $result; } /** * Finalize derived flags. * * @param array $result Result. * @return array */ private static function finish( array $result ) { $result['is_valid'] = ! in_array( $result['state'], array( self::STATE_ERROR, self::STATE_STALE ), true ); return $result; } }