Plugin Directory

Changeset 3814912


Ignore:
Timestamp:
11/21/2026 07:19:29 AM (23 hours ago)
Author:
habibhq
Message:

Release 2.0.0

Location:
slugh
Files:
26 added
62 edited
1 copied

Legend:

Unmodified
Added
Removed
  • slugh/tags/2.0.0/assets/js/slugh-admin.js

    r3795795 r3814912  
    109109                var reviewBtn = $( '#slugh-review' );
    110110                var dupWarning = $( '#slugh-dup-warning' );
    111                 var draftOthers = {}; // post_id => key, for draft items not on this page.
     111                var draftOthers = {}; // row key ("123" for a post, "t123" for a term) => duplicate key, for draft items.
    112112                var inputs = $$( '.slugh-slug-input' );
    113113                var onPage = {};
    … …  
    115115                var locked = false;
    116116
     117                // Posts and terms can share an ID, so rows are keyed by object type too.
     118                function rowKey( objectType, id ) {
     119                        return ( 'term' === objectType ? 't' : '' ) + String( id );
     120                }
     121                function inputKey( input ) {
     122                        return rowKey( input.dataset.objectType, input.dataset.postId );
     123                }
     124
    117125                inputs.forEach( function ( input ) {
    118                         onPage[ input.dataset.postId ] = input;
     126                        onPage[ inputKey( input ) ] = input;
    119127                } );
    120128
    … …  
    173181                                }
    174182                                var key = input.dataset.keyPrefix + norm( input.value );
    175                                 keys[ key ] = ( keys[ key ] || [] ).concat( [ input.dataset.postId ] );
     183                                keys[ key ] = ( keys[ key ] || [] ).concat( [ inputKey( input ) ] );
    176184                        } );
    177185
    … …  
    189197                        inputs.forEach( function ( input ) {
    190198                                var row = rowOf( input );
    191                                 var dup = !! dupIds[ input.dataset.postId ];
     199                                var dup = !! dupIds[ inputKey( input ) ];
    192200                                row.classList.toggle( 'slugh-duplicate', dup );
    193201                                input.setAttribute( 'aria-invalid', dup ? 'true' : 'false' );
    … …  
    202210                                        __( 'Duplicate new slugs in this draft (records %s). Resolve them before applying.', 'slugh' ),
    203211                                        groups.map( function ( g ) {
    204                                                 return '#' + g.join( ', #' );
     212                                                return g.map( function ( k ) {
     213                                                        return 't' === k.charAt( 0 ) ? sprintf( __( 'term #%s', 'slugh' ), k.slice( 1 ) ) : '#' + k;
     214                                                } ).join( ', ' );
    205215                                        } ).join( '; ' )
    206216                                );
    … …  
    245255                        }
    246256                        var items = list.map( function ( input ) {
    247                                 return { post_id: parseInt( input.dataset.postId, 10 ), new_slug: input.value };
     257                                return { post_id: parseInt( input.dataset.postId, 10 ), object_type: input.dataset.objectType || 'post', new_slug: input.value };
    248258                        } );
    249259                        return post( 'drafts/items', { items: items } ).then( function ( response ) {
    … …  
    255265                                }
    256266                                response.results.forEach( function ( res ) {
    257                                         var input = onPage[ res.post_id ];
     267                                        var resKey = rowKey( res.object_type, res.post_id );
     268                                        var input = onPage[ resKey ];
    258269                                        if ( ! input ) {
    259270                                                return;
    … …  
    269280                                                input.value = res.item.new_slug;
    270281                                                input.dataset.saved = res.item.new_slug;
    271                                                 draftOthers[ res.post_id ] = res.item.key;
     282                                                draftOthers[ resKey ] = res.item.key;
    272283                                                row.classList.add( 'slugh-in-draft' );
    273284                                        } else {
    274285                                                input.dataset.saved = input.value;
    275                                                 delete draftOthers[ res.post_id ];
     286                                                delete draftOthers[ resKey ];
    276287                                                row.classList.remove( 'slugh-in-draft' );
    277288                                        }
    … …  
    461472                api( 'drafts' ).then( function ( draft ) {
    462473                        ( draft.items || [] ).forEach( function ( item ) {
    463                                 draftOthers[ item.post_id ] = item.key;
     474                                draftOthers[ rowKey( item.object_type, item.post_id ) ] = item.key;
    464475                        } );
    465476                        inputs.forEach( updateRow );
    … …  
    747758                if ( all ) {
    748759                        all.addEventListener( 'change', function () {
    749                                 $$( 'input[name="post_ids[]"]' ).forEach( function ( box ) {
     760                                $$( 'input[name="post_ids[]"], input[name="term_ids[]"]' ).forEach( function ( box ) {
    750761                                        box.checked = all.checked;
    751762                                } );
  • slugh/tags/2.0.0/readme.txt

    r3795795 r3814912  
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 1.0.7
     7Stable tag: 2.0.0
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    1010
    11 Find, edit and bulk-update post slugs with safe 301 redirects.
     11Find, edit and bulk-update post, page and category slugs with safe 301 redirects.
    1212
    1313== Description ==
    … …  
    4141Product slugs use the same engine when WooCommerce is active. SKUs, prices, stock, attributes, variations and categories are covered by the integrity check and are never changed. slugH declares compatibility with High-Performance Order Storage and never touches orders.
    4242
     43= Latin slug suggestions (optional) =
     44
     45Turn on **Settings → Slug suggestions → Transliteration** to get a Latin spelling suggested for each slug in another script. Bangla uses slugH's own phonetic rules (আমার সোনার বাংলা → amar-sonar-bangla); other scripts use the PHP intl extension when the server has it. Suggestions are never applied on their own: you review and edit them in the preview first.
     46
     47= WP-CLI =
     48
     49Scan, paste or import slug changes, preview, apply, roll back and manage redirects from the command line: `wp slugh scan`, `wp slugh results`, `wp slugh paste`, `wp slugh import`, `wp slugh job preview|apply|rollback`, `wp slugh redirect add|import|list|test|check`. The commands use the same preview, checks, redirects and audit log as the admin screens. Run them with `--user=<administrator>`; see `wp help slugh`.
     50
    4351= Privacy =
    4452
    … …  
    6775Saving a post runs WordPress content filters. For users without the unfiltered_html capability those filters can strip embeds or scripts from content nobody edited, so slugH blocks slug changes for those users and explains why.
    6876
    69 = Does slugH support multisite or WPML/Polylang? =
     77= Can slugH change media (attachment) slugs? =
    7078
    71 Not in version 1. slugH runs on single sites only and blocks network activation. Multilingual plugins have not been tested.
     79Yes, from version 2.0. Tick "Media" under Post types in slugH Settings. If WordPress attachment pages are on, slugH redirects changed attachment URLs, including media attached to a post or page whose URL changes. If they are off (the default on sites installed with WordPress 6.4 or later), attachment URLs already lead to the file, so slugH changes the slug without creating redirects. Media files themselves are never renamed.
     80
     81= Can slugH change category and tag slugs? =
     82
     83Yes, from version 2.0. Categories and tags are on by default; other public taxonomies (and WooCommerce product categories and tags) can be ticked in Settings. Use the Terms view of the Slug Editor. slugH redirects the old category or tag archive, including its later pages and feeds. Posts whose URL contains the category, and child categories, are already redirected or still served by WordPress itself. When someone changes a term slug on the WordPress term screen, slugH adds the redirect too.
     84
     85= Does slugH support multisite, Polylang or WPML? =
     86
     87Polylang is supported from version 2.0 (tested with Polylang 3.9.2, language in the directory name). Each language's slugs are changed on their own, translation links are kept, and redirects keep the language prefix (for example /en/). Scan & Audit and the Slug Editor show a Language column and filter, the Slug Editor shows the slugs of the linked translations, and translated front pages are no longer flagged as permalink problems. Languages on subdomains or separate domains are not supported for redirects. WPML is not supported yet, and slugH runs on single sites only (network activation is blocked).
    7288
    7389== Screenshots ==
    … …  
    78944. Results: each record's actual new slug and URL, the redirects created and their test result, with exports and rollback.
    79955. Redirects: add, edit, import and export redirects, and test any URL hop by hop on the server.
    80 6. Settings: choose who owns redirects, and how slugH behaves on rollback, trial runs and uninstall.
     966. Settings: choose the post types, statuses and taxonomies slugH manages, and who owns redirects.
    8197
    8298== Changelog ==
     99
     100= 2.0.0 =
     101* Added: category, tag and custom taxonomy term slugs: scan, edit in the Slug Editor's Terms view, preview, apply with a redirect from the old archive (its pages and feeds follow), rollback. A term slug changed elsewhere in WordPress also gets a redirect.
     102* Added: media (attachment) slugs, opt-in in Settings, with redirects when WordPress attachment pages are on, including media under a renamed post or page.
     103* Added: Polylang support: Language column and filter, translation slugs shown in the Slug Editor, language in exports, and translated front pages are no longer flagged as permalink problems.
     104* Added: WP-CLI commands (`wp slugh`) for scans, slug change jobs with preview and rollback, and redirects.
     105* Added: optional Latin slug suggestions (transliteration), with Bangla phonetic rules built in.
     106* Added: after a scan, a notice lists public post types that have content but were not scanned.
     107* Fixed: rolling back a change to a parent page and its child page together now restores both.
     108* Fixed: a static front page is no longer flagged as a permalink problem in the scan.
     109* Docs: REST clients must keep calling the job run route until it reports done (apply, then verify).
    83110
    84111= 1.0.7 =
    … …  
    107134= 1.0.0 =
    108135* First release: scanning, slug editor with draft and preview, CSV import and export, redirect engine, jobs with snapshots and rollback, audit log, WooCommerce product support.
     136
     137== Upgrade Notice ==
     138
     139= 2.0.0 =
     140Adds category, tag and media slugs, Polylang support and WP-CLI commands. The database tables are updated automatically on upgrade.
  • slugh/tags/2.0.0/slugh.php

    r3795795 r3814912  
    44 * Plugin URI:        https://silitive.com/slugh/
    55 * Description:       Find, edit and bulk-update post slugs with safe 301 redirects.
    6  * Version:           1.0.7
     6 * Version:           2.0.0
    77 * Requires at least: 6.4
    88 * Requires PHP:      7.4
    … …  
    2020defined( 'ABSPATH' ) || exit;
    2121
    22 define( 'SLUGH_VERSION', '1.0.7' );
     22define( 'SLUGH_VERSION', '2.0.0' );
    2323define( 'SLUGH_FILE', __FILE__ );
    2424define( 'SLUGH_PATH', plugin_dir_path( __FILE__ ) );
  • slugh/tags/2.0.0/src/Admin/Actions.php

    r3795795 r3814912  
    1010use SlugH\Database\Migrations;
    1111use SlugH\Integrations\ConflictDetector;
     12use SlugH\Integrations\Polylang;
    1213use SlugH\Jobs\AuditLogger;
    1314use SlugH\Jobs\DraftManager;
    1415use SlugH\Jobs\JobRepository;
     16use SlugH\Redirects\RedirectImporter;
    1517use SlugH\Redirects\RedirectRepository;
    1618use SlugH\Scan\Flags;
    … …  
    170172                $all      = 'all' === $this->param( 'scope' );
    171173                $types    = $all ? PostTypes::get_enabled() : PostTypes::filter_types( sanitize_key( $this->text( 'post_type' ) ) );
    172                 $statuses = $all ? PostTypes::get_enabled_statuses() : PostTypes::filter_statuses( sanitize_key( $this->text( 'post_status' ) ) );
     174                $status   = $all ? '' : sanitize_key( $this->text( 'post_status' ) );
     175                $statuses = '' === $status ? PostTypes::query_statuses( $types, PostTypes::get_enabled_statuses() ) : PostTypes::filter_statuses( $status );
    173176                $search   = $all ? '' : sanitize_text_field( $this->text( 's' ) );
     177                $language = $all ? '' : sanitize_key( $this->text( 'slugh_lang' ) );
     178                $by_lang  = Polylang::is_active();
    174179                $rows     = array();
    175180                $last_id  = 0;
    … …  
    185190                                $binds[] = '%' . $wpdb->esc_like( sanitize_title( $search ) ) . '%';
    186191                        }
     192                        if ( $by_lang && '' !== $language ) {
     193                                $condition = Polylang::language_condition( 'ID', $language );
     194                                $sql      .= $condition ? ' AND ' . $condition[0] : ' AND 1 = 0';
     195                                if ( $condition ) {
     196                                        $binds[] = $condition[1];
     197                                }
     198                        }
    187199                        // 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().
    188                         $batch = $wpdb->get_results( $wpdb->prepare( $sql . ' ORDER BY ID ASC LIMIT 1000', $binds ) );
     200                        $batch     = $wpdb->get_results( $wpdb->prepare( $sql . ' ORDER BY ID ASC LIMIT 1000', $binds ) );
     201                        $languages = $by_lang ? Polylang::languages_for( wp_list_pluck( (array) $batch, 'ID' ) ) : array();
    189202                        foreach ( (array) $batch as $row ) {
    190203                                $last_id = (int) $row->ID;
    191204                                if ( current_user_can( 'edit_post', $row->ID ) ) {
    192                                         $rows[] = array( $row->ID, $row->post_type, rawurldecode( $row->post_name ), '' );
     205                                        $cells = array( $row->ID, $row->post_type, rawurldecode( $row->post_name ), '' );
     206                                        if ( $by_lang ) {
     207                                                $cells[] = isset( $languages[ $last_id ] ) ? $languages[ $last_id ] : '';
     208                                        }
     209                                        $rows[] = $cells;
    193210                                }
    194211                        }
    … …  
    196213                } while ( 1000 === $batch_size );
    197214
    198                 CsvHandler::send_download( 'slugh-records-' . gmdate( 'Ymd-His' ) . '.csv', array( 'content_id', 'post_type', 'old_slug', 'new_slug' ), $rows );
     215                $headers = array( 'content_id', 'post_type', 'old_slug', 'new_slug' );
     216                if ( $by_lang ) {
     217                        $headers[] = 'language';
     218                }
     219                CsvHandler::send_download( 'slugh-records-' . gmdate( 'Ymd-His' ) . '.csv', $headers, $rows );
    199220        }
    200221
    … …  
    213234                        'search'      => sanitize_text_field( $this->text( 's' ) ),
    214235                        'issues_only' => (bool) $this->param( 'issues_only' ),
     236                        'language'    => sanitize_key( $this->text( 'slugh_lang' ) ),
    215237                        'per_page'    => 500,
    216238                );
     239                $by_lang = Polylang::is_active();
    217240                $labels  = Flags::get_labels();
    218241                $rows    = array();
    … …  
    221244                        $filters['page'] = $page;
    222245                        $result          = Scanner::query_results( $scan_id, $filters );
     246                        $languages       = $by_lang ? Polylang::languages_for( wp_list_pluck( $result['items'], 'post_id' ) ) : array();
    223247                        foreach ( $result['items'] as $item ) {
    224248                                $names = array();
    … …  
    228252                                        }
    229253                                }
    230                                 $rows[] = array( $item->post_id, $item->post_type, $item->decoded_slug, '', $item->post_status, implode( '; ', $names ) );
     254                                $cells = array( $item->post_id, $item->post_type, $item->decoded_slug, '', $item->post_status, implode( '; ', $names ), 'term' === $item->object_type ? $item->post_type : '' );
     255                                if ( $by_lang ) {
     256                                        $cells[] = isset( $languages[ (int) $item->post_id ] ) ? $languages[ (int) $item->post_id ] : '';
     257                                }
     258                                $rows[] = $cells;
    231259                        }
    232260                        ++$page;
    … …  
    234262                } while ( 500 === $page_size );
    235263
    236                 CsvHandler::send_download( 'slugh-scan-' . $scan_id . '.csv', array( 'content_id', 'post_type', 'old_slug', 'new_slug', 'status', 'flags' ), $rows );
     264                // "taxonomy" is set for term rows (content_id is then a term ID); imports route those rows to terms.
     265                $headers = array( 'content_id', 'post_type', 'old_slug', 'new_slug', 'status', 'flags', 'taxonomy' );
     266                if ( $by_lang ) {
     267                        $headers[] = 'language';
     268                }
     269                CsvHandler::send_download( 'slugh-scan-' . $scan_id . '.csv', $headers, $rows );
    237270        }
    238271
    … …  
    402435                        $this->back( 'slugh-redirects' );
    403436                }
    404                 $missing = array_diff( array( 'source', 'destination' ), $parsed['headers'] );
    405                 if ( ! empty( $missing ) ) {
    406                         /* translators: %s: column names */
    407                         Notices::add( sprintf( __( 'The file is missing required columns: %s. Nothing was imported.', 'slugh' ), implode( ', ', $missing ) ), 'error' );
     437                $result = RedirectImporter::import( $parsed, (bool) $this->param( 'replace_existing' ), $file['name'] );
     438                if ( is_wp_error( $result ) ) {
     439                        Notices::add( $result->get_error_message(), 'error' );
    408440                        $this->back( 'slugh-redirects' );
    409441                }
    410 
    411                 $replace = (bool) $this->param( 'replace_existing' );
    412                 $counts  = array(
    413                         'created'   => 0,
    414                         'reenabled' => 0,
    415                         'replaced'  => 0,
    416                 );
    417                 $errors  = array();
    418 
    419                 foreach ( $parsed['rows'] as $row ) {
    420                         $data   = $row['data'];
    421                         $result = RedirectRepository::create(
    422                                 array(
    423                                         'source'      => Sanitizer::path_input( $data['source'] ),
    424                                         'destination' => Sanitizer::path_input( $data['destination'] ),
    425                                         'status_code' => isset( $data['status'] ) && '' !== $data['status'] ? absint( $data['status'] ) : 301,
    426                                         'enabled'     => ! isset( $data['enabled'] ) || '' === $data['enabled'] ? true : (bool) absint( $data['enabled'] ),
    427                                         'match_mode'  => isset( $data['match_mode'] ) && '' !== $data['match_mode'] ? sanitize_key( $data['match_mode'] ) : '404_only',
    428                                         'origin'      => 'import',
    429                                         'on_conflict' => $replace ? 'replace' : 'error',
    430                                 )
    431                         );
    432                         if ( is_wp_error( $result ) ) {
    433                                 /* translators: 1: line number, 2: reason */
    434                                 $errors[] = sprintf( __( 'Line %1$d: %2$s', 'slugh' ), $row['line'], $result->get_error_message() );
    435                         } elseif ( isset( $counts[ $result['action'] ] ) ) {
    436                                 ++$counts[ $result['action'] ];
    437                         }
    438                 }
    439 
    440                 AuditLogger::log( 'import', 'redirect', 0, array( 'filename' => $file['name'] ), array_merge( $counts, array( 'invalid' => count( $errors ) ) ) );
     442                $counts = $result;
     443                $errors = $result['errors'];
    441444
    442445                Notices::add(
    … …  
    547550                                'supported_post_types'        => array_map( 'sanitize_key', (array) $this->param( 'supported_post_types', array() ) ),
    548551                                'supported_post_statuses'     => array_map( 'sanitize_key', (array) $this->param( 'supported_post_statuses', array() ) ),
     552                                'supported_taxonomies'        => array_map( 'sanitize_key', (array) $this->param( 'supported_taxonomies', array() ) ),
     553                                'term_edit_redirects'         => (bool) $this->param( 'term_edit_redirects' ),
    549554                                'redirect_ownership_mode'     => $mode,
    550555                                'redirect_private_posts'      => (bool) $this->param( 'redirect_private_posts' ),
    … …  
    554559                                'trial_mode'                  => (bool) $this->param( 'trial_mode' ),
    555560                                'allow_external_destinations' => (bool) $this->param( 'allow_external_destinations' ),
     561                                'transliteration'             => (bool) $this->param( 'transliteration' ),
    556562                                'integrity_excluded_meta'     => array_filter( array_map( 'sanitize_text_field', (array) $excluded ) ),
    557563                                'scan_batch_size'             => absint( $this->param( 'scan_batch_size', 500 ) ),
    … …  
    607613                }
    608614
     615                // Terms (Slug Editor "Terms" view and term rows of Scan & Audit).
     616                foreach ( array_filter( array_map( 'absint', (array) $this->param( 'term_ids', array() ) ) ) as $term_id ) {
     617                        if ( 'suggest' === $action ) {
     618                                $term = get_term( $term_id );
     619                                if ( ! $term instanceof \WP_Term ) {
     620                                        continue;
     621                                }
     622                                $result = DraftManager::upsert_term_item( $job_id, $term_id, RulesSuggester::instance()->suggest( rawurldecode( $term->slug ), $term ) );
     623                                if ( in_array( $result['status'], array( 'added', 'updated' ), true ) ) {
     624                                        ++$done;
     625                                }
     626                        } elseif ( 'remove' === $action && DraftManager::remove_item( $job_id, $term_id, 'term' ) ) {
     627                                ++$done;
     628                        }
     629                }
     630
    609631                /* translators: %d: number of rows */
    610632                Notices::add( sprintf( __( '%d row(s) updated in the draft. Nothing is applied until you preview and confirm.', 'slugh' ), $done ) );
  • slugh/tags/2.0.0/src/Admin/ListTables/EditorListTable.php

    r3795795 r3814912  
    99
    1010use SlugH\Database\Schema;
     11use SlugH\Integrations\Polylang;
    1112use SlugH\Jobs\JobRepository;
    1213use SlugH\Scan\Flags;
    … …  
    3738         */
    3839        private $draft = array();
     40
     41        /**
     42         * Polylang language slugs of the rows on this page, keyed by post ID.
     43         *
     44         * @var array<int, string>
     45         */
     46        private $languages = array();
    3947
    4048        /**
    … …  
    8896         */
    8997        public function get_columns() {
    90                 return array(
    91                         'cb'       => '<input type="checkbox" />',
    92                         'id'       => __( 'ID', 'slugh' ),
    93                         'title'    => __( 'Title', 'slugh' ),
    94                         'type'     => __( 'Type / status', 'slugh' ),
    95                         'current'  => __( 'Current slug', 'slugh' ),
    96                         'new_slug' => __( 'New slug', 'slugh' ),
    97                         'state'    => __( 'Change', 'slugh' ),
     98                $columns = array(
     99                        'cb'    => '<input type="checkbox" />',
     100                        'id'    => __( 'ID', 'slugh' ),
     101                        'title' => __( 'Title', 'slugh' ),
     102                        'type'  => __( 'Type / status', 'slugh' ),
     103                );
     104                if ( Polylang::is_active() ) {
     105                        $columns['language'] = __( 'Language', 'slugh' );
     106                }
     107                return array_merge(
     108                        $columns,
     109                        array(
     110                                'current'  => __( 'Current slug', 'slugh' ),
     111                                'new_slug' => __( 'New slug', 'slugh' ),
     112                                'state'    => __( 'Change', 'slugh' ),
     113                        )
    98114                );
    99115        }
    … …  
    119135        protected function get_bulk_actions() {
    120136                return array(
    121                         'suggest' => __( 'Add cleanup suggestion to draft', 'slugh' ),
     137                        'suggest' => __( 'Add suggested slug to draft', 'slugh' ),
    122138                        'remove'  => __( 'Remove from draft', 'slugh' ),
    123139                );
    … …  
    140156                $flag     = absint( self::filter( 'flag' ) );
    141157                $in_draft = '1' === self::filter( 'in_draft' );
     158                $language = Polylang::is_active() ? sanitize_key( self::filter( 'slugh_lang' ) ) : '';
    142159                $per_page = self::per_page();
    143160                $paged    = $this->get_pagenum();
    … …  
    147164                if ( $this->job_id ) {
    148165                        foreach ( JobRepository::get_items( $this->job_id, array( 'kind' => 'direct' ) ) as $item ) {
    149                                 $this->draft[ $item->post_id ] = $item;
     166                                if ( 'term' !== $item->object_type ) {
     167                                        $this->draft[ $item->post_id ] = $item;
     168                                }
    150169                        }
    151170                }
    … …  
    166185
    167186                $types    = $type && in_array( $type, $types, true ) ? array( $type ) : $types;
    168                 $statuses = $status && in_array( $status, $statuses, true ) ? array( $status ) : $statuses;
     187                $statuses = $status && in_array( $status, $statuses, true ) ? array( $status ) : PostTypes::query_statuses( $types, $statuses );
    169188                $where[]  = 'p.post_type IN (' . implode( ',', array_fill( 0, count( $types ), '%s' ) ) . ')';
    170189                $binds    = array_merge( $binds, $types );
    … …  
    187206                        $binds[] = $flag;
    188207                        $binds[] = $flag;
     208                }
     209
     210                if ( '' !== $language ) {
     211                        $condition = Polylang::language_condition( 'p.ID', $language );
     212                        $where[]   = $condition ? $condition[0] : '1 = 0';
     213                        if ( $condition ) {
     214                                $binds[] = $condition[1];
     215                        }
    189216                }
    190217
    … …  
    218245
    219246                $this->items = (array) $rows;
     247                if ( Polylang::is_active() ) {
     248                        $this->languages = Polylang::languages_for( wp_list_pluck( $this->items, 'ID' ) );
     249                }
    220250                $this->set_pagination_args(
    221251                        array(
    … …  
    255285                echo '</select>';
    256286
     287                if ( Polylang::is_active() ) {
     288                        echo '<label class="screen-reader-text" for="slugh-filter-lang">' . esc_html__( 'Filter by language', 'slugh' ) . '</label>';
     289                        echo '<select name="slugh_lang" id="slugh-filter-lang"><option value="">' . esc_html__( 'All languages', 'slugh' ) . '</option>';
     290                        foreach ( Polylang::languages() as $slug => $name ) {
     291                                printf( '<option value="%s"%s>%s</option>', esc_attr( $slug ), selected( self::filter( 'slugh_lang' ), $slug, false ), esc_html( $name ) );
     292                        }
     293                        echo '</select>';
     294                }
     295
    257296                echo '<label class="screen-reader-text" for="slugh-filter-flag">' . esc_html__( 'Filter by detection category from the latest scan', 'slugh' ) . '</label>';
    258297                echo '<select name="flag" id="slugh-filter-flag"><option value="">' . esc_html__( 'Any detection category', 'slugh' ) . '</option>';
    … …  
    292331                        esc_html( sprintf( __( 'Select %s', 'slugh' ), $this->title( $item ) ) )
    293332                );
     333        }
     334
     335        /**
     336         * Language slug of a row ('' when it has none).
     337         *
     338         * @param int $post_id Post ID.
     339         * @return string
     340         */
     341        private function language_of( $post_id ) {
     342                return isset( $this->languages[ (int) $post_id ] ) ? $this->languages[ (int) $post_id ] : '';
     343        }
     344
     345        /**
     346         * Linked Polylang translations with their current slugs, as a hint for writing the slug.
     347         *
     348         * @param object $item Row.
     349         * @return string HTML ('' without Polylang or without translations).
     350         */
     351        private function translations_hint( $item ) {
     352                if ( ! Polylang::is_active() ) {
     353                        return '';
     354                }
     355                $translations = Polylang::translations( $item->ID );
     356                if ( empty( $translations ) ) {
     357                        return '';
     358                }
     359                $parts = array();
     360                foreach ( $translations as $slug => $id ) {
     361                        $post = get_post( $id );
     362                        if ( ! $post ) {
     363                                continue;
     364                        }
     365                        $parts[] = sprintf(
     366                                '%1$s: <a href="%2$s"><code dir="ltr">%3$s</code></a>',
     367                                esc_html( Polylang::language_name( $slug ) ),
     368                                esc_url(
     369                                        add_query_arg(
     370                                                array(
     371                                                        'page' => 'slugh-editor',
     372                                                        's'    => $id,
     373                                                ),
     374                                                admin_url( 'admin.php' )
     375                                        )
     376                                ),
     377                                esc_html( '' === $post->post_name ? '—' : rawurldecode( $post->post_name ) )
     378                        );
     379                }
     380                return $parts ? '<div class="slugh-translations slugh-muted">' . esc_html__( 'Translations:', 'slugh' ) . ' ' . implode( ', ', $parts ) . '</div>' : '';
    294381        }
    295382
    … …  
    329416                                $out .= '<span class="view"><a href="' . esc_url( (string) $view ) . '" target="_blank" rel="noopener">' . esc_html__( 'View', 'slugh' ) . '</a></span>';
    330417                                $out .= '</div>';
    331                                 return $out;
     418                                return $out . $this->translations_hint( $item );
     419
     420                        case 'language':
     421                                return esc_html( Polylang::language_name( $this->language_of( $item->ID ) ) );
    332422
    333423                        case 'type':
    … …  
    349439                                        (int) $item->ID,
    350440                                        esc_attr( $decoded ),
    351                                         esc_attr( $item->post_type . '|' . ( is_post_type_hierarchical( $item->post_type ) ? (int) $item->post_parent : 0 ) . '|' ),
     441                                        esc_attr( JobRepository::duplicate_key_prefix( $item->post_type, $item->post_parent, $this->language_of( $item->ID ) ) ),
    352442                                        esc_attr( $this->title( $item ) ),
    353443                                        $can ? '' : ' disabled'
  • slugh/tags/2.0.0/src/Admin/Screens/DiagnosticsScreen.php

    r3795795 r3814912  
    1212use SlugH\Integrations\CacheManager;
    1313use SlugH\Integrations\ConflictDetector;
     14use SlugH\Integrations\Polylang;
    1415use SlugH\Integrations\WooCommerce;
    1516use SlugH\Jobs\JobRepository;
    … …  
    6768                                'type' => 'warning',
    6869                                'text' => __( 'Ownership mode "Slug only, no redirects" is active: changed public URLs will return 404.', 'slugh' ),
     70                        );
     71                }
     72                if ( Polylang::uses_other_hosts() ) {
     73                        $warnings[] = array(
     74                                'type' => 'warning',
     75                                'text' => __( 'Polylang sets the language from subdomains or separate domains. slugH redirects and the redirect tester work only on the main site address; URLs on the other language hosts are treated as external.', 'slugh' ),
    6976                        );
    7077                }
    … …  
    156163                        __( 'Page caches purged on apply', 'slugh' ) => CacheManager::active_purgers() ? implode( ', ', CacheManager::active_purgers() ) : __( 'None detected', 'slugh' ),
    157164                        __( 'WooCommerce product support', 'slugh' ) => true === $wc ? __( 'On', 'slugh' ) : __( 'Off', 'slugh' ) . ' — ' . $wc,
     165                        __( 'Multilingual (Polylang)', 'slugh' )     => Polylang::describe(),
    158166                        __( 'Redirect ownership mode', 'slugh' )     => Settings::get( 'redirect_ownership_mode' ),
    159167                        __( 'slugH schema version', 'slugh' )        => $db_version . ' (' . __( 'code expects', 'slugh' ) . ' ' . Schema::DB_VERSION . ')',
  • slugh/tags/2.0.0/src/Admin/Screens/EditorScreen.php

    r3795795 r3814912  
    99
    1010use SlugH\Admin\ListTables\EditorListTable;
     11use SlugH\Admin\ListTables\TermsListTable;
    1112use SlugH\Admin\Notices;
    1213use SlugH\Jobs\DraftManager;
    … …  
    5960                        }
    6061                }
     62                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Verified above.
     63                $term_ids = isset( $_GET['term_ids'] ) ? array_map( 'absint', (array) wp_unslash( $_GET['term_ids'] ) ) : array();
     64                foreach ( array_filter( $term_ids ) as $term_id ) {
     65                        if ( 'suggest' === $action ) {
     66                                $term = get_term( $term_id );
     67                                if ( $term instanceof \WP_Term ) {
     68                                        $res   = DraftManager::upsert_term_item( $job_id, $term_id, RulesSuggester::instance()->suggest( rawurldecode( $term->slug ), $term ) );
     69                                        $done += in_array( $res['status'], array( 'added', 'updated' ), true ) ? 1 : 0;
     70                                }
     71                        } elseif ( DraftManager::remove_item( $job_id, $term_id, 'term' ) ) {
     72                                ++$done;
     73                        }
     74                }
    6175
    6276                /* translators: %d: number of rows */
    6377                Notices::add( sprintf( __( '%d row(s) changed in the draft. Nothing is applied until you preview and confirm the draft.', 'slugh' ), $done ) );
    64                 wp_safe_redirect( remove_query_arg( array( 'action', 'action2', 'post_ids', '_wpnonce', '_wp_http_referer' ) ) );
     78                wp_safe_redirect( remove_query_arg( array( 'action', 'action2', 'post_ids', 'term_ids', '_wpnonce', '_wp_http_referer' ) ) );
    6579                exit;
    6680        }
    … …  
    7488                $job_id = DraftManager::get_editor_draft( false );
    7589                $count  = $job_id ? count( JobRepository::get_items( $job_id, array( 'kind' => 'direct' ) ) ) : 0;
    76                 $table  = new EditorListTable( $job_id );
     90                $terms  = 'terms' === EditorListTable::filter( 'slugh_view' );
     91                $table  = $terms ? new TermsListTable( $job_id ) : new EditorListTable( $job_id );
    7792                $table->prepare_items();
     93                $base   = admin_url( 'admin.php?page=slugh-editor' );
    7894                $review = $job_id ? admin_url( 'admin.php?page=slugh-history&job=' . $job_id ) : '';
    7995                ?>
    … …  
    86102                                <div class="notice notice-error"><p><?php echo esc_html( SlugUpdater::unfiltered_html_message() ); ?></p></div>
    87103                        <?php endif; ?>
     104
     105                        <ul class="subsubsub slugh-views">
     106                                <li><a href="<?php echo esc_url( $base ); ?>"<?php echo $terms ? '' : ' class="current" aria-current="page"'; ?>><?php esc_html_e( 'Posts, pages and other content', 'slugh' ); ?></a> |</li>
     107                                <li><a href="<?php echo esc_url( add_query_arg( 'slugh_view', 'terms', $base ) ); ?>"<?php echo $terms ? ' class="current" aria-current="page"' : ''; ?>><?php esc_html_e( 'Terms (categories, tags, taxonomies)', 'slugh' ); ?></a></li>
     108                        </ul>
     109                        <br class="clear" />
    88110
    89111                        <p class="description"><?php esc_html_e( 'Type a new slug beside any record. Enter saves the row to your draft, Escape reverts it, Tab moves to the next input. Saved changes stay in the draft until you preview and confirm them; nothing on the site changes before that.', 'slugh' ); ?></p>
    … …  
    118140                                        <summary><?php esc_html_e( 'Bulk paste by ID (recommended)', 'slugh' ); ?></summary>
    119141                                        <p><?php esc_html_e( 'One line per record: content_id,new_slug — comma or tab separated, so a two-column paste from Excel or Google Sheets works. Each line carries its ID, so a missing or extra line never shifts slugs onto the wrong records.', 'slugh' ); ?></p>
     142                                        <p class="description"><?php esc_html_e( 'For a term add its taxonomy as a third column: term_id,new_slug,category (or post_tag, or another enabled taxonomy).', 'slugh' ); ?></p>
    120143                                        <label for="slugh-paste-id-text" class="screen-reader-text"><?php esc_html_e( 'Lines of content_id and new slug', 'slugh' ); ?></label>
    121144                                        <textarea id="slugh-paste-id-text" rows="6" class="large-text code" dir="ltr" placeholder="1024,new-title&#10;2048      about"></textarea>
    … …  
    139162                        <form method="get" id="slugh-editor-form">
    140163                                <input type="hidden" name="page" value="slugh-editor" />
    141                                 <?php $table->search_box( __( 'Search title or slug', 'slugh' ), 'slugh-editor-search' ); ?>
     164                                <?php if ( $terms ) : ?>
     165                                        <input type="hidden" name="slugh_view" value="terms" />
     166                                <?php endif; ?>
     167                                <?php $table->search_box( $terms ? __( 'Search name or slug', 'slugh' ) : __( 'Search title or slug', 'slugh' ), 'slugh-editor-search' ); ?>
    142168                                <?php $table->display(); ?>
    143169                        </form>
  • slugh/tags/2.0.0/src/Admin/Screens/ImportExportScreen.php

    r3795795 r3814912  
    99
    1010use SlugH\Admin\Notices;
     11use SlugH\Integrations\Polylang;
    1112use SlugH\Support\Capabilities;
    1213use SlugH\Support\PostTypes;
    … …  
    7071                                                        </select>
    7172                                                </label>
     73                                                <?php if ( Polylang::is_active() ) : ?>
     74                                                        <label><?php esc_html_e( 'Language', 'slugh' ); ?>
     75                                                                <select name="slugh_lang"><option value=""><?php esc_html_e( 'All', 'slugh' ); ?></option>
     76                                                                        <?php foreach ( Polylang::languages() as $slug => $name ) : ?>
     77                                                                                <option value="<?php echo esc_attr( $slug ); ?>"><?php echo esc_html( $name ); ?></option>
     78                                                                        <?php endforeach; ?>
     79                                                                </select>
     80                                                        </label>
     81                                                <?php endif; ?>
    7282                                                <label><?php esc_html_e( 'Search', 'slugh' ); ?> <input type="search" name="s" /></label>
    7383                                                <?php submit_button( __( 'Export filtered view', 'slugh' ), 'secondary', 'submit', false ); ?>
  • slugh/tags/2.0.0/src/Admin/Screens/JobView.php

    r3795795 r3814912  
    441441        private function render_item_row( $item, $is_draft, $selectable ) {
    442442                $validation = isset( $item->message['validation'] ) ? (array) $item->message['validation'] : array();
    443                 $title      = get_the_title( $item->post_id );
     443                $is_term    = isset( $item->object_type ) && 'term' === $item->object_type;
     444                $term       = $is_term ? get_term( (int) $item->post_id ) : null;
     445                $title      = $is_term ? ( $term instanceof \WP_Term ? $term->name : '' ) : get_the_title( $item->post_id );
    444446                $old_slug   = rawurldecode( $item->old_post_name );
    445447                $new_slug   = rawurldecode( (string) ( $item->actual_post_name ? $item->actual_post_name : ( ! empty( $validation['predicted_slug'] ) ? $validation['predicted_slug'] : $item->requested_post_name ) ) );
    … …  
    461463                        <td class="column-primary">
    462464                                <strong>#<?php echo (int) $item->post_id; ?></strong> <?php echo esc_html( $title ); ?><br>
    463                                 <span class="slugh-muted"><?php echo esc_html( $item->post_type . ( 'descendant' === $item->kind ? ' · ' . __( 'descendant', 'slugh' ) : '' ) ); ?></span>
     465                                <span class="slugh-muted"><?php echo esc_html( $item->post_type . ( $is_term ? ' · ' . __( 'term', 'slugh' ) : '' ) . ( 'descendant' === $item->kind ? ' · ' . __( 'descendant', 'slugh' ) : '' ) ); ?></span>
    464466                        </td>
    465467                        <td dir="ltr"><code><?php echo esc_html( $old_slug ); ?></code><br>→ <code><?php echo esc_html( $new_slug ); ?></code></td>
  • slugh/tags/2.0.0/src/Admin/Screens/ScanScreen.php

    r3795795 r3814912  
    1010use SlugH\Admin\Notices;
    1111use SlugH\Database\Schema;
     12use SlugH\Integrations\Polylang;
    1213use SlugH\Jobs\JobRepository;
    1314use SlugH\Scan\Flags;
    … …  
    1516use SlugH\Slugs\RulesSuggester;
    1617use SlugH\Slugs\SlugValidator;
     18use SlugH\Slugs\TermSlugs;
    1719use SlugH\Support\Capabilities;
    1820use SlugH\Support\PostTypes;
     21use SlugH\Support\Taxonomies;
    1922
    2023defined( 'ABSPATH' ) || exit;
    … …  
    9497                                                <?php endforeach; ?>
    9598                                        </fieldset>
     99                                        <p class="description">
     100                                                <?php
     101                                                $taxonomy_names = array();
     102                                                foreach ( Taxonomies::get_enabled() as $taxonomy_name ) {
     103                                                        $taxonomy_object  = get_taxonomy( $taxonomy_name );
     104                                                        $taxonomy_names[] = $taxonomy_object ? $taxonomy_object->labels->name : $taxonomy_name;
     105                                                }
     106                                                echo esc_html(
     107                                                        $taxonomy_names
     108                                                                /* translators: %s: list of taxonomies */
     109                                                                ? sprintf( __( 'Terms are scanned too: %s (change in Settings).', 'slugh' ), implode( ', ', $taxonomy_names ) )
     110                                                                : __( 'No taxonomies are enabled in Settings, so no terms are scanned.', 'slugh' )
     111                                                );
     112                                                ?>
     113                                        </p>
    96114                                        <p><button type="submit" class="button button-primary" id="slugh-scan-start"><?php esc_html_e( 'Start scan', 'slugh' ); ?></button></p>
    97115                                </form>
    … …  
    147165                        'modified_to'   => preg_match( '/^\d{4}-\d{2}-\d{2}$/', $this->text_filter( 'modified_to' ) ) ? $this->text_filter( 'modified_to' ) : '',
    148166                        'issues_only'   => '1' === $this->filter( 'issues_only' ),
     167                        'language'      => Polylang::is_active() ? sanitize_key( $this->text_filter( 'slugh_lang' ) ) : '',
    149168                        'orderby'       => sanitize_key( $this->text_filter( 'orderby' ) ),
    150169                        'order'         => sanitize_key( $this->text_filter( 'order' ) ),
    … …  
    153172                );
    154173                $result  = Scanner::query_results( $scan_id, $filters );
     174                $langs   = Polylang::is_active() ? Polylang::languages() : array();
     175                $columns = $langs ? 11 : 10;
    155176                $export  = wp_nonce_url(
    156177                        add_query_arg(
    … …  
    163184                                                's'           => $filters['search'],
    164185                                                'issues_only' => $filters['issues_only'] ? '1' : '',
     186                                                'slugh_lang'  => $filters['language'],
    165187                                                'flags'       => $flags,
    166188                                        )
    … …  
    178200                                ?>
    179201                        </h2>
     202                        <?php $this->render_skipped_types_notice( $scan, $available ); ?>
    180203                        <ul class="slugh-count-list">
    181204                                <li><strong><?php echo (int) $counts['total']; ?></strong> <?php esc_html_e( 'records', 'slugh' ); ?></li>
    … …  
    207230                                                        <option value="<?php echo esc_attr( $name ); ?>" <?php selected( $filters['post_type'], $name ); ?>><?php echo esc_html( $object->labels->name ); ?></option>
    208231                                                <?php endforeach; ?>
     232                                                <?php foreach ( Taxonomies::get_available() as $name => $object ) : ?>
     233                                                        <option value="<?php echo esc_attr( $name ); ?>" <?php selected( $filters['post_type'], $name ); ?>><?php echo esc_html( $object->labels->name . ' (' . __( 'terms', 'slugh' ) . ')' ); ?></option>
     234                                                <?php endforeach; ?>
    209235                                                </select>
    210236                                        </label>
    … …  
    216242                                                </select>
    217243                                        </label>
     244                                        <?php if ( $langs ) : ?>
     245                                                <label><?php esc_html_e( 'Language', 'slugh' ); ?>
     246                                                        <select name="slugh_lang"><option value=""><?php esc_html_e( 'All', 'slugh' ); ?></option>
     247                                                        <?php foreach ( $langs as $slug => $name ) : ?>
     248                                                                <option value="<?php echo esc_attr( $slug ); ?>" <?php selected( $filters['language'], $slug ); ?>><?php echo esc_html( $name ); ?></option>
     249                                                        <?php endforeach; ?>
     250                                                        </select>
     251                                                </label>
     252                                        <?php endif; ?>
    218253                                        <label><?php esc_html_e( 'Modified from', 'slugh' ); ?> <input type="date" name="modified_from" value="<?php echo esc_attr( $filters['modified_from'] ); ?>" /></label>
    219254                                        <label><?php esc_html_e( 'to', 'slugh' ); ?> <input type="date" name="modified_to" value="<?php echo esc_attr( $filters['modified_to'] ); ?>" /></label>
    … …  
    238273                                <?php wp_nonce_field( 'slugh_editor_bulk' ); ?>
    239274                                <?php if ( current_user_can( Capabilities::CAP_EDIT_SLUGS ) ) : ?>
    240                                         <p><button type="submit" class="button"><?php esc_html_e( 'Add cleanup suggestions for checked rows to the Slug Editor draft', 'slugh' ); ?></button></p>
     275                                        <p><button type="submit" class="button"><?php esc_html_e( 'Add suggested slugs for checked rows to the Slug Editor draft', 'slugh' ); ?></button></p>
    241276                                <?php endif; ?>
    242277                                <div class="slugh-table-scroll">
    … …  
    248283                                                        <th scope="col"><?php esc_html_e( 'Title', 'slugh' ); ?></th>
    249284                                                        <th scope="col"><?php esc_html_e( 'Type / status', 'slugh' ); ?></th>
     285                                                        <?php if ( $langs ) : ?>
     286                                                                <th scope="col"><?php esc_html_e( 'Language', 'slugh' ); ?></th>
     287                                                        <?php endif; ?>
    250288                                                        <th scope="col"><?php esc_html_e( 'Current slug and permalink', 'slugh' ); ?></th>
    251289                                                        <th scope="col"><?php esc_html_e( 'Proposed slug and permalink', 'slugh' ); ?></th>
    … …  
    258296                                        <tbody>
    259297                                        <?php if ( empty( $result['items'] ) ) : ?>
    260                                                 <tr><td colspan="10"><?php esc_html_e( 'No records match these filters.', 'slugh' ); ?></td></tr>
     298                                                <tr><td colspan="<?php echo (int) $columns; ?>"><?php esc_html_e( 'No records match these filters.', 'slugh' ); ?></td></tr>
    261299                                        <?php endif; ?>
    262300                                        <?php foreach ( $result['items'] as $item ) : ?>
    263                                                 <?php $this->render_row( $item, $labels ); ?>
     301                                                <?php $this->render_row( $item, $labels, (bool) $langs ); ?>
    264302                                        <?php endforeach; ?>
    265303                                        </tbody>
    … …  
    273311
    274312        /**
     313         * Tell the administrator which public post types with content the scan left out.
     314         *
     315         * @param object|null $scan      Scan job.
     316         * @param array       $available Available post types keyed by name.
     317         * @return void
     318         */
     319        private function render_skipped_types_notice( $scan, array $available ) {
     320                if ( ! $scan || empty( $scan->settings['post_types'] ) ) {
     321                        return;
     322                }
     323                $scanned = (array) $scan->settings['post_types'];
     324                $skipped = array();
     325                foreach ( $available as $name => $object ) {
     326                        if ( in_array( $name, $scanned, true ) ) {
     327                                continue;
     328                        }
     329                        $counts = (array) wp_count_posts( $name );
     330                        $total  = 0;
     331                        foreach ( PostTypes::SUPPORTED_STATUSES as $status ) {
     332                                $total += isset( $counts[ $status ] ) ? (int) $counts[ $status ] : 0;
     333                        }
     334                        if ( $total > 0 ) {
     335                                /* translators: 1: post type label, 2: post type name, 3: number of items */
     336                                $skipped[] = sprintf( _n( '%1$s (%2$s, %3$s item)', '%1$s (%2$s, %3$s items)', $total, 'slugh' ), $object->labels->name, $name, number_format_i18n( $total ) );
     337                        }
     338                }
     339                if ( ! $skipped ) {
     340                        return;
     341                }
     342                ?>
     343                <div class="notice notice-info inline slugh-skipped-types">
     344                        <p>
     345                                <?php
     346                                echo esc_html(
     347                                        sprintf(
     348                                                /* translators: %s: comma-separated list of post types */
     349                                                __( 'This scan did not include these public post types, which have content: %s. Tick them under "Post types" above and scan again.', 'slugh' ),
     350                                                implode( ', ', $skipped )
     351                                        )
     352                                );
     353                                ?>
     354                                <a href="<?php echo esc_url( admin_url( 'admin.php?page=slugh-settings' ) ); ?>"><?php esc_html_e( 'Enable them by default in Settings', 'slugh' ); ?></a>
     355                        </p>
     356                </div>
     357                <?php
     358        }
     359
     360        /**
    275361         * One results row.
    276362         *
    277363         * @param object $item   Scan row.
    278364         * @param array  $labels Flag labels.
     365         * @param bool   $multilingual Whether to show the Language column (Polylang active).
    279366         * @return void
    280367         */
    281         private function render_row( $item, array $labels ) {
     368        private function render_row( $item, array $labels, $multilingual = false ) {
    282369                global $wpdb;
    283370
    284                 $post      = get_post( $item->post_id );
    285                 $permalink = $post ? (string) get_permalink( $post ) : '';
     371                $is_term   = 'term' === $item->object_type;
     372                $post      = $is_term ? get_term( (int) $item->post_id ) : get_post( $item->post_id );
     373                $post      = $post && ! is_wp_error( $post ) ? $post : null;
     374                $slug      = $post ? ( $is_term ? $post->slug : $post->post_name ) : '';
     375                $permalink = $post ? ( $is_term ? TermSlugs::link( $post ) : (string) get_permalink( $post ) ) : '';
    286376                $proposed  = '';
    287377                $predicted = '';
    … …  
    289379
    290380                if ( $post ) {
    291                         $suggestion = RulesSuggester::instance()->suggest( rawurldecode( $post->post_name ), $post );
    292                         if ( '' !== $suggestion && rawurldecode( $post->post_name ) !== $suggestion ) {
    293                                 $validation = SlugValidator::validate( $post->ID, $suggestion );
     381                        $suggestion = RulesSuggester::instance()->suggest( rawurldecode( $slug ), $post );
     382                        if ( '' !== $suggestion && rawurldecode( $slug ) !== $suggestion ) {
     383                                $validation = $is_term ? TermSlugs::validate( $item->post_id, $suggestion ) : SlugValidator::validate( $post->ID, $suggestion );
    294384                                $proposed   = $validation['predicted_decoded'];
    295385                                $predicted  = $validation['predicted_permalink'];
    … …  
    300390                $table = Schema::get_table_name( 'slugh_redirects' );
    301391                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    302                 $redirects = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE post_id = %d AND enabled = 1', $table, $item->post_id ) );
     392                $redirects = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE post_id = %d AND object_type = %s AND enabled = 1', $table, $item->post_id, $is_term ? 'term' : 'post' ) );
     393                $box_name  = $is_term ? 'term_ids[]' : 'post_ids[]';
     394                $box_id    = ( $is_term ? 'slugh-scan-term-' : 'slugh-scan-' ) . (int) $item->post_id;
    303395
    304396                $badges = array();
    … …  
    310402                ?>
    311403                <tr<?php echo $item->is_stale ? ' class="slugh-stale"' : ''; ?>>
    312                         <th scope="row" class="check-column"><label class="screen-reader-text" for="slugh-scan-<?php echo (int) $item->post_id; ?>"><?php esc_html_e( 'Select', 'slugh' ); ?></label><input type="checkbox" name="post_ids[]" id="slugh-scan-<?php echo (int) $item->post_id; ?>" value="<?php echo (int) $item->post_id; ?>" /></th>
     404                        <th scope="row" class="check-column"><label class="screen-reader-text" for="<?php echo esc_attr( $box_id ); ?>"><?php esc_html_e( 'Select', 'slugh' ); ?></label><input type="checkbox" name="<?php echo esc_attr( $box_name ); ?>" id="<?php echo esc_attr( $box_id ); ?>" value="<?php echo (int) $item->post_id; ?>" /></th>
    313405                        <td><?php echo (int) $item->post_id; ?></td>
    314406                        <td><?php echo esc_html( null === $item->post_title ? __( '(deleted)', 'slugh' ) : $item->post_title ); ?></td>
    315                         <td><code><?php echo esc_html( $item->post_type ); ?></code><br><span class="slugh-muted"><?php echo esc_html( $item->post_status ); ?></span></td>
     407                        <td><code><?php echo esc_html( $item->post_type ); ?></code><br><span class="slugh-muted"><?php echo esc_html( $is_term ? __( 'term', 'slugh' ) : $item->post_status ); ?></span></td>
     408                        <?php if ( $multilingual ) : ?>
     409                                <td><?php echo esc_html( Polylang::language_name( Polylang::post_language( $item->post_id ) ) ); ?></td>
     410                        <?php endif; ?>
    316411                        <td dir="ltr"><code class="slugh-slug"><?php echo esc_html( '' === $item->decoded_slug ? '—' : $item->decoded_slug ); ?></code><br><span class="slugh-links"><?php echo esc_html( rawurldecode( $permalink ) ); ?></span></td>
    317412                        <td dir="ltr">
  • slugh/tags/2.0.0/src/Admin/Screens/SettingsScreen.php

    r3795795 r3814912  
    1111use SlugH\Integrations\ConflictDetector;
    1212use SlugH\Integrations\WooCommerce;
     13use SlugH\Slugs\TransliterationSuggester;
    1314use SlugH\Support\PostTypes;
    1415use SlugH\Support\Settings;
     16use SlugH\Support\Taxonomies;
    1517
    1618defined( 'ABSPATH' ) || exit;
    … …  
    5456                                                                <label class="slugh-inline-check"><input type="checkbox" name="supported_post_types[]" value="<?php echo esc_attr( $name ); ?>" <?php checked( in_array( $name, (array) $s['supported_post_types'], true ) ); ?> /> <?php echo esc_html( $object->labels->name ); ?> <code><?php echo esc_html( $name ); ?></code></label>
    5557                                                        <?php endforeach; ?>
    56                                                         <p class="description"><?php esc_html_e( 'Discovered at runtime. Attachments, revisions, menu items, templates, reusable blocks and product variations are never handled.', 'slugh' ); ?></p>
     58                                                        <p class="description"><?php esc_html_e( 'Discovered at runtime. Media (attachments) are off unless you tick them. Revisions, menu items, templates, reusable blocks and product variations are never handled.', 'slugh' ); ?></p>
     59                                                        <p class="description">
     60                                                                <?php
     61                                                                echo esc_html(
     62                                                                        PostTypes::attachment_pages_enabled()
     63                                                                                ? __( 'Attachment pages are on in WordPress: changed media URLs get redirects, including media attached to a record whose URL changes.', 'slugh' )
     64                                                                                : __( 'Attachment pages are off in WordPress (media URLs redirect to the file), so slugH creates no redirects for media slugs.', 'slugh' )
     65                                                                );
     66                                                                ?>
     67                                                        </p>
    5768                                                </fieldset></td>
    5869                                        </tr>
    … …  
    6374                                                                <label class="slugh-inline-check"><input type="checkbox" name="supported_post_statuses[]" value="<?php echo esc_attr( $status ); ?>" <?php checked( in_array( $status, (array) $s['supported_post_statuses'], true ) ); ?> /> <?php echo esc_html( $status ); ?></label>
    6475                                                        <?php endforeach; ?>
     76                                                </fieldset></td>
     77                                        </tr>
     78                                        <tr>
     79                                                <th scope="row"><?php esc_html_e( 'Taxonomies', 'slugh' ); ?></th>
     80                                                <td><fieldset><legend class="screen-reader-text"><?php esc_html_e( 'Taxonomies', 'slugh' ); ?></legend>
     81                                                        <?php foreach ( Taxonomies::get_available() as $name => $object ) : ?>
     82                                                                <label class="slugh-inline-check"><input type="checkbox" name="supported_taxonomies[]" value="<?php echo esc_attr( $name ); ?>" <?php checked( in_array( $name, (array) $s['supported_taxonomies'], true ) ); ?> /> <?php echo esc_html( $object->labels->name ); ?> <code><?php echo esc_html( $name ); ?></code></label>
     83                                                        <?php endforeach; ?>
     84                                                        <p class="description"><?php esc_html_e( 'Term slugs of these taxonomies are scanned and can be changed in the Slug Editor\'s Terms view. A changed term gets one redirect from its old archive URL; its archive pages and feeds follow it.', 'slugh' ); ?></p>
     85                                                        <p><label><input type="checkbox" name="term_edit_redirects" value="1" <?php checked( $s['term_edit_redirects'] ); ?> /> <?php esc_html_e( 'Also redirect the old URL when a term slug is changed elsewhere in WordPress (term edit screen, quick edit). WordPress keeps no old term slugs.', 'slugh' ); ?></label></p>
    6586                                                </fieldset></td>
    6687                                        </tr>
    … …  
    108129                                </table>
    109130
     131                                <h2><?php esc_html_e( 'Slug suggestions', 'slugh' ); ?></h2>
     132                                <table class="form-table" role="presentation">
     133                                        <tr>
     134                                                <th scope="row"><?php esc_html_e( 'Transliteration', 'slugh' ); ?></th>
     135                                                <td>
     136                                                        <label><input type="checkbox" name="transliteration" value="1" <?php checked( $s['transliteration'] ); ?> /> <?php esc_html_e( 'Suggest Latin spellings for slugs in other scripts', 'slugh' ); ?></label>
     137                                                        <p class="description"><?php esc_html_e( 'Suggestions only: you see and can edit every suggestion in the preview, and nothing changes until you apply a job. Bangla uses slugH\'s own phonetic rules (for example আমার সোনার বাংলা becomes amar-sonar-bangla). Spellings vary, so check each one.', 'slugh' ); ?></p>
     138                                                        <?php if ( ! TransliterationSuggester::icu_available() ) : ?>
     139                                                                <p class="description"><?php esc_html_e( 'PHP intl transliteration for other scripts is not available on this server (the intl extension or its script data is missing), so only Bangla slugs get Latin suggestions. Other scripts (Hindi, Arabic, Urdu and others) get the basic cleanup only.', 'slugh' ); ?></p>
     140                                                        <?php endif; ?>
     141                                                </td>
     142                                        </tr>
     143                                </table>
     144
    110145                                <h2><?php esc_html_e( 'Updates, cache and trial mode', 'slugh' ); ?></h2>
    111146                                <table class="form-table" role="presentation">
  • slugh/tags/2.0.0/src/Database/Migrations.php

    r3795795 r3814912  
    2626                        // Adds job_items.sort_order, scan_items.permalink_hash and redirects.destination_hash.
    2727                        '1.1.0' => array( __CLASS__, 'migrate_1_1_0' ),
     28                        // Adds object_type (post/term) to redirects, job_items and scan_items; scan_items key includes it.
     29                        '1.2.0' => array( __CLASS__, 'migrate_1_2_0' ),
    2830                );
    2931        }
    … …  
    5860                require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    5961
     62                self::prepare_scan_items_key();
     63
    6064                foreach ( Schema::get_schemas() as $sql ) {
    6165                        dbDelta( $sql );
    6266                }
     67        }
     68
     69        /**
     70         * Before dbDelta: give an existing scan_items table the object_type column and the
     71         * (scan_id, object_type, post_id) primary key. dbDelta cannot change a primary key and
     72         * would fail with "Multiple primary key defined".
     73         *
     74         * @return void
     75         */
     76        private static function prepare_scan_items_key() {
     77                global $wpdb;
     78
     79                $table = Schema::get_table_name( 'slugh_scan_items' );
     80                // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
     81                if ( $table !== $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) ) ) ) {
     82                        return;
     83                }
     84                $primary = (array) $wpdb->get_col( $wpdb->prepare( "SHOW INDEX FROM %i WHERE Key_name = 'PRIMARY'", $table ), 4 );
     85                if ( in_array( 'object_type', $primary, true ) ) {
     86                        return;
     87                }
     88                $has_column = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW COLUMNS FROM %i LIKE %s', $table, 'object_type' ) );
     89                if ( ! $has_column ) {
     90                        $wpdb->query( $wpdb->prepare( "ALTER TABLE %i ADD COLUMN object_type varchar(10) NOT NULL DEFAULT 'post' AFTER post_id", $table ) );
     91                }
     92                $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i DROP PRIMARY KEY, ADD PRIMARY KEY (scan_id, object_type, post_id)', $table ) );
     93                // phpcs:enable
    6394        }
    6495
    … …  
    85116
    86117        /**
     118         * Step 1.2.0: add object_type columns (existing rows become "post"); install() widens
     119         * the scan_items primary key first.
     120         *
     121         * @return void
     122         */
     123        public static function migrate_1_2_0() {
     124                self::install();
     125        }
     126
     127        /**
    87128         * Drop all custom tables (used only on uninstall when configured).
    88129         *
  • slugh/tags/2.0.0/src/Database/Schema.php

    r3795795 r3814912  
    1515class Schema {
    1616
    17         const DB_VERSION        = '1.1.0';
     17        const DB_VERSION        = '1.2.0';
    1818        const DB_VERSION_OPTION = 'slugh_db_version';
    1919
    … …  
    7272                                match_mode varchar(20) NOT NULL DEFAULT '404_only',
    7373                                post_id bigint(20) unsigned DEFAULT NULL,
     74                                object_type varchar(10) NOT NULL DEFAULT 'post',
    7475                                job_id bigint(20) unsigned DEFAULT NULL,
    7576                                origin varchar(20) NOT NULL DEFAULT 'manual',
    … …  
    112113                                job_id bigint(20) unsigned NOT NULL,
    113114                                post_id bigint(20) unsigned NOT NULL,
     115                                object_type varchar(10) NOT NULL DEFAULT 'post',
    114116                                kind varchar(20) NOT NULL DEFAULT 'direct',
    115117                                post_type varchar(50) NOT NULL,
    … …  
    139141                                scan_id bigint(20) unsigned NOT NULL,
    140142                                post_id bigint(20) unsigned NOT NULL,
     143                                object_type varchar(10) NOT NULL DEFAULT 'post',
    141144                                post_type varchar(50) NOT NULL,
    142145                                post_status varchar(20) NOT NULL,
    … …  
    146149                                permalink_hash char(40) NOT NULL DEFAULT '',
    147150                                scanned_at datetime NOT NULL,
    148                                 PRIMARY KEY  (scan_id, post_id),
     151                                PRIMARY KEY  (scan_id, object_type, post_id),
    149152                                KEY scan_id_post_type (scan_id, post_type),
    150153                                KEY scan_id_permalink (scan_id, permalink_hash)
  • slugh/tags/2.0.0/src/Jobs/DraftManager.php

    r3795795 r3814912  
    99
    1010use SlugH\Slugs\SlugValidator;
     11use SlugH\Slugs\TermSlugs;
    1112use SlugH\Support\PostTypes;
     13use SlugH\Support\Taxonomies;
    1214
    1315defined( 'ABSPATH' ) || exit;
    … …  
    117119                        );
    118120                }
    119                 if ( ! in_array( $post->post_status, PostTypes::SUPPORTED_STATUSES, true ) ) {
     121                if ( ! in_array( $post->post_status, PostTypes::query_statuses( array( $post->post_type ), PostTypes::SUPPORTED_STATUSES ), true ) ) {
    120122                        return array(
    121123                                'status'  => 'error',
    … …  
    184186
    185187        /**
    186          * Remove a post's change from a draft.
    187          *
    188          * @param int $job_id  Job ID.
    189          * @param int $post_id Post ID.
     188         * Add or update one draft change for a taxonomy term (spec section 26.5).
     189         *
     190         * @param int         $job_id            Draft job ID.
     191         * @param int         $term_id           Term ID.
     192         * @param string      $new_slug          Proposed slug.
     193         * @param string|null $expected_old_slug Old slug safeguard (null = current slug).
     194         * @param string|null $expected_taxonomy Taxonomy safeguard (null = current taxonomy).
     195         * @param array       $extra             Extra message data.
     196         * @return array{status: string, item_id?: int, message?: string}
     197         */
     198        public static function upsert_term_item( $job_id, $term_id, $new_slug, $expected_old_slug = null, $expected_taxonomy = null, array $extra = array() ) {
     199                $job = JobRepository::get( $job_id );
     200                if ( ! $job || ! in_array( $job->status, array( 'draft', 'validated' ), true ) ) {
     201                        return array(
     202                                'status'  => 'error',
     203                                'message' => __( 'This job is no longer a draft.', 'slugh' ),
     204                        );
     205                }
     206                $term = get_term( absint( $term_id ) );
     207                if ( ! $term instanceof \WP_Term ) {
     208                        return array(
     209                                'status'  => 'error',
     210                                'message' => __( 'No term with this ID.', 'slugh' ),
     211                        );
     212                }
     213                if ( null !== $expected_taxonomy && '' !== $expected_taxonomy && sanitize_key( $expected_taxonomy ) !== $term->taxonomy ) {
     214                        return array(
     215                                'status'  => 'error',
     216                                /* translators: 1: term ID, 2: taxonomy */
     217                                'message' => sprintf( __( 'Term %1$d is not in the taxonomy "%2$s".', 'slugh' ), (int) $term->term_id, sanitize_key( $expected_taxonomy ) ),
     218                        );
     219                }
     220                if ( ! Taxonomies::is_supported( $term->taxonomy ) ) {
     221                        return array(
     222                                'status'  => 'error',
     223                                /* translators: %s: taxonomy */
     224                                'message' => sprintf( __( 'Taxonomy "%s" is not managed by slugH.', 'slugh' ), $term->taxonomy ),
     225                        );
     226                }
     227                if ( ! current_user_can( 'edit_term', $term->term_id ) ) {
     228                        return array(
     229                                'status'  => 'error',
     230                                'message' => __( 'You cannot edit this term.', 'slugh' ),
     231                        );
     232                }
     233
     234                $requested = self::sanitize_candidate( $new_slug );
     235                if ( '' === $requested ) {
     236                        return array(
     237                                'status'  => 'error',
     238                                'message' => __( 'The new slug is empty after sanitization.', 'slugh' ),
     239                        );
     240                }
     241
     242                $existing = JobRepository::find_item( $job_id, $term->term_id, 'term' );
     243                $expected = null === $expected_old_slug ? ( $existing ? $existing->old_post_name : $term->slug ) : (string) $expected_old_slug;
     244
     245                if ( SlugValidator::compare_form( $requested ) === SlugValidator::compare_form( $term->slug ) && SlugValidator::compare_form( $expected ) === SlugValidator::compare_form( $term->slug ) ) {
     246                        if ( $existing ) {
     247                                JobRepository::delete_draft_item( $existing->id );
     248                        }
     249                        self::mark_dirty( $job_id );
     250                        return array(
     251                                'status'  => 'unchanged',
     252                                'message' => __( 'Same as the current slug; nothing to change.', 'slugh' ),
     253                        );
     254                }
     255
     256                $data = array(
     257                        'post_id'             => $term->term_id,
     258                        'object_type'         => 'term',
     259                        'kind'                => 'direct',
     260                        'post_type'           => $term->taxonomy,
     261                        'parent_id'           => (int) $term->parent,
     262                        'old_post_name'       => $expected,
     263                        'requested_post_name' => $requested,
     264                        'old_permalink'       => TermSlugs::link( $term ),
     265                        'validation_state'    => 'pending',
     266                        'result'              => 'pending',
     267                        'message'             => array_merge( array( 'input' => (string) $new_slug ), $extra ),
     268                );
     269
     270                if ( $existing ) {
     271                        JobRepository::update_item( $existing->id, $data );
     272                        $item_id = $existing->id;
     273                } else {
     274                        $item_id = JobRepository::add_item( $job_id, $data );
     275                }
     276                self::mark_dirty( $job_id );
     277
     278                return array(
     279                        'status'  => $existing ? 'updated' : 'added',
     280                        'item_id' => $item_id,
     281                );
     282        }
     283
     284        /**
     285         * Remove a post's or term's change from a draft.
     286         *
     287         * @param int    $job_id      Job ID.
     288         * @param int    $post_id     Post or term ID.
     289         * @param string $object_type post or term.
    190290         * @return bool
    191291         */
    192         public static function remove_item( $job_id, $post_id ) {
    193                 $item = JobRepository::find_item( $job_id, $post_id );
     292        public static function remove_item( $job_id, $post_id, $object_type = 'post' ) {
     293                $item = JobRepository::find_item( $job_id, $post_id, $object_type );
    194294                if ( ! $item ) {
    195295                        return false;
    … …  
    230330        /**
    231331         * Parse "content_id,new_slug" lines (comma or tab separated) into the draft.
     332         * A third column with a taxonomy makes the line a term: "term_id,new_slug,category".
    232333         *
    233334         * @param int    $job_id Draft job ID.
    … …  
    252353                        }
    253354
    254                         $parts = false !== strpos( $line, "\t" ) ? explode( "\t", $line, 2 ) : str_getcsv( $line, ',', '"', '\\' );
     355                        $parts = false !== strpos( $line, "\t" ) ? explode( "\t", $line, 3 ) : str_getcsv( $line, ',', '"', '\\' );
    255356                        if ( count( $parts ) < 2 ) {
    256357                                $report['errors'][] = array(
    … …  
    262363                        }
    263364
    264                         $id   = trim( (string) $parts[0] );
    265                         $slug = trim( (string) $parts[1] );
     365                        $id       = trim( (string) $parts[0] );
     366                        $slug     = trim( (string) $parts[1] );
     367                        $taxonomy = isset( $parts[2] ) ? sanitize_key( trim( (string) $parts[2] ) ) : '';
    266368
    267369                        if ( ! preg_match( '/^[0-9]+$/D', $id ) ) {
    … …  
    277379                        }
    278380
    279                         if ( isset( $seen[ $id ] ) ) {
     381                        $seen_key = ( '' === $taxonomy ? 'post:' : 'term:' ) . $id;
     382                        if ( isset( $seen[ $seen_key ] ) ) {
    280383                                $report['errors'][] = array(
    281384                                        'line'   => $line_number,
    282385                                        'text'   => $line,
    283386                                        /* translators: %d: earlier line number */
    284                                         'reason' => sprintf( __( 'Duplicate content ID; line %d already sets it.', 'slugh' ), $seen[ $id ] ),
    285                                 );
    286                                 continue;
    287                         }
    288                         $seen[ $id ] = $line_number;
    289 
    290                         $res = self::upsert_item( $job_id, (int) $id, $slug, null, null, array( 'source' => 'paste' ) );
     387                                        'reason' => sprintf( __( 'Duplicate content ID; line %d already sets it.', 'slugh' ), $seen[ $seen_key ] ),
     388                                );
     389                                continue;
     390                        }
     391                        $seen[ $seen_key ] = $line_number;
     392
     393                        $res = '' === $taxonomy
     394                                ? self::upsert_item( $job_id, (int) $id, $slug, null, null, array( 'source' => 'paste' ) )
     395                                : self::upsert_term_item( $job_id, (int) $id, $slug, null, $taxonomy, array( 'source' => 'paste' ) );
    291396                        if ( 'error' === $res['status'] ) {
    292397                                $report['errors'][] = array(
    … …  
    358463                                continue;
    359464                        }
    360                         if ( isset( $seen[ $id ] ) ) {
     465                        // A "taxonomy" column (spec section 26.5) makes the row a term; content_id is then a term ID.
     466                        $taxonomy = isset( $data['taxonomy'] ) ? sanitize_key( (string) $data['taxonomy'] ) : '';
     467                        $seen_key = ( '' === $taxonomy ? 'post:' : 'term:' ) . $id;
     468                        if ( isset( $seen[ $seen_key ] ) ) {
    361469                                $report['errors'][] = array(
    362470                                        'line'   => $line,
    363471                                        /* translators: %d: earlier line number */
    364                                         'reason' => sprintf( __( 'Duplicate content_id; line %d already sets it.', 'slugh' ), $seen[ $id ] ),
    365                                 );
    366                                 continue;
    367                         }
    368                         $seen[ $id ] = $line;
    369 
    370                         $res = self::upsert_item(
    371                                 $job_id,
    372                                 (int) $id,
    373                                 (string) $data['new_slug'],
    374                                 (string) $data['old_slug'],
    375                                 (string) $data['post_type'],
    376                                 array(
    377                                         'source' => 'csv',
    378                                         'line'   => $line,
    379                                 )
    380                         );
     472                                        'reason' => sprintf( __( 'Duplicate content_id; line %d already sets it.', 'slugh' ), $seen[ $seen_key ] ),
     473                                );
     474                                continue;
     475                        }
     476                        $seen[ $seen_key ] = $line;
     477
     478                        $extra = array(
     479                                'source' => 'csv',
     480                                'line'   => $line,
     481                        );
     482                        $res   = '' === $taxonomy
     483                                ? self::upsert_item( $job_id, (int) $id, (string) $data['new_slug'], (string) $data['old_slug'], (string) $data['post_type'], $extra )
     484                                : self::upsert_term_item( $job_id, (int) $id, (string) $data['new_slug'], (string) $data['old_slug'], $taxonomy, $extra );
    381485
    382486                        if ( 'error' === $res['status'] ) {
  • slugh/tags/2.0.0/src/Jobs/JobRepository.php

    r3795795 r3814912  
    99
    1010use SlugH\Database\Schema;
     11use SlugH\Integrations\Polylang;
    1112
    1213defined( 'ABSPATH' ) || exit;
    … …  
    214215                        'job_id'              => absint( $job_id ),
    215216                        'post_id'             => absint( $data['post_id'] ),
     217                        'object_type'         => isset( $data['object_type'] ) && 'term' === $data['object_type'] ? 'term' : 'post',
    216218                        'kind'                => isset( $data['kind'] ) && 'descendant' === $data['kind'] ? 'descendant' : 'direct',
    217219                        'post_type'           => isset( $data['post_type'] ) ? sanitize_key( $data['post_type'] ) : '',
    … …  
    229231
    230232                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    231                 $wpdb->insert( self::items_table(), $row, array( '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s' ) );
     233                $wpdb->insert( self::items_table(), $row, array( '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s' ) );
    232234                return (int) $wpdb->insert_id;
    233235        }
    … …  
    324326
    325327        /**
    326          * Find a job's direct item for a post.
    327          *
    328          * @param int $job_id  Job ID.
    329          * @param int $post_id Post ID.
     328         * Find a job's direct item for a post or term.
     329         *
     330         * @param int    $job_id      Job ID.
     331         * @param int    $post_id     Post or term ID.
     332         * @param string $object_type post or term.
    330333         * @return object|null
    331334         */
    332         public static function find_item( $job_id, $post_id ) {
     335        public static function find_item( $job_id, $post_id, $object_type = 'post' ) {
    333336                global $wpdb;
    334337                $table = self::items_table();
    335338                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    336                 $item = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE job_id = %d AND post_id = %d AND kind = 'direct' LIMIT 1", $table, absint( $job_id ), absint( $post_id ) ) );
     339                $item = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE job_id = %d AND post_id = %d AND object_type = %s AND kind = 'direct' LIMIT 1", $table, absint( $job_id ), absint( $post_id ), 'term' === $object_type ? 'term' : 'post' ) );
    337340                return $item ? self::decode_item( $item ) : null;
    338341        }
    … …  
    419422
    420423        /**
    421          * Find in-job duplicates: same new slug, post type and parent among active direct items.
     424         * Find in-job duplicates: same new slug, post type, parent (and language with Polylang) among active direct items.
    422425         *
    423426         * @param int $job_id Job ID.
    424          * @return array<string, bool> Keys "post_type|parent_id|slug".
     427         * @return array<string, bool> Keys from duplicate_key().
    425428         */
    426429        public static function duplicate_keys( $job_id ) {
    427430                global $wpdb;
    428431                $table = self::items_table();
     432                // Terms are unique per taxonomy whatever their parent, so their parent is grouped as 0.
    429433                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    430                 $rows = $wpdb->get_results( $wpdb->prepare( "SELECT post_type, parent_id, requested_post_name FROM %i WHERE job_id = %d AND kind = 'direct' AND result NOT IN ('excluded','unchanged') GROUP BY post_type, parent_id, requested_post_name HAVING COUNT(*) > 1", $table, absint( $job_id ) ) );
     434                $rows = $wpdb->get_results( $wpdb->prepare( "SELECT object_type, post_type, CASE WHEN object_type = 'term' THEN 0 ELSE parent_id END AS parent_id, requested_post_name FROM %i WHERE job_id = %d AND kind = 'direct' AND result NOT IN ('excluded','unchanged') GROUP BY object_type, post_type, CASE WHEN object_type = 'term' THEN 0 ELSE parent_id END, requested_post_name HAVING COUNT(*) > 1", $table, absint( $job_id ) ) );
    431435                $keys = array();
     436
     437                if ( ! Polylang::is_active() ) {
     438                        foreach ( (array) $rows as $row ) {
     439                                $keys[ self::duplicate_key( self::key_type( $row->object_type, $row->post_type ), $row->parent_id, $row->requested_post_name ) ] = true;
     440                        }
     441                        return $keys;
     442                }
     443
     444                // With Polylang, records in different languages may share a slug: split each group by language.
     445                $counts = array();
    432446                foreach ( (array) $rows as $row ) {
    433                         $keys[ self::duplicate_key( $row->post_type, $row->parent_id, $row->requested_post_name ) ] = true;
     447                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     448                        if ( 'term' === $row->object_type ) {
     449                                // Term languages are not compared: WordPress keeps term slugs unique per taxonomy.
     450                                $keys[ self::duplicate_key( self::key_type( 'term', $row->post_type ), 0, $row->requested_post_name ) ] = true;
     451                                continue;
     452                        }
     453                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     454                        $ids       = array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( "SELECT post_id FROM %i WHERE job_id = %d AND kind = 'direct' AND object_type = 'post' AND result NOT IN ('excluded','unchanged') AND post_type = %s AND parent_id = %d AND requested_post_name = %s", $table, absint( $job_id ), $row->post_type, (int) $row->parent_id, $row->requested_post_name ) ) );
     455                        $languages = Polylang::languages_for( $ids );
     456                        foreach ( $ids as $id ) {
     457                                $key            = self::duplicate_key( $row->post_type, $row->parent_id, $row->requested_post_name, isset( $languages[ $id ] ) ? $languages[ $id ] : '' );
     458                                $counts[ $key ] = isset( $counts[ $key ] ) ? $counts[ $key ] + 1 : 1;
     459                        }
     460                }
     461                foreach ( $counts as $key => $count ) {
     462                        if ( $count > 1 ) {
     463                                $keys[ $key ] = true;
     464                        }
    434465                }
    435466                return $keys;
    … …  
    442473         * @param int    $parent_id Parent ID.
    443474         * @param string $slug      Sanitized slug.
     475         * @param string $language  Polylang language slug ('' without Polylang or without a language).
    444476         * @return string
    445477         */
    446         public static function duplicate_key( $post_type, $parent_id, $slug ) {
    447                 return $post_type . '|' . ( is_post_type_hierarchical( $post_type ) ? (int) $parent_id : 0 ) . '|' . $slug;
     478        public static function duplicate_key( $post_type, $parent_id, $slug, $language = '' ) {
     479                return self::duplicate_key_prefix( $post_type, $parent_id, $language ) . $slug;
     480        }
     481
     482        /**
     483         * Type part of a duplicate key: the post type, or "term:<taxonomy>".
     484         *
     485         * @param string $object_type post or term.
     486         * @param string $type        Post type or taxonomy.
     487         * @return string
     488         */
     489        public static function key_type( $object_type, $type ) {
     490                return 'term' === $object_type ? 'term:' . $type : $type;
     491        }
     492
     493        /**
     494         * Everything of the duplicate key before the slug (also used by the Slug Editor script).
     495         *
     496         * @param string $post_type Post type.
     497         * @param int    $parent_id Parent ID.
     498         * @param string $language  Polylang language slug or ''.
     499         * @return string
     500         */
     501        public static function duplicate_key_prefix( $post_type, $parent_id, $language = '' ) {
     502                $prefix = $post_type . '|' . ( is_post_type_hierarchical( $post_type ) ? (int) $parent_id : 0 ) . '|';
     503                return '' === $language ? $prefix : $prefix . 'lang:' . $language . '|';
    448504        }
    449505
  • slugh/tags/2.0.0/src/Jobs/JobRunner.php

    r3795795 r3814912  
    99
    1010use SlugH\Integrations\CacheManager;
     11use SlugH\Integrations\Polylang;
    1112use SlugH\Redirects\Normalizer;
    1213use SlugH\Redirects\RedirectRepository;
    … …  
    1617use SlugH\Slugs\SlugUpdater;
    1718use SlugH\Slugs\SlugValidator;
     19use SlugH\Slugs\TermSlugs;
     20use SlugH\Support\PostTypes;
    1821use SlugH\Support\Settings;
    1922
    … …  
    8790         */
    8891        private static function validate_item( $item, array $duplicates ) {
    89                 $key        = JobRepository::duplicate_key( $item->post_type, $item->parent_id, $item->requested_post_name );
    90                 $validation = SlugValidator::validate(
    91                         $item->post_id,
    92                         $item->requested_post_name,
    93                         array(
    94                                 'expected_old_slug'  => $item->old_post_name,
    95                                 'expected_post_type' => $item->post_type,
    96                                 'in_job_duplicate'   => isset( $duplicates[ $key ] ),
    97                         )
    98                 );
     92                if ( self::is_term( $item ) ) {
     93                        $key        = JobRepository::duplicate_key( JobRepository::key_type( 'term', $item->post_type ), 0, $item->requested_post_name );
     94                        $validation = TermSlugs::validate(
     95                                $item->post_id,
     96                                $item->requested_post_name,
     97                                array(
     98                                        'expected_old_slug' => $item->old_post_name,
     99                                        'expected_taxonomy' => $item->post_type,
     100                                        'in_job_duplicate'  => isset( $duplicates[ $key ] ),
     101                                )
     102                        );
     103                } else {
     104                        $key        = JobRepository::duplicate_key( $item->post_type, $item->parent_id, $item->requested_post_name, Polylang::post_language( $item->post_id ) );
     105                        $validation = SlugValidator::validate(
     106                                $item->post_id,
     107                                $item->requested_post_name,
     108                                array(
     109                                        'expected_old_slug'  => $item->old_post_name,
     110                                        'expected_post_type' => $item->post_type,
     111                                        'in_job_duplicate'   => isset( $duplicates[ $key ] ),
     112                                )
     113                        );
     114                }
    99115
    100116                $state  = $validation['state'];
    … …  
    115131
    116132                return $validation;
     133        }
     134
     135        /**
     136         * Whether a job item is a taxonomy term.
     137         *
     138         * @param object $item Item.
     139         * @return bool
     140         */
     141        public static function is_term( $item ) {
     142                return isset( $item->object_type ) && 'term' === $item->object_type;
    117143        }
    118144
    … …  
    276302                $direct_ids = array();
    277303                foreach ( $included as $item ) {
    278                         $direct_ids[ $item->post_id ] = true;
     304                        if ( ! self::is_term( $item ) ) {
     305                                $direct_ids[ $item->post_id ] = true;
     306                        }
    279307                }
    280308
    281309                $descendant_count = 0;
    282310                foreach ( $included as $item ) {
     311                        if ( self::is_term( $item ) ) {
     312                                // Term snapshot: name, description, parent, taxonomy and term meta hashes. Terms have no descendant items:
     313                                // child terms still answer under the old path (spec section 26.5).
     314                                $term       = get_term( $item->post_id );
     315                                $components = TermSlugs::components( $item->post_id );
     316                                JobRepository::merge_item_message(
     317                                        $item,
     318                                        array(
     319                                                'snapshot' => array(
     320                                                        'post_status' => 'publish',
     321                                                        'url_status'  => 'publish',
     322                                                        'post_parent' => $term instanceof \WP_Term ? (int) $term->parent : 0,
     323                                                        'components'  => $components,
     324                                                ),
     325                                        ),
     326                                        array(
     327                                                'old_post_name' => $term instanceof \WP_Term ? $term->slug : $item->old_post_name,
     328                                                'old_permalink' => TermSlugs::link( $item->post_id ),
     329                                                'post_type'     => $term instanceof \WP_Term ? $term->taxonomy : $item->post_type,
     330                                                'parent_id'     => $term instanceof \WP_Term ? (int) $term->parent : 0,
     331                                                'hash_before'   => IntegrityChecker::combine( $components ),
     332                                                'sort_order'    => 0,
     333                                        )
     334                                );
     335                                continue;
     336                        }
    283337                        $post = get_post( $item->post_id );
    284338
    … …  
    290344                                        'snapshot' => array(
    291345                                                'post_status'   => $post->post_status,
     346                                                'url_status'    => PostTypes::url_status( $post ),
    292347                                                'post_parent'   => (int) $post->post_parent,
    293348                                                'post_modified' => $post->post_modified,
    … …  
    306361
    307362                        $validation = isset( $item->message['validation'] ) ? $item->message['validation'] : array();
    308                         if ( empty( $validation['url_changes'] ) || ! is_post_type_hierarchical( $post->post_type ) ) {
     363                        if ( empty( $validation['url_changes'] ) ) {
    309364                                continue;
    310365                        }
    311366
    312                         // Descendant snapshots; a descendant that is itself a direct item handles its own URL.
    313                         foreach ( DescendantPropagator::get_descendants( $post->ID ) as $descendant_id ) {
     367                        // Descendant snapshots (child records, then attachments under any of them);
     368                        // a descendant that is itself a direct item handles its own URL.
     369                        $descendants = is_post_type_hierarchical( $post->post_type ) ? DescendantPropagator::get_descendants( $post->ID ) : array();
     370                        $descendants = array_merge( $descendants, DescendantPropagator::get_attachments( $post->ID, $descendants ) );
     371                        foreach ( $descendants as $descendant_id ) {
    314372                                if ( isset( $direct_ids[ $descendant_id ] ) || self::has_descendant_item( $job_id, $descendant_id ) ) {
    315373                                        continue;
    … …  
    331389                                                'message'             => array(
    332390                                                        'parent_item' => $item->id,
    333                                                         'snapshot'    => array( 'post_status' => $descendant->post_status ),
     391                                                        'snapshot'    => array(
     392                                                                'post_status' => $descendant->post_status,
     393                                                                'url_status'  => PostTypes::url_status( $descendant ),
     394                                                        ),
    334395                                                ),
    335396                                        )
    … …  
    392453                $table = \SlugH\Database\Schema::get_table_name( 'slugh_job_items' );
    393454                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    394                 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 ) );
     455                return (bool) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM %i WHERE job_id = %d AND post_id = %d AND object_type = 'post' AND kind = 'descendant' LIMIT 1", $table, $job_id, $post_id ) );
    395456        }
    396457
    … …  
    520581         */
    521582        private static function process_direct( $job, $item ) {
    522                 $validation = SlugValidator::validate(
    523                         $item->post_id,
    524                         $item->requested_post_name,
    525                         array(
    526                                 'expected_old_slug'  => $item->old_post_name,
    527                                 'expected_post_type' => $item->post_type,
    528                         )
    529                 );
     583                $validation = self::is_term( $item )
     584                        ? TermSlugs::validate(
     585                                $item->post_id,
     586                                $item->requested_post_name,
     587                                array(
     588                                        'expected_old_slug' => $item->old_post_name,
     589                                        'expected_taxonomy' => $item->post_type,
     590                                )
     591                        )
     592                        : SlugValidator::validate(
     593                                $item->post_id,
     594                                $item->requested_post_name,
     595                                array(
     596                                        'expected_old_slug'  => $item->old_post_name,
     597                                        'expected_post_type' => $item->post_type,
     598                                )
     599                        );
    530600
    531601                if ( 'stale' === $validation['state'] ) {
    … …  
    562632                }
    563633
    564                 $post       = get_post( $item->post_id );
    565                 $old_status = $post->post_status;
     634                $is_term    = self::is_term( $item );
     635                $post       = $is_term ? null : get_post( $item->post_id );
     636                $old_status = $is_term ? 'publish' : PostTypes::url_status( $post );
    566637                $redirect   = array(
    567638                        'ids'       => array(),
    … …  
    581652                }
    582653
    583                 $update = SlugUpdater::update( $item->post_id, $item->requested_post_name, $job->id );
     654                $update = $is_term ? TermSlugs::update( $item->post_id, $item->requested_post_name, $job->id ) : SlugUpdater::update( $item->post_id, $item->requested_post_name, $job->id );
    584655                if ( is_wp_error( $update ) ) {
    585656                        return self::finish_item(
    … …  
    614685                        $notes['changed_fields'] = $update['changed_fields'];
    615686                        self::finish_item( $item, 'integrity_changed', $notes, $columns );
    616                         AuditLogger::log( 'integrity_changed', 'post', $item->post_id, null, array( 'fields' => $update['changed_fields'] ), $job->id );
     687                        AuditLogger::log( 'integrity_changed', $is_term ? 'term' : 'post', $item->post_id, null, array( 'fields' => $update['changed_fields'] ), $job->id );
    617688                        return 'integrity_changed';
    618689                }
    … …  
    630701                                        'origin'      => 'job',
    631702                                        'post_id'     => $item->post_id,
     703                                        'object_type' => $is_term ? 'term' : 'post',
    632704                                        'job_id'      => $job->id,
    633705                                        'on_conflict' => 'keep' === $resolution ? 'keep' : ( 'replace' === $resolution ? 'replace' : 'error' ),
    … …  
    641713                }
    642714
    643                 CacheManager::purge_urls( array( $item->old_permalink, $update['actual_permalink'] ), $item->post_id );
     715                CacheManager::purge_urls( array( $item->old_permalink, $update['actual_permalink'] ), $is_term ? 0 : $item->post_id );
    644716
    645717                AuditLogger::log(
    646718                        'slug_apply',
    647                         'post',
     719                        $is_term ? 'term' : 'post',
    648720                        $item->post_id,
    649721                        array(
    … …  
    702774                $public_statuses = Settings::get( 'redirect_private_posts', false ) ? array( 'publish', 'private' ) : array( 'publish' );
    703775
    704                 if ( Settings::MODE_SLUGH === $mode && in_array( $post->post_status, $public_statuses, true ) ) {
     776                if ( Settings::MODE_SLUGH === $mode && in_array( PostTypes::url_status( $post ), $public_statuses, true ) ) {
    705777                        $created = RedirectRepository::create(
    706778                                array(
    … …  
    802874                                continue;
    803875                        }
    804                         $status_before = isset( $item->message['snapshot']['post_status'] ) ? $item->message['snapshot']['post_status'] : 'publish';
     876                        $snapshot      = isset( $item->message['snapshot'] ) ? (array) $item->message['snapshot'] : array();
     877                        $status_before = isset( $snapshot['url_status'] ) ? $snapshot['url_status'] : ( isset( $snapshot['post_status'] ) ? $snapshot['post_status'] : 'publish' );
    805878                        if ( ! in_array( $status_before, array( 'publish', 'private' ), true ) ) {
    806879                                continue;
  • slugh/tags/2.0.0/src/Jobs/RollbackManager.php

    r3795795 r3814912  
    88namespace SlugH\Jobs;
    99
     10use SlugH\Database\Schema;
    1011use SlugH\Integrations\CacheManager;
    1112use SlugH\Redirects\Normalizer;
    … …  
    1314use SlugH\Slugs\DescendantPropagator;
    1415use SlugH\Slugs\SlugUpdater;
     16use SlugH\Slugs\TermSlugs;
     17use SlugH\Support\PostTypes;
    1518use SlugH\Support\Settings;
    1619
    … …  
    149152                                'post_id'             => $item->post_id,
    150153                                'kind'                => $item->kind,
     154                                'object_type'         => isset( $item->object_type ) ? $item->object_type : 'post',
    151155                                'post_type'           => $item->post_type,
    152156                                'parent_id'           => $item->parent_id,
    … …  
    160164                                'message'             => array(
    161165                                        'target_item' => $item->id,
    162                                         'snapshot'    => isset( $item->message['snapshot'] ) ? array( 'post_status' => isset( $item->message['snapshot']['post_status'] ) ? $item->message['snapshot']['post_status'] : '' ) : array(),
     166                                        'snapshot'    => isset( $item->message['snapshot'] ) ? array_intersect_key( (array) $item->message['snapshot'], array_flip( array( 'post_status', 'url_status' ) ) ) : array(),
    163167                                ),
    164168                        )
    … …  
    177181                if ( ! $target_item ) {
    178182                        return JobRunner::finish_item( $item, 'failed', array( 'reason' => 'target_missing' ) );
     183                }
     184
     185                if ( JobRunner::is_term( $item ) ) {
     186                        return self::process_term( $job, $item, $target_item );
    179187                }
    180188
    … …  
    200208                $current_link = (string) get_permalink( $post );
    201209
    202                 // The record must still be exactly as the job left it.
    203                 if ( $post->post_name !== $item->old_post_name || Normalizer::normalize_path( $current_link ) !== Normalizer::normalize_path( $item->old_permalink ) ) {
     210                // The record must still be exactly as the job left it. When this rollback has already restored
     211                // an ancestor (a parent page, or the record an attachment belongs to), the URL moved with it,
     212                // so only the record's own slug is compared.
     213                $url_moved = self::ancestor_restored( $job->id, $post );
     214                if ( $post->post_name !== $item->old_post_name || ( ! $url_moved && Normalizer::normalize_path( $current_link ) !== Normalizer::normalize_path( $item->old_permalink ) ) ) {
    204215                        return JobRunner::finish_item(
    205216                                $item,
    … …  
    207218                                array(
    208219                                        'reason' => 'changed_since_job',
    209                                         'detail' => sprintf(
    210                                                 /* translators: 1: slug the job set, 2: current slug */
    211                                                 __( 'The slug changed after the job (job set "%1$s", now "%2$s").', 'slugh' ),
    212                                                 rawurldecode( $item->old_post_name ),
    213                                                 rawurldecode( $post->post_name )
    214                                         ),
     220                                        'detail' => $post->post_name !== $item->old_post_name
     221                                                ? sprintf(
     222                                                        /* translators: 1: slug the job set, 2: current slug */
     223                                                        __( 'The slug changed after the job (job set "%1$s", now "%2$s").', 'slugh' ),
     224                                                        rawurldecode( $item->old_post_name ),
     225                                                        rawurldecode( $post->post_name )
     226                                                )
     227                                                : sprintf(
     228                                                        /* translators: 1: URL after the job, 2: current URL */
     229                                                        __( 'The URL changed after the job, for example because a parent changed (job left "%1$s", now "%2$s").', 'slugh' ),
     230                                                        rawurldecode( $item->old_permalink ),
     231                                                        rawurldecode( $current_link )
     232                                                ),
    215233                                )
    216234                        );
    … …  
    261279
    262280                $redirect = self::undo_redirects( $job, $target_item );
    263                 $reverse  = self::reverse_redirect( $job, $item, $update['actual_permalink'], $post->post_status );
     281                $reverse  = self::reverse_redirect( $job, $item, $update['actual_permalink'], PostTypes::url_status( $post ) );
    264282                if ( $reverse ) {
    265283                        JobRunner::record_redirect( $redirect, $reverse );
    … …  
    302320
    303321                $redirect = self::undo_redirects( $job, $target_item );
    304                 $reverse  = self::reverse_redirect( $job, $item, $current_link, $post->post_status );
     322                $reverse  = self::reverse_redirect( $job, $item, $current_link, PostTypes::url_status( $post ) );
    305323                if ( $reverse ) {
    306324                        JobRunner::record_redirect( $redirect, $reverse );
    … …  
    383401
    384402        /**
     403         * Restore a term's slug (spec section 26.5).
     404         *
     405         * @param object $job         Rollback job.
     406         * @param object $item        Rollback item.
     407         * @param object $target_item Target item.
     408         * @return string Result.
     409         */
     410        private static function process_term( $job, $item, $target_item ) {
     411                clean_term_cache( (int) $item->post_id );
     412                $term = get_term( (int) $item->post_id );
     413                if ( ! $term instanceof \WP_Term ) {
     414                        return JobRunner::finish_item( $item, 'skipped', array( 'reason' => 'not_found' ) );
     415                }
     416
     417                $current_link = TermSlugs::link( $term );
     418                if ( $term->slug !== $item->old_post_name ) {
     419                        return JobRunner::finish_item(
     420                                $item,
     421                                'skipped',
     422                                array(
     423                                        'reason' => 'changed_since_job',
     424                                        'detail' => sprintf(
     425                                                /* translators: 1: slug the job set, 2: current slug */
     426                                                __( 'The slug changed after the job (job set "%1$s", now "%2$s").', 'slugh' ),
     427                                                rawurldecode( $item->old_post_name ),
     428                                                rawurldecode( $term->slug )
     429                                        ),
     430                                )
     431                        );
     432                }
     433
     434                $original = $item->requested_post_name;
     435                $taken    = get_term_by( 'slug', $original, $term->taxonomy );
     436                if ( $taken instanceof \WP_Term && (int) $taken->term_id !== (int) $term->term_id ) {
     437                        return JobRunner::finish_item(
     438                                $item,
     439                                'skipped',
     440                                array(
     441                                        'reason' => 'original_slug_taken',
     442                                        'detail' => __( 'Another term now uses the original slug.', 'slugh' ),
     443                                )
     444                        );
     445                }
     446
     447                $update = TermSlugs::update( $term->term_id, $original, $job->id );
     448                if ( is_wp_error( $update ) ) {
     449                        return JobRunner::finish_item(
     450                                $item,
     451                                'failed',
     452                                array(
     453                                        'reason' => $update->get_error_code(),
     454                                        'detail' => $update->get_error_message(),
     455                                )
     456                        );
     457                }
     458
     459                $columns = array(
     460                        'actual_post_name' => $update['actual_slug'],
     461                        'actual_permalink' => $update['actual_permalink'],
     462                        'hash_after'       => $update['hash_after'],
     463                        'hash_before'      => $update['hash_before'],
     464                );
     465                if ( ! empty( $update['changed_fields'] ) ) {
     466                        JobRunner::finish_item( $item, 'integrity_changed', array( 'changed_fields' => $update['changed_fields'] ), $columns );
     467                        return 'integrity_changed';
     468                }
     469
     470                $notes = array();
     471                if ( $update['actual_slug'] !== $original ) {
     472                        $notes['restore_mismatch'] = $update['actual_slug'];
     473                }
     474                if ( '' !== $current_link && Normalizer::normalize_path( $current_link ) !== Normalizer::normalize_path( $item->old_permalink ) ) {
     475                        $notes['url_moved'] = $current_link;
     476                }
     477
     478                $redirect = self::undo_redirects( $job, $target_item );
     479                $reverse  = self::reverse_redirect( $job, $item, $update['actual_permalink'], 'publish', 'term' );
     480                if ( $reverse ) {
     481                        JobRunner::record_redirect( $redirect, $reverse );
     482                }
     483
     484                CacheManager::purge_urls( array( $item->old_permalink, $update['actual_permalink'] ) );
     485                AuditLogger::log( 'rollback_item', 'term', $term->term_id, array( 'slug' => $item->old_post_name ), array( 'slug' => $update['actual_slug'] ), $job->id );
     486                JobRepository::merge_item_message( $target_item, array( 'rolled_back_by' => $job->id ) );
     487
     488                $notes['redirects']      = $redirect;
     489                $columns['redirect_ids'] = $redirect['ids'];
     490
     491                return JobRunner::finish_item( $item, 'applied', $notes, $columns );
     492        }
     493
     494        /**
     495         * Whether this rollback job has already restored one of the record's ancestors.
     496         *
     497         * @param int      $rollback_job_id Rollback job ID.
     498         * @param \WP_Post $post            Record.
     499         * @return bool
     500         */
     501        private static function ancestor_restored( $rollback_job_id, \WP_Post $post ) {
     502                global $wpdb;
     503                $ancestors = array_map( 'intval', get_post_ancestors( $post ) );
     504                if ( empty( $ancestors ) ) {
     505                        return false;
     506                }
     507                $table        = Schema::get_table_name( 'slugh_job_items' );
     508                $placeholders = implode( ',', array_fill( 0, count( $ancestors ), '%d' ) );
     509                // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     510                $found = $wpdb->get_var(
     511                        $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- Values are passed as one array.
     512                                "SELECT id FROM %i WHERE job_id = %d AND result = 'applied' AND object_type = 'post' AND post_id IN ({$placeholders}) LIMIT 1",
     513                                array_merge( array( $table, absint( $rollback_job_id ) ), $ancestors )
     514                        )
     515                );
     516                // phpcs:enable
     517                return null !== $found;
     518        }
     519
     520        /**
    385521         * Reverse redirect from the abandoned job URL to the restored URL (setting, on by default).
    386522         *
    … …  
    389525         * @param string $restored_url Restored permalink.
    390526         * @param string $post_status  Current status.
     527         * @param string $object_type  post or term.
    391528         * @return array|null create() result.
    392529         */
    393         private static function reverse_redirect( $job, $item, $restored_url, $post_status ) {
     530        private static function reverse_redirect( $job, $item, $restored_url, $post_status, $object_type = 'post' ) {
    394531                $public = Settings::get( 'redirect_private_posts', false ) ? array( 'publish', 'private' ) : array( 'publish' );
    395532
    … …  
    408545                                'origin'      => 'rollback',
    409546                                'post_id'     => $item->post_id,
     547                                'object_type' => $object_type,
    410548                                'job_id'      => $job->id,
    411549                                'on_conflict' => 'keep',
  • slugh/tags/2.0.0/src/Plugin.php

    r3795795 r3814912  
    6060                // Front-end redirect engine on template_redirect at priority 1.
    6161                ( new Redirects\RedirectHandler() )->register();
     62                ( new Redirects\TermWatcher() )->register();
    6263
    6364                // WooCommerce integration (HPOS declaration and product integrity data).
    6465                ( new Integrations\WooCommerce() )->register();
     66
     67                if ( defined( 'WP_CLI' ) && WP_CLI ) {
     68                        Cli\Command::register();
     69                }
    6570
    6671                add_action( 'admin_init', array( $this, 'check_multisite_activation' ) );
  • slugh/tags/2.0.0/src/Redirects/RedirectHandler.php

    r3795795 r3814912  
    7373                $source_hash    = Normalizer::compute_hash( $canonical_path );
    7474                $is_404         = is_404();
     75                // WordPress answers 200 with an empty feed for a term that no longer exists; treat it like a 404.
     76                $missing_feed = ! $is_404 && is_feed() && ( is_category() || is_tag() || is_tax() ) && ! ( get_queried_object() instanceof \WP_Term );
    7577
    7678                // Normal (non-404) requests only need the cached set of "always" hashes; no query.
    77                 if ( ! $is_404 && ! in_array( $source_hash, RedirectRepository::get_always_hashes(), true ) ) {
     79                if ( ! $is_404 && ! $missing_feed && ! in_array( $source_hash, RedirectRepository::get_always_hashes(), true ) ) {
    7880                        return;
    7981                }
    8082
    8183                $redirect = RedirectRepository::find_by_hash( $source_hash, $canonical_path );
     84                if ( $redirect && '404_only' === $redirect->match_mode && ! $is_404 ) {
     85                        $redirect = null;
     86                }
     87                $suffix = '';
     88                if ( ! $redirect && ( $is_404 || $missing_feed ) ) {
     89                        list( $redirect, $suffix ) = $this->find_term_archive_redirect( $canonical_path );
     90                }
    8291                if ( ! $redirect ) {
    83                         return;
    84                 }
    85 
    86                 if ( '404_only' === $redirect->match_mode && ! $is_404 ) {
    8792                        return;
    8893                }
    … …  
    112117                }
    113118
    114                 $destination_url = $this->build_destination_url( $redirect->destination, $redirect->destination_type, $request_uri );
     119                $destination = $redirect->destination;
     120                if ( '' !== $suffix ) {
     121                        // Same archive page or feed under the new term URL (spec section 26.5).
     122                        $destination = untrailingslashit( preg_replace( '/[?#].*$/s', '', $destination ) ) . '/' . $suffix . '/';
     123                }
     124                $destination_url = $this->build_destination_url( $destination, $redirect->destination_type, $request_uri );
    115125
    116126                if ( 'external' === $redirect->destination_type ) {
    … …  
    120130                }
    121131                exit;
     132        }
     133
     134        /**
     135         * For a 404 under an old term URL with /page/<n>/, /feed/ or /feed/<type>/ after it,
     136         * find the term redirect of the base URL.
     137         *
     138         * @param string $canonical_path Canonical requested path.
     139         * @return array{0: object|null, 1: string} Redirect (or null) and the suffix to carry over.
     140         */
     141        private function find_term_archive_redirect( $canonical_path ) {
     142                if ( ! preg_match( '#^(/.+?)/(page/[0-9]+|feed(?:/(?:feed|rdf|rss|rss2|atom))?)$#', $canonical_path, $matches ) ) {
     143                        return array( null, '' );
     144                }
     145                $base     = Normalizer::normalize_path( $matches[1] );
     146                $redirect = RedirectRepository::find_by_hash( Normalizer::compute_hash( $base ), $base );
     147                if ( ! $redirect || ! isset( $redirect->object_type ) || 'term' !== $redirect->object_type || 'internal' !== $redirect->destination_type ) {
     148                        return array( null, '' );
     149                }
     150                return array( $redirect, $matches[2] );
    122151        }
    123152
  • slugh/tags/2.0.0/src/Redirects/RedirectRepository.php

    r3795795 r3814912  
    2424        const STATUS_CODES     = array( 301, 302, 307, 308, 410 );
    2525        const JOB_STATUS_CODES = array( 301, 302 );
    26         const ORIGINS          = array( 'job', 'descendant', 'manual', 'import', 'rollback' );
     26        const ORIGINS          = array( 'job', 'descendant', 'manual', 'import', 'rollback', 'term_edit' );
    2727        const MATCH_MODES      = array( '404_only', 'always' );
    2828
    … …  
    5454                        $row = $wpdb->get_row(
    5555                                $wpdb->prepare(
    56                                         'SELECT id, source_path, source_hash, destination, destination_type, status_code, match_mode, enabled
     56                                        'SELECT id, source_path, source_hash, destination, destination_type, status_code, match_mode, enabled, object_type
    5757                                        FROM %i
    5858                                        WHERE source_hash = %s AND enabled = 1
    … …  
    293293                        'match_mode'       => $match_mode,
    294294                        'post_id'          => $post_id,
     295                        'object_type'      => isset( $data['object_type'] ) && 'term' === $data['object_type'] ? 'term' : 'post',
    295296                        'job_id'           => $job_id,
    296297                        'origin'           => $origin,
    … …  
    298299                        'updated_at'       => $now,
    299300                );
    300                 $formats = array( '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%d', '%s' );
     301                $formats = array( '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%d', '%s', '%d', '%s', '%d', '%s' );
    301302
    302303                if ( $existing ) {
  • slugh/tags/2.0.0/src/Rest/DraftsController.php

    r3795795 r3814912  
    88namespace SlugH\Rest;
    99
     10use SlugH\Integrations\Polylang;
    1011use SlugH\Jobs\DraftManager;
    1112use SlugH\Jobs\JobRepository;
    … …  
    6465         */
    6566        private static function item_payload( $item ) {
     67                $is_term = isset( $item->object_type ) && 'term' === $item->object_type;
    6668                return array(
    67                         'post_id'   => $item->post_id,
    68                         'post_type' => $item->post_type,
    69                         'parent_id' => (int) $item->parent_id,
    70                         'old_slug'  => rawurldecode( $item->old_post_name ),
    71                         'new_slug'  => rawurldecode( $item->requested_post_name ),
    72                         'key'       => JobRepository::duplicate_key( $item->post_type, $item->parent_id, $item->requested_post_name ),
     69                        'post_id'     => $item->post_id,
     70                        'object_type' => $is_term ? 'term' : 'post',
     71                        'post_type'   => $item->post_type,
     72                        'parent_id'   => (int) $item->parent_id,
     73                        'old_slug'    => rawurldecode( $item->old_post_name ),
     74                        'new_slug'    => rawurldecode( $item->requested_post_name ),
     75                        'key'         => $is_term
     76                                ? JobRepository::duplicate_key( JobRepository::key_type( 'term', $item->post_type ), 0, $item->requested_post_name )
     77                                : JobRepository::duplicate_key( $item->post_type, $item->parent_id, $item->requested_post_name, Polylang::post_language( $item->post_id ) ),
    7378                );
    7479        }
    … …  
    8792                foreach ( array_slice( $items, 0, 500 ) as $entry ) {
    8893                        $post_id = isset( $entry['post_id'] ) ? absint( $entry['post_id'] ) : 0;
     94                        $type    = isset( $entry['object_type'] ) && 'term' === $entry['object_type'] ? 'term' : 'post';
    8995                        $slug    = isset( $entry['new_slug'] ) ? Sanitizer::slug_input( $entry['new_slug'] ) : '';
    90                         $res     = DraftManager::upsert_item( $job_id, $post_id, $slug );
    91                         $item    = JobRepository::find_item( $job_id, $post_id );
     96                        $res     = 'term' === $type ? DraftManager::upsert_term_item( $job_id, $post_id, $slug ) : DraftManager::upsert_item( $job_id, $post_id, $slug );
     97                        $item    = JobRepository::find_item( $job_id, $post_id, $type );
    9298
    9399                        $out[] = array(
    94                                 'post_id' => $post_id,
    95                                 'status'  => $res['status'],
    96                                 'message' => isset( $res['message'] ) ? $res['message'] : '',
    97                                 'item'    => $item ? self::item_payload( $item ) : null,
     100                                'post_id'     => $post_id,
     101                                'object_type' => $type,
     102                                'status'      => $res['status'],
     103                                'message'     => isset( $res['message'] ) ? $res['message'] : '',
     104                                'item'        => $item ? self::item_payload( $item ) : null,
    98105                        );
    99106                }
    … …  
    115122        public function remove_item( \WP_REST_Request $request ) {
    116123                $job_id = DraftManager::get_editor_draft( false );
    117                 return $this->respond( array( 'removed' => $job_id && DraftManager::remove_item( $job_id, absint( $request['post_id'] ) ) ) );
     124                $type   = 'term' === $request->get_param( 'object_type' ) ? 'term' : 'post';
     125                return $this->respond( array( 'removed' => $job_id && DraftManager::remove_item( $job_id, absint( $request['post_id'] ), $type ) ) );
    118126        }
    119127
  • slugh/tags/2.0.0/src/Scan/Scanner.php

    r3795795 r3814912  
    99
    1010use SlugH\Database\Schema;
     11use SlugH\Integrations\Polylang;
    1112use SlugH\Jobs\AuditLogger;
    1213use SlugH\Jobs\JobRepository;
    1314use SlugH\Redirects\Normalizer;
     15use SlugH\Slugs\TermSlugs;
    1416use SlugH\Support\PostTypes;
    1517use SlugH\Support\Settings;
     18use SlugH\Support\Taxonomies;
    1619
    1720defined( 'ABSPATH' ) || exit;
    … …  
    2932         * @param array $post_types Post types.
    3033         * @param array $statuses   Statuses.
     34         * @param array $taxonomies Taxonomies whose terms are scanned after the posts (null: the enabled ones).
    3135         * @return int Scan ID.
    3236         */
    33         public static function start( $post_types, $statuses ) {
    34                 $types    = PostTypes::filter_types( $post_types );
    35                 $statuses = PostTypes::filter_statuses( $statuses );
     37        public static function start( $post_types, $statuses, $taxonomies = null ) {
     38                $types      = PostTypes::filter_types( $post_types );
     39                $statuses   = PostTypes::filter_statuses( $statuses );
     40                $taxonomies = null === $taxonomies ? Taxonomies::get_enabled() : Taxonomies::filter( $taxonomies );
    3641
    3742                $scan_id = JobRepository::create(
    … …  
    4146                                'post_types' => $types,
    4247                                'statuses'   => $statuses,
     48                                'taxonomies' => array_values( $taxonomies ),
    4349                                'last_id'    => 0,
    4450                        )
    … …  
    5359                                'post_types' => $types,
    5460                                'statuses'   => $statuses,
     61                                'taxonomies' => array_values( $taxonomies ),
    5562                        ),
    5663                        $scan_id
    … …  
    7784                }
    7885
     86                if ( isset( $job->settings['phase'] ) && 'terms' === $job->settings['phase'] ) {
     87                        $result = self::run_term_batch( $job );
     88                        JobRepository::release_lock( $scan_id );
     89                        return $result;
     90                }
     91
    7992                $types      = (array) $job->settings['post_types'];
    80                 $statuses   = (array) $job->settings['statuses'];
     93                $statuses   = PostTypes::query_statuses( $types, (array) $job->settings['statuses'] );
    8194                $last_id    = isset( $job->settings['last_id'] ) ? (int) $job->settings['last_id'] : 0;
    8295                $batch_size = (int) Settings::get( 'scan_batch_size', 500 );
    … …  
    99112                // phpcs:enable
    100113
    101                 $table       = Schema::get_table_name( 'slugh_scan_items' );
    102                 $now         = current_time( 'mysql', true );
    103                 $pretty      = (bool) get_option( 'permalink_structure' );
    104                 $front_page  = (int) get_option( 'page_on_front' );
     114                $table      = Schema::get_table_name( 'slugh_scan_items' );
     115                $now        = current_time( 'mysql', true );
     116                $pretty     = (bool) get_option( 'permalink_structure' );
     117                $front_page = 'page' === get_option( 'show_on_front' ) ? (int) get_option( 'page_on_front' ) : 0;
     118                // Polylang serves each translation of the front page at its language home (for example /en/).
     119                $front_pages = array_unique( array_filter( array_merge( array( $front_page ), Polylang::front_page_ids() ) ) );
     120                $by_language = Polylang::is_active();
    105121                $processed   = 0;
    106122                $posts       = array();
    … …  
    129145                        $perm_hash = '';
    130146
    131                         if ( 'publish' === $post->post_status ) {
     147                        // Attachments count as published when their parent is; with attachment pages off they have no page to check.
     148                        if ( 'publish' === PostTypes::url_status( $post ) ) {
    132149                                $perm_hash = Normalizer::compute_hash( Normalizer::normalize_path( $permalink ) );
    133150
    134                                 if ( $pretty && $post->ID !== $front_page && DetectorRegistry::has_permalink_problem( $post, $permalink ) ) {
     151                                if ( $pretty && ! in_array( (int) $post->ID, $front_pages, true ) && DetectorRegistry::has_permalink_problem( $post, $permalink ) ) {
    135152                                        $flags |= Flags::PERMALINK_ISSUE;
    136153                                }
    … …  
    138155                                if ( '' !== $post->post_name ) {
    139156                                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    140                                         $duplicate = $wpdb->get_var(
     157                                        $duplicates = $wpdb->get_col(
    141158                                                $wpdb->prepare(
    142                                                         "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",
     159                                                        "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 50",
    143160                                                        $post->post_type,
    144161                                                        $post->post_parent,
    … …  
    147164                                                )
    148165                                        );
    149                                         if ( $duplicate ) {
     166                                        if ( $duplicates && $by_language ) {
     167                                                // Only records of the same language share a URL (Polylang Pro can share slugs across languages).
     168                                                $language   = Polylang::post_language( $post->ID );
     169                                                $duplicates = array_filter(
     170                                                        $duplicates,
     171                                                        function ( $id ) use ( $language ) {
     172                                                                return Polylang::post_language( (int) $id ) === $language;
     173                                                        }
     174                                                );
     175                                        }
     176                                        if ( $duplicates ) {
    150177                                                $flags |= Flags::DUPLICATE;
    151178                                        }
    … …  
    188215                );
    189216
    190                 if ( $done ) {
     217                if ( $done && ! empty( $job->settings['taxonomies'] ) ) {
     218                        // Posts are done; the next batches read the terms of the enabled taxonomies.
     219                        $job = JobRepository::get( $scan_id );
     220                        JobRepository::update(
     221                                $scan_id,
     222                                array(
     223                                        'settings' => array_merge(
     224                                                $job->settings,
     225                                                array(
     226                                                        'phase'        => 'terms',
     227                                                        'term_last_id' => 0,
     228                                                )
     229                                        ),
     230                                )
     231                        );
     232                        $done = false;
     233                } elseif ( $done ) {
    191234                        self::finish( $scan_id );
    192235                }
    … …  
    196239                return array(
    197240                        'scan_id'   => $scan_id,
     241                        'processed' => $processed,
     242                        'scanned'   => $scanned,
     243                        'last_id'   => $last_id,
     244                        'done'      => $done,
     245                );
     246        }
     247
     248        /**
     249         * One batch of terms (spec section 26.5): the slug detectors, the archive URL hash.
     250         *
     251         * @param object $job Scan job.
     252         * @return array Same keys as run_batch().
     253         */
     254        private static function run_term_batch( $job ) {
     255                global $wpdb;
     256
     257                $taxonomies = (array) $job->settings['taxonomies'];
     258                $last_id    = isset( $job->settings['term_last_id'] ) ? (int) $job->settings['term_last_id'] : 0;
     259                $scanned    = isset( $job->settings['scanned'] ) ? (int) $job->settings['scanned'] : 0;
     260                $batch_size = (int) Settings::get( 'scan_batch_size', 500 );
     261                $tax_in     = implode( ',', array_fill( 0, count( $taxonomies ), '%s' ) );
     262
     263                // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     264                $rows = $wpdb->get_results(
     265                        $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- Values are passed as one array.
     266                                "SELECT t.term_id, t.slug, tt.taxonomy FROM {$wpdb->terms} t
     267                                JOIN {$wpdb->term_taxonomy} tt ON tt.term_id = t.term_id
     268                                WHERE t.term_id > %d AND tt.taxonomy IN ({$tax_in})
     269                                ORDER BY t.term_id ASC
     270                                LIMIT %d",
     271                                array_merge( array( $last_id ), $taxonomies, array( $batch_size ) )
     272                        )
     273                );
     274                // phpcs:enable
     275
     276                $table     = Schema::get_table_name( 'slugh_scan_items' );
     277                $now       = current_time( 'mysql', true );
     278                $processed = 0;
     279                foreach ( (array) $rows as $row ) {
     280                        $last_id = max( $last_id, (int) $row->term_id );
     281                        ++$processed;
     282                        if ( ! current_user_can( 'edit_term', (int) $row->term_id ) ) {
     283                                continue;
     284                        }
     285                        $analysis = DetectorRegistry::analyze(
     286                                (object) array(
     287                                        'post_name'   => $row->slug,
     288                                        'post_status' => 'publish',
     289                                )
     290                        );
     291                        $link     = TermSlugs::link( (int) $row->term_id );
     292                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     293                        $wpdb->replace(
     294                                $table,
     295                                array(
     296                                        'scan_id'        => $job->id,
     297                                        'post_id'        => (int) $row->term_id,
     298                                        'object_type'    => 'term',
     299                                        'post_type'      => $row->taxonomy,
     300                                        'post_status'    => 'publish',
     301                                        'decoded_slug'   => mb_substr( $analysis['decoded_slug'], 0, 500 ),
     302                                        'flags'          => $analysis['flags'],
     303                                        'scripts'        => $analysis['scripts'],
     304                                        'permalink_hash' => '' === $link ? '' : Normalizer::compute_hash( Normalizer::normalize_path( $link ) ),
     305                                        'scanned_at'     => $now,
     306                                ),
     307                                array( '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s' )
     308                        );
     309                        ++$scanned;
     310                }
     311
     312                $done = count( (array) $rows ) < $batch_size;
     313                JobRepository::update(
     314                        $job->id,
     315                        array(
     316                                'settings' => array_merge(
     317                                        $job->settings,
     318                                        array(
     319                                                'term_last_id' => $last_id,
     320                                                'scanned'      => $scanned,
     321                                        )
     322                                ),
     323                        )
     324                );
     325                if ( $done ) {
     326                        self::finish( $job->id );
     327                }
     328
     329                return array(
     330                        'scan_id'   => (int) $job->id,
    198331                        'processed' => $processed,
    199332                        'scanned'   => $scanned,
    … …  
    303436         *
    304437         * @param int   $scan_id Scan ID.
    305          * @param array $args    post_type, post_status, flags (int[] all must match), search, modified_from, modified_to, orderby, order, per_page, page.
     438         * @param array $args    post_type, post_status, flags (int[] all must match), issues_only, language (Polylang slug), search, modified_from, modified_to, orderby, order, per_page, page.
    306439         * @return array{items: array, total: int}
    307440         */
    … …  
    318451                        $where[] = 's.post_type = %s';
    319452                        $binds[] = sanitize_key( $args['post_type'] );
     453                }
     454                if ( ! empty( $args['object_type'] ) && in_array( $args['object_type'], array( 'post', 'term' ), true ) ) {
     455                        $where[] = 's.object_type = %s';
     456                        $binds[] = $args['object_type'];
    320457                }
    321458                if ( ! empty( $args['post_status'] ) ) {
    … …  
    337474                        $where[] = 's.flags != 0';
    338475                }
     476                if ( ! empty( $args['language'] ) ) {
     477                        $condition = Polylang::language_condition( 's.post_id', sanitize_key( $args['language'] ) );
     478                        // An unknown language matches nothing rather than everything. Term languages are not filtered.
     479                        $where[] = $condition ? "s.object_type = 'post' AND " . $condition[0] : '1 = 0';
     480                        if ( $condition ) {
     481                                $binds[] = $condition[1];
     482                        }
     483                }
    339484                if ( isset( $args['search'] ) && '' !== $args['search'] ) {
    340485                        $like    = '%' . $wpdb->esc_like( (string) $args['search'] ) . '%';
    341                         $where[] = '(p.post_title LIKE %s OR s.decoded_slug LIKE %s)';
     486                        $where[] = '(p.post_title LIKE %s OR tm.name LIKE %s OR s.decoded_slug LIKE %s)';
     487                        $binds[] = $like;
    342488                        $binds[] = $like;
    343489                        $binds[] = $like;
    … …  
    362508                $order       = isset( $args['order'] ) && 'desc' === strtolower( $args['order'] ) ? 'DESC' : 'ASC';
    363509                $where_sql   = implode( ' AND ', $where );
    364                 $from        = "%i s LEFT JOIN {$wpdb->posts} p ON p.ID = s.post_id";
     510                $from        = "%i s LEFT JOIN {$wpdb->posts} p ON p.ID = s.post_id AND s.object_type = 'post' LEFT JOIN {$wpdb->terms} tm ON tm.term_id = s.post_id AND s.object_type = 'term'";
    365511                $binds       = array_merge( array( $table ), $binds );
    366512
    … …  
    371517                $items = $wpdb->get_results(
    372518                        $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- Values are passed as one array.
    373                                 "SELECT s.*, p.post_title, p.post_name AS current_post_name, p.post_modified, p.post_modified_gmt
     519                                "SELECT s.*, COALESCE( p.post_title, tm.name ) AS post_title, COALESCE( p.post_name, tm.slug ) AS current_post_name, p.post_modified, p.post_modified_gmt
    374520                                FROM {$from} WHERE {$where_sql} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d",
    375521                                array_merge( $binds, array( $per_page, ( $page - 1 ) * $per_page ) )
  • slugh/tags/2.0.0/src/Slugs/DescendantPropagator.php

    r3795795 r3814912  
    77
    88namespace SlugH\Slugs;
     9
     10use SlugH\Support\PostTypes;
    911
    1012defined( 'ABSPATH' ) || exit;
    … …  
    5759
    5860        /**
     61         * Attachments whose attachment-page URL lives under a record or its hierarchical descendants.
     62         *
     63         * Empty when attachment pages are off (their URLs redirect to the file) or for an attachment itself.
     64         *
     65         * @param int   $post_id        Record ID.
     66         * @param int[] $descendant_ids Its hierarchical descendants (from get_descendants()).
     67         * @return int[]
     68         */
     69        public static function get_attachments( $post_id, array $descendant_ids = array() ) {
     70                global $wpdb;
     71
     72                $post = get_post( $post_id );
     73                if ( ! $post || 'attachment' === $post->post_type || ! PostTypes::attachment_pages_enabled() ) {
     74                        return array();
     75                }
     76                $parents      = array_merge( array( (int) $post->ID ), array_map( 'intval', $descendant_ids ) );
     77                $placeholders = implode( ',', array_fill( 0, count( $parents ), '%d' ) );
     78                // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     79                $ids = $wpdb->get_col(
     80                        $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- Values are passed as one array.
     81                                "SELECT ID FROM {$wpdb->posts} WHERE post_parent IN ({$placeholders}) AND post_type = 'attachment' AND post_status = 'inherit' ORDER BY ID ASC",
     82                                $parents
     83                        )
     84                );
     85                // phpcs:enable
     86                return array_map( 'intval', (array) $ids );
     87        }
     88
     89        /**
    5990         * Depth of a record in its hierarchy (0 for top level). Used to process parents first.
    6091         *
  • slugh/tags/2.0.0/src/Slugs/RulesSuggester.php

    r3795795 r3814912  
    3737        public static function instance() {
    3838                /**
    39                  * Filter the slug suggester (v2 transliteration plugs in here).
     39                 * Filter the slug suggester. The default is TransliterationSuggester when the
     40                 * "transliteration" setting is on, otherwise these rules.
    4041                 *
    4142                 * @param SlugSuggester $suggester Suggester.
    4243                 */
    43                 $suggester = apply_filters( 'slugh_slug_suggester', new self() );
    44                 return $suggester instanceof SlugSuggester ? $suggester : new self();
     44                $default   = \SlugH\Support\Settings::get( 'transliteration', false ) ? new TransliterationSuggester() : new self();
     45                $suggester = apply_filters( 'slugh_slug_suggester', $default );
     46                return $suggester instanceof SlugSuggester ? $suggester : $default;
    4547        }
    4648}
  • slugh/tags/2.0.0/src/Slugs/SlugSuggester.php

    r3795795 r3814912  
    1111
    1212/**
    13  * Produces preview-only slug suggestions. Rules-based cleanup is the v1 implementation;
    14  * transliteration plugs in here in v2 (spec sections 14 and 20).
     13 * Produces preview-only slug suggestions: RulesSuggester (cleanup) and
     14 * TransliterationSuggester (spec section 26.2).
    1515 */
    1616interface SlugSuggester {
    … …  
    1919         * Suggest a slug. Suggestions are never applied automatically.
    2020         *
    21          * @param string   $decoded_slug Current decoded slug.
    22          * @param \WP_Post $post         Post the slug belongs to.
     21         * @param string            $decoded_slug Current decoded slug.
     22         * @param \WP_Post|\WP_Term $post Record the slug belongs to: a post, or a term (from 2.0.0).
    2323         * @return string Suggested decoded slug, or the input unchanged when there is nothing to suggest.
    2424         */
  • slugh/tags/2.0.0/src/Slugs/SlugValidator.php

    r3795795 r3814912  
    88namespace SlugH\Slugs;
    99
     10use SlugH\Integrations\Polylang;
    1011use SlugH\Redirects\LoopDetector;
    1112use SlugH\Redirects\Normalizer;
    … …  
    8586                        'creates_redirect'    => false,
    8687                        'descendants'         => 0,
     88                        'attachments'         => 0,
    8789                        'descendant_samples'  => array(),
    8890                        'conflicts'           => array(),
    … …  
    250252
    251253                $public_statuses            = Settings::get( 'redirect_private_posts', false ) ? array( 'publish', 'private' ) : array( 'publish' );
    252                 $result['creates_redirect'] = $result['url_changes'] && in_array( $post->post_status, $public_statuses, true ) && Settings::slugh_owns_redirects();
    253 
    254                 if ( $result['url_changes'] && ! in_array( $post->post_status, $public_statuses, true ) ) {
     254                $url_status                 = PostTypes::url_status( $post );
     255                $result['creates_redirect'] = $result['url_changes'] && in_array( $url_status, $public_statuses, true ) && Settings::slugh_owns_redirects();
     256
     257                if ( $result['url_changes'] && 'no_page' === $url_status ) {
     258                        $result = self::add( $result, 'info', 'attachment_pages_off', __( 'Attachment pages are turned off in WordPress, so the attachment URL redirects to the file. slugH creates no redirect; the old attachment URL will return 404.', 'slugh' ) );
     259                } elseif ( $result['url_changes'] && ! in_array( $url_status, $public_statuses, true ) ) {
    255260                        $result = self::add( $result, 'info', 'no_redirect_status', __( 'No redirect will be created because this record has no public URL yet.', 'slugh' ) );
    256261                }
    … …  
    277282                }
    278283
     284                $descendants = $result['url_changes'] && is_post_type_hierarchical( $post->post_type ) ? DescendantPropagator::get_descendants( $post->ID ) : array();
     285                $attachments = $result['url_changes'] ? DescendantPropagator::get_attachments( $post->ID, $descendants ) : array();
     286                if ( ! empty( $attachments ) ) {
     287                        $result['attachments'] = count( $attachments );
     288                        $result                = self::add(
     289                                $result,
     290                                'info',
     291                                'attachments',
     292                                sprintf(
     293                                        /* translators: %d: number of attachments */
     294                                        _n( '%d attachment page URL will change and get its own redirect.', '%d attachment page URLs will change and get their own redirects.', count( $attachments ), 'slugh' ),
     295                                        count( $attachments )
     296                                )
     297                        );
     298                }
     299
    279300                if ( $result['url_changes'] && is_post_type_hierarchical( $post->post_type ) ) {
    280                         $descendants = DescendantPropagator::get_descendants( $post->ID );
    281301                        if ( ! empty( $descendants ) ) {
    282302                                $result['descendants']        = count( $descendants );
    … …  
    344364                $others = $wpdb->get_col(
    345365                        $wpdb->prepare(
    346                                 "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",
     366                                "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') ) OR ( %d = 1 AND post_type = 'attachment' AND post_status = 'inherit' ) ) LIMIT 20",
    347367                                $slug,
    348                                 $post->ID
     368                                $post->ID,
     369                                PostTypes::attachment_pages_enabled() ? 1 : 0
    349370                        )
    350371                );
    … …  
    401422         * @return array
    402423         */
    403         private static function check_redirect_conflicts( array $result ) {
     424        public static function check_redirect_conflicts( array $result ) {
    404425                $at_new = RedirectRepository::find_by_source( $result['new_path'] );
    405426                if ( $at_new && (int) $at_new->enabled ) {
    … …  
    484505                if ( is_post_type_hierarchical( $post->post_type ) ) {
    485506                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    486                         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 ) );
    487                 }
    488                 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    489                 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 ) );
     507                        $ids = $wpdb->get_col( $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 50", $slug, $post->post_type, $post->post_parent, $post->ID ) );
     508                } else {
     509                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     510                        $ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_name = %s AND post_type = %s AND post_status = 'publish' AND ID != %d LIMIT 50", $slug, $post->post_type, $post->ID ) );
     511                }
     512                $ids = array_map( 'intval', (array) $ids );
     513                if ( $ids && Polylang::is_active() ) {
     514                        // Only a record of the same language would take the URL (Polylang Pro can share slugs).
     515                        $language  = Polylang::post_language( $post->ID );
     516                        $languages = Polylang::languages_for( $ids );
     517                        $ids       = array_values(
     518                                array_filter(
     519                                        $ids,
     520                                        function ( $id ) use ( $language, $languages ) {
     521                                                return ( isset( $languages[ $id ] ) ? $languages[ $id ] : '' ) === $language;
     522                                        }
     523                                )
     524                        );
     525                }
     526                return $ids ? $ids[0] : 0;
    490527        }
    491528
    … …  
    538575         * @return array
    539576         */
    540         private static function add( array $result, $level, $code, $text, $needs_confirmation = false ) {
     577        public static function add( array $result, $level, $code, $text, $needs_confirmation = false ) {
    541578                $result['messages'][] = array(
    542579                        'level' => $level,
    … …  
    573610         * @return array
    574611         */
    575         private static function finish( array $result ) {
     612        public static function finish( array $result ) {
    576613                $result['is_valid'] = ! in_array( $result['state'], array( self::STATE_ERROR, self::STATE_STALE ), true );
    577614                return $result;
  • slugh/tags/2.0.0/src/Support/PostTypes.php

    r3795795 r3814912  
    2020
    2121        /**
    22          * Internal types never handled by v1.
     22         * Internal types never handled. Attachments are handled from 2.0.0 (spec section 26.4), opt-in.
    2323         *
    2424         * @var string[]
    2525         */
    2626        const EXCLUDED_TYPES = array(
    27                 'attachment',
    2827                'revision',
    2928                'nav_menu_item',
    … …  
    9695
    9796        /**
     97         * Statuses to query for a set of post types: attachments always have "inherit".
     98         *
     99         * @param string[] $types    Post types.
     100         * @param string[] $statuses Selected statuses.
     101         * @return string[]
     102         */
     103        public static function query_statuses( array $types, array $statuses ) {
     104                if ( in_array( 'attachment', $types, true ) && ! in_array( 'inherit', $statuses, true ) ) {
     105                        $statuses[] = 'inherit';
     106                }
     107                return array_values( $statuses );
     108        }
     109
     110        /**
     111         * Whether WordPress shows attachment pages (option added in WordPress 6.4; before that they always exist).
     112         *
     113         * @return bool
     114         */
     115        public static function attachment_pages_enabled() {
     116                return (bool) (int) get_option( 'wp_attachment_pages_enabled', 1 );
     117        }
     118
     119        /**
     120         * Status that decides whether a record's URL is public and gets redirects.
     121         *
     122         * Attachments use their parent's status (unattached: publish), or "no_page"
     123         * when WordPress sends attachment pages to the file.
     124         *
     125         * @param \WP_Post $post Post.
     126         * @return string
     127         */
     128        public static function url_status( \WP_Post $post ) {
     129                if ( 'attachment' !== $post->post_type ) {
     130                        return $post->post_status;
     131                }
     132                if ( ! self::attachment_pages_enabled() ) {
     133                        return 'no_page';
     134                }
     135                if ( 'inherit' !== $post->post_status ) {
     136                        return $post->post_status;
     137                }
     138                $parent = $post->post_parent ? get_post( $post->post_parent ) : null;
     139                return $parent ? $parent->post_status : 'publish';
     140        }
     141
     142        /**
    98143         * Restrict requested post types to the available set.
    99144         *
  • slugh/tags/2.0.0/src/Support/Settings.php

    r3795795 r3814912  
    3030                        'supported_post_types'        => array( 'post', 'page' ),
    3131                        'supported_post_statuses'     => array( 'publish', 'future', 'draft', 'pending', 'private' ),
     32                        'supported_taxonomies'        => array( 'category', 'post_tag' ),
     33                        'term_edit_redirects'         => true,
    3234                        'redirect_ownership_mode'     => self::MODE_SLUGH,
    3335                        'redirect_private_posts'      => false,
    … …  
    3739                        'trial_mode'                  => false,
    3840                        'allow_external_destinations' => false,
     41                        'transliteration'             => false,
    3942                        'integrity_excluded_meta'     => array(),
    4043                        'scan_batch_size'             => 500,
    … …  
    104107
    105108                $clean['supported_post_types']    = array_map( 'sanitize_key', $clean['supported_post_types'] );
     109                $clean['supported_taxonomies']    = array_map( 'sanitize_key', $clean['supported_taxonomies'] );
    106110                $clean['supported_post_statuses'] = array_values( array_intersect( array_map( 'sanitize_key', $clean['supported_post_statuses'] ), PostTypes::SUPPORTED_STATUSES ) );
    107111                $clean['scan_batch_size']         = min( 2000, max( 50, $clean['scan_batch_size'] ) );
  • slugh/trunk/assets/js/slugh-admin.js

    r3795795 r3814912  
    109109                var reviewBtn = $( '#slugh-review' );
    110110                var dupWarning = $( '#slugh-dup-warning' );
    111                 var draftOthers = {}; // post_id => key, for draft items not on this page.
     111                var draftOthers = {}; // row key ("123" for a post, "t123" for a term) => duplicate key, for draft items.
    112112                var inputs = $$( '.slugh-slug-input' );
    113113                var onPage = {};
    … …  
    115115                var locked = false;
    116116
     117                // Posts and terms can share an ID, so rows are keyed by object type too.
     118                function rowKey( objectType, id ) {
     119                        return ( 'term' === objectType ? 't' : '' ) + String( id );
     120                }
     121                function inputKey( input ) {
     122                        return rowKey( input.dataset.objectType, input.dataset.postId );
     123                }
     124
    117125                inputs.forEach( function ( input ) {
    118                         onPage[ input.dataset.postId ] = input;
     126                        onPage[ inputKey( input ) ] = input;
    119127                } );
    120128
    … …  
    173181                                }
    174182                                var key = input.dataset.keyPrefix + norm( input.value );
    175                                 keys[ key ] = ( keys[ key ] || [] ).concat( [ input.dataset.postId ] );
     183                                keys[ key ] = ( keys[ key ] || [] ).concat( [ inputKey( input ) ] );
    176184                        } );
    177185
    … …  
    189197                        inputs.forEach( function ( input ) {
    190198                                var row = rowOf( input );
    191                                 var dup = !! dupIds[ input.dataset.postId ];
     199                                var dup = !! dupIds[ inputKey( input ) ];
    192200                                row.classList.toggle( 'slugh-duplicate', dup );
    193201                                input.setAttribute( 'aria-invalid', dup ? 'true' : 'false' );
    … …  
    202210                                        __( 'Duplicate new slugs in this draft (records %s). Resolve them before applying.', 'slugh' ),
    203211                                        groups.map( function ( g ) {
    204                                                 return '#' + g.join( ', #' );
     212                                                return g.map( function ( k ) {
     213                                                        return 't' === k.charAt( 0 ) ? sprintf( __( 'term #%s', 'slugh' ), k.slice( 1 ) ) : '#' + k;
     214                                                } ).join( ', ' );
    205215                                        } ).join( '; ' )
    206216                                );
    … …  
    245255                        }
    246256                        var items = list.map( function ( input ) {
    247                                 return { post_id: parseInt( input.dataset.postId, 10 ), new_slug: input.value };
     257                                return { post_id: parseInt( input.dataset.postId, 10 ), object_type: input.dataset.objectType || 'post', new_slug: input.value };
    248258                        } );
    249259                        return post( 'drafts/items', { items: items } ).then( function ( response ) {
    … …  
    255265                                }
    256266                                response.results.forEach( function ( res ) {
    257                                         var input = onPage[ res.post_id ];
     267                                        var resKey = rowKey( res.object_type, res.post_id );
     268                                        var input = onPage[ resKey ];
    258269                                        if ( ! input ) {
    259270                                                return;
    … …  
    269280                                                input.value = res.item.new_slug;
    270281                                                input.dataset.saved = res.item.new_slug;
    271                                                 draftOthers[ res.post_id ] = res.item.key;
     282                                                draftOthers[ resKey ] = res.item.key;
    272283                                                row.classList.add( 'slugh-in-draft' );
    273284                                        } else {
    274285                                                input.dataset.saved = input.value;
    275                                                 delete draftOthers[ res.post_id ];
     286                                                delete draftOthers[ resKey ];
    276287                                                row.classList.remove( 'slugh-in-draft' );
    277288                                        }
    … …  
    461472                api( 'drafts' ).then( function ( draft ) {
    462473                        ( draft.items || [] ).forEach( function ( item ) {
    463                                 draftOthers[ item.post_id ] = item.key;
     474                                draftOthers[ rowKey( item.object_type, item.post_id ) ] = item.key;
    464475                        } );
    465476                        inputs.forEach( updateRow );
    … …  
    747758                if ( all ) {
    748759                        all.addEventListener( 'change', function () {
    749                                 $$( 'input[name="post_ids[]"]' ).forEach( function ( box ) {
     760                                $$( 'input[name="post_ids[]"], input[name="term_ids[]"]' ).forEach( function ( box ) {
    750761                                        box.checked = all.checked;
    751762                                } );
  • slugh/trunk/readme.txt

    r3795795 r3814912  
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 1.0.7
     7Stable tag: 2.0.0
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    1010
    11 Find, edit and bulk-update post slugs with safe 301 redirects.
     11Find, edit and bulk-update post, page and category slugs with safe 301 redirects.
    1212
    1313== Description ==
    … …  
    4141Product slugs use the same engine when WooCommerce is active. SKUs, prices, stock, attributes, variations and categories are covered by the integrity check and are never changed. slugH declares compatibility with High-Performance Order Storage and never touches orders.
    4242
     43= Latin slug suggestions (optional) =
     44
     45Turn on **Settings → Slug suggestions → Transliteration** to get a Latin spelling suggested for each slug in another script. Bangla uses slugH's own phonetic rules (আমার সোনার বাংলা → amar-sonar-bangla); other scripts use the PHP intl extension when the server has it. Suggestions are never applied on their own: you review and edit them in the preview first.
     46
     47= WP-CLI =
     48
     49Scan, paste or import slug changes, preview, apply, roll back and manage redirects from the command line: `wp slugh scan`, `wp slugh results`, `wp slugh paste`, `wp slugh import`, `wp slugh job preview|apply|rollback`, `wp slugh redirect add|import|list|test|check`. The commands use the same preview, checks, redirects and audit log as the admin screens. Run them with `--user=<administrator>`; see `wp help slugh`.
     50
    4351= Privacy =
    4452
    … …  
    6775Saving a post runs WordPress content filters. For users without the unfiltered_html capability those filters can strip embeds or scripts from content nobody edited, so slugH blocks slug changes for those users and explains why.
    6876
    69 = Does slugH support multisite or WPML/Polylang? =
     77= Can slugH change media (attachment) slugs? =
    7078
    71 Not in version 1. slugH runs on single sites only and blocks network activation. Multilingual plugins have not been tested.
     79Yes, from version 2.0. Tick "Media" under Post types in slugH Settings. If WordPress attachment pages are on, slugH redirects changed attachment URLs, including media attached to a post or page whose URL changes. If they are off (the default on sites installed with WordPress 6.4 or later), attachment URLs already lead to the file, so slugH changes the slug without creating redirects. Media files themselves are never renamed.
     80
     81= Can slugH change category and tag slugs? =
     82
     83Yes, from version 2.0. Categories and tags are on by default; other public taxonomies (and WooCommerce product categories and tags) can be ticked in Settings. Use the Terms view of the Slug Editor. slugH redirects the old category or tag archive, including its later pages and feeds. Posts whose URL contains the category, and child categories, are already redirected or still served by WordPress itself. When someone changes a term slug on the WordPress term screen, slugH adds the redirect too.
     84
     85= Does slugH support multisite, Polylang or WPML? =
     86
     87Polylang is supported from version 2.0 (tested with Polylang 3.9.2, language in the directory name). Each language's slugs are changed on their own, translation links are kept, and redirects keep the language prefix (for example /en/). Scan & Audit and the Slug Editor show a Language column and filter, the Slug Editor shows the slugs of the linked translations, and translated front pages are no longer flagged as permalink problems. Languages on subdomains or separate domains are not supported for redirects. WPML is not supported yet, and slugH runs on single sites only (network activation is blocked).
    7288
    7389== Screenshots ==
    … …  
    78944. Results: each record's actual new slug and URL, the redirects created and their test result, with exports and rollback.
    79955. Redirects: add, edit, import and export redirects, and test any URL hop by hop on the server.
    80 6. Settings: choose who owns redirects, and how slugH behaves on rollback, trial runs and uninstall.
     966. Settings: choose the post types, statuses and taxonomies slugH manages, and who owns redirects.
    8197
    8298== Changelog ==
     99
     100= 2.0.0 =
     101* Added: category, tag and custom taxonomy term slugs: scan, edit in the Slug Editor's Terms view, preview, apply with a redirect from the old archive (its pages and feeds follow), rollback. A term slug changed elsewhere in WordPress also gets a redirect.
     102* Added: media (attachment) slugs, opt-in in Settings, with redirects when WordPress attachment pages are on, including media under a renamed post or page.
     103* Added: Polylang support: Language column and filter, translation slugs shown in the Slug Editor, language in exports, and translated front pages are no longer flagged as permalink problems.
     104* Added: WP-CLI commands (`wp slugh`) for scans, slug change jobs with preview and rollback, and redirects.
     105* Added: optional Latin slug suggestions (transliteration), with Bangla phonetic rules built in.
     106* Added: after a scan, a notice lists public post types that have content but were not scanned.
     107* Fixed: rolling back a change to a parent page and its child page together now restores both.
     108* Fixed: a static front page is no longer flagged as a permalink problem in the scan.
     109* Docs: REST clients must keep calling the job run route until it reports done (apply, then verify).
    83110
    84111= 1.0.7 =
    … …  
    107134= 1.0.0 =
    108135* First release: scanning, slug editor with draft and preview, CSV import and export, redirect engine, jobs with snapshots and rollback, audit log, WooCommerce product support.
     136
     137== Upgrade Notice ==
     138
     139= 2.0.0 =
     140Adds category, tag and media slugs, Polylang support and WP-CLI commands. The database tables are updated automatically on upgrade.
  • slugh/trunk/slugh.php

    r3795795 r3814912  
    44 * Plugin URI:        https://silitive.com/slugh/
    55 * Description:       Find, edit and bulk-update post slugs with safe 301 redirects.
    6  * Version:           1.0.7
     6 * Version:           2.0.0
    77 * Requires at least: 6.4
    88 * Requires PHP:      7.4
    … …  
    2020defined( 'ABSPATH' ) || exit;
    2121
    22 define( 'SLUGH_VERSION', '1.0.7' );
     22define( 'SLUGH_VERSION', '2.0.0' );
    2323define( 'SLUGH_FILE', __FILE__ );
    2424define( 'SLUGH_PATH', plugin_dir_path( __FILE__ ) );
  • slugh/trunk/src/Admin/Actions.php

    r3795795 r3814912  
    1010use SlugH\Database\Migrations;
    1111use SlugH\Integrations\ConflictDetector;
     12use SlugH\Integrations\Polylang;
    1213use SlugH\Jobs\AuditLogger;
    1314use SlugH\Jobs\DraftManager;
    1415use SlugH\Jobs\JobRepository;
     16use SlugH\Redirects\RedirectImporter;
    1517use SlugH\Redirects\RedirectRepository;
    1618use SlugH\Scan\Flags;
    … …  
    170172                $all      = 'all' === $this->param( 'scope' );
    171173                $types    = $all ? PostTypes::get_enabled() : PostTypes::filter_types( sanitize_key( $this->text( 'post_type' ) ) );
    172                 $statuses = $all ? PostTypes::get_enabled_statuses() : PostTypes::filter_statuses( sanitize_key( $this->text( 'post_status' ) ) );
     174                $status   = $all ? '' : sanitize_key( $this->text( 'post_status' ) );
     175                $statuses = '' === $status ? PostTypes::query_statuses( $types, PostTypes::get_enabled_statuses() ) : PostTypes::filter_statuses( $status );
    173176                $search   = $all ? '' : sanitize_text_field( $this->text( 's' ) );
     177                $language = $all ? '' : sanitize_key( $this->text( 'slugh_lang' ) );
     178                $by_lang  = Polylang::is_active();
    174179                $rows     = array();
    175180                $last_id  = 0;
    … …  
    185190                                $binds[] = '%' . $wpdb->esc_like( sanitize_title( $search ) ) . '%';
    186191                        }
     192                        if ( $by_lang && '' !== $language ) {
     193                                $condition = Polylang::language_condition( 'ID', $language );
     194                                $sql      .= $condition ? ' AND ' . $condition[0] : ' AND 1 = 0';
     195                                if ( $condition ) {
     196                                        $binds[] = $condition[1];
     197                                }
     198                        }
    187199                        // 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().
    188                         $batch = $wpdb->get_results( $wpdb->prepare( $sql . ' ORDER BY ID ASC LIMIT 1000', $binds ) );
     200                        $batch     = $wpdb->get_results( $wpdb->prepare( $sql . ' ORDER BY ID ASC LIMIT 1000', $binds ) );
     201                        $languages = $by_lang ? Polylang::languages_for( wp_list_pluck( (array) $batch, 'ID' ) ) : array();
    189202                        foreach ( (array) $batch as $row ) {
    190203                                $last_id = (int) $row->ID;
    191204                                if ( current_user_can( 'edit_post', $row->ID ) ) {
    192                                         $rows[] = array( $row->ID, $row->post_type, rawurldecode( $row->post_name ), '' );
     205                                        $cells = array( $row->ID, $row->post_type, rawurldecode( $row->post_name ), '' );
     206                                        if ( $by_lang ) {
     207                                                $cells[] = isset( $languages[ $last_id ] ) ? $languages[ $last_id ] : '';
     208                                        }
     209                                        $rows[] = $cells;
    193210                                }
    194211                        }
    … …  
    196213                } while ( 1000 === $batch_size );
    197214
    198                 CsvHandler::send_download( 'slugh-records-' . gmdate( 'Ymd-His' ) . '.csv', array( 'content_id', 'post_type', 'old_slug', 'new_slug' ), $rows );
     215                $headers = array( 'content_id', 'post_type', 'old_slug', 'new_slug' );
     216                if ( $by_lang ) {
     217                        $headers[] = 'language';
     218                }
     219                CsvHandler::send_download( 'slugh-records-' . gmdate( 'Ymd-His' ) . '.csv', $headers, $rows );
    199220        }
    200221
    … …  
    213234                        'search'      => sanitize_text_field( $this->text( 's' ) ),
    214235                        'issues_only' => (bool) $this->param( 'issues_only' ),
     236                        'language'    => sanitize_key( $this->text( 'slugh_lang' ) ),
    215237                        'per_page'    => 500,
    216238                );
     239                $by_lang = Polylang::is_active();
    217240                $labels  = Flags::get_labels();
    218241                $rows    = array();
    … …  
    221244                        $filters['page'] = $page;
    222245                        $result          = Scanner::query_results( $scan_id, $filters );
     246                        $languages       = $by_lang ? Polylang::languages_for( wp_list_pluck( $result['items'], 'post_id' ) ) : array();
    223247                        foreach ( $result['items'] as $item ) {
    224248                                $names = array();
    … …  
    228252                                        }
    229253                                }
    230                                 $rows[] = array( $item->post_id, $item->post_type, $item->decoded_slug, '', $item->post_status, implode( '; ', $names ) );
     254                                $cells = array( $item->post_id, $item->post_type, $item->decoded_slug, '', $item->post_status, implode( '; ', $names ), 'term' === $item->object_type ? $item->post_type : '' );
     255                                if ( $by_lang ) {
     256                                        $cells[] = isset( $languages[ (int) $item->post_id ] ) ? $languages[ (int) $item->post_id ] : '';
     257                                }
     258                                $rows[] = $cells;
    231259                        }
    232260                        ++$page;
    … …  
    234262                } while ( 500 === $page_size );
    235263
    236                 CsvHandler::send_download( 'slugh-scan-' . $scan_id . '.csv', array( 'content_id', 'post_type', 'old_slug', 'new_slug', 'status', 'flags' ), $rows );
     264                // "taxonomy" is set for term rows (content_id is then a term ID); imports route those rows to terms.
     265                $headers = array( 'content_id', 'post_type', 'old_slug', 'new_slug', 'status', 'flags', 'taxonomy' );
     266                if ( $by_lang ) {
     267                        $headers[] = 'language';
     268                }
     269                CsvHandler::send_download( 'slugh-scan-' . $scan_id . '.csv', $headers, $rows );
    237270        }
    238271
    … …  
    402435                        $this->back( 'slugh-redirects' );
    403436                }
    404                 $missing = array_diff( array( 'source', 'destination' ), $parsed['headers'] );
    405                 if ( ! empty( $missing ) ) {
    406                         /* translators: %s: column names */
    407                         Notices::add( sprintf( __( 'The file is missing required columns: %s. Nothing was imported.', 'slugh' ), implode( ', ', $missing ) ), 'error' );
     437                $result = RedirectImporter::import( $parsed, (bool) $this->param( 'replace_existing' ), $file['name'] );
     438                if ( is_wp_error( $result ) ) {
     439                        Notices::add( $result->get_error_message(), 'error' );
    408440                        $this->back( 'slugh-redirects' );
    409441                }
    410 
    411                 $replace = (bool) $this->param( 'replace_existing' );
    412                 $counts  = array(
    413                         'created'   => 0,
    414                         'reenabled' => 0,
    415                         'replaced'  => 0,
    416                 );
    417                 $errors  = array();
    418 
    419                 foreach ( $parsed['rows'] as $row ) {
    420                         $data   = $row['data'];
    421                         $result = RedirectRepository::create(
    422                                 array(
    423                                         'source'      => Sanitizer::path_input( $data['source'] ),
    424                                         'destination' => Sanitizer::path_input( $data['destination'] ),
    425                                         'status_code' => isset( $data['status'] ) && '' !== $data['status'] ? absint( $data['status'] ) : 301,
    426                                         'enabled'     => ! isset( $data['enabled'] ) || '' === $data['enabled'] ? true : (bool) absint( $data['enabled'] ),
    427                                         'match_mode'  => isset( $data['match_mode'] ) && '' !== $data['match_mode'] ? sanitize_key( $data['match_mode'] ) : '404_only',
    428                                         'origin'      => 'import',
    429                                         'on_conflict' => $replace ? 'replace' : 'error',
    430                                 )
    431                         );
    432                         if ( is_wp_error( $result ) ) {
    433                                 /* translators: 1: line number, 2: reason */
    434                                 $errors[] = sprintf( __( 'Line %1$d: %2$s', 'slugh' ), $row['line'], $result->get_error_message() );
    435                         } elseif ( isset( $counts[ $result['action'] ] ) ) {
    436                                 ++$counts[ $result['action'] ];
    437                         }
    438                 }
    439 
    440                 AuditLogger::log( 'import', 'redirect', 0, array( 'filename' => $file['name'] ), array_merge( $counts, array( 'invalid' => count( $errors ) ) ) );
     442                $counts = $result;
     443                $errors = $result['errors'];
    441444
    442445                Notices::add(
    … …  
    547550                                'supported_post_types'        => array_map( 'sanitize_key', (array) $this->param( 'supported_post_types', array() ) ),
    548551                                'supported_post_statuses'     => array_map( 'sanitize_key', (array) $this->param( 'supported_post_statuses', array() ) ),
     552                                'supported_taxonomies'        => array_map( 'sanitize_key', (array) $this->param( 'supported_taxonomies', array() ) ),
     553                                'term_edit_redirects'         => (bool) $this->param( 'term_edit_redirects' ),
    549554                                'redirect_ownership_mode'     => $mode,
    550555                                'redirect_private_posts'      => (bool) $this->param( 'redirect_private_posts' ),
    … …  
    554559                                'trial_mode'                  => (bool) $this->param( 'trial_mode' ),
    555560                                'allow_external_destinations' => (bool) $this->param( 'allow_external_destinations' ),
     561                                'transliteration'             => (bool) $this->param( 'transliteration' ),
    556562                                'integrity_excluded_meta'     => array_filter( array_map( 'sanitize_text_field', (array) $excluded ) ),
    557563                                'scan_batch_size'             => absint( $this->param( 'scan_batch_size', 500 ) ),
    … …  
    607613                }
    608614
     615                // Terms (Slug Editor "Terms" view and term rows of Scan & Audit).
     616                foreach ( array_filter( array_map( 'absint', (array) $this->param( 'term_ids', array() ) ) ) as $term_id ) {
     617                        if ( 'suggest' === $action ) {
     618                                $term = get_term( $term_id );
     619                                if ( ! $term instanceof \WP_Term ) {
     620                                        continue;
     621                                }
     622                                $result = DraftManager::upsert_term_item( $job_id, $term_id, RulesSuggester::instance()->suggest( rawurldecode( $term->slug ), $term ) );
     623                                if ( in_array( $result['status'], array( 'added', 'updated' ), true ) ) {
     624                                        ++$done;
     625                                }
     626                        } elseif ( 'remove' === $action && DraftManager::remove_item( $job_id, $term_id, 'term' ) ) {
     627                                ++$done;
     628                        }
     629                }
     630
    609631                /* translators: %d: number of rows */
    610632                Notices::add( sprintf( __( '%d row(s) updated in the draft. Nothing is applied until you preview and confirm.', 'slugh' ), $done ) );
  • slugh/trunk/src/Admin/ListTables/EditorListTable.php

    r3795795 r3814912  
    99
    1010use SlugH\Database\Schema;
     11use SlugH\Integrations\Polylang;
    1112use SlugH\Jobs\JobRepository;
    1213use SlugH\Scan\Flags;
    … …  
    3738         */
    3839        private $draft = array();
     40
     41        /**
     42         * Polylang language slugs of the rows on this page, keyed by post ID.
     43         *
     44         * @var array<int, string>
     45         */
     46        private $languages = array();
    3947
    4048        /**
    … …  
    8896         */
    8997        public function get_columns() {
    90                 return array(
    91                         'cb'       => '<input type="checkbox" />',
    92                         'id'       => __( 'ID', 'slugh' ),
    93                         'title'    => __( 'Title', 'slugh' ),
    94                         'type'     => __( 'Type / status', 'slugh' ),
    95                         'current'  => __( 'Current slug', 'slugh' ),
    96                         'new_slug' => __( 'New slug', 'slugh' ),
    97                         'state'    => __( 'Change', 'slugh' ),
     98                $columns = array(
     99                        'cb'    => '<input type="checkbox" />',
     100                        'id'    => __( 'ID', 'slugh' ),
     101                        'title' => __( 'Title', 'slugh' ),
     102                        'type'  => __( 'Type / status', 'slugh' ),
     103                );
     104                if ( Polylang::is_active() ) {
     105                        $columns['language'] = __( 'Language', 'slugh' );
     106                }
     107                return array_merge(
     108                        $columns,
     109                        array(
     110                                'current'  => __( 'Current slug', 'slugh' ),
     111                                'new_slug' => __( 'New slug', 'slugh' ),
     112                                'state'    => __( 'Change', 'slugh' ),
     113                        )
    98114                );
    99115        }
    … …  
    119135        protected function get_bulk_actions() {
    120136                return array(
    121                         'suggest' => __( 'Add cleanup suggestion to draft', 'slugh' ),
     137                        'suggest' => __( 'Add suggested slug to draft', 'slugh' ),
    122138                        'remove'  => __( 'Remove from draft', 'slugh' ),
    123139                );
    … …  
    140156                $flag     = absint( self::filter( 'flag' ) );
    141157                $in_draft = '1' === self::filter( 'in_draft' );
     158                $language = Polylang::is_active() ? sanitize_key( self::filter( 'slugh_lang' ) ) : '';
    142159                $per_page = self::per_page();
    143160                $paged    = $this->get_pagenum();
    … …  
    147164                if ( $this->job_id ) {
    148165                        foreach ( JobRepository::get_items( $this->job_id, array( 'kind' => 'direct' ) ) as $item ) {
    149                                 $this->draft[ $item->post_id ] = $item;
     166                                if ( 'term' !== $item->object_type ) {
     167                                        $this->draft[ $item->post_id ] = $item;
     168                                }
    150169                        }
    151170                }
    … …  
    166185
    167186                $types    = $type && in_array( $type, $types, true ) ? array( $type ) : $types;
    168                 $statuses = $status && in_array( $status, $statuses, true ) ? array( $status ) : $statuses;
     187                $statuses = $status && in_array( $status, $statuses, true ) ? array( $status ) : PostTypes::query_statuses( $types, $statuses );
    169188                $where[]  = 'p.post_type IN (' . implode( ',', array_fill( 0, count( $types ), '%s' ) ) . ')';
    170189                $binds    = array_merge( $binds, $types );
    … …  
    187206                        $binds[] = $flag;
    188207                        $binds[] = $flag;
     208                }
     209
     210                if ( '' !== $language ) {
     211                        $condition = Polylang::language_condition( 'p.ID', $language );
     212                        $where[]   = $condition ? $condition[0] : '1 = 0';
     213                        if ( $condition ) {
     214                                $binds[] = $condition[1];
     215                        }
    189216                }
    190217
    … …  
    218245
    219246                $this->items = (array) $rows;
     247                if ( Polylang::is_active() ) {
     248                        $this->languages = Polylang::languages_for( wp_list_pluck( $this->items, 'ID' ) );
     249                }
    220250                $this->set_pagination_args(
    221251                        array(
    … …  
    255285                echo '</select>';
    256286
     287                if ( Polylang::is_active() ) {
     288                        echo '<label class="screen-reader-text" for="slugh-filter-lang">' . esc_html__( 'Filter by language', 'slugh' ) . '</label>';
     289                        echo '<select name="slugh_lang" id="slugh-filter-lang"><option value="">' . esc_html__( 'All languages', 'slugh' ) . '</option>';
     290                        foreach ( Polylang::languages() as $slug => $name ) {
     291                                printf( '<option value="%s"%s>%s</option>', esc_attr( $slug ), selected( self::filter( 'slugh_lang' ), $slug, false ), esc_html( $name ) );
     292                        }
     293                        echo '</select>';
     294                }
     295
    257296                echo '<label class="screen-reader-text" for="slugh-filter-flag">' . esc_html__( 'Filter by detection category from the latest scan', 'slugh' ) . '</label>';
    258297                echo '<select name="flag" id="slugh-filter-flag"><option value="">' . esc_html__( 'Any detection category', 'slugh' ) . '</option>';
    … …  
    292331                        esc_html( sprintf( __( 'Select %s', 'slugh' ), $this->title( $item ) ) )
    293332                );
     333        }
     334
     335        /**
     336         * Language slug of a row ('' when it has none).
     337         *
     338         * @param int $post_id Post ID.
     339         * @return string
     340         */
     341        private function language_of( $post_id ) {
     342                return isset( $this->languages[ (int) $post_id ] ) ? $this->languages[ (int) $post_id ] : '';
     343        }
     344
     345        /**
     346         * Linked Polylang translations with their current slugs, as a hint for writing the slug.
     347         *
     348         * @param object $item Row.
     349         * @return string HTML ('' without Polylang or without translations).
     350         */
     351        private function translations_hint( $item ) {
     352                if ( ! Polylang::is_active() ) {
     353                        return '';
     354                }
     355                $translations = Polylang::translations( $item->ID );
     356                if ( empty( $translations ) ) {
     357                        return '';
     358                }
     359                $parts = array();
     360                foreach ( $translations as $slug => $id ) {
     361                        $post = get_post( $id );
     362                        if ( ! $post ) {
     363                                continue;
     364                        }
     365                        $parts[] = sprintf(
     366                                '%1$s: <a href="%2$s"><code dir="ltr">%3$s</code></a>',
     367                                esc_html( Polylang::language_name( $slug ) ),
     368                                esc_url(
     369                                        add_query_arg(
     370                                                array(
     371                                                        'page' => 'slugh-editor',
     372                                                        's'    => $id,
     373                                                ),
     374                                                admin_url( 'admin.php' )
     375                                        )
     376                                ),
     377                                esc_html( '' === $post->post_name ? '—' : rawurldecode( $post->post_name ) )
     378                        );
     379                }
     380                return $parts ? '<div class="slugh-translations slugh-muted">' . esc_html__( 'Translations:', 'slugh' ) . ' ' . implode( ', ', $parts ) . '</div>' : '';
    294381        }
    295382
    … …  
    329416                                $out .= '<span class="view"><a href="' . esc_url( (string) $view ) . '" target="_blank" rel="noopener">' . esc_html__( 'View', 'slugh' ) . '</a></span>';
    330417                                $out .= '</div>';
    331                                 return $out;
     418                                return $out . $this->translations_hint( $item );
     419
     420                        case 'language':
     421                                return esc_html( Polylang::language_name( $this->language_of( $item->ID ) ) );
    332422
    333423                        case 'type':
    … …  
    349439                                        (int) $item->ID,
    350440                                        esc_attr( $decoded ),
    351                                         esc_attr( $item->post_type . '|' . ( is_post_type_hierarchical( $item->post_type ) ? (int) $item->post_parent : 0 ) . '|' ),
     441                                        esc_attr( JobRepository::duplicate_key_prefix( $item->post_type, $item->post_parent, $this->language_of( $item->ID ) ) ),
    352442                                        esc_attr( $this->title( $item ) ),
    353443                                        $can ? '' : ' disabled'
  • slugh/trunk/src/Admin/Screens/DiagnosticsScreen.php

    r3795795 r3814912  
    1212use SlugH\Integrations\CacheManager;
    1313use SlugH\Integrations\ConflictDetector;
     14use SlugH\Integrations\Polylang;
    1415use SlugH\Integrations\WooCommerce;
    1516use SlugH\Jobs\JobRepository;
    … …  
    6768                                'type' => 'warning',
    6869                                'text' => __( 'Ownership mode "Slug only, no redirects" is active: changed public URLs will return 404.', 'slugh' ),
     70                        );
     71                }
     72                if ( Polylang::uses_other_hosts() ) {
     73                        $warnings[] = array(
     74                                'type' => 'warning',
     75                                'text' => __( 'Polylang sets the language from subdomains or separate domains. slugH redirects and the redirect tester work only on the main site address; URLs on the other language hosts are treated as external.', 'slugh' ),
    6976                        );
    7077                }
    … …  
    156163                        __( 'Page caches purged on apply', 'slugh' ) => CacheManager::active_purgers() ? implode( ', ', CacheManager::active_purgers() ) : __( 'None detected', 'slugh' ),
    157164                        __( 'WooCommerce product support', 'slugh' ) => true === $wc ? __( 'On', 'slugh' ) : __( 'Off', 'slugh' ) . ' — ' . $wc,
     165                        __( 'Multilingual (Polylang)', 'slugh' )     => Polylang::describe(),
    158166                        __( 'Redirect ownership mode', 'slugh' )     => Settings::get( 'redirect_ownership_mode' ),
    159167                        __( 'slugH schema version', 'slugh' )        => $db_version . ' (' . __( 'code expects', 'slugh' ) . ' ' . Schema::DB_VERSION . ')',
  • slugh/trunk/src/Admin/Screens/EditorScreen.php

    r3795795 r3814912  
    99
    1010use SlugH\Admin\ListTables\EditorListTable;
     11use SlugH\Admin\ListTables\TermsListTable;
    1112use SlugH\Admin\Notices;
    1213use SlugH\Jobs\DraftManager;
    … …  
    5960                        }
    6061                }
     62                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Verified above.
     63                $term_ids = isset( $_GET['term_ids'] ) ? array_map( 'absint', (array) wp_unslash( $_GET['term_ids'] ) ) : array();
     64                foreach ( array_filter( $term_ids ) as $term_id ) {
     65                        if ( 'suggest' === $action ) {
     66                                $term = get_term( $term_id );
     67                                if ( $term instanceof \WP_Term ) {
     68                                        $res   = DraftManager::upsert_term_item( $job_id, $term_id, RulesSuggester::instance()->suggest( rawurldecode( $term->slug ), $term ) );
     69                                        $done += in_array( $res['status'], array( 'added', 'updated' ), true ) ? 1 : 0;
     70                                }
     71                        } elseif ( DraftManager::remove_item( $job_id, $term_id, 'term' ) ) {
     72                                ++$done;
     73                        }
     74                }
    6175
    6276                /* translators: %d: number of rows */
    6377                Notices::add( sprintf( __( '%d row(s) changed in the draft. Nothing is applied until you preview and confirm the draft.', 'slugh' ), $done ) );
    64                 wp_safe_redirect( remove_query_arg( array( 'action', 'action2', 'post_ids', '_wpnonce', '_wp_http_referer' ) ) );
     78                wp_safe_redirect( remove_query_arg( array( 'action', 'action2', 'post_ids', 'term_ids', '_wpnonce', '_wp_http_referer' ) ) );
    6579                exit;
    6680        }
    … …  
    7488                $job_id = DraftManager::get_editor_draft( false );
    7589                $count  = $job_id ? count( JobRepository::get_items( $job_id, array( 'kind' => 'direct' ) ) ) : 0;
    76                 $table  = new EditorListTable( $job_id );
     90                $terms  = 'terms' === EditorListTable::filter( 'slugh_view' );
     91                $table  = $terms ? new TermsListTable( $job_id ) : new EditorListTable( $job_id );
    7792                $table->prepare_items();
     93                $base   = admin_url( 'admin.php?page=slugh-editor' );
    7894                $review = $job_id ? admin_url( 'admin.php?page=slugh-history&job=' . $job_id ) : '';
    7995                ?>
    … …  
    86102                                <div class="notice notice-error"><p><?php echo esc_html( SlugUpdater::unfiltered_html_message() ); ?></p></div>
    87103                        <?php endif; ?>
     104
     105                        <ul class="subsubsub slugh-views">
     106                                <li><a href="<?php echo esc_url( $base ); ?>"<?php echo $terms ? '' : ' class="current" aria-current="page"'; ?>><?php esc_html_e( 'Posts, pages and other content', 'slugh' ); ?></a> |</li>
     107                                <li><a href="<?php echo esc_url( add_query_arg( 'slugh_view', 'terms', $base ) ); ?>"<?php echo $terms ? ' class="current" aria-current="page"' : ''; ?>><?php esc_html_e( 'Terms (categories, tags, taxonomies)', 'slugh' ); ?></a></li>
     108                        </ul>
     109                        <br class="clear" />
    88110
    89111                        <p class="description"><?php esc_html_e( 'Type a new slug beside any record. Enter saves the row to your draft, Escape reverts it, Tab moves to the next input. Saved changes stay in the draft until you preview and confirm them; nothing on the site changes before that.', 'slugh' ); ?></p>
    … …  
    118140                                        <summary><?php esc_html_e( 'Bulk paste by ID (recommended)', 'slugh' ); ?></summary>
    119141                                        <p><?php esc_html_e( 'One line per record: content_id,new_slug — comma or tab separated, so a two-column paste from Excel or Google Sheets works. Each line carries its ID, so a missing or extra line never shifts slugs onto the wrong records.', 'slugh' ); ?></p>
     142                                        <p class="description"><?php esc_html_e( 'For a term add its taxonomy as a third column: term_id,new_slug,category (or post_tag, or another enabled taxonomy).', 'slugh' ); ?></p>
    120143                                        <label for="slugh-paste-id-text" class="screen-reader-text"><?php esc_html_e( 'Lines of content_id and new slug', 'slugh' ); ?></label>
    121144                                        <textarea id="slugh-paste-id-text" rows="6" class="large-text code" dir="ltr" placeholder="1024,new-title&#10;2048      about"></textarea>
    … …  
    139162                        <form method="get" id="slugh-editor-form">
    140163                                <input type="hidden" name="page" value="slugh-editor" />
    141                                 <?php $table->search_box( __( 'Search title or slug', 'slugh' ), 'slugh-editor-search' ); ?>
     164                                <?php if ( $terms ) : ?>
     165                                        <input type="hidden" name="slugh_view" value="terms" />
     166                                <?php endif; ?>
     167                                <?php $table->search_box( $terms ? __( 'Search name or slug', 'slugh' ) : __( 'Search title or slug', 'slugh' ), 'slugh-editor-search' ); ?>
    142168                                <?php $table->display(); ?>
    143169                        </form>
  • slugh/trunk/src/Admin/Screens/ImportExportScreen.php

    r3795795 r3814912  
    99
    1010use SlugH\Admin\Notices;
     11use SlugH\Integrations\Polylang;
    1112use SlugH\Support\Capabilities;
    1213use SlugH\Support\PostTypes;
    … …  
    7071                                                        </select>
    7172                                                </label>
     73                                                <?php if ( Polylang::is_active() ) : ?>
     74                                                        <label><?php esc_html_e( 'Language', 'slugh' ); ?>
     75                                                                <select name="slugh_lang"><option value=""><?php esc_html_e( 'All', 'slugh' ); ?></option>
     76                                                                        <?php foreach ( Polylang::languages() as $slug => $name ) : ?>
     77                                                                                <option value="<?php echo esc_attr( $slug ); ?>"><?php echo esc_html( $name ); ?></option>
     78                                                                        <?php endforeach; ?>
     79                                                                </select>
     80                                                        </label>
     81                                                <?php endif; ?>
    7282                                                <label><?php esc_html_e( 'Search', 'slugh' ); ?> <input type="search" name="s" /></label>
    7383                                                <?php submit_button( __( 'Export filtered view', 'slugh' ), 'secondary', 'submit', false ); ?>
  • slugh/trunk/src/Admin/Screens/JobView.php

    r3795795 r3814912  
    441441        private function render_item_row( $item, $is_draft, $selectable ) {
    442442                $validation = isset( $item->message['validation'] ) ? (array) $item->message['validation'] : array();
    443                 $title      = get_the_title( $item->post_id );
     443                $is_term    = isset( $item->object_type ) && 'term' === $item->object_type;
     444                $term       = $is_term ? get_term( (int) $item->post_id ) : null;
     445                $title      = $is_term ? ( $term instanceof \WP_Term ? $term->name : '' ) : get_the_title( $item->post_id );
    444446                $old_slug   = rawurldecode( $item->old_post_name );
    445447                $new_slug   = rawurldecode( (string) ( $item->actual_post_name ? $item->actual_post_name : ( ! empty( $validation['predicted_slug'] ) ? $validation['predicted_slug'] : $item->requested_post_name ) ) );
    … …  
    461463                        <td class="column-primary">
    462464                                <strong>#<?php echo (int) $item->post_id; ?></strong> <?php echo esc_html( $title ); ?><br>
    463                                 <span class="slugh-muted"><?php echo esc_html( $item->post_type . ( 'descendant' === $item->kind ? ' · ' . __( 'descendant', 'slugh' ) : '' ) ); ?></span>
     465                                <span class="slugh-muted"><?php echo esc_html( $item->post_type . ( $is_term ? ' · ' . __( 'term', 'slugh' ) : '' ) . ( 'descendant' === $item->kind ? ' · ' . __( 'descendant', 'slugh' ) : '' ) ); ?></span>
    464466                        </td>
    465467                        <td dir="ltr"><code><?php echo esc_html( $old_slug ); ?></code><br>→ <code><?php echo esc_html( $new_slug ); ?></code></td>
  • slugh/trunk/src/Admin/Screens/ScanScreen.php

    r3795795 r3814912  
    1010use SlugH\Admin\Notices;
    1111use SlugH\Database\Schema;
     12use SlugH\Integrations\Polylang;
    1213use SlugH\Jobs\JobRepository;
    1314use SlugH\Scan\Flags;
    … …  
    1516use SlugH\Slugs\RulesSuggester;
    1617use SlugH\Slugs\SlugValidator;
     18use SlugH\Slugs\TermSlugs;
    1719use SlugH\Support\Capabilities;
    1820use SlugH\Support\PostTypes;
     21use SlugH\Support\Taxonomies;
    1922
    2023defined( 'ABSPATH' ) || exit;
    … …  
    9497                                                <?php endforeach; ?>
    9598                                        </fieldset>
     99                                        <p class="description">
     100                                                <?php
     101                                                $taxonomy_names = array();
     102                                                foreach ( Taxonomies::get_enabled() as $taxonomy_name ) {
     103                                                        $taxonomy_object  = get_taxonomy( $taxonomy_name );
     104                                                        $taxonomy_names[] = $taxonomy_object ? $taxonomy_object->labels->name : $taxonomy_name;
     105                                                }
     106                                                echo esc_html(
     107                                                        $taxonomy_names
     108                                                                /* translators: %s: list of taxonomies */
     109                                                                ? sprintf( __( 'Terms are scanned too: %s (change in Settings).', 'slugh' ), implode( ', ', $taxonomy_names ) )
     110                                                                : __( 'No taxonomies are enabled in Settings, so no terms are scanned.', 'slugh' )
     111                                                );
     112                                                ?>
     113                                        </p>
    96114                                        <p><button type="submit" class="button button-primary" id="slugh-scan-start"><?php esc_html_e( 'Start scan', 'slugh' ); ?></button></p>
    97115                                </form>
    … …  
    147165                        'modified_to'   => preg_match( '/^\d{4}-\d{2}-\d{2}$/', $this->text_filter( 'modified_to' ) ) ? $this->text_filter( 'modified_to' ) : '',
    148166                        'issues_only'   => '1' === $this->filter( 'issues_only' ),
     167                        'language'      => Polylang::is_active() ? sanitize_key( $this->text_filter( 'slugh_lang' ) ) : '',
    149168                        'orderby'       => sanitize_key( $this->text_filter( 'orderby' ) ),
    150169                        'order'         => sanitize_key( $this->text_filter( 'order' ) ),
    … …  
    153172                );
    154173                $result  = Scanner::query_results( $scan_id, $filters );
     174                $langs   = Polylang::is_active() ? Polylang::languages() : array();
     175                $columns = $langs ? 11 : 10;
    155176                $export  = wp_nonce_url(
    156177                        add_query_arg(
    … …  
    163184                                                's'           => $filters['search'],
    164185                                                'issues_only' => $filters['issues_only'] ? '1' : '',
     186                                                'slugh_lang'  => $filters['language'],
    165187                                                'flags'       => $flags,
    166188                                        )
    … …  
    178200                                ?>
    179201                        </h2>
     202                        <?php $this->render_skipped_types_notice( $scan, $available ); ?>
    180203                        <ul class="slugh-count-list">
    181204                                <li><strong><?php echo (int) $counts['total']; ?></strong> <?php esc_html_e( 'records', 'slugh' ); ?></li>
    … …  
    207230                                                        <option value="<?php echo esc_attr( $name ); ?>" <?php selected( $filters['post_type'], $name ); ?>><?php echo esc_html( $object->labels->name ); ?></option>
    208231                                                <?php endforeach; ?>
     232                                                <?php foreach ( Taxonomies::get_available() as $name => $object ) : ?>
     233                                                        <option value="<?php echo esc_attr( $name ); ?>" <?php selected( $filters['post_type'], $name ); ?>><?php echo esc_html( $object->labels->name . ' (' . __( 'terms', 'slugh' ) . ')' ); ?></option>
     234                                                <?php endforeach; ?>
    209235                                                </select>
    210236                                        </label>
    … …  
    216242                                                </select>
    217243                                        </label>
     244                                        <?php if ( $langs ) : ?>
     245                                                <label><?php esc_html_e( 'Language', 'slugh' ); ?>
     246                                                        <select name="slugh_lang"><option value=""><?php esc_html_e( 'All', 'slugh' ); ?></option>
     247                                                        <?php foreach ( $langs as $slug => $name ) : ?>
     248                                                                <option value="<?php echo esc_attr( $slug ); ?>" <?php selected( $filters['language'], $slug ); ?>><?php echo esc_html( $name ); ?></option>
     249                                                        <?php endforeach; ?>
     250                                                        </select>
     251                                                </label>
     252                                        <?php endif; ?>
    218253                                        <label><?php esc_html_e( 'Modified from', 'slugh' ); ?> <input type="date" name="modified_from" value="<?php echo esc_attr( $filters['modified_from'] ); ?>" /></label>
    219254                                        <label><?php esc_html_e( 'to', 'slugh' ); ?> <input type="date" name="modified_to" value="<?php echo esc_attr( $filters['modified_to'] ); ?>" /></label>
    … …  
    238273                                <?php wp_nonce_field( 'slugh_editor_bulk' ); ?>
    239274                                <?php if ( current_user_can( Capabilities::CAP_EDIT_SLUGS ) ) : ?>
    240                                         <p><button type="submit" class="button"><?php esc_html_e( 'Add cleanup suggestions for checked rows to the Slug Editor draft', 'slugh' ); ?></button></p>
     275                                        <p><button type="submit" class="button"><?php esc_html_e( 'Add suggested slugs for checked rows to the Slug Editor draft', 'slugh' ); ?></button></p>
    241276                                <?php endif; ?>
    242277                                <div class="slugh-table-scroll">
    … …  
    248283                                                        <th scope="col"><?php esc_html_e( 'Title', 'slugh' ); ?></th>
    249284                                                        <th scope="col"><?php esc_html_e( 'Type / status', 'slugh' ); ?></th>
     285                                                        <?php if ( $langs ) : ?>
     286                                                                <th scope="col"><?php esc_html_e( 'Language', 'slugh' ); ?></th>
     287                                                        <?php endif; ?>
    250288                                                        <th scope="col"><?php esc_html_e( 'Current slug and permalink', 'slugh' ); ?></th>
    251289                                                        <th scope="col"><?php esc_html_e( 'Proposed slug and permalink', 'slugh' ); ?></th>
    … …  
    258296                                        <tbody>
    259297                                        <?php if ( empty( $result['items'] ) ) : ?>
    260                                                 <tr><td colspan="10"><?php esc_html_e( 'No records match these filters.', 'slugh' ); ?></td></tr>
     298                                                <tr><td colspan="<?php echo (int) $columns; ?>"><?php esc_html_e( 'No records match these filters.', 'slugh' ); ?></td></tr>
    261299                                        <?php endif; ?>
    262300                                        <?php foreach ( $result['items'] as $item ) : ?>
    263                                                 <?php $this->render_row( $item, $labels ); ?>
     301                                                <?php $this->render_row( $item, $labels, (bool) $langs ); ?>
    264302                                        <?php endforeach; ?>
    265303                                        </tbody>
    … …  
    273311
    274312        /**
     313         * Tell the administrator which public post types with content the scan left out.
     314         *
     315         * @param object|null $scan      Scan job.
     316         * @param array       $available Available post types keyed by name.
     317         * @return void
     318         */
     319        private function render_skipped_types_notice( $scan, array $available ) {
     320                if ( ! $scan || empty( $scan->settings['post_types'] ) ) {
     321                        return;
     322                }
     323                $scanned = (array) $scan->settings['post_types'];
     324                $skipped = array();
     325                foreach ( $available as $name => $object ) {
     326                        if ( in_array( $name, $scanned, true ) ) {
     327                                continue;
     328                        }
     329                        $counts = (array) wp_count_posts( $name );
     330                        $total  = 0;
     331                        foreach ( PostTypes::SUPPORTED_STATUSES as $status ) {
     332                                $total += isset( $counts[ $status ] ) ? (int) $counts[ $status ] : 0;
     333                        }
     334                        if ( $total > 0 ) {
     335                                /* translators: 1: post type label, 2: post type name, 3: number of items */
     336                                $skipped[] = sprintf( _n( '%1$s (%2$s, %3$s item)', '%1$s (%2$s, %3$s items)', $total, 'slugh' ), $object->labels->name, $name, number_format_i18n( $total ) );
     337                        }
     338                }
     339                if ( ! $skipped ) {
     340                        return;
     341                }
     342                ?>
     343                <div class="notice notice-info inline slugh-skipped-types">
     344                        <p>
     345                                <?php
     346                                echo esc_html(
     347                                        sprintf(
     348                                                /* translators: %s: comma-separated list of post types */
     349                                                __( 'This scan did not include these public post types, which have content: %s. Tick them under "Post types" above and scan again.', 'slugh' ),
     350                                                implode( ', ', $skipped )
     351                                        )
     352                                );
     353                                ?>
     354                                <a href="<?php echo esc_url( admin_url( 'admin.php?page=slugh-settings' ) ); ?>"><?php esc_html_e( 'Enable them by default in Settings', 'slugh' ); ?></a>
     355                        </p>
     356                </div>
     357                <?php
     358        }
     359
     360        /**
    275361         * One results row.
    276362         *
    277363         * @param object $item   Scan row.
    278364         * @param array  $labels Flag labels.
     365         * @param bool   $multilingual Whether to show the Language column (Polylang active).
    279366         * @return void
    280367         */
    281         private function render_row( $item, array $labels ) {
     368        private function render_row( $item, array $labels, $multilingual = false ) {
    282369                global $wpdb;
    283370
    284                 $post      = get_post( $item->post_id );
    285                 $permalink = $post ? (string) get_permalink( $post ) : '';
     371                $is_term   = 'term' === $item->object_type;
     372                $post      = $is_term ? get_term( (int) $item->post_id ) : get_post( $item->post_id );
     373                $post      = $post && ! is_wp_error( $post ) ? $post : null;
     374                $slug      = $post ? ( $is_term ? $post->slug : $post->post_name ) : '';
     375                $permalink = $post ? ( $is_term ? TermSlugs::link( $post ) : (string) get_permalink( $post ) ) : '';
    286376                $proposed  = '';
    287377                $predicted = '';
    … …  
    289379
    290380                if ( $post ) {
    291                         $suggestion = RulesSuggester::instance()->suggest( rawurldecode( $post->post_name ), $post );
    292                         if ( '' !== $suggestion && rawurldecode( $post->post_name ) !== $suggestion ) {
    293                                 $validation = SlugValidator::validate( $post->ID, $suggestion );
     381                        $suggestion = RulesSuggester::instance()->suggest( rawurldecode( $slug ), $post );
     382                        if ( '' !== $suggestion && rawurldecode( $slug ) !== $suggestion ) {
     383                                $validation = $is_term ? TermSlugs::validate( $item->post_id, $suggestion ) : SlugValidator::validate( $post->ID, $suggestion );
    294384                                $proposed   = $validation['predicted_decoded'];
    295385                                $predicted  = $validation['predicted_permalink'];
    … …  
    300390                $table = Schema::get_table_name( 'slugh_redirects' );
    301391                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    302                 $redirects = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE post_id = %d AND enabled = 1', $table, $item->post_id ) );
     392                $redirects = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE post_id = %d AND object_type = %s AND enabled = 1', $table, $item->post_id, $is_term ? 'term' : 'post' ) );
     393                $box_name  = $is_term ? 'term_ids[]' : 'post_ids[]';
     394                $box_id    = ( $is_term ? 'slugh-scan-term-' : 'slugh-scan-' ) . (int) $item->post_id;
    303395
    304396                $badges = array();
    … …  
    310402                ?>
    311403                <tr<?php echo $item->is_stale ? ' class="slugh-stale"' : ''; ?>>
    312                         <th scope="row" class="check-column"><label class="screen-reader-text" for="slugh-scan-<?php echo (int) $item->post_id; ?>"><?php esc_html_e( 'Select', 'slugh' ); ?></label><input type="checkbox" name="post_ids[]" id="slugh-scan-<?php echo (int) $item->post_id; ?>" value="<?php echo (int) $item->post_id; ?>" /></th>
     404                        <th scope="row" class="check-column"><label class="screen-reader-text" for="<?php echo esc_attr( $box_id ); ?>"><?php esc_html_e( 'Select', 'slugh' ); ?></label><input type="checkbox" name="<?php echo esc_attr( $box_name ); ?>" id="<?php echo esc_attr( $box_id ); ?>" value="<?php echo (int) $item->post_id; ?>" /></th>
    313405                        <td><?php echo (int) $item->post_id; ?></td>
    314406                        <td><?php echo esc_html( null === $item->post_title ? __( '(deleted)', 'slugh' ) : $item->post_title ); ?></td>
    315                         <td><code><?php echo esc_html( $item->post_type ); ?></code><br><span class="slugh-muted"><?php echo esc_html( $item->post_status ); ?></span></td>
     407                        <td><code><?php echo esc_html( $item->post_type ); ?></code><br><span class="slugh-muted"><?php echo esc_html( $is_term ? __( 'term', 'slugh' ) : $item->post_status ); ?></span></td>
     408                        <?php if ( $multilingual ) : ?>
     409                                <td><?php echo esc_html( Polylang::language_name( Polylang::post_language( $item->post_id ) ) ); ?></td>
     410                        <?php endif; ?>
    316411                        <td dir="ltr"><code class="slugh-slug"><?php echo esc_html( '' === $item->decoded_slug ? '—' : $item->decoded_slug ); ?></code><br><span class="slugh-links"><?php echo esc_html( rawurldecode( $permalink ) ); ?></span></td>
    317412                        <td dir="ltr">
  • slugh/trunk/src/Admin/Screens/SettingsScreen.php

    r3795795 r3814912  
    1111use SlugH\Integrations\ConflictDetector;
    1212use SlugH\Integrations\WooCommerce;
     13use SlugH\Slugs\TransliterationSuggester;
    1314use SlugH\Support\PostTypes;
    1415use SlugH\Support\Settings;
     16use SlugH\Support\Taxonomies;
    1517
    1618defined( 'ABSPATH' ) || exit;
    … …  
    5456                                                                <label class="slugh-inline-check"><input type="checkbox" name="supported_post_types[]" value="<?php echo esc_attr( $name ); ?>" <?php checked( in_array( $name, (array) $s['supported_post_types'], true ) ); ?> /> <?php echo esc_html( $object->labels->name ); ?> <code><?php echo esc_html( $name ); ?></code></label>
    5557                                                        <?php endforeach; ?>
    56                                                         <p class="description"><?php esc_html_e( 'Discovered at runtime. Attachments, revisions, menu items, templates, reusable blocks and product variations are never handled.', 'slugh' ); ?></p>
     58                                                        <p class="description"><?php esc_html_e( 'Discovered at runtime. Media (attachments) are off unless you tick them. Revisions, menu items, templates, reusable blocks and product variations are never handled.', 'slugh' ); ?></p>
     59                                                        <p class="description">
     60                                                                <?php
     61                                                                echo esc_html(
     62                                                                        PostTypes::attachment_pages_enabled()
     63                                                                                ? __( 'Attachment pages are on in WordPress: changed media URLs get redirects, including media attached to a record whose URL changes.', 'slugh' )
     64                                                                                : __( 'Attachment pages are off in WordPress (media URLs redirect to the file), so slugH creates no redirects for media slugs.', 'slugh' )
     65                                                                );
     66                                                                ?>
     67                                                        </p>
    5768                                                </fieldset></td>
    5869                                        </tr>
    … …  
    6374                                                                <label class="slugh-inline-check"><input type="checkbox" name="supported_post_statuses[]" value="<?php echo esc_attr( $status ); ?>" <?php checked( in_array( $status, (array) $s['supported_post_statuses'], true ) ); ?> /> <?php echo esc_html( $status ); ?></label>
    6475                                                        <?php endforeach; ?>
     76                                                </fieldset></td>
     77                                        </tr>
     78                                        <tr>
     79                                                <th scope="row"><?php esc_html_e( 'Taxonomies', 'slugh' ); ?></th>
     80                                                <td><fieldset><legend class="screen-reader-text"><?php esc_html_e( 'Taxonomies', 'slugh' ); ?></legend>
     81                                                        <?php foreach ( Taxonomies::get_available() as $name => $object ) : ?>
     82                                                                <label class="slugh-inline-check"><input type="checkbox" name="supported_taxonomies[]" value="<?php echo esc_attr( $name ); ?>" <?php checked( in_array( $name, (array) $s['supported_taxonomies'], true ) ); ?> /> <?php echo esc_html( $object->labels->name ); ?> <code><?php echo esc_html( $name ); ?></code></label>
     83                                                        <?php endforeach; ?>
     84                                                        <p class="description"><?php esc_html_e( 'Term slugs of these taxonomies are scanned and can be changed in the Slug Editor\'s Terms view. A changed term gets one redirect from its old archive URL; its archive pages and feeds follow it.', 'slugh' ); ?></p>
     85                                                        <p><label><input type="checkbox" name="term_edit_redirects" value="1" <?php checked( $s['term_edit_redirects'] ); ?> /> <?php esc_html_e( 'Also redirect the old URL when a term slug is changed elsewhere in WordPress (term edit screen, quick edit). WordPress keeps no old term slugs.', 'slugh' ); ?></label></p>
    6586                                                </fieldset></td>
    6687                                        </tr>
    … …  
    108129                                </table>
    109130
     131                                <h2><?php esc_html_e( 'Slug suggestions', 'slugh' ); ?></h2>
     132                                <table class="form-table" role="presentation">
     133                                        <tr>
     134                                                <th scope="row"><?php esc_html_e( 'Transliteration', 'slugh' ); ?></th>
     135                                                <td>
     136                                                        <label><input type="checkbox" name="transliteration" value="1" <?php checked( $s['transliteration'] ); ?> /> <?php esc_html_e( 'Suggest Latin spellings for slugs in other scripts', 'slugh' ); ?></label>
     137                                                        <p class="description"><?php esc_html_e( 'Suggestions only: you see and can edit every suggestion in the preview, and nothing changes until you apply a job. Bangla uses slugH\'s own phonetic rules (for example আমার সোনার বাংলা becomes amar-sonar-bangla). Spellings vary, so check each one.', 'slugh' ); ?></p>
     138                                                        <?php if ( ! TransliterationSuggester::icu_available() ) : ?>
     139                                                                <p class="description"><?php esc_html_e( 'PHP intl transliteration for other scripts is not available on this server (the intl extension or its script data is missing), so only Bangla slugs get Latin suggestions. Other scripts (Hindi, Arabic, Urdu and others) get the basic cleanup only.', 'slugh' ); ?></p>
     140                                                        <?php endif; ?>
     141                                                </td>
     142                                        </tr>
     143                                </table>
     144
    110145                                <h2><?php esc_html_e( 'Updates, cache and trial mode', 'slugh' ); ?></h2>
    111146                                <table class="form-table" role="presentation">
  • slugh/trunk/src/Database/Migrations.php

    r3795795 r3814912  
    2626                        // Adds job_items.sort_order, scan_items.permalink_hash and redirects.destination_hash.
    2727                        '1.1.0' => array( __CLASS__, 'migrate_1_1_0' ),
     28                        // Adds object_type (post/term) to redirects, job_items and scan_items; scan_items key includes it.
     29                        '1.2.0' => array( __CLASS__, 'migrate_1_2_0' ),
    2830                );
    2931        }
    … …  
    5860                require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    5961
     62                self::prepare_scan_items_key();
     63
    6064                foreach ( Schema::get_schemas() as $sql ) {
    6165                        dbDelta( $sql );
    6266                }
     67        }
     68
     69        /**
     70         * Before dbDelta: give an existing scan_items table the object_type column and the
     71         * (scan_id, object_type, post_id) primary key. dbDelta cannot change a primary key and
     72         * would fail with "Multiple primary key defined".
     73         *
     74         * @return void
     75         */
     76        private static function prepare_scan_items_key() {
     77                global $wpdb;
     78
     79                $table = Schema::get_table_name( 'slugh_scan_items' );
     80                // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
     81                if ( $table !== $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) ) ) ) {
     82                        return;
     83                }
     84                $primary = (array) $wpdb->get_col( $wpdb->prepare( "SHOW INDEX FROM %i WHERE Key_name = 'PRIMARY'", $table ), 4 );
     85                if ( in_array( 'object_type', $primary, true ) ) {
     86                        return;
     87                }
     88                $has_column = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW COLUMNS FROM %i LIKE %s', $table, 'object_type' ) );
     89                if ( ! $has_column ) {
     90                        $wpdb->query( $wpdb->prepare( "ALTER TABLE %i ADD COLUMN object_type varchar(10) NOT NULL DEFAULT 'post' AFTER post_id", $table ) );
     91                }
     92                $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i DROP PRIMARY KEY, ADD PRIMARY KEY (scan_id, object_type, post_id)', $table ) );
     93                // phpcs:enable
    6394        }
    6495
    … …  
    85116
    86117        /**
     118         * Step 1.2.0: add object_type columns (existing rows become "post"); install() widens
     119         * the scan_items primary key first.
     120         *
     121         * @return void
     122         */
     123        public static function migrate_1_2_0() {
     124                self::install();
     125        }
     126
     127        /**
    87128         * Drop all custom tables (used only on uninstall when configured).
    88129         *
  • slugh/trunk/src/Database/Schema.php

    r3795795 r3814912  
    1515class Schema {
    1616
    17         const DB_VERSION        = '1.1.0';
     17        const DB_VERSION        = '1.2.0';
    1818        const DB_VERSION_OPTION = 'slugh_db_version';
    1919
    … …  
    7272                                match_mode varchar(20) NOT NULL DEFAULT '404_only',
    7373                                post_id bigint(20) unsigned DEFAULT NULL,
     74                                object_type varchar(10) NOT NULL DEFAULT 'post',
    7475                                job_id bigint(20) unsigned DEFAULT NULL,
    7576                                origin varchar(20) NOT NULL DEFAULT 'manual',
    … …  
    112113                                job_id bigint(20) unsigned NOT NULL,
    113114                                post_id bigint(20) unsigned NOT NULL,
     115                                object_type varchar(10) NOT NULL DEFAULT 'post',
    114116                                kind varchar(20) NOT NULL DEFAULT 'direct',
    115117                                post_type varchar(50) NOT NULL,
    … …  
    139141                                scan_id bigint(20) unsigned NOT NULL,
    140142                                post_id bigint(20) unsigned NOT NULL,
     143                                object_type varchar(10) NOT NULL DEFAULT 'post',
    141144                                post_type varchar(50) NOT NULL,
    142145                                post_status varchar(20) NOT NULL,
    … …  
    146149                                permalink_hash char(40) NOT NULL DEFAULT '',
    147150                                scanned_at datetime NOT NULL,
    148                                 PRIMARY KEY  (scan_id, post_id),
     151                                PRIMARY KEY  (scan_id, object_type, post_id),
    149152                                KEY scan_id_post_type (scan_id, post_type),
    150153                                KEY scan_id_permalink (scan_id, permalink_hash)
  • slugh/trunk/src/Jobs/DraftManager.php

    r3795795 r3814912  
    99
    1010use SlugH\Slugs\SlugValidator;
     11use SlugH\Slugs\TermSlugs;
    1112use SlugH\Support\PostTypes;
     13use SlugH\Support\Taxonomies;
    1214
    1315defined( 'ABSPATH' ) || exit;
    … …  
    117119                        );
    118120                }
    119                 if ( ! in_array( $post->post_status, PostTypes::SUPPORTED_STATUSES, true ) ) {
     121                if ( ! in_array( $post->post_status, PostTypes::query_statuses( array( $post->post_type ), PostTypes::SUPPORTED_STATUSES ), true ) ) {
    120122                        return array(
    121123                                'status'  => 'error',
    … …  
    184186
    185187        /**
    186          * Remove a post's change from a draft.
    187          *
    188          * @param int $job_id  Job ID.
    189          * @param int $post_id Post ID.
     188         * Add or update one draft change for a taxonomy term (spec section 26.5).
     189         *
     190         * @param int         $job_id            Draft job ID.
     191         * @param int         $term_id           Term ID.
     192         * @param string      $new_slug          Proposed slug.
     193         * @param string|null $expected_old_slug Old slug safeguard (null = current slug).
     194         * @param string|null $expected_taxonomy Taxonomy safeguard (null = current taxonomy).
     195         * @param array       $extra             Extra message data.
     196         * @return array{status: string, item_id?: int, message?: string}
     197         */
     198        public static function upsert_term_item( $job_id, $term_id, $new_slug, $expected_old_slug = null, $expected_taxonomy = null, array $extra = array() ) {
     199                $job = JobRepository::get( $job_id );
     200                if ( ! $job || ! in_array( $job->status, array( 'draft', 'validated' ), true ) ) {
     201                        return array(
     202                                'status'  => 'error',
     203                                'message' => __( 'This job is no longer a draft.', 'slugh' ),
     204                        );
     205                }
     206                $term = get_term( absint( $term_id ) );
     207                if ( ! $term instanceof \WP_Term ) {
     208                        return array(
     209                                'status'  => 'error',
     210                                'message' => __( 'No term with this ID.', 'slugh' ),
     211                        );
     212                }
     213                if ( null !== $expected_taxonomy && '' !== $expected_taxonomy && sanitize_key( $expected_taxonomy ) !== $term->taxonomy ) {
     214                        return array(
     215                                'status'  => 'error',
     216                                /* translators: 1: term ID, 2: taxonomy */
     217                                'message' => sprintf( __( 'Term %1$d is not in the taxonomy "%2$s".', 'slugh' ), (int) $term->term_id, sanitize_key( $expected_taxonomy ) ),
     218                        );
     219                }
     220                if ( ! Taxonomies::is_supported( $term->taxonomy ) ) {
     221                        return array(
     222                                'status'  => 'error',
     223                                /* translators: %s: taxonomy */
     224                                'message' => sprintf( __( 'Taxonomy "%s" is not managed by slugH.', 'slugh' ), $term->taxonomy ),
     225                        );
     226                }
     227                if ( ! current_user_can( 'edit_term', $term->term_id ) ) {
     228                        return array(
     229                                'status'  => 'error',
     230                                'message' => __( 'You cannot edit this term.', 'slugh' ),
     231                        );
     232                }
     233
     234                $requested = self::sanitize_candidate( $new_slug );
     235                if ( '' === $requested ) {
     236                        return array(
     237                                'status'  => 'error',
     238                                'message' => __( 'The new slug is empty after sanitization.', 'slugh' ),
     239                        );
     240                }
     241
     242                $existing = JobRepository::find_item( $job_id, $term->term_id, 'term' );
     243                $expected = null === $expected_old_slug ? ( $existing ? $existing->old_post_name : $term->slug ) : (string) $expected_old_slug;
     244
     245                if ( SlugValidator::compare_form( $requested ) === SlugValidator::compare_form( $term->slug ) && SlugValidator::compare_form( $expected ) === SlugValidator::compare_form( $term->slug ) ) {
     246                        if ( $existing ) {
     247                                JobRepository::delete_draft_item( $existing->id );
     248                        }
     249                        self::mark_dirty( $job_id );
     250                        return array(
     251                                'status'  => 'unchanged',
     252                                'message' => __( 'Same as the current slug; nothing to change.', 'slugh' ),
     253                        );
     254                }
     255
     256                $data = array(
     257                        'post_id'             => $term->term_id,
     258                        'object_type'         => 'term',
     259                        'kind'                => 'direct',
     260                        'post_type'           => $term->taxonomy,
     261                        'parent_id'           => (int) $term->parent,
     262                        'old_post_name'       => $expected,
     263                        'requested_post_name' => $requested,
     264                        'old_permalink'       => TermSlugs::link( $term ),
     265                        'validation_state'    => 'pending',
     266                        'result'              => 'pending',
     267                        'message'             => array_merge( array( 'input' => (string) $new_slug ), $extra ),
     268                );
     269
     270                if ( $existing ) {
     271                        JobRepository::update_item( $existing->id, $data );
     272                        $item_id = $existing->id;
     273                } else {
     274                        $item_id = JobRepository::add_item( $job_id, $data );
     275                }
     276                self::mark_dirty( $job_id );
     277
     278                return array(
     279                        'status'  => $existing ? 'updated' : 'added',
     280                        'item_id' => $item_id,
     281                );
     282        }
     283
     284        /**
     285         * Remove a post's or term's change from a draft.
     286         *
     287         * @param int    $job_id      Job ID.
     288         * @param int    $post_id     Post or term ID.
     289         * @param string $object_type post or term.
    190290         * @return bool
    191291         */
    192         public static function remove_item( $job_id, $post_id ) {
    193                 $item = JobRepository::find_item( $job_id, $post_id );
     292        public static function remove_item( $job_id, $post_id, $object_type = 'post' ) {
     293                $item = JobRepository::find_item( $job_id, $post_id, $object_type );
    194294                if ( ! $item ) {
    195295                        return false;
    … …  
    230330        /**
    231331         * Parse "content_id,new_slug" lines (comma or tab separated) into the draft.
     332         * A third column with a taxonomy makes the line a term: "term_id,new_slug,category".
    232333         *
    233334         * @param int    $job_id Draft job ID.
    … …  
    252353                        }
    253354
    254                         $parts = false !== strpos( $line, "\t" ) ? explode( "\t", $line, 2 ) : str_getcsv( $line, ',', '"', '\\' );
     355                        $parts = false !== strpos( $line, "\t" ) ? explode( "\t", $line, 3 ) : str_getcsv( $line, ',', '"', '\\' );
    255356                        if ( count( $parts ) < 2 ) {
    256357                                $report['errors'][] = array(
    … …  
    262363                        }
    263364
    264                         $id   = trim( (string) $parts[0] );
    265                         $slug = trim( (string) $parts[1] );
     365                        $id       = trim( (string) $parts[0] );
     366                        $slug     = trim( (string) $parts[1] );
     367                        $taxonomy = isset( $parts[2] ) ? sanitize_key( trim( (string) $parts[2] ) ) : '';
    266368
    267369                        if ( ! preg_match( '/^[0-9]+$/D', $id ) ) {
    … …  
    277379                        }
    278380
    279                         if ( isset( $seen[ $id ] ) ) {
     381                        $seen_key = ( '' === $taxonomy ? 'post:' : 'term:' ) . $id;
     382                        if ( isset( $seen[ $seen_key ] ) ) {
    280383                                $report['errors'][] = array(
    281384                                        'line'   => $line_number,
    282385                                        'text'   => $line,
    283386                                        /* translators: %d: earlier line number */
    284                                         'reason' => sprintf( __( 'Duplicate content ID; line %d already sets it.', 'slugh' ), $seen[ $id ] ),
    285                                 );
    286                                 continue;
    287                         }
    288                         $seen[ $id ] = $line_number;
    289 
    290                         $res = self::upsert_item( $job_id, (int) $id, $slug, null, null, array( 'source' => 'paste' ) );
     387                                        'reason' => sprintf( __( 'Duplicate content ID; line %d already sets it.', 'slugh' ), $seen[ $seen_key ] ),
     388                                );
     389                                continue;
     390                        }
     391                        $seen[ $seen_key ] = $line_number;
     392
     393                        $res = '' === $taxonomy
     394                                ? self::upsert_item( $job_id, (int) $id, $slug, null, null, array( 'source' => 'paste' ) )
     395                                : self::upsert_term_item( $job_id, (int) $id, $slug, null, $taxonomy, array( 'source' => 'paste' ) );
    291396                        if ( 'error' === $res['status'] ) {
    292397                                $report['errors'][] = array(
    … …  
    358463                                continue;
    359464                        }
    360                         if ( isset( $seen[ $id ] ) ) {
     465                        // A "taxonomy" column (spec section 26.5) makes the row a term; content_id is then a term ID.
     466                        $taxonomy = isset( $data['taxonomy'] ) ? sanitize_key( (string) $data['taxonomy'] ) : '';
     467                        $seen_key = ( '' === $taxonomy ? 'post:' : 'term:' ) . $id;
     468                        if ( isset( $seen[ $seen_key ] ) ) {
    361469                                $report['errors'][] = array(
    362470                                        'line'   => $line,
    363471                                        /* translators: %d: earlier line number */
    364                                         'reason' => sprintf( __( 'Duplicate content_id; line %d already sets it.', 'slugh' ), $seen[ $id ] ),
    365                                 );
    366                                 continue;
    367                         }
    368                         $seen[ $id ] = $line;
    369 
    370                         $res = self::upsert_item(
    371                                 $job_id,
    372                                 (int) $id,
    373                                 (string) $data['new_slug'],
    374                                 (string) $data['old_slug'],
    375                                 (string) $data['post_type'],
    376                                 array(
    377                                         'source' => 'csv',
    378                                         'line'   => $line,
    379                                 )
    380                         );
     472                                        'reason' => sprintf( __( 'Duplicate content_id; line %d already sets it.', 'slugh' ), $seen[ $seen_key ] ),
     473                                );
     474                                continue;
     475                        }
     476                        $seen[ $seen_key ] = $line;
     477
     478                        $extra = array(
     479                                'source' => 'csv',
     480                                'line'   => $line,
     481                        );
     482                        $res   = '' === $taxonomy
     483                                ? self::upsert_item( $job_id, (int) $id, (string) $data['new_slug'], (string) $data['old_slug'], (string) $data['post_type'], $extra )
     484                                : self::upsert_term_item( $job_id, (int) $id, (string) $data['new_slug'], (string) $data['old_slug'], $taxonomy, $extra );
    381485
    382486                        if ( 'error' === $res['status'] ) {
  • slugh/trunk/src/Jobs/JobRepository.php

    r3795795 r3814912  
    99
    1010use SlugH\Database\Schema;
     11use SlugH\Integrations\Polylang;
    1112
    1213defined( 'ABSPATH' ) || exit;
    … …  
    214215                        'job_id'              => absint( $job_id ),
    215216                        'post_id'             => absint( $data['post_id'] ),
     217                        'object_type'         => isset( $data['object_type'] ) && 'term' === $data['object_type'] ? 'term' : 'post',
    216218                        'kind'                => isset( $data['kind'] ) && 'descendant' === $data['kind'] ? 'descendant' : 'direct',
    217219                        'post_type'           => isset( $data['post_type'] ) ? sanitize_key( $data['post_type'] ) : '',
    … …  
    229231
    230232                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    231                 $wpdb->insert( self::items_table(), $row, array( '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s' ) );
     233                $wpdb->insert( self::items_table(), $row, array( '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s' ) );
    232234                return (int) $wpdb->insert_id;
    233235        }
    … …  
    324326
    325327        /**
    326          * Find a job's direct item for a post.
    327          *
    328          * @param int $job_id  Job ID.
    329          * @param int $post_id Post ID.
     328         * Find a job's direct item for a post or term.
     329         *
     330         * @param int    $job_id      Job ID.
     331         * @param int    $post_id     Post or term ID.
     332         * @param string $object_type post or term.
    330333         * @return object|null
    331334         */
    332         public static function find_item( $job_id, $post_id ) {
     335        public static function find_item( $job_id, $post_id, $object_type = 'post' ) {
    333336                global $wpdb;
    334337                $table = self::items_table();
    335338                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    336                 $item = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE job_id = %d AND post_id = %d AND kind = 'direct' LIMIT 1", $table, absint( $job_id ), absint( $post_id ) ) );
     339                $item = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE job_id = %d AND post_id = %d AND object_type = %s AND kind = 'direct' LIMIT 1", $table, absint( $job_id ), absint( $post_id ), 'term' === $object_type ? 'term' : 'post' ) );
    337340                return $item ? self::decode_item( $item ) : null;
    338341        }
    … …  
    419422
    420423        /**
    421          * Find in-job duplicates: same new slug, post type and parent among active direct items.
     424         * Find in-job duplicates: same new slug, post type, parent (and language with Polylang) among active direct items.
    422425         *
    423426         * @param int $job_id Job ID.
    424          * @return array<string, bool> Keys "post_type|parent_id|slug".
     427         * @return array<string, bool> Keys from duplicate_key().
    425428         */
    426429        public static function duplicate_keys( $job_id ) {
    427430                global $wpdb;
    428431                $table = self::items_table();
     432                // Terms are unique per taxonomy whatever their parent, so their parent is grouped as 0.
    429433                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    430                 $rows = $wpdb->get_results( $wpdb->prepare( "SELECT post_type, parent_id, requested_post_name FROM %i WHERE job_id = %d AND kind = 'direct' AND result NOT IN ('excluded','unchanged') GROUP BY post_type, parent_id, requested_post_name HAVING COUNT(*) > 1", $table, absint( $job_id ) ) );
     434                $rows = $wpdb->get_results( $wpdb->prepare( "SELECT object_type, post_type, CASE WHEN object_type = 'term' THEN 0 ELSE parent_id END AS parent_id, requested_post_name FROM %i WHERE job_id = %d AND kind = 'direct' AND result NOT IN ('excluded','unchanged') GROUP BY object_type, post_type, CASE WHEN object_type = 'term' THEN 0 ELSE parent_id END, requested_post_name HAVING COUNT(*) > 1", $table, absint( $job_id ) ) );
    431435                $keys = array();
     436
     437                if ( ! Polylang::is_active() ) {
     438                        foreach ( (array) $rows as $row ) {
     439                                $keys[ self::duplicate_key( self::key_type( $row->object_type, $row->post_type ), $row->parent_id, $row->requested_post_name ) ] = true;
     440                        }
     441                        return $keys;
     442                }
     443
     444                // With Polylang, records in different languages may share a slug: split each group by language.
     445                $counts = array();
    432446                foreach ( (array) $rows as $row ) {
    433                         $keys[ self::duplicate_key( $row->post_type, $row->parent_id, $row->requested_post_name ) ] = true;
     447                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     448                        if ( 'term' === $row->object_type ) {
     449                                // Term languages are not compared: WordPress keeps term slugs unique per taxonomy.
     450                                $keys[ self::duplicate_key( self::key_type( 'term', $row->post_type ), 0, $row->requested_post_name ) ] = true;
     451                                continue;
     452                        }
     453                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     454                        $ids       = array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( "SELECT post_id FROM %i WHERE job_id = %d AND kind = 'direct' AND object_type = 'post' AND result NOT IN ('excluded','unchanged') AND post_type = %s AND parent_id = %d AND requested_post_name = %s", $table, absint( $job_id ), $row->post_type, (int) $row->parent_id, $row->requested_post_name ) ) );
     455                        $languages = Polylang::languages_for( $ids );
     456                        foreach ( $ids as $id ) {
     457                                $key            = self::duplicate_key( $row->post_type, $row->parent_id, $row->requested_post_name, isset( $languages[ $id ] ) ? $languages[ $id ] : '' );
     458                                $counts[ $key ] = isset( $counts[ $key ] ) ? $counts[ $key ] + 1 : 1;
     459                        }
     460                }
     461                foreach ( $counts as $key => $count ) {
     462                        if ( $count > 1 ) {
     463                                $keys[ $key ] = true;
     464                        }
    434465                }
    435466                return $keys;
    … …  
    442473         * @param int    $parent_id Parent ID.
    443474         * @param string $slug      Sanitized slug.
     475         * @param string $language  Polylang language slug ('' without Polylang or without a language).
    444476         * @return string
    445477         */
    446         public static function duplicate_key( $post_type, $parent_id, $slug ) {
    447                 return $post_type . '|' . ( is_post_type_hierarchical( $post_type ) ? (int) $parent_id : 0 ) . '|' . $slug;
     478        public static function duplicate_key( $post_type, $parent_id, $slug, $language = '' ) {
     479                return self::duplicate_key_prefix( $post_type, $parent_id, $language ) . $slug;
     480        }
     481
     482        /**
     483         * Type part of a duplicate key: the post type, or "term:<taxonomy>".
     484         *
     485         * @param string $object_type post or term.
     486         * @param string $type        Post type or taxonomy.
     487         * @return string
     488         */
     489        public static function key_type( $object_type, $type ) {
     490                return 'term' === $object_type ? 'term:' . $type : $type;
     491        }
     492
     493        /**
     494         * Everything of the duplicate key before the slug (also used by the Slug Editor script).
     495         *
     496         * @param string $post_type Post type.
     497         * @param int    $parent_id Parent ID.
     498         * @param string $language  Polylang language slug or ''.
     499         * @return string
     500         */
     501        public static function duplicate_key_prefix( $post_type, $parent_id, $language = '' ) {
     502                $prefix = $post_type . '|' . ( is_post_type_hierarchical( $post_type ) ? (int) $parent_id : 0 ) . '|';
     503                return '' === $language ? $prefix : $prefix . 'lang:' . $language . '|';
    448504        }
    449505
  • slugh/trunk/src/Jobs/JobRunner.php

    r3795795 r3814912  
    99
    1010use SlugH\Integrations\CacheManager;
     11use SlugH\Integrations\Polylang;
    1112use SlugH\Redirects\Normalizer;
    1213use SlugH\Redirects\RedirectRepository;
    … …  
    1617use SlugH\Slugs\SlugUpdater;
    1718use SlugH\Slugs\SlugValidator;
     19use SlugH\Slugs\TermSlugs;
     20use SlugH\Support\PostTypes;
    1821use SlugH\Support\Settings;
    1922
    … …  
    8790         */
    8891        private static function validate_item( $item, array $duplicates ) {
    89                 $key        = JobRepository::duplicate_key( $item->post_type, $item->parent_id, $item->requested_post_name );
    90                 $validation = SlugValidator::validate(
    91                         $item->post_id,
    92                         $item->requested_post_name,
    93                         array(
    94                                 'expected_old_slug'  => $item->old_post_name,
    95                                 'expected_post_type' => $item->post_type,
    96                                 'in_job_duplicate'   => isset( $duplicates[ $key ] ),
    97                         )
    98                 );
     92                if ( self::is_term( $item ) ) {
     93                        $key        = JobRepository::duplicate_key( JobRepository::key_type( 'term', $item->post_type ), 0, $item->requested_post_name );
     94                        $validation = TermSlugs::validate(
     95                                $item->post_id,
     96                                $item->requested_post_name,
     97                                array(
     98                                        'expected_old_slug' => $item->old_post_name,
     99                                        'expected_taxonomy' => $item->post_type,
     100                                        'in_job_duplicate'  => isset( $duplicates[ $key ] ),
     101                                )
     102                        );
     103                } else {
     104                        $key        = JobRepository::duplicate_key( $item->post_type, $item->parent_id, $item->requested_post_name, Polylang::post_language( $item->post_id ) );
     105                        $validation = SlugValidator::validate(
     106                                $item->post_id,
     107                                $item->requested_post_name,
     108                                array(
     109                                        'expected_old_slug'  => $item->old_post_name,
     110                                        'expected_post_type' => $item->post_type,
     111                                        'in_job_duplicate'   => isset( $duplicates[ $key ] ),
     112                                )
     113                        );
     114                }
    99115
    100116                $state  = $validation['state'];
    … …  
    115131
    116132                return $validation;
     133        }
     134
     135        /**
     136         * Whether a job item is a taxonomy term.
     137         *
     138         * @param object $item Item.
     139         * @return bool
     140         */
     141        public static function is_term( $item ) {
     142                return isset( $item->object_type ) && 'term' === $item->object_type;
    117143        }
    118144
    … …  
    276302                $direct_ids = array();
    277303                foreach ( $included as $item ) {
    278                         $direct_ids[ $item->post_id ] = true;
     304                        if ( ! self::is_term( $item ) ) {
     305                                $direct_ids[ $item->post_id ] = true;
     306                        }
    279307                }
    280308
    281309                $descendant_count = 0;
    282310                foreach ( $included as $item ) {
     311                        if ( self::is_term( $item ) ) {
     312                                // Term snapshot: name, description, parent, taxonomy and term meta hashes. Terms have no descendant items:
     313                                // child terms still answer under the old path (spec section 26.5).
     314                                $term       = get_term( $item->post_id );
     315                                $components = TermSlugs::components( $item->post_id );
     316                                JobRepository::merge_item_message(
     317                                        $item,
     318                                        array(
     319                                                'snapshot' => array(
     320                                                        'post_status' => 'publish',
     321                                                        'url_status'  => 'publish',
     322                                                        'post_parent' => $term instanceof \WP_Term ? (int) $term->parent : 0,
     323                                                        'components'  => $components,
     324                                                ),
     325                                        ),
     326                                        array(
     327                                                'old_post_name' => $term instanceof \WP_Term ? $term->slug : $item->old_post_name,
     328                                                'old_permalink' => TermSlugs::link( $item->post_id ),
     329                                                'post_type'     => $term instanceof \WP_Term ? $term->taxonomy : $item->post_type,
     330                                                'parent_id'     => $term instanceof \WP_Term ? (int) $term->parent : 0,
     331                                                'hash_before'   => IntegrityChecker::combine( $components ),
     332                                                'sort_order'    => 0,
     333                                        )
     334                                );
     335                                continue;
     336                        }
    283337                        $post = get_post( $item->post_id );
    284338
    … …  
    290344                                        'snapshot' => array(
    291345                                                'post_status'   => $post->post_status,
     346                                                'url_status'    => PostTypes::url_status( $post ),
    292347                                                'post_parent'   => (int) $post->post_parent,
    293348                                                'post_modified' => $post->post_modified,
    … …  
    306361
    307362                        $validation = isset( $item->message['validation'] ) ? $item->message['validation'] : array();
    308                         if ( empty( $validation['url_changes'] ) || ! is_post_type_hierarchical( $post->post_type ) ) {
     363                        if ( empty( $validation['url_changes'] ) ) {
    309364                                continue;
    310365                        }
    311366
    312                         // Descendant snapshots; a descendant that is itself a direct item handles its own URL.
    313                         foreach ( DescendantPropagator::get_descendants( $post->ID ) as $descendant_id ) {
     367                        // Descendant snapshots (child records, then attachments under any of them);
     368                        // a descendant that is itself a direct item handles its own URL.
     369                        $descendants = is_post_type_hierarchical( $post->post_type ) ? DescendantPropagator::get_descendants( $post->ID ) : array();
     370                        $descendants = array_merge( $descendants, DescendantPropagator::get_attachments( $post->ID, $descendants ) );
     371                        foreach ( $descendants as $descendant_id ) {
    314372                                if ( isset( $direct_ids[ $descendant_id ] ) || self::has_descendant_item( $job_id, $descendant_id ) ) {
    315373                                        continue;
    … …  
    331389                                                'message'             => array(
    332390                                                        'parent_item' => $item->id,
    333                                                         'snapshot'    => array( 'post_status' => $descendant->post_status ),
     391                                                        'snapshot'    => array(
     392                                                                'post_status' => $descendant->post_status,
     393                                                                'url_status'  => PostTypes::url_status( $descendant ),
     394                                                        ),
    334395                                                ),
    335396                                        )
    … …  
    392453                $table = \SlugH\Database\Schema::get_table_name( 'slugh_job_items' );
    393454                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    394                 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 ) );
     455                return (bool) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM %i WHERE job_id = %d AND post_id = %d AND object_type = 'post' AND kind = 'descendant' LIMIT 1", $table, $job_id, $post_id ) );
    395456        }
    396457
    … …  
    520581         */
    521582        private static function process_direct( $job, $item ) {
    522                 $validation = SlugValidator::validate(
    523                         $item->post_id,
    524                         $item->requested_post_name,
    525                         array(
    526                                 'expected_old_slug'  => $item->old_post_name,
    527                                 'expected_post_type' => $item->post_type,
    528                         )
    529                 );
     583                $validation = self::is_term( $item )
     584                        ? TermSlugs::validate(
     585                                $item->post_id,
     586                                $item->requested_post_name,
     587                                array(
     588                                        'expected_old_slug' => $item->old_post_name,
     589                                        'expected_taxonomy' => $item->post_type,
     590                                )
     591                        )
     592                        : SlugValidator::validate(
     593                                $item->post_id,
     594                                $item->requested_post_name,
     595                                array(
     596                                        'expected_old_slug'  => $item->old_post_name,
     597                                        'expected_post_type' => $item->post_type,
     598                                )
     599                        );
    530600
    531601                if ( 'stale' === $validation['state'] ) {
    … …  
    562632                }
    563633
    564                 $post       = get_post( $item->post_id );
    565                 $old_status = $post->post_status;
     634                $is_term    = self::is_term( $item );
     635                $post       = $is_term ? null : get_post( $item->post_id );
     636                $old_status = $is_term ? 'publish' : PostTypes::url_status( $post );
    566637                $redirect   = array(
    567638                        'ids'       => array(),
    … …  
    581652                }
    582653
    583                 $update = SlugUpdater::update( $item->post_id, $item->requested_post_name, $job->id );
     654                $update = $is_term ? TermSlugs::update( $item->post_id, $item->requested_post_name, $job->id ) : SlugUpdater::update( $item->post_id, $item->requested_post_name, $job->id );
    584655                if ( is_wp_error( $update ) ) {
    585656                        return self::finish_item(
    … …  
    614685                        $notes['changed_fields'] = $update['changed_fields'];
    615686                        self::finish_item( $item, 'integrity_changed', $notes, $columns );
    616                         AuditLogger::log( 'integrity_changed', 'post', $item->post_id, null, array( 'fields' => $update['changed_fields'] ), $job->id );
     687                        AuditLogger::log( 'integrity_changed', $is_term ? 'term' : 'post', $item->post_id, null, array( 'fields' => $update['changed_fields'] ), $job->id );
    617688                        return 'integrity_changed';
    618689                }
    … …  
    630701                                        'origin'      => 'job',
    631702                                        'post_id'     => $item->post_id,
     703                                        'object_type' => $is_term ? 'term' : 'post',
    632704                                        'job_id'      => $job->id,
    633705                                        'on_conflict' => 'keep' === $resolution ? 'keep' : ( 'replace' === $resolution ? 'replace' : 'error' ),
    … …  
    641713                }
    642714
    643                 CacheManager::purge_urls( array( $item->old_permalink, $update['actual_permalink'] ), $item->post_id );
     715                CacheManager::purge_urls( array( $item->old_permalink, $update['actual_permalink'] ), $is_term ? 0 : $item->post_id );
    644716
    645717                AuditLogger::log(
    646718                        'slug_apply',
    647                         'post',
     719                        $is_term ? 'term' : 'post',
    648720                        $item->post_id,
    649721                        array(
    … …  
    702774                $public_statuses = Settings::get( 'redirect_private_posts', false ) ? array( 'publish', 'private' ) : array( 'publish' );
    703775
    704                 if ( Settings::MODE_SLUGH === $mode && in_array( $post->post_status, $public_statuses, true ) ) {
     776                if ( Settings::MODE_SLUGH === $mode && in_array( PostTypes::url_status( $post ), $public_statuses, true ) ) {
    705777                        $created = RedirectRepository::create(
    706778                                array(
    … …  
    802874                                continue;
    803875                        }
    804                         $status_before = isset( $item->message['snapshot']['post_status'] ) ? $item->message['snapshot']['post_status'] : 'publish';
     876                        $snapshot      = isset( $item->message['snapshot'] ) ? (array) $item->message['snapshot'] : array();
     877                        $status_before = isset( $snapshot['url_status'] ) ? $snapshot['url_status'] : ( isset( $snapshot['post_status'] ) ? $snapshot['post_status'] : 'publish' );
    805878                        if ( ! in_array( $status_before, array( 'publish', 'private' ), true ) ) {
    806879                                continue;
  • slugh/trunk/src/Jobs/RollbackManager.php

    r3795795 r3814912  
    88namespace SlugH\Jobs;
    99
     10use SlugH\Database\Schema;
    1011use SlugH\Integrations\CacheManager;
    1112use SlugH\Redirects\Normalizer;
    … …  
    1314use SlugH\Slugs\DescendantPropagator;
    1415use SlugH\Slugs\SlugUpdater;
     16use SlugH\Slugs\TermSlugs;
     17use SlugH\Support\PostTypes;
    1518use SlugH\Support\Settings;
    1619
    … …  
    149152                                'post_id'             => $item->post_id,
    150153                                'kind'                => $item->kind,
     154                                'object_type'         => isset( $item->object_type ) ? $item->object_type : 'post',
    151155                                'post_type'           => $item->post_type,
    152156                                'parent_id'           => $item->parent_id,
    … …  
    160164                                'message'             => array(
    161165                                        'target_item' => $item->id,
    162                                         'snapshot'    => isset( $item->message['snapshot'] ) ? array( 'post_status' => isset( $item->message['snapshot']['post_status'] ) ? $item->message['snapshot']['post_status'] : '' ) : array(),
     166                                        'snapshot'    => isset( $item->message['snapshot'] ) ? array_intersect_key( (array) $item->message['snapshot'], array_flip( array( 'post_status', 'url_status' ) ) ) : array(),
    163167                                ),
    164168                        )
    … …  
    177181                if ( ! $target_item ) {
    178182                        return JobRunner::finish_item( $item, 'failed', array( 'reason' => 'target_missing' ) );
     183                }
     184
     185                if ( JobRunner::is_term( $item ) ) {
     186                        return self::process_term( $job, $item, $target_item );
    179187                }
    180188
    … …  
    200208                $current_link = (string) get_permalink( $post );
    201209
    202                 // The record must still be exactly as the job left it.
    203                 if ( $post->post_name !== $item->old_post_name || Normalizer::normalize_path( $current_link ) !== Normalizer::normalize_path( $item->old_permalink ) ) {
     210                // The record must still be exactly as the job left it. When this rollback has already restored
     211                // an ancestor (a parent page, or the record an attachment belongs to), the URL moved with it,
     212                // so only the record's own slug is compared.
     213                $url_moved = self::ancestor_restored( $job->id, $post );
     214                if ( $post->post_name !== $item->old_post_name || ( ! $url_moved && Normalizer::normalize_path( $current_link ) !== Normalizer::normalize_path( $item->old_permalink ) ) ) {
    204215                        return JobRunner::finish_item(
    205216                                $item,
    … …  
    207218                                array(
    208219                                        'reason' => 'changed_since_job',
    209                                         'detail' => sprintf(
    210                                                 /* translators: 1: slug the job set, 2: current slug */
    211                                                 __( 'The slug changed after the job (job set "%1$s", now "%2$s").', 'slugh' ),
    212                                                 rawurldecode( $item->old_post_name ),
    213                                                 rawurldecode( $post->post_name )
    214                                         ),
     220                                        'detail' => $post->post_name !== $item->old_post_name
     221                                                ? sprintf(
     222                                                        /* translators: 1: slug the job set, 2: current slug */
     223                                                        __( 'The slug changed after the job (job set "%1$s", now "%2$s").', 'slugh' ),
     224                                                        rawurldecode( $item->old_post_name ),
     225                                                        rawurldecode( $post->post_name )
     226                                                )
     227                                                : sprintf(
     228                                                        /* translators: 1: URL after the job, 2: current URL */
     229                                                        __( 'The URL changed after the job, for example because a parent changed (job left "%1$s", now "%2$s").', 'slugh' ),
     230                                                        rawurldecode( $item->old_permalink ),
     231                                                        rawurldecode( $current_link )
     232                                                ),
    215233                                )
    216234                        );
    … …  
    261279
    262280                $redirect = self::undo_redirects( $job, $target_item );
    263                 $reverse  = self::reverse_redirect( $job, $item, $update['actual_permalink'], $post->post_status );
     281                $reverse  = self::reverse_redirect( $job, $item, $update['actual_permalink'], PostTypes::url_status( $post ) );
    264282                if ( $reverse ) {
    265283                        JobRunner::record_redirect( $redirect, $reverse );
    … …  
    302320
    303321                $redirect = self::undo_redirects( $job, $target_item );
    304                 $reverse  = self::reverse_redirect( $job, $item, $current_link, $post->post_status );
     322                $reverse  = self::reverse_redirect( $job, $item, $current_link, PostTypes::url_status( $post ) );
    305323                if ( $reverse ) {
    306324                        JobRunner::record_redirect( $redirect, $reverse );
    … …  
    383401
    384402        /**
     403         * Restore a term's slug (spec section 26.5).
     404         *
     405         * @param object $job         Rollback job.
     406         * @param object $item        Rollback item.
     407         * @param object $target_item Target item.
     408         * @return string Result.
     409         */
     410        private static function process_term( $job, $item, $target_item ) {
     411                clean_term_cache( (int) $item->post_id );
     412                $term = get_term( (int) $item->post_id );
     413                if ( ! $term instanceof \WP_Term ) {
     414                        return JobRunner::finish_item( $item, 'skipped', array( 'reason' => 'not_found' ) );
     415                }
     416
     417                $current_link = TermSlugs::link( $term );
     418                if ( $term->slug !== $item->old_post_name ) {
     419                        return JobRunner::finish_item(
     420                                $item,
     421                                'skipped',
     422                                array(
     423                                        'reason' => 'changed_since_job',
     424                                        'detail' => sprintf(
     425                                                /* translators: 1: slug the job set, 2: current slug */
     426                                                __( 'The slug changed after the job (job set "%1$s", now "%2$s").', 'slugh' ),
     427                                                rawurldecode( $item->old_post_name ),
     428                                                rawurldecode( $term->slug )
     429                                        ),
     430                                )
     431                        );
     432                }
     433
     434                $original = $item->requested_post_name;
     435                $taken    = get_term_by( 'slug', $original, $term->taxonomy );
     436                if ( $taken instanceof \WP_Term && (int) $taken->term_id !== (int) $term->term_id ) {
     437                        return JobRunner::finish_item(
     438                                $item,
     439                                'skipped',
     440                                array(
     441                                        'reason' => 'original_slug_taken',
     442                                        'detail' => __( 'Another term now uses the original slug.', 'slugh' ),
     443                                )
     444                        );
     445                }
     446
     447                $update = TermSlugs::update( $term->term_id, $original, $job->id );
     448                if ( is_wp_error( $update ) ) {
     449                        return JobRunner::finish_item(
     450                                $item,
     451                                'failed',
     452                                array(
     453                                        'reason' => $update->get_error_code(),
     454                                        'detail' => $update->get_error_message(),
     455                                )
     456                        );
     457                }
     458
     459                $columns = array(
     460                        'actual_post_name' => $update['actual_slug'],
     461                        'actual_permalink' => $update['actual_permalink'],
     462                        'hash_after'       => $update['hash_after'],
     463                        'hash_before'      => $update['hash_before'],
     464                );
     465                if ( ! empty( $update['changed_fields'] ) ) {
     466                        JobRunner::finish_item( $item, 'integrity_changed', array( 'changed_fields' => $update['changed_fields'] ), $columns );
     467                        return 'integrity_changed';
     468                }
     469
     470                $notes = array();
     471                if ( $update['actual_slug'] !== $original ) {
     472                        $notes['restore_mismatch'] = $update['actual_slug'];
     473                }
     474                if ( '' !== $current_link && Normalizer::normalize_path( $current_link ) !== Normalizer::normalize_path( $item->old_permalink ) ) {
     475                        $notes['url_moved'] = $current_link;
     476                }
     477
     478                $redirect = self::undo_redirects( $job, $target_item );
     479                $reverse  = self::reverse_redirect( $job, $item, $update['actual_permalink'], 'publish', 'term' );
     480                if ( $reverse ) {
     481                        JobRunner::record_redirect( $redirect, $reverse );
     482                }
     483
     484                CacheManager::purge_urls( array( $item->old_permalink, $update['actual_permalink'] ) );
     485                AuditLogger::log( 'rollback_item', 'term', $term->term_id, array( 'slug' => $item->old_post_name ), array( 'slug' => $update['actual_slug'] ), $job->id );
     486                JobRepository::merge_item_message( $target_item, array( 'rolled_back_by' => $job->id ) );
     487
     488                $notes['redirects']      = $redirect;
     489                $columns['redirect_ids'] = $redirect['ids'];
     490
     491                return JobRunner::finish_item( $item, 'applied', $notes, $columns );
     492        }
     493
     494        /**
     495         * Whether this rollback job has already restored one of the record's ancestors.
     496         *
     497         * @param int      $rollback_job_id Rollback job ID.
     498         * @param \WP_Post $post            Record.
     499         * @return bool
     500         */
     501        private static function ancestor_restored( $rollback_job_id, \WP_Post $post ) {
     502                global $wpdb;
     503                $ancestors = array_map( 'intval', get_post_ancestors( $post ) );
     504                if ( empty( $ancestors ) ) {
     505                        return false;
     506                }
     507                $table        = Schema::get_table_name( 'slugh_job_items' );
     508                $placeholders = implode( ',', array_fill( 0, count( $ancestors ), '%d' ) );
     509                // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     510                $found = $wpdb->get_var(
     511                        $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- Values are passed as one array.
     512                                "SELECT id FROM %i WHERE job_id = %d AND result = 'applied' AND object_type = 'post' AND post_id IN ({$placeholders}) LIMIT 1",
     513                                array_merge( array( $table, absint( $rollback_job_id ) ), $ancestors )
     514                        )
     515                );
     516                // phpcs:enable
     517                return null !== $found;
     518        }
     519
     520        /**
    385521         * Reverse redirect from the abandoned job URL to the restored URL (setting, on by default).
    386522         *
    … …  
    389525         * @param string $restored_url Restored permalink.
    390526         * @param string $post_status  Current status.
     527         * @param string $object_type  post or term.
    391528         * @return array|null create() result.
    392529         */
    393         private static function reverse_redirect( $job, $item, $restored_url, $post_status ) {
     530        private static function reverse_redirect( $job, $item, $restored_url, $post_status, $object_type = 'post' ) {
    394531                $public = Settings::get( 'redirect_private_posts', false ) ? array( 'publish', 'private' ) : array( 'publish' );
    395532
    … …  
    408545                                'origin'      => 'rollback',
    409546                                'post_id'     => $item->post_id,
     547                                'object_type' => $object_type,
    410548                                'job_id'      => $job->id,
    411549                                'on_conflict' => 'keep',
  • slugh/trunk/src/Plugin.php

    r3795795 r3814912  
    6060                // Front-end redirect engine on template_redirect at priority 1.
    6161                ( new Redirects\RedirectHandler() )->register();
     62                ( new Redirects\TermWatcher() )->register();
    6263
    6364                // WooCommerce integration (HPOS declaration and product integrity data).
    6465                ( new Integrations\WooCommerce() )->register();
     66
     67                if ( defined( 'WP_CLI' ) && WP_CLI ) {
     68                        Cli\Command::register();
     69                }
    6570
    6671                add_action( 'admin_init', array( $this, 'check_multisite_activation' ) );
  • slugh/trunk/src/Redirects/RedirectHandler.php

    r3795795 r3814912  
    7373                $source_hash    = Normalizer::compute_hash( $canonical_path );
    7474                $is_404         = is_404();
     75                // WordPress answers 200 with an empty feed for a term that no longer exists; treat it like a 404.
     76                $missing_feed = ! $is_404 && is_feed() && ( is_category() || is_tag() || is_tax() ) && ! ( get_queried_object() instanceof \WP_Term );
    7577
    7678                // Normal (non-404) requests only need the cached set of "always" hashes; no query.
    77                 if ( ! $is_404 && ! in_array( $source_hash, RedirectRepository::get_always_hashes(), true ) ) {
     79                if ( ! $is_404 && ! $missing_feed && ! in_array( $source_hash, RedirectRepository::get_always_hashes(), true ) ) {
    7880                        return;
    7981                }
    8082
    8183                $redirect = RedirectRepository::find_by_hash( $source_hash, $canonical_path );
     84                if ( $redirect && '404_only' === $redirect->match_mode && ! $is_404 ) {
     85                        $redirect = null;
     86                }
     87                $suffix = '';
     88                if ( ! $redirect && ( $is_404 || $missing_feed ) ) {
     89                        list( $redirect, $suffix ) = $this->find_term_archive_redirect( $canonical_path );
     90                }
    8291                if ( ! $redirect ) {
    83                         return;
    84                 }
    85 
    86                 if ( '404_only' === $redirect->match_mode && ! $is_404 ) {
    8792                        return;
    8893                }
    … …  
    112117                }
    113118
    114                 $destination_url = $this->build_destination_url( $redirect->destination, $redirect->destination_type, $request_uri );
     119                $destination = $redirect->destination;
     120                if ( '' !== $suffix ) {
     121                        // Same archive page or feed under the new term URL (spec section 26.5).
     122                        $destination = untrailingslashit( preg_replace( '/[?#].*$/s', '', $destination ) ) . '/' . $suffix . '/';
     123                }
     124                $destination_url = $this->build_destination_url( $destination, $redirect->destination_type, $request_uri );
    115125
    116126                if ( 'external' === $redirect->destination_type ) {
    … …  
    120130                }
    121131                exit;
     132        }
     133
     134        /**
     135         * For a 404 under an old term URL with /page/<n>/, /feed/ or /feed/<type>/ after it,
     136         * find the term redirect of the base URL.
     137         *
     138         * @param string $canonical_path Canonical requested path.
     139         * @return array{0: object|null, 1: string} Redirect (or null) and the suffix to carry over.
     140         */
     141        private function find_term_archive_redirect( $canonical_path ) {
     142                if ( ! preg_match( '#^(/.+?)/(page/[0-9]+|feed(?:/(?:feed|rdf|rss|rss2|atom))?)$#', $canonical_path, $matches ) ) {
     143                        return array( null, '' );
     144                }
     145                $base     = Normalizer::normalize_path( $matches[1] );
     146                $redirect = RedirectRepository::find_by_hash( Normalizer::compute_hash( $base ), $base );
     147                if ( ! $redirect || ! isset( $redirect->object_type ) || 'term' !== $redirect->object_type || 'internal' !== $redirect->destination_type ) {
     148                        return array( null, '' );
     149                }
     150                return array( $redirect, $matches[2] );
    122151        }
    123152
  • slugh/trunk/src/Redirects/RedirectRepository.php

    r3795795 r3814912  
    2424        const STATUS_CODES     = array( 301, 302, 307, 308, 410 );
    2525        const JOB_STATUS_CODES = array( 301, 302 );
    26         const ORIGINS          = array( 'job', 'descendant', 'manual', 'import', 'rollback' );
     26        const ORIGINS          = array( 'job', 'descendant', 'manual', 'import', 'rollback', 'term_edit' );
    2727        const MATCH_MODES      = array( '404_only', 'always' );
    2828
    … …  
    5454                        $row = $wpdb->get_row(
    5555                                $wpdb->prepare(
    56                                         'SELECT id, source_path, source_hash, destination, destination_type, status_code, match_mode, enabled
     56                                        'SELECT id, source_path, source_hash, destination, destination_type, status_code, match_mode, enabled, object_type
    5757                                        FROM %i
    5858                                        WHERE source_hash = %s AND enabled = 1
    … …  
    293293                        'match_mode'       => $match_mode,
    294294                        'post_id'          => $post_id,
     295                        'object_type'      => isset( $data['object_type'] ) && 'term' === $data['object_type'] ? 'term' : 'post',
    295296                        'job_id'           => $job_id,
    296297                        'origin'           => $origin,
    … …  
    298299                        'updated_at'       => $now,
    299300                );
    300                 $formats = array( '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%d', '%s' );
     301                $formats = array( '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%d', '%s', '%d', '%s', '%d', '%s' );
    301302
    302303                if ( $existing ) {
  • slugh/trunk/src/Rest/DraftsController.php

    r3795795 r3814912  
    88namespace SlugH\Rest;
    99
     10use SlugH\Integrations\Polylang;
    1011use SlugH\Jobs\DraftManager;
    1112use SlugH\Jobs\JobRepository;
    … …  
    6465         */
    6566        private static function item_payload( $item ) {
     67                $is_term = isset( $item->object_type ) && 'term' === $item->object_type;
    6668                return array(
    67                         'post_id'   => $item->post_id,
    68                         'post_type' => $item->post_type,
    69                         'parent_id' => (int) $item->parent_id,
    70                         'old_slug'  => rawurldecode( $item->old_post_name ),
    71                         'new_slug'  => rawurldecode( $item->requested_post_name ),
    72                         'key'       => JobRepository::duplicate_key( $item->post_type, $item->parent_id, $item->requested_post_name ),
     69                        'post_id'     => $item->post_id,
     70                        'object_type' => $is_term ? 'term' : 'post',
     71                        'post_type'   => $item->post_type,
     72                        'parent_id'   => (int) $item->parent_id,
     73                        'old_slug'    => rawurldecode( $item->old_post_name ),
     74                        'new_slug'    => rawurldecode( $item->requested_post_name ),
     75                        'key'         => $is_term
     76                                ? JobRepository::duplicate_key( JobRepository::key_type( 'term', $item->post_type ), 0, $item->requested_post_name )
     77                                : JobRepository::duplicate_key( $item->post_type, $item->parent_id, $item->requested_post_name, Polylang::post_language( $item->post_id ) ),
    7378                );
    7479        }
    … …  
    8792                foreach ( array_slice( $items, 0, 500 ) as $entry ) {
    8893                        $post_id = isset( $entry['post_id'] ) ? absint( $entry['post_id'] ) : 0;
     94                        $type    = isset( $entry['object_type'] ) && 'term' === $entry['object_type'] ? 'term' : 'post';
    8995                        $slug    = isset( $entry['new_slug'] ) ? Sanitizer::slug_input( $entry['new_slug'] ) : '';
    90                         $res     = DraftManager::upsert_item( $job_id, $post_id, $slug );
    91                         $item    = JobRepository::find_item( $job_id, $post_id );
     96                        $res     = 'term' === $type ? DraftManager::upsert_term_item( $job_id, $post_id, $slug ) : DraftManager::upsert_item( $job_id, $post_id, $slug );
     97                        $item    = JobRepository::find_item( $job_id, $post_id, $type );
    9298
    9399                        $out[] = array(
    94                                 'post_id' => $post_id,
    95                                 'status'  => $res['status'],
    96                                 'message' => isset( $res['message'] ) ? $res['message'] : '',
    97                                 'item'    => $item ? self::item_payload( $item ) : null,
     100                                'post_id'     => $post_id,
     101                                'object_type' => $type,
     102                                'status'      => $res['status'],
     103                                'message'     => isset( $res['message'] ) ? $res['message'] : '',
     104                                'item'        => $item ? self::item_payload( $item ) : null,
    98105                        );
    99106                }
    … …  
    115122        public function remove_item( \WP_REST_Request $request ) {
    116123                $job_id = DraftManager::get_editor_draft( false );
    117                 return $this->respond( array( 'removed' => $job_id && DraftManager::remove_item( $job_id, absint( $request['post_id'] ) ) ) );
     124                $type   = 'term' === $request->get_param( 'object_type' ) ? 'term' : 'post';
     125                return $this->respond( array( 'removed' => $job_id && DraftManager::remove_item( $job_id, absint( $request['post_id'] ), $type ) ) );
    118126        }
    119127
  • slugh/trunk/src/Scan/Scanner.php

    r3795795 r3814912  
    99
    1010use SlugH\Database\Schema;
     11use SlugH\Integrations\Polylang;
    1112use SlugH\Jobs\AuditLogger;
    1213use SlugH\Jobs\JobRepository;
    1314use SlugH\Redirects\Normalizer;
     15use SlugH\Slugs\TermSlugs;
    1416use SlugH\Support\PostTypes;
    1517use SlugH\Support\Settings;
     18use SlugH\Support\Taxonomies;
    1619
    1720defined( 'ABSPATH' ) || exit;
    … …  
    2932         * @param array $post_types Post types.
    3033         * @param array $statuses   Statuses.
     34         * @param array $taxonomies Taxonomies whose terms are scanned after the posts (null: the enabled ones).
    3135         * @return int Scan ID.
    3236         */
    33         public static function start( $post_types, $statuses ) {
    34                 $types    = PostTypes::filter_types( $post_types );
    35                 $statuses = PostTypes::filter_statuses( $statuses );
     37        public static function start( $post_types, $statuses, $taxonomies = null ) {
     38                $types      = PostTypes::filter_types( $post_types );
     39                $statuses   = PostTypes::filter_statuses( $statuses );
     40                $taxonomies = null === $taxonomies ? Taxonomies::get_enabled() : Taxonomies::filter( $taxonomies );
    3641
    3742                $scan_id = JobRepository::create(
    … …  
    4146                                'post_types' => $types,
    4247                                'statuses'   => $statuses,
     48                                'taxonomies' => array_values( $taxonomies ),
    4349                                'last_id'    => 0,
    4450                        )
    … …  
    5359                                'post_types' => $types,
    5460                                'statuses'   => $statuses,
     61                                'taxonomies' => array_values( $taxonomies ),
    5562                        ),
    5663                        $scan_id
    … …  
    7784                }
    7885
     86                if ( isset( $job->settings['phase'] ) && 'terms' === $job->settings['phase'] ) {
     87                        $result = self::run_term_batch( $job );
     88                        JobRepository::release_lock( $scan_id );
     89                        return $result;
     90                }
     91
    7992                $types      = (array) $job->settings['post_types'];
    80                 $statuses   = (array) $job->settings['statuses'];
     93                $statuses   = PostTypes::query_statuses( $types, (array) $job->settings['statuses'] );
    8194                $last_id    = isset( $job->settings['last_id'] ) ? (int) $job->settings['last_id'] : 0;
    8295                $batch_size = (int) Settings::get( 'scan_batch_size', 500 );
    … …  
    99112                // phpcs:enable
    100113
    101                 $table       = Schema::get_table_name( 'slugh_scan_items' );
    102                 $now         = current_time( 'mysql', true );
    103                 $pretty      = (bool) get_option( 'permalink_structure' );
    104                 $front_page  = (int) get_option( 'page_on_front' );
     114                $table      = Schema::get_table_name( 'slugh_scan_items' );
     115                $now        = current_time( 'mysql', true );
     116                $pretty     = (bool) get_option( 'permalink_structure' );
     117                $front_page = 'page' === get_option( 'show_on_front' ) ? (int) get_option( 'page_on_front' ) : 0;
     118                // Polylang serves each translation of the front page at its language home (for example /en/).
     119                $front_pages = array_unique( array_filter( array_merge( array( $front_page ), Polylang::front_page_ids() ) ) );
     120                $by_language = Polylang::is_active();
    105121                $processed   = 0;
    106122                $posts       = array();
    … …  
    129145                        $perm_hash = '';
    130146
    131                         if ( 'publish' === $post->post_status ) {
     147                        // Attachments count as published when their parent is; with attachment pages off they have no page to check.
     148                        if ( 'publish' === PostTypes::url_status( $post ) ) {
    132149                                $perm_hash = Normalizer::compute_hash( Normalizer::normalize_path( $permalink ) );
    133150
    134                                 if ( $pretty && $post->ID !== $front_page && DetectorRegistry::has_permalink_problem( $post, $permalink ) ) {
     151                                if ( $pretty && ! in_array( (int) $post->ID, $front_pages, true ) && DetectorRegistry::has_permalink_problem( $post, $permalink ) ) {
    135152                                        $flags |= Flags::PERMALINK_ISSUE;
    136153                                }
    … …  
    138155                                if ( '' !== $post->post_name ) {
    139156                                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    140                                         $duplicate = $wpdb->get_var(
     157                                        $duplicates = $wpdb->get_col(
    141158                                                $wpdb->prepare(
    142                                                         "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",
     159                                                        "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 50",
    143160                                                        $post->post_type,
    144161                                                        $post->post_parent,
    … …  
    147164                                                )
    148165                                        );
    149                                         if ( $duplicate ) {
     166                                        if ( $duplicates && $by_language ) {
     167                                                // Only records of the same language share a URL (Polylang Pro can share slugs across languages).
     168                                                $language   = Polylang::post_language( $post->ID );
     169                                                $duplicates = array_filter(
     170                                                        $duplicates,
     171                                                        function ( $id ) use ( $language ) {
     172                                                                return Polylang::post_language( (int) $id ) === $language;
     173                                                        }
     174                                                );
     175                                        }
     176                                        if ( $duplicates ) {
    150177                                                $flags |= Flags::DUPLICATE;
    151178                                        }
    … …  
    188215                );
    189216
    190                 if ( $done ) {
     217                if ( $done && ! empty( $job->settings['taxonomies'] ) ) {
     218                        // Posts are done; the next batches read the terms of the enabled taxonomies.
     219                        $job = JobRepository::get( $scan_id );
     220                        JobRepository::update(
     221                                $scan_id,
     222                                array(
     223                                        'settings' => array_merge(
     224                                                $job->settings,
     225                                                array(
     226                                                        'phase'        => 'terms',
     227                                                        'term_last_id' => 0,
     228                                                )
     229                                        ),
     230                                )
     231                        );
     232                        $done = false;
     233                } elseif ( $done ) {
    191234                        self::finish( $scan_id );
    192235                }
    … …  
    196239                return array(
    197240                        'scan_id'   => $scan_id,
     241                        'processed' => $processed,
     242                        'scanned'   => $scanned,
     243                        'last_id'   => $last_id,
     244                        'done'      => $done,
     245                );
     246        }
     247
     248        /**
     249         * One batch of terms (spec section 26.5): the slug detectors, the archive URL hash.
     250         *
     251         * @param object $job Scan job.
     252         * @return array Same keys as run_batch().
     253         */
     254        private static function run_term_batch( $job ) {
     255                global $wpdb;
     256
     257                $taxonomies = (array) $job->settings['taxonomies'];
     258                $last_id    = isset( $job->settings['term_last_id'] ) ? (int) $job->settings['term_last_id'] : 0;
     259                $scanned    = isset( $job->settings['scanned'] ) ? (int) $job->settings['scanned'] : 0;
     260                $batch_size = (int) Settings::get( 'scan_batch_size', 500 );
     261                $tax_in     = implode( ',', array_fill( 0, count( $taxonomies ), '%s' ) );
     262
     263                // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     264                $rows = $wpdb->get_results(
     265                        $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- Values are passed as one array.
     266                                "SELECT t.term_id, t.slug, tt.taxonomy FROM {$wpdb->terms} t
     267                                JOIN {$wpdb->term_taxonomy} tt ON tt.term_id = t.term_id
     268                                WHERE t.term_id > %d AND tt.taxonomy IN ({$tax_in})
     269                                ORDER BY t.term_id ASC
     270                                LIMIT %d",
     271                                array_merge( array( $last_id ), $taxonomies, array( $batch_size ) )
     272                        )
     273                );
     274                // phpcs:enable
     275
     276                $table     = Schema::get_table_name( 'slugh_scan_items' );
     277                $now       = current_time( 'mysql', true );
     278                $processed = 0;
     279                foreach ( (array) $rows as $row ) {
     280                        $last_id = max( $last_id, (int) $row->term_id );
     281                        ++$processed;
     282                        if ( ! current_user_can( 'edit_term', (int) $row->term_id ) ) {
     283                                continue;
     284                        }
     285                        $analysis = DetectorRegistry::analyze(
     286                                (object) array(
     287                                        'post_name'   => $row->slug,
     288                                        'post_status' => 'publish',
     289                                )
     290                        );
     291                        $link     = TermSlugs::link( (int) $row->term_id );
     292                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     293                        $wpdb->replace(
     294                                $table,
     295                                array(
     296                                        'scan_id'        => $job->id,
     297                                        'post_id'        => (int) $row->term_id,
     298                                        'object_type'    => 'term',
     299                                        'post_type'      => $row->taxonomy,
     300                                        'post_status'    => 'publish',
     301                                        'decoded_slug'   => mb_substr( $analysis['decoded_slug'], 0, 500 ),
     302                                        'flags'          => $analysis['flags'],
     303                                        'scripts'        => $analysis['scripts'],
     304                                        'permalink_hash' => '' === $link ? '' : Normalizer::compute_hash( Normalizer::normalize_path( $link ) ),
     305                                        'scanned_at'     => $now,
     306                                ),
     307                                array( '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s' )
     308                        );
     309                        ++$scanned;
     310                }
     311
     312                $done = count( (array) $rows ) < $batch_size;
     313                JobRepository::update(
     314                        $job->id,
     315                        array(
     316                                'settings' => array_merge(
     317                                        $job->settings,
     318                                        array(
     319                                                'term_last_id' => $last_id,
     320                                                'scanned'      => $scanned,
     321                                        )
     322                                ),
     323                        )
     324                );
     325                if ( $done ) {
     326                        self::finish( $job->id );
     327                }
     328
     329                return array(
     330                        'scan_id'   => (int) $job->id,
    198331                        'processed' => $processed,
    199332                        'scanned'   => $scanned,
    … …  
    303436         *
    304437         * @param int   $scan_id Scan ID.
    305          * @param array $args    post_type, post_status, flags (int[] all must match), search, modified_from, modified_to, orderby, order, per_page, page.
     438         * @param array $args    post_type, post_status, flags (int[] all must match), issues_only, language (Polylang slug), search, modified_from, modified_to, orderby, order, per_page, page.
    306439         * @return array{items: array, total: int}
    307440         */
    … …  
    318451                        $where[] = 's.post_type = %s';
    319452                        $binds[] = sanitize_key( $args['post_type'] );
     453                }
     454                if ( ! empty( $args['object_type'] ) && in_array( $args['object_type'], array( 'post', 'term' ), true ) ) {
     455                        $where[] = 's.object_type = %s';
     456                        $binds[] = $args['object_type'];
    320457                }
    321458                if ( ! empty( $args['post_status'] ) ) {
    … …  
    337474                        $where[] = 's.flags != 0';
    338475                }
     476                if ( ! empty( $args['language'] ) ) {
     477                        $condition = Polylang::language_condition( 's.post_id', sanitize_key( $args['language'] ) );
     478                        // An unknown language matches nothing rather than everything. Term languages are not filtered.
     479                        $where[] = $condition ? "s.object_type = 'post' AND " . $condition[0] : '1 = 0';
     480                        if ( $condition ) {
     481                                $binds[] = $condition[1];
     482                        }
     483                }
    339484                if ( isset( $args['search'] ) && '' !== $args['search'] ) {
    340485                        $like    = '%' . $wpdb->esc_like( (string) $args['search'] ) . '%';
    341                         $where[] = '(p.post_title LIKE %s OR s.decoded_slug LIKE %s)';
     486                        $where[] = '(p.post_title LIKE %s OR tm.name LIKE %s OR s.decoded_slug LIKE %s)';
     487                        $binds[] = $like;
    342488                        $binds[] = $like;
    343489                        $binds[] = $like;
    … …  
    362508                $order       = isset( $args['order'] ) && 'desc' === strtolower( $args['order'] ) ? 'DESC' : 'ASC';
    363509                $where_sql   = implode( ' AND ', $where );
    364                 $from        = "%i s LEFT JOIN {$wpdb->posts} p ON p.ID = s.post_id";
     510                $from        = "%i s LEFT JOIN {$wpdb->posts} p ON p.ID = s.post_id AND s.object_type = 'post' LEFT JOIN {$wpdb->terms} tm ON tm.term_id = s.post_id AND s.object_type = 'term'";
    365511                $binds       = array_merge( array( $table ), $binds );
    366512
    … …  
    371517                $items = $wpdb->get_results(
    372518                        $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- Values are passed as one array.
    373                                 "SELECT s.*, p.post_title, p.post_name AS current_post_name, p.post_modified, p.post_modified_gmt
     519                                "SELECT s.*, COALESCE( p.post_title, tm.name ) AS post_title, COALESCE( p.post_name, tm.slug ) AS current_post_name, p.post_modified, p.post_modified_gmt
    374520                                FROM {$from} WHERE {$where_sql} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d",
    375521                                array_merge( $binds, array( $per_page, ( $page - 1 ) * $per_page ) )
  • slugh/trunk/src/Slugs/DescendantPropagator.php

    r3795795 r3814912  
    77
    88namespace SlugH\Slugs;
     9
     10use SlugH\Support\PostTypes;
    911
    1012defined( 'ABSPATH' ) || exit;
    … …  
    5759
    5860        /**
     61         * Attachments whose attachment-page URL lives under a record or its hierarchical descendants.
     62         *
     63         * Empty when attachment pages are off (their URLs redirect to the file) or for an attachment itself.
     64         *
     65         * @param int   $post_id        Record ID.
     66         * @param int[] $descendant_ids Its hierarchical descendants (from get_descendants()).
     67         * @return int[]
     68         */
     69        public static function get_attachments( $post_id, array $descendant_ids = array() ) {
     70                global $wpdb;
     71
     72                $post = get_post( $post_id );
     73                if ( ! $post || 'attachment' === $post->post_type || ! PostTypes::attachment_pages_enabled() ) {
     74                        return array();
     75                }
     76                $parents      = array_merge( array( (int) $post->ID ), array_map( 'intval', $descendant_ids ) );
     77                $placeholders = implode( ',', array_fill( 0, count( $parents ), '%d' ) );
     78                // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     79                $ids = $wpdb->get_col(
     80                        $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- Values are passed as one array.
     81                                "SELECT ID FROM {$wpdb->posts} WHERE post_parent IN ({$placeholders}) AND post_type = 'attachment' AND post_status = 'inherit' ORDER BY ID ASC",
     82                                $parents
     83                        )
     84                );
     85                // phpcs:enable
     86                return array_map( 'intval', (array) $ids );
     87        }
     88
     89        /**
    5990         * Depth of a record in its hierarchy (0 for top level). Used to process parents first.
    6091         *
  • slugh/trunk/src/Slugs/RulesSuggester.php

    r3795795 r3814912  
    3737        public static function instance() {
    3838                /**
    39                  * Filter the slug suggester (v2 transliteration plugs in here).
     39                 * Filter the slug suggester. The default is TransliterationSuggester when the
     40                 * "transliteration" setting is on, otherwise these rules.
    4041                 *
    4142                 * @param SlugSuggester $suggester Suggester.
    4243                 */
    43                 $suggester = apply_filters( 'slugh_slug_suggester', new self() );
    44                 return $suggester instanceof SlugSuggester ? $suggester : new self();
     44                $default   = \SlugH\Support\Settings::get( 'transliteration', false ) ? new TransliterationSuggester() : new self();
     45                $suggester = apply_filters( 'slugh_slug_suggester', $default );
     46                return $suggester instanceof SlugSuggester ? $suggester : $default;
    4547        }
    4648}
  • slugh/trunk/src/Slugs/SlugSuggester.php

    r3795795 r3814912  
    1111
    1212/**
    13  * Produces preview-only slug suggestions. Rules-based cleanup is the v1 implementation;
    14  * transliteration plugs in here in v2 (spec sections 14 and 20).
     13 * Produces preview-only slug suggestions: RulesSuggester (cleanup) and
     14 * TransliterationSuggester (spec section 26.2).
    1515 */
    1616interface SlugSuggester {
    … …  
    1919         * Suggest a slug. Suggestions are never applied automatically.
    2020         *
    21          * @param string   $decoded_slug Current decoded slug.
    22          * @param \WP_Post $post         Post the slug belongs to.
     21         * @param string            $decoded_slug Current decoded slug.
     22         * @param \WP_Post|\WP_Term $post Record the slug belongs to: a post, or a term (from 2.0.0).
    2323         * @return string Suggested decoded slug, or the input unchanged when there is nothing to suggest.
    2424         */
  • slugh/trunk/src/Slugs/SlugValidator.php

    r3795795 r3814912  
    88namespace SlugH\Slugs;
    99
     10use SlugH\Integrations\Polylang;
    1011use SlugH\Redirects\LoopDetector;
    1112use SlugH\Redirects\Normalizer;
    … …  
    8586                        'creates_redirect'    => false,
    8687                        'descendants'         => 0,
     88                        'attachments'         => 0,
    8789                        'descendant_samples'  => array(),
    8890                        'conflicts'           => array(),
    … …  
    250252
    251253                $public_statuses            = Settings::get( 'redirect_private_posts', false ) ? array( 'publish', 'private' ) : array( 'publish' );
    252                 $result['creates_redirect'] = $result['url_changes'] && in_array( $post->post_status, $public_statuses, true ) && Settings::slugh_owns_redirects();
    253 
    254                 if ( $result['url_changes'] && ! in_array( $post->post_status, $public_statuses, true ) ) {
     254                $url_status                 = PostTypes::url_status( $post );
     255                $result['creates_redirect'] = $result['url_changes'] && in_array( $url_status, $public_statuses, true ) && Settings::slugh_owns_redirects();
     256
     257                if ( $result['url_changes'] && 'no_page' === $url_status ) {
     258                        $result = self::add( $result, 'info', 'attachment_pages_off', __( 'Attachment pages are turned off in WordPress, so the attachment URL redirects to the file. slugH creates no redirect; the old attachment URL will return 404.', 'slugh' ) );
     259                } elseif ( $result['url_changes'] && ! in_array( $url_status, $public_statuses, true ) ) {
    255260                        $result = self::add( $result, 'info', 'no_redirect_status', __( 'No redirect will be created because this record has no public URL yet.', 'slugh' ) );
    256261                }
    … …  
    277282                }
    278283
     284                $descendants = $result['url_changes'] && is_post_type_hierarchical( $post->post_type ) ? DescendantPropagator::get_descendants( $post->ID ) : array();
     285                $attachments = $result['url_changes'] ? DescendantPropagator::get_attachments( $post->ID, $descendants ) : array();
     286                if ( ! empty( $attachments ) ) {
     287                        $result['attachments'] = count( $attachments );
     288                        $result                = self::add(
     289                                $result,
     290                                'info',
     291                                'attachments',
     292                                sprintf(
     293                                        /* translators: %d: number of attachments */
     294                                        _n( '%d attachment page URL will change and get its own redirect.', '%d attachment page URLs will change and get their own redirects.', count( $attachments ), 'slugh' ),
     295                                        count( $attachments )
     296                                )
     297                        );
     298                }
     299
    279300                if ( $result['url_changes'] && is_post_type_hierarchical( $post->post_type ) ) {
    280                         $descendants = DescendantPropagator::get_descendants( $post->ID );
    281301                        if ( ! empty( $descendants ) ) {
    282302                                $result['descendants']        = count( $descendants );
    … …  
    344364                $others = $wpdb->get_col(
    345365                        $wpdb->prepare(
    346                                 "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",
     366                                "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') ) OR ( %d = 1 AND post_type = 'attachment' AND post_status = 'inherit' ) ) LIMIT 20",
    347367                                $slug,
    348                                 $post->ID
     368                                $post->ID,
     369                                PostTypes::attachment_pages_enabled() ? 1 : 0
    349370                        )
    350371                );
    … …  
    401422         * @return array
    402423         */
    403         private static function check_redirect_conflicts( array $result ) {
     424        public static function check_redirect_conflicts( array $result ) {
    404425                $at_new = RedirectRepository::find_by_source( $result['new_path'] );
    405426                if ( $at_new && (int) $at_new->enabled ) {
    … …  
    484505                if ( is_post_type_hierarchical( $post->post_type ) ) {
    485506                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    486                         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 ) );
    487                 }
    488                 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    489                 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 ) );
     507                        $ids = $wpdb->get_col( $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 50", $slug, $post->post_type, $post->post_parent, $post->ID ) );
     508                } else {
     509                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     510                        $ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_name = %s AND post_type = %s AND post_status = 'publish' AND ID != %d LIMIT 50", $slug, $post->post_type, $post->ID ) );
     511                }
     512                $ids = array_map( 'intval', (array) $ids );
     513                if ( $ids && Polylang::is_active() ) {
     514                        // Only a record of the same language would take the URL (Polylang Pro can share slugs).
     515                        $language  = Polylang::post_language( $post->ID );
     516                        $languages = Polylang::languages_for( $ids );
     517                        $ids       = array_values(
     518                                array_filter(
     519                                        $ids,
     520                                        function ( $id ) use ( $language, $languages ) {
     521                                                return ( isset( $languages[ $id ] ) ? $languages[ $id ] : '' ) === $language;
     522                                        }
     523                                )
     524                        );
     525                }
     526                return $ids ? $ids[0] : 0;
    490527        }
    491528
    … …  
    538575         * @return array
    539576         */
    540         private static function add( array $result, $level, $code, $text, $needs_confirmation = false ) {
     577        public static function add( array $result, $level, $code, $text, $needs_confirmation = false ) {
    541578                $result['messages'][] = array(
    542579                        'level' => $level,
    … …  
    573610         * @return array
    574611         */
    575         private static function finish( array $result ) {
     612        public static function finish( array $result ) {
    576613                $result['is_valid'] = ! in_array( $result['state'], array( self::STATE_ERROR, self::STATE_STALE ), true );
    577614                return $result;
  • slugh/trunk/src/Support/PostTypes.php

    r3795795 r3814912  
    2020
    2121        /**
    22          * Internal types never handled by v1.
     22         * Internal types never handled. Attachments are handled from 2.0.0 (spec section 26.4), opt-in.
    2323         *
    2424         * @var string[]
    2525         */
    2626        const EXCLUDED_TYPES = array(
    27                 'attachment',
    2827                'revision',
    2928                'nav_menu_item',
    … …  
    9695
    9796        /**
     97         * Statuses to query for a set of post types: attachments always have "inherit".
     98         *
     99         * @param string[] $types    Post types.
     100         * @param string[] $statuses Selected statuses.
     101         * @return string[]
     102         */
     103        public static function query_statuses( array $types, array $statuses ) {
     104                if ( in_array( 'attachment', $types, true ) && ! in_array( 'inherit', $statuses, true ) ) {
     105                        $statuses[] = 'inherit';
     106                }
     107                return array_values( $statuses );
     108        }
     109
     110        /**
     111         * Whether WordPress shows attachment pages (option added in WordPress 6.4; before that they always exist).
     112         *
     113         * @return bool
     114         */
     115        public static function attachment_pages_enabled() {
     116                return (bool) (int) get_option( 'wp_attachment_pages_enabled', 1 );
     117        }
     118
     119        /**
     120         * Status that decides whether a record's URL is public and gets redirects.
     121         *
     122         * Attachments use their parent's status (unattached: publish), or "no_page"
     123         * when WordPress sends attachment pages to the file.
     124         *
     125         * @param \WP_Post $post Post.
     126         * @return string
     127         */
     128        public static function url_status( \WP_Post $post ) {
     129                if ( 'attachment' !== $post->post_type ) {
     130                        return $post->post_status;
     131                }
     132                if ( ! self::attachment_pages_enabled() ) {
     133                        return 'no_page';
     134                }
     135                if ( 'inherit' !== $post->post_status ) {
     136                        return $post->post_status;
     137                }
     138                $parent = $post->post_parent ? get_post( $post->post_parent ) : null;
     139                return $parent ? $parent->post_status : 'publish';
     140        }
     141
     142        /**
    98143         * Restrict requested post types to the available set.
    99144         *
  • slugh/trunk/src/Support/Settings.php

    r3795795 r3814912  
    3030                        'supported_post_types'        => array( 'post', 'page' ),
    3131                        'supported_post_statuses'     => array( 'publish', 'future', 'draft', 'pending', 'private' ),
     32                        'supported_taxonomies'        => array( 'category', 'post_tag' ),
     33                        'term_edit_redirects'         => true,
    3234                        'redirect_ownership_mode'     => self::MODE_SLUGH,
    3335                        'redirect_private_posts'      => false,
    … …  
    3739                        'trial_mode'                  => false,
    3840                        'allow_external_destinations' => false,
     41                        'transliteration'             => false,
    3942                        'integrity_excluded_meta'     => array(),
    4043                        'scan_batch_size'             => 500,
    … …  
    104107
    105108                $clean['supported_post_types']    = array_map( 'sanitize_key', $clean['supported_post_types'] );
     109                $clean['supported_taxonomies']    = array_map( 'sanitize_key', $clean['supported_taxonomies'] );
    106110                $clean['supported_post_statuses'] = array_values( array_intersect( array_map( 'sanitize_key', $clean['supported_post_statuses'] ), PostTypes::SUPPORTED_STATUSES ) );
    107111                $clean['scan_batch_size']         = min( 2000, max( 50, $clean['scan_batch_size'] ) );
Note: See TracChangeset for help on using the changeset viewer.