[method, capability]. * * @return array */ private function actions() { return array( 'slugh_export_records' => array( 'export_records', Capabilities::CAP_VIEW ), 'slugh_export_scan' => array( 'export_scan', Capabilities::CAP_VIEW ), 'slugh_export_template' => array( 'export_template', Capabilities::CAP_VIEW ), 'slugh_export_redirects' => array( 'export_redirects', Capabilities::CAP_VIEW ), 'slugh_export_job' => array( 'export_job', Capabilities::CAP_VIEW ), 'slugh_export_audit' => array( 'export_audit', Capabilities::CAP_VIEW ), 'slugh_purge_audit' => array( 'purge_audit', Capabilities::CAP_MANAGE_SETTINGS ), 'slugh_import_slugs' => array( 'import_slugs', Capabilities::CAP_EDIT_SLUGS ), 'slugh_import_redirects' => array( 'import_redirects', Capabilities::CAP_MANAGE_REDIRECTS ), 'slugh_save_redirect' => array( 'save_redirect', Capabilities::CAP_MANAGE_REDIRECTS ), 'slugh_redirect_bulk' => array( 'redirect_bulk', Capabilities::CAP_MANAGE_REDIRECTS ), 'slugh_save_settings' => array( 'save_settings', Capabilities::CAP_MANAGE_SETTINGS ), 'slugh_run_migrations' => array( 'run_migrations', Capabilities::CAP_MANAGE_SETTINGS ), 'slugh_editor_bulk' => array( 'editor_bulk', Capabilities::CAP_EDIT_SLUGS ), ); } /** * Register handlers. * * @return void */ public function register() { foreach ( $this->actions() as $action => $def ) { add_action( 'admin_post_' . $action, function () use ( $action, $def ) { if ( ! current_user_can( $def[1] ) ) { wp_die( esc_html__( 'You do not have permission to do this.', 'slugh' ), 403 ); } check_admin_referer( $action ); $this->{$def[0]}(); } ); } } /** * Read a request value, sanitized as plain text (arrays element by element). * * Callers still cast or narrow the value (absint(), sanitize_key(), ...) for the field they need. * * @param string $key Key. * @param mixed $fallback Default. * @return mixed */ private function param( $key, $fallback = '' ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing -- Nonce checked in register(). if ( ! isset( $_REQUEST[ $key ] ) ) { return $fallback; } // phpcs:disable WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing -- Nonce checked in register(). if ( is_array( $_REQUEST[ $key ] ) ) { return array_map( 'sanitize_text_field', wp_unslash( $_REQUEST[ $key ] ) ); } return sanitize_text_field( wp_unslash( $_REQUEST[ $key ] ) ); // phpcs:enable } /** * Read a request value that must be a single piece of text. An array (for example key[]=x) gives the fallback. * * @param string $key Key. * @param string $fallback Default. * @return string */ private function text( $key, $fallback = '' ) { $value = $this->param( $key, $fallback ); return is_scalar( $value ) ? (string) $value : (string) $fallback; } /** * Read a redirect source or destination from the request. * * Paths go through the path sanitizer because the plain-text sanitizer would strip percent-encoded octets. * * @param string $key Key. * @return string */ private function path_param( $key ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing -- Nonce checked in register(). if ( ! isset( $_REQUEST[ $key ] ) || ! is_string( $_REQUEST[ $key ] ) ) { return ''; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce checked in register(); sanitized by Sanitizer::path_input(). return Sanitizer::path_input( wp_unslash( $_REQUEST[ $key ] ) ); } /** * Read the uploaded CSV from $_FILES, keeping only the sanitized fields that are used. * * @return array{name: string, tmp_name: string, size: int, error: int}|null Null when no file was sent. */ private function uploaded_csv() { // phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce checked in register(). if ( ! isset( $_FILES['slugh_csv']['tmp_name'] ) || ! is_string( $_FILES['slugh_csv']['tmp_name'] ) ) { return null; } // The temporary path is checked with is_uploaded_file() in CsvHandler::validate_upload(). $file = array( 'name' => isset( $_FILES['slugh_csv']['name'] ) && is_string( $_FILES['slugh_csv']['name'] ) ? sanitize_file_name( $_FILES['slugh_csv']['name'] ) : '', 'tmp_name' => sanitize_text_field( $_FILES['slugh_csv']['tmp_name'] ), 'size' => isset( $_FILES['slugh_csv']['size'] ) ? absint( $_FILES['slugh_csv']['size'] ) : 0, 'error' => isset( $_FILES['slugh_csv']['error'] ) ? absint( $_FILES['slugh_csv']['error'] ) : UPLOAD_ERR_NO_FILE, ); // phpcs:enable return $file; } /** * Redirect back to a SlugH screen. * * @param string $page Page slug. * @param array $args Query args. * @return void */ private function back( $page, array $args = array() ) { wp_safe_redirect( add_query_arg( array_merge( array( 'page' => $page ), $args ), admin_url( 'admin.php' ) ) ); exit; } /** * Export records and current slugs in the import format (new_slug empty): filtered view or everything. * * @return void */ private function export_records() { global $wpdb; $all = 'all' === $this->param( 'scope' ); $types = $all ? PostTypes::get_enabled() : PostTypes::filter_types( sanitize_key( $this->text( 'post_type' ) ) ); $statuses = $all ? PostTypes::get_enabled_statuses() : PostTypes::filter_statuses( sanitize_key( $this->text( 'post_status' ) ) ); $search = $all ? '' : sanitize_text_field( $this->text( 's' ) ); $rows = array(); $last_id = 0; do { $sql = 'SELECT ID, post_type, post_name FROM %i WHERE ID > %d' . ' AND post_type IN (' . implode( ',', array_fill( 0, count( $types ), '%s' ) ) . ')' . ' AND post_status IN (' . implode( ',', array_fill( 0, count( $statuses ), '%s' ) ) . ')'; $binds = array_merge( array( $wpdb->posts, $last_id ), $types, $statuses ); if ( '' !== $search ) { $sql .= ' AND (post_title LIKE %s OR post_name LIKE %s)'; $binds[] = '%' . $wpdb->esc_like( $search ) . '%'; $binds[] = '%' . $wpdb->esc_like( sanitize_title( $search ) ) . '%'; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Placeholders are built to match $binds; every value is bound by prepare(). $batch = $wpdb->get_results( $wpdb->prepare( $sql . ' ORDER BY ID ASC LIMIT 1000', $binds ) ); foreach ( (array) $batch as $row ) { $last_id = (int) $row->ID; if ( current_user_can( 'edit_post', $row->ID ) ) { $rows[] = array( $row->ID, $row->post_type, rawurldecode( $row->post_name ), '' ); } } $batch_size = count( (array) $batch ); } while ( 1000 === $batch_size ); CsvHandler::send_download( 'slugh-records-' . gmdate( 'Ymd-His' ) . '.csv', array( 'content_id', 'post_type', 'old_slug', 'new_slug' ), $rows ); } /** * Export scan results (filtered) in the import format plus flags. * * @return void */ private function export_scan() { $scan_id = absint( $this->param( 'scan_id' ) ); $scan_id = $scan_id ? $scan_id : (int) Scanner::get_latest_scan_id(); $filters = array( 'post_type' => sanitize_key( $this->text( 'post_type' ) ), 'post_status' => sanitize_key( $this->text( 'post_status' ) ), 'flags' => array_map( 'absint', (array) $this->param( 'flags', array() ) ), 'search' => sanitize_text_field( $this->text( 's' ) ), 'issues_only' => (bool) $this->param( 'issues_only' ), 'per_page' => 500, ); $labels = Flags::get_labels(); $rows = array(); $page = 1; do { $filters['page'] = $page; $result = Scanner::query_results( $scan_id, $filters ); foreach ( $result['items'] as $item ) { $names = array(); foreach ( $labels as $flag => $label ) { if ( Flags::has( $item->flags, $flag ) ) { $names[] = $label; } } $rows[] = array( $item->post_id, $item->post_type, $item->decoded_slug, '', $item->post_status, implode( '; ', $names ) ); } ++$page; $page_size = count( $result['items'] ); } while ( 500 === $page_size ); CsvHandler::send_download( 'slugh-scan-' . $scan_id . '.csv', array( 'content_id', 'post_type', 'old_slug', 'new_slug', 'status', 'flags' ), $rows ); } /** * Download a CSV template. * * @return void */ private function export_template() { $files = array( 'slugs' => 'slug-import-template.csv', 'redirects' => 'redirect-import-template.csv', 'example' => 'example-redirects.csv', ); $which = sanitize_key( $this->text( 'template' ) ); $file = isset( $files[ $which ] ) ? $files[ $which ] : $files['slugs']; $path = SLUGH_PATH . 'templates/' . $file; nocache_headers(); header( 'Content-Type: text/csv; charset=utf-8' ); header( 'Content-Disposition: attachment; filename="' . $file . '"' ); readfile( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile exit; } /** * Export redirects (all, or a job's). * * @return void */ private function export_redirects() { $job_id = absint( $this->param( 'job_id' ) ); if ( ! $job_id && ! current_user_can( Capabilities::CAP_MANAGE_REDIRECTS ) ) { wp_die( esc_html__( 'You do not have permission to export all redirects.', 'slugh' ), 403 ); } $rows = array(); foreach ( RedirectRepository::export_rows( $job_id ) as $r ) { $rows[] = array( $r->source_path, $r->destination, $r->status_code, $r->enabled, $r->match_mode, $r->origin, $r->post_id, $r->job_id, $r->hits, $r->last_hit_at, $r->source_raw ); } CsvHandler::send_download( $job_id ? 'slugh-job-' . $job_id . '-redirects.csv' : 'slugh-redirects-' . gmdate( 'Ymd-His' ) . '.csv', array( 'source', 'destination', 'status', 'enabled', 'match_mode', 'origin', 'post_id', 'job_id', 'hits', 'last_hit_at', 'source_raw' ), $rows ); } /** * Export a job's before/after state. * * @return void */ private function export_job() { $job_id = absint( $this->param( 'job_id' ) ); $rows = array(); foreach ( JobRepository::get_items( $job_id ) as $item ) { $rows[] = array( $item->post_id, $item->post_type, $item->kind, rawurldecode( $item->old_post_name ), rawurldecode( (string) ( $item->actual_post_name ? $item->actual_post_name : $item->requested_post_name ) ), $item->old_permalink, $item->actual_permalink ? $item->actual_permalink : $item->expected_permalink, $item->result, isset( $item->message['reason'] ) ? $item->message['reason'] : '', ); } CsvHandler::send_download( 'slugh-job-' . $job_id . '-before-after.csv', array( 'content_id', 'post_type', 'kind', 'old_slug', 'new_slug', 'old_permalink', 'new_permalink', 'result', 'reason' ), $rows ); } /** * Export the audit log (optionally only entries older than N days). * * @return void */ private function export_audit() { $days = absint( $this->param( 'days' ) ); $before = $days ? gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS ) : ''; $rows = array(); foreach ( AuditLogger::export_rows( $before ) as $row ) { $rows[] = array( $row->id, $row->created_at, $row->event, $row->object_type, $row->object_id, $row->job_id, $row->user_id, $row->before_value, $row->after_value ); } CsvHandler::send_download( 'slugh-audit-log-' . gmdate( 'Ymd-His' ) . '.csv', array( 'id', 'created_at_gmt', 'event', 'object_type', 'object_id', 'job_id', 'user_id', 'before', 'after' ), $rows ); } /** * Purge audit entries older than N days: explicit administrator action after an export was offered. * * @return void */ private function purge_audit() { $days = absint( $this->param( 'days' ) ); if ( $days < 30 || ! $this->param( 'confirm_exported' ) ) { Notices::add( __( 'Nothing was purged. Choose at least 30 days and confirm that you exported the entries first.', 'slugh' ), 'error' ); $this->back( 'slugh-history', array( 'tab' => 'audit' ) ); } $deleted = AuditLogger::purge_before( gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS ) ); /* translators: %d: number of entries */ Notices::add( sprintf( _n( 'Purged %d audit entry.', 'Purged %d audit entries.', $deleted, 'slugh' ), $deleted ) ); $this->back( 'slugh-history', array( 'tab' => 'audit' ) ); } /** * CSV slug import → draft import job → review page. * * @return void */ private function import_slugs() { $file = $this->uploaded_csv(); $path = CsvHandler::validate_upload( $file ); if ( is_wp_error( $path ) ) { Notices::add( $path->get_error_message(), 'error' ); $this->back( 'slugh-import-export' ); } $parsed = CsvHandler::parse_file( $path ); if ( is_wp_error( $parsed ) ) { Notices::add( $parsed->get_error_message(), 'error' ); $this->back( 'slugh-import-export' ); } $report = DraftManager::import_csv( $parsed, $file['name'] ); if ( is_wp_error( $report ) ) { Notices::add( $report->get_error_message(), 'error' ); $this->back( 'slugh-import-export' ); } $details = array(); foreach ( array_slice( $report['errors'], 0, 200 ) as $error ) { /* translators: 1: line number, 2: reason */ $details[] = sprintf( __( 'Line %1$d: %2$s', 'slugh' ), $error['line'], $error['reason'] ); } Notices::add( sprintf( /* translators: 1: rows added, 2: invalid rows, 3: rows with empty new_slug, 4: unchanged rows */ __( 'Import draft created: %1$d rows ready for preview, %2$d invalid, %3$d with an empty new_slug skipped, %4$d unchanged. Nothing has been applied yet.', 'slugh' ), $report['added'], count( $report['errors'] ), $report['skipped_empty'], $report['unchanged'] ), empty( $report['errors'] ) ? 'success' : 'warning', $details ); if ( $report['added'] > 0 ) { $this->back( 'slugh-history', array( 'job' => $report['job_id'] ) ); } $this->back( 'slugh-import-export' ); } /** * Redirect CSV import: source,destination,status,enabled,match_mode. * * @return void */ private function import_redirects() { $file = $this->uploaded_csv(); $path = CsvHandler::validate_upload( $file ); if ( is_wp_error( $path ) ) { Notices::add( $path->get_error_message(), 'error' ); $this->back( 'slugh-redirects' ); } $parsed = CsvHandler::parse_file( $path ); if ( is_wp_error( $parsed ) ) { Notices::add( $parsed->get_error_message(), 'error' ); $this->back( 'slugh-redirects' ); } $missing = array_diff( array( 'source', 'destination' ), $parsed['headers'] ); if ( ! empty( $missing ) ) { /* translators: %s: column names */ Notices::add( sprintf( __( 'The file is missing required columns: %s. Nothing was imported.', 'slugh' ), implode( ', ', $missing ) ), 'error' ); $this->back( 'slugh-redirects' ); } $replace = (bool) $this->param( 'replace_existing' ); $counts = array( 'created' => 0, 'reenabled' => 0, 'replaced' => 0, ); $errors = array(); foreach ( $parsed['rows'] as $row ) { $data = $row['data']; $result = RedirectRepository::create( array( 'source' => Sanitizer::path_input( $data['source'] ), 'destination' => Sanitizer::path_input( $data['destination'] ), 'status_code' => isset( $data['status'] ) && '' !== $data['status'] ? absint( $data['status'] ) : 301, 'enabled' => ! isset( $data['enabled'] ) || '' === $data['enabled'] ? true : (bool) absint( $data['enabled'] ), 'match_mode' => isset( $data['match_mode'] ) && '' !== $data['match_mode'] ? sanitize_key( $data['match_mode'] ) : '404_only', 'origin' => 'import', 'on_conflict' => $replace ? 'replace' : 'error', ) ); if ( is_wp_error( $result ) ) { /* translators: 1: line number, 2: reason */ $errors[] = sprintf( __( 'Line %1$d: %2$s', 'slugh' ), $row['line'], $result->get_error_message() ); } elseif ( isset( $counts[ $result['action'] ] ) ) { ++$counts[ $result['action'] ]; } } AuditLogger::log( 'import', 'redirect', 0, array( 'filename' => $file['name'] ), array_merge( $counts, array( 'invalid' => count( $errors ) ) ) ); Notices::add( sprintf( /* translators: 1: created, 2: re-enabled, 3: replaced, 4: rejected */ __( 'Redirect import finished: %1$d created, %2$d re-enabled, %3$d replaced, %4$d rejected. Run "Check chains and loops" if the file contained chains.', 'slugh' ), $counts['created'], $counts['reenabled'], $counts['replaced'], count( $errors ) ), empty( $errors ) ? 'success' : 'warning', $errors ); $this->back( 'slugh-redirects' ); } /** * Add or edit a redirect from the Redirects screen form. * * @return void */ private function save_redirect() { $id = absint( $this->param( 'redirect_id' ) ); $fields = array( 'source' => $this->path_param( 'source' ), 'destination' => $this->path_param( 'destination' ), 'status_code' => absint( $this->param( 'status_code', 301 ) ), 'match_mode' => sanitize_key( $this->text( 'match_mode', '404_only' ) ), 'enabled' => (bool) $this->param( 'enabled' ), ); if ( $id ) { $result = RedirectRepository::update( $id, $fields ); } else { $fields['origin'] = 'manual'; $fields['on_conflict'] = $this->param( 'replace_existing' ) ? 'replace' : 'error'; $result = RedirectRepository::create( $fields ); } if ( is_wp_error( $result ) ) { Notices::add( $result->get_error_message(), 'error' ); $this->back( 'slugh-redirects', $id ? array( 'edit' => $id ) : array() ); } Notices::add( $id ? __( 'Redirect updated.', 'slugh' ) : __( 'Redirect saved.', 'slugh' ) ); $this->back( 'slugh-redirects' ); } /** * Enable, disable or delete redirects (row or bulk). * * @return void */ private function redirect_bulk() { $action = sanitize_key( $this->text( 'bulk_action' ) ); if ( '-1' === $action || '' === $action ) { $action = sanitize_key( $this->text( 'bulk_action2' ) ); } $ids = array_filter( array_map( 'absint', (array) $this->param( 'redirect_ids', array() ) ) ); if ( $this->param( 'redirect_id' ) ) { $ids[] = absint( $this->param( 'redirect_id' ) ); } $done = 0; $errors = array(); foreach ( array_unique( $ids ) as $id ) { if ( 'delete' === $action ) { $ok = RedirectRepository::delete( $id ); } elseif ( in_array( $action, array( 'enable', 'disable' ), true ) ) { $ok = RedirectRepository::set_enabled( $id, 'enable' === $action ); } else { continue; } if ( is_wp_error( $ok ) ) { $errors[] = '#' . $id . ': ' . $ok->get_error_message(); } elseif ( $ok ) { ++$done; } } /* translators: 1: number of redirects, 2: action */ Notices::add( sprintf( __( '%1$d redirect(s) updated (%2$s).', 'slugh' ), $done, $action ), empty( $errors ) ? 'success' : 'warning', $errors ); $this->back( 'slugh-redirects' ); } /** * Save settings. * * @return void */ private function save_settings() { $mode = sanitize_key( $this->text( 'redirect_ownership_mode', Settings::MODE_SLUGH ) ); $current = Settings::get( 'redirect_ownership_mode' ); if ( Settings::MODE_SEO_PLUGIN === $mode && ! ConflictDetector::seo_redirects_available() ) { Notices::add( __( '"Hand off to the SEO plugin" needs Rank Math or Yoast SEO Premium with its redirect feature enabled. The ownership mode was not changed.', 'slugh' ), 'error' ); $mode = $current; } if ( Settings::MODE_SLUG_ONLY === $mode && Settings::MODE_SLUG_ONLY !== $current && ! $this->param( 'confirm_slug_only' ) ) { Notices::add( __( '"Slug only, no redirects" was not selected: tick the box confirming that old URLs will return 404.', 'slugh' ), 'error' ); $mode = $current; } $excluded = preg_split( '/[\s,]+/', $this->text( 'integrity_excluded_meta' ) ); Settings::update_all( array( 'supported_post_types' => array_map( 'sanitize_key', (array) $this->param( 'supported_post_types', array() ) ), 'supported_post_statuses' => array_map( 'sanitize_key', (array) $this->param( 'supported_post_statuses', array() ) ), 'redirect_ownership_mode' => $mode, 'redirect_private_posts' => (bool) $this->param( 'redirect_private_posts' ), 'rollback_reverse_redirect' => (bool) $this->param( 'rollback_reverse_redirect' ), 'preserve_modified_date' => (bool) $this->param( 'preserve_modified_date' ), 'woocommerce_enabled' => (bool) $this->param( 'woocommerce_enabled' ), 'trial_mode' => (bool) $this->param( 'trial_mode' ), 'allow_external_destinations' => (bool) $this->param( 'allow_external_destinations' ), 'integrity_excluded_meta' => array_filter( array_map( 'sanitize_text_field', (array) $excluded ) ), 'scan_batch_size' => absint( $this->param( 'scan_batch_size', 500 ) ), 'job_batch_size' => absint( $this->param( 'job_batch_size', 25 ) ), 'delete_data_on_uninstall' => (bool) $this->param( 'delete_data_on_uninstall' ), ) ); Notices::add( __( 'Settings saved. Changing the ownership mode never deletes existing redirects.', 'slugh' ) ); $this->back( 'slugh-settings' ); } /** * Run pending migrations. * * @return void */ private function run_migrations() { Migrations::run(); AuditLogger::log( 'migrations_run', 'settings', 0, null, array( 'db_version' => get_option( 'slugh_db_version' ) ) ); Notices::add( __( 'Migrations checked; the schema is up to date.', 'slugh' ) ); $this->back( 'slugh-diagnostics' ); } /** * Slug Editor bulk actions on checked rows. * * @return void */ private function editor_bulk() { $action = sanitize_key( $this->text( 'bulk_action' ) ); if ( '-1' === $action || '' === $action ) { $action = sanitize_key( $this->text( 'bulk_action2' ) ); } $ids = array_filter( array_map( 'absint', (array) $this->param( 'post_ids', array() ) ) ); $job_id = DraftManager::get_editor_draft( true ); $done = 0; foreach ( $ids as $post_id ) { if ( 'suggest' === $action ) { $post = get_post( $post_id ); if ( ! $post ) { continue; } $suggestion = RulesSuggester::instance()->suggest( rawurldecode( $post->post_name ), $post ); $result = DraftManager::upsert_item( $job_id, $post_id, $suggestion ); if ( in_array( $result['status'], array( 'added', 'updated' ), true ) ) { ++$done; } } elseif ( 'remove' === $action && DraftManager::remove_item( $job_id, $post_id ) ) { ++$done; } } /* translators: %d: number of rows */ Notices::add( sprintf( __( '%d row(s) updated in the draft. Nothing is applied until you preview and confirm.', 'slugh' ), $done ) ); wp_safe_redirect( wp_get_referer() ? wp_get_referer() : admin_url( 'admin.php?page=slugh-editor' ) ); exit; } }