Plugin Directory

Changeset 3814937


Ignore:
Timestamp:
11/21/2026 07:44:45 AM (9 days ago)
Author:
nazim848
Message:

Release Rapid Media Reclaim 1.1.0

Location:
rapid-media-reclaim
Files:
139 added
52 edited
1 copied

Legend:

Unmodified
Added
Removed
  • rapid-media-reclaim/tags/1.1.0/assets/css/app.css

    r3794616 r3814937  
    25882588        }
    25892589}
     2590
     2591/* Tool actions stay readable inside the existing accessible modal. */
     2592.smc-tools__actions { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; margin: 16px 0; }
     2593.smc-tools__actions .smc-btn { white-space: normal; height: auto; min-height: 40px; text-align: center; }
     2594.smc-dialog__body pre { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 280px; overflow: auto; }
     2595@media (max-width: 540px) { .smc-tools__actions { grid-template-columns: minmax(0, 1fr); } }
     2596
     2597.smc-tools__output { min-width: 0; overflow-wrap: anywhere; }
     2598
     2599/* Backup recovery keeps its confirmation and conflicts separate from discovery. */
     2600.smc-recovery { margin-top: 24px; padding-top: 20px; border-top: 1px solid var(--smc-border, #dcdcde); }
     2601.smc-recovery input[type="file"] { display: block; max-width: 100%; margin-bottom: 12px; }
     2602.smc-recovery__preview { max-height: 50vh; overflow: auto; overflow-wrap: anywhere; }
     2603.smc-recovery__preview li { margin-bottom: 12px; }
     2604.smc-recovery__preview li p { margin: 4px 0; }
     2605.smc-recovery__conflicts { color: #8a2424; }
     2606
     2607.smc-savings__metrics { display: grid; grid-template-columns: repeat(auto-fit,minmax(150px,1fr)); gap: 16px; margin: 16px 0; }
     2608.smc-savings__metrics dt { color: var(--smc-muted); font-size: 12px; }
     2609.smc-savings__metrics dd { font-size: 22px; font-weight: 600; margin: 8px 0 0; overflow-wrap: anywhere; }
     2610.smc-savings__history { max-height: 260px; overflow: auto; font-size: 12px; }
     2611
     2612/* Keep live audit checks separate from their saved ownership hints. */
     2613.smc-dialog__body .smc-audit-result { padding-block: 12px; border-bottom: 1px solid var(--smc-border-soft, #e8e8ea); overflow-wrap: anywhere; }
     2614.smc-dialog__body .smc-audit-result > .smc-btn { display: block; margin-block: 8px; max-width: 100%; white-space: normal; height: auto; min-height: 32px; }
     2615.smc-dialog__body .smc-audit-result p { margin-block: 6px; }
  • rapid-media-reclaim/tags/1.1.0/assets/js/app.js

    r3794616 r3814937  
    2020        const PER_PAGE = 60;
    2121        const MAX_IDS = boot.maxIds || 500;
     22        const MAX_FILE_IDS = boot.maxFileIds || 10;
    2223
    2324        const VIEWS = [
    … …  
    545546
    546547        function eligibleIds( action, entries ) {
     548                if ( [ 'quarantine', 'purge' ].includes( action ) && state.summary && state.summary.storage && state.summary.storage.audit_only ) { return []; }
    547549                const out = [];
    548550                entries.forEach( ( s, id ) => {
    … …  
    631633                const body = [
    632634                        h( 'p', null, __( 'The files are deleted from the server and their Media Library entries are removed. This can’t be undone.', 'rapid-media-reclaim' ) ),
     635                        h( 'p', { class: 'smc-callout smc-callout--warning' }, __( 'Routing verification may be incomplete, expired or browser-only. Quarantine age is separate from the verified window. No recognized requests does not prove that a file is unused. Saved-backup confirmation and all deletion checks still apply.', 'rapid-media-reclaim' ) ),
    633636                ];
    634637                const buttons = [];
    … …  
    656659                                )
    657660                        );
    658                         buttons.push( {
    659                                 label: rest.length ? sprintf( /* translators: %s: number of files */ __( 'Delete all %s anyway', 'rapid-media-reclaim' ), num( ids.length ) ) : __( 'Delete anyway', 'rapid-media-reclaim' ),
    660                                 value: 'force',
    661                                 variant: 'danger-outline',
    662                         } );
     661
    663662                }
    664663                if ( rest.length ) {
    … …  
    683682                        buttons,
    684683                } );
    685                 if ( value === 'force' ) {
    686                         return { ids, force: true };
    687                 }
    688684                if ( value === 'ready' ) {
    689685                        return { ids: rest, force: false };
    … …  
    692688        }
    693689
    694         /** Send ids in chunks of MAX_IDS; aggregates the results. */
     690        /** Send file operations in small serial chunks; Keep uses its larger metadata limit. */
    695691        async function runBulk( path, ids, payload, okKey, progressLabel ) {
    696                 const parts = SMC.chunk( ids, MAX_IDS );
     692                const parts = SMC.chunk( ids, path === '/keep' ? MAX_IDS : MAX_FILE_IDS );
    697693                const out = { ok: [], failed: [], bytes: 0, batches: [], error: null };
    698694                const handle = parts.length > 1 ? SMC.toast( { type: 'info', message: progressLabel( 0, ids.length ), timeout: 0 } ) : null;
    … …  
    826822                                                filesLabel( shown( res.ok ), res.bytes )
    827823                                        ),
    828                                         action: { label: __( 'Undo', 'rapid-media-reclaim' ), onClick: () => undo( () => Promise.all( batches.map( ( batch ) => api.post( '/restore', { batch } ) ) ), shown( res.ok ) ) },
     824                                        action: { label: __( 'Undo', 'rapid-media-reclaim' ), onClick: () => undo( () => restoreBatches( batches ), shown( res.ok ) ) },
    829825                                } );
    830826                        }
    … …  
    841837                                } );
    842838                                const other = res.failed.filter( ( f ) => f.code !== 'shared' );
    843                                 failureToast( other, _n( '%s file couldn’t be moved', '%s files couldn’t be moved', other.length, 'rapid-media-reclaim' ) );
     839                                failureToast( other, /* translators: %s: number of files */ _n( '%s file couldn’t be moved', '%s files couldn’t be moved', other.length, 'rapid-media-reclaim' ) );
    844840                        } else {
    845                                 failureToast( res.failed, _n( '%s file couldn’t be moved', '%s files couldn’t be moved', res.failed.length, 'rapid-media-reclaim' ) );
     841                                failureToast( res.failed, /* translators: %s: number of files */ _n( '%s file couldn’t be moved', '%s files couldn’t be moved', res.failed.length, 'rapid-media-reclaim' ) );
    846842                        }
    847843                } else if ( action === 'restore' ) {
    … …  
    856852                                } );
    857853                        }
    858                         failureToast( res.failed, _n( '%s file couldn’t be restored', '%s files couldn’t be restored', res.failed.length, 'rapid-media-reclaim' ) );
     854                        failureToast( res.failed, /* translators: %s: number of files */ _n( '%s file couldn’t be restored', '%s files couldn’t be restored', res.failed.length, 'rapid-media-reclaim' ) );
    859855                } else if ( action === 'purge' ) {
    860856                        res = await runBulk( '/purge', ids, { force }, 'purged', progress );
    … …  
    870866                                } );
    871867                        }
    872                         failureToast( other, _n( '%s file couldn’t be deleted', '%s files couldn’t be deleted', other.length, 'rapid-media-reclaim' ) );
     868                        failureToast( other, /* translators: %s: number of files */ _n( '%s file couldn’t be deleted', '%s files couldn’t be deleted', other.length, 'rapid-media-reclaim' ) );
    873869                        if ( tooRecent.length ) {
    874870                                putBack( res.failed.map( ( f ) => f.id ) );
    … …  
    889885                                } );
    890886                        }
    891                         failureToast( res.failed, _n( '%s file couldn’t be updated', '%s files couldn’t be updated', res.failed.length, 'rapid-media-reclaim' ) );
     887                        failureToast( res.failed, /* translators: %s: number of files */ _n( '%s file couldn’t be updated', '%s files couldn’t be updated', res.failed.length, 'rapid-media-reclaim' ) );
    892888                }
    893889
    … …  
    910906                } );
    911907                return Array.from( ids );
     908        }
     909
     910        /** Drain bounded restore windows in order, stopping on the first recoverable failure. */
     911        async function restoreBatches( batches ) {
     912                const results = [];
     913                for ( const batch of batches ) {
     914                        let res;
     915                        do {
     916                                res = await api.post( '/restore', { batch } );
     917                                applySummary( res.summary );
     918                                results.push( res );
     919                                if ( res.failed && res.failed.length ) {
     920                                        throw new Error( res.failed[0].message );
     921                                }
     922                        } while ( res.remaining > 0 );
     923                }
     924                return results;
    912925        }
    913926
    … …  
    923936                        } );
    924937                } catch ( err ) {
     938                        details.clear();
     939                        invalidate();
    925940                        SMC.toast( { type: 'error', message: err.message } );
    926941                }
    … …  
    11541169
    11551170        function renderHeader() {
     1171                const focused = els.header.contains( document.activeElement ) ? document.activeElement : null;
    11561172                const last = state.summary && state.summary.last_scan;
    11571173                let meta = null;
    … …  
    11671183
    11681184                const actions = h( 'div', { class: 'smc-header__actions' } );
     1185                actions.appendChild( h( 'button', { type: 'button', id: 'smc-tools-button', class: 'smc-btn smc-btn--secondary', onClick: openTools }, __( 'Tools', 'rapid-media-reclaim' ) ) );
    11691186
    11701187                if ( scanned() ) {
    … …  
    11921209                        actions
    11931210                );
     1211                if ( focused ) {
     1212                        const nextFocus = Array.from( els.header.querySelectorAll( 'button' ) ).find( ( node ) => ! node.disabled && node.textContent === focused.textContent && node.getAttribute( 'aria-label' ) === focused.getAttribute( 'aria-label' ) );
     1213                        if ( nextFocus ) { nextFocus.focus(); }
     1214                }
    11941215                renderNotices();
    11951216        }
    11961217
    11971218        // ------------------------------------------------------------------
     1219        const toolJobs = new Map();
     1220
     1221        /** Next-release tools share the core services; discovery never authorizes deletion. */
     1222        async function openTools() {
     1223                let active = true;
     1224                let exportJob = null;
     1225                let observationTimer = null;
     1226                const progress = h( 'p', { role: 'status', 'aria-live': 'polite' }, __( 'Loading storage and observation status…', 'rapid-media-reclaim' ) );
     1227                const output = h( 'div', { class: 'smc-tools__output' } );
     1228                const savings = h( 'section', { class: 'smc-recovery smc-savings', 'aria-label': __( 'Space saved report', 'rapid-media-reclaim' ) } );
     1229                const history = h( 'div', { class: 'smc-savings__history' } );
     1230                let historyAfter = 0;
     1231                const loadHistory = async () => {
     1232                        const page = await api.get( '/tools/report-history', { after: historyAfter, limit: 20 } );
     1233                        if ( ! active ) { return; }
     1234                        if ( page.status === 'unavailable' ) { throw new Error( __( 'Operation history unavailable. Check database access.', 'rapid-media-reclaim' ) ); }
     1235                        const labels = { quarantine: __( 'Quarantine', 'rapid-media-reclaim' ), restore: __( 'Restore', 'rapid-media-reclaim' ), remove: __( 'Permanent removal', 'rapid-media-reclaim' ), verified: __( 'Verified', 'rapid-media-reclaim' ), failed: __( 'Failed', 'rapid-media-reclaim' ), pending: __( 'Pending', 'rapid-media-reclaim' ), unknown: __( 'Unknown', 'rapid-media-reclaim' ), tracked: __( 'Tracked', 'rapid-media-reclaim' ), legacy: __( 'Legacy', 'rapid-media-reclaim' ), import: __( 'Imported backup', 'rapid-media-reclaim' ) };
     1236                        if ( historyAfter === 0 && ! page.items.length ) { history.appendChild( h( 'p', null, __( 'No tracked operations yet. Earlier activity is unknown.', 'rapid-media-reclaim' ) ) ); }
     1237                        page.items.forEach( ( row ) => history.appendChild( h( 'p', null, '#' + row.id + ' · ' + labels[ row.operation ] + ' · ' + labels[ row.result ] + ' · ' + bytes( row.bytes ) + ' · ' + labels[ row.coverage ] + ' · ' + row.updated_at + ' UTC' ) ) );
     1238                        historyAfter = page.next;
     1239                        historyMore.hidden = page.next === null;
     1240                };
     1241                const historyMore = h( 'button', { class: 'smc-btn smc-btn--secondary', type: 'button', onClick: async () => { historyMore.disabled = true; try { await loadHistory(); } catch ( error ) { progress.textContent = error.message; } finally { historyMore.disabled = false; } } }, __( 'Load operation history', 'rapid-media-reclaim' ) );
     1242                const showSavings = ( report ) => {
     1243                        const value = ( amount ) => amount === null ? __( 'Unknown', 'rapid-media-reclaim' ) : bytes( amount );
     1244                        const metrics = h( 'dl', { class: 'smc-savings__metrics' } );
     1245                        [ [ __( 'Estimated reclaimable', 'rapid-media-reclaim' ), report.estimated_reclaimable_bytes ], [ __( 'Media Library quarantine storage', 'rapid-media-reclaim' ), report.current_quarantine_bytes ], [ __( 'Media Library verified removed', 'rapid-media-reclaim' ), report.cumulative_verified_removed_bytes ] ].forEach( ( [ label, bytes ] ) => metrics.appendChild( h( 'div', null, h( 'dt', null, label ), h( 'dd', null, value( bytes ) ) ) ) );
     1246                        replace( savings, h( 'h3', null, __( 'Space saved report', 'rapid-media-reclaim' ) ), metrics,
     1247                                h( 'p', null, __( 'Logical bytes only. Physical disk allocation: not measured. Estimated reclaimable bytes do not authorize deletion.', 'rapid-media-reclaim' ) ),
     1248                                h( 'p', null, sprintf( /* translators: 1: tracking start UTC, 2: pending file operations, 3: unknown operations, 4: untracked active recovery records */ __( 'Tracking started: %1$s UTC. Pending: %2$s. Unknown operations: %3$s. Untracked active records: %4$s.', 'rapid-media-reclaim' ), report.tracking_started_at || __( 'Unknown', 'rapid-media-reclaim' ), report.pending_files === null ? __( 'Unknown', 'rapid-media-reclaim' ) : num( report.pending_files + report.pending_records ), report.unknown_operation_files === null ? __( 'Unknown', 'rapid-media-reclaim' ) : num( report.unknown_operation_files ), report.legacy_active_records === null ? __( 'Unknown', 'rapid-media-reclaim' ) : num( report.legacy_active_records ) ) ),
     1249                                h( 'p', null, sprintf( /* translators: 1: inventory estimate observation UTC, 2: oldest storage observation UTC */ __( 'Inventory estimate observed: %1$s UTC. Oldest storage observation: %2$s UTC.', 'rapid-media-reclaim' ), report.estimate_observed_at || __( 'Unknown', 'rapid-media-reclaim' ), report.oldest_storage_observation_at || __( 'Unknown', 'rapid-media-reclaim' ) ) ), h( 'p', null, report.coverage ), h( 'p', null, report.action_required ), history, historyMore );
     1250                };
     1251                const observation = h( 'section', { class: 'smc-recovery', 'aria-label': __( 'Routing verification', 'rapid-media-reclaim' ) } );
     1252                const showObservation = ( status ) => {
     1253                        const w = status.window || {};
     1254                        const modeLabels = { 'verified-PHP': __( 'PHP routing checked', 'rapid-media-reclaim' ), 'browser-only': __( 'Browser reports only', 'rapid-media-reclaim' ), unavailable: __( 'Unavailable', 'rapid-media-reclaim' ) };
     1255                        const current = status.mode === 'verified-PHP' && w.start && status.expires_at * 1000 > Date.now();
     1256                        const date = ( value ) => value ? new Date( value * 1000 ).toLocaleString() : __( 'Unknown', 'rapid-media-reclaim' );
     1257                        replace( observation, h( 'h3', null, __( 'Routing verification', 'rapid-media-reclaim' ) ),
     1258                                h( 'p', null, current ? __( 'No known interruption in routing verification', 'rapid-media-reclaim' ) : __( 'Routing verification incomplete, expired or paused', 'rapid-media-reclaim' ) ),
     1259                                h( 'p', null, sprintf( /* translators: 1: mode, 2: start date, 3: last success date, 4: expiry date, 5: interruptions */ __( 'Mode: %1$s. Window start: %2$s. Last successful check: %3$s. Expires: %4$s. Interruptions: %5$s.', 'rapid-media-reclaim' ), modeLabels[ current ? status.mode : ( status.fallback_mode || 'unavailable' ) ] || __( 'Unknown', 'rapid-media-reclaim' ), date( w.start ), date( status.verified_at ), date( status.expires_at ), num( w.interruptions || 0 ) ) ),
     1260                                h( 'p', null, sprintf( /* translators: 1: elapsed verification days, 2: required days */ __( 'Site routing period: %1$s of %2$s days. Each quarantined group also starts no earlier than its latest member.', 'rapid-media-reclaim' ), num( Math.floor( ( status.elapsed_seconds || 0 ) / 86400 ) ), num( status.required_days || 14 ) ) ),
     1261                                h( 'p', null, sprintf( /* translators: %s: most recent interruption date */ __( 'Latest known interruption: %s. Any interruption restarts the period after a new successful routing check.', 'rapid-media-reclaim' ), date( status.coverage_gap_at ) ) ),
     1262                                h( 'p', null, status.effective_scope ), h( 'p', null, status.coverage ) );
     1263                        clearTimeout( observationTimer );
     1264                        observationTimer = setTimeout( async () => {
     1265                                if ( ! active ) { return; }
     1266                                try { const fresh = await api.get( '/tools/status' ); if ( active ) { showObservation( fresh.observation ); } }
     1267                                catch ( error ) { if ( active ) { replace( observation, h( 'p', null, __( 'Routing status unavailable. Refresh Tools before relying on a previous check.', 'rapid-media-reclaim' ) ) ); } }
     1268                        }, current ? Math.max( 1000, Math.min( 60000, status.expires_at * 1000 - Date.now() ) ) : 60000 );
     1269                };
     1270                const actions = h( 'div', { class: 'smc-tools__actions' } );
     1271                const mergeSelect = h( 'select', { class: 'smc-select', 'aria-label': __( 'Reference job', 'rapid-media-reclaim' ), hidden: true } );
     1272                const rememberMerge = ( job ) => {
     1273                        toolJobs.set( 'merge', job );
     1274                        if ( ! Array.from( mergeSelect.options ).some( ( option ) => option.value === job.token ) ) { mergeSelect.appendChild( h( 'option', { value: job.token }, '#' + job.canonical + ' · ' + job.status ) ); }
     1275                        mergeSelect.value = job.token; mergeSelect.hidden = false;
     1276                };
     1277                const taskError = ( error ) => {
     1278                        const messages = {
     1279                                file_review_selection_stale: __( 'This audit selection is stale or unfinished. Run a fresh scan and uploads audit.', 'rapid-media-reclaim' ),
     1280                                file_review_selection_invalid: __( 'This saved row cannot be reviewed. Choose a supported image or PDF in a fresh audit.', 'rapid-media-reclaim' ),
     1281                                file_review_file_changed: __( 'The file changed, disappeared or exceeds the 16 MiB live-review limit. Start a fresh audit or review it manually.', 'rapid-media-reclaim' ),
     1282                                visual_gd_unavailable: __( 'Your server needs the PHP GD imaging extension for local visual search.', 'rapid-media-reclaim' ),
     1283                                visual_inventory_unavailable: __( 'The media inventory could not be read. Check database access and retry this step.', 'rapid-media-reclaim' ),
     1284                                visual_signature_invalid: __( 'Saved visual search data is unreadable. Start a new search; originals were not changed.', 'rapid-media-reclaim' ),
     1285                                visual_results_unavailable: __( 'Visual results could not be read. Retry after checking database access.', 'rapid-media-reclaim' ),
     1286                                visual_results_invalid: __( 'Saved visual results are invalid. Start a new search; originals were not changed.', 'rapid-media-reclaim' ),
     1287                                inventory_root_changed: __( 'Uploads storage changed or this is an older audit. Start a new uploads audit; no files were changed.', 'rapid-media-reclaim' ),
     1288                                inventory_filter_invalid: __( 'Choose a valid category, alphanumeric extension and minimum byte count.', 'rapid-media-reclaim' ),
     1289                                inventory_job_busy: __( 'The audit is finishing a step. Retry cancellation shortly.', 'rapid-media-reclaim' ),
     1290                                inventory_cancel_not_saved: __( 'Cancellation could not be saved. Retry after checking database access.', 'rapid-media-reclaim' ),
     1291                                retirement_fresh_scan_required: __( 'Prepare duplicate quarantine and complete its new scan before continuing.', 'rapid-media-reclaim' ),
     1292                                retirement_scan_busy: __( 'Wait for the current scan to finish, then prepare duplicate quarantine.', 'rapid-media-reclaim' ),
     1293                                retirement_usage_review_required: __( 'Usage evidence still references a duplicate. Review it and keep the file available.', 'rapid-media-reclaim' ),
     1294                                retirement_cache_review_required: __( 'Regenerate this reference job’s supported builder caches first. Unsupported builder caches keep quarantine blocked.', 'rapid-media-reclaim' ),
     1295                                retirement_cache_changed: __( 'Generated cache files changed. Regenerate them, prepare duplicate quarantine again and complete a new scan.', 'rapid-media-reclaim' ),
     1296                                retirement_saved_backup_required: __( 'Download and confirm a current duplicate backup before quarantine.', 'rapid-media-reclaim' ),
     1297                                retirement_unverified_variants: __( 'Image variants or edit backups could not be matched safely. Originals remain available for review.', 'rapid-media-reclaim' ),
     1298                                retirement_state_not_saved: __( 'Completion could not be saved. Refresh Quarantine and use reference rollback; recovery data was retained.', 'rapid-media-reclaim' ),
     1299                                retirement_recovery_batch_changed: __( 'Recovery ownership changed. Review the quarantine records before restoring this reference job.', 'rapid-media-reclaim' ),
     1300                                retirement_backup_budget: __( 'This duplicate group exceeds the current limit of 100 files or 64 MiB. Originals remain available.', 'rapid-media-reclaim' ),
     1301                                retirement_other_recovery_job: __( 'Another reference recovery journal protects this media. Resolve that operation first.', 'rapid-media-reclaim' ),
     1302                                retirement_attachment_unavailable: __( 'A duplicate is kept, shared, already quarantined or unavailable. Review its recovery state first.', 'rapid-media-reclaim' ),
     1303                                retirement_storage_or_index_incomplete: __( 'Storage or usage indexing needs review. Complete pending work before quarantine.', 'rapid-media-reclaim' ),
     1304                                cache_source_changed: __( 'A source changed after this merge. Resolve its reference recovery job before quarantine.', 'rapid-media-reclaim' )
     1305                        };
     1306                        return messages[ error.message ] || error.message || __( 'The task could not finish. No media was deleted.', 'rapid-media-reclaim' );
     1307                };
     1308                const run = ( label, action ) => {
     1309                        const button = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: async () => {
     1310                                button.disabled = true;
     1311                                try { await action(); } catch ( error ) { progress.textContent = taskError( error ); }
     1312                                finally {
     1313                                        button.disabled = false;
     1314                                        if ( active && button.isConnected && document.activeElement === document.body ) { button.focus(); }
     1315                                }
     1316                        } }, label );
     1317                        actions.appendChild( button );
     1318                        return button;
     1319                };
     1320                const uploadSelect = h( 'select', { class: 'smc-select', 'aria-label': __( 'Saved uploads audits', 'rapid-media-reclaim' ) }, h( 'option', { value: '' }, __( 'Choose a saved uploads audit', 'rapid-media-reclaim' ) ) );
     1321                const uploadStatus = h( 'p', { role: 'status', 'aria-live': 'polite' } );
     1322                const rememberUpload = ( job ) => {
     1323                        if ( job.kind !== 'uploads' ) { return; }
     1324                        toolJobs.set( 'uploads:' + job.token, job );
     1325                        let option = Array.from( uploadSelect.options ).find( ( item ) => item.value === job.token );
     1326                        if ( ! option ) { option = h( 'option', { value: job.token } ); uploadSelect.appendChild( option ); }
     1327                        const status = { running: __( 'Paused or running', 'rapid-media-reclaim' ), done: __( 'Walk finished', 'rapid-media-reclaim' ), cancelled: __( 'Cancelled', 'rapid-media-reclaim' ) };
     1328                        option.textContent = ( job.created ? new Date( job.created * 1000 ).toLocaleString() : job.token.slice( 0, 8 ) ) + ' · ' + ( status[ job.status ] || job.status ) + ' · ' + num( job.processed );
     1329                        uploadSelect.value = job.token;
     1330                };
     1331
     1332                const fileSelect = h( 'select', { class: 'smc-select', 'aria-label': __( 'Standalone recovery job', 'rapid-media-reclaim' ) }, h( 'option', { value: '' }, __( 'Choose standalone recovery', 'rapid-media-reclaim' ) ) );
     1333                const fileOutput = h( 'div', { class: 'smc-recovery__preview', role: 'status', 'aria-live': 'polite' } );
     1334                let fileBusy = false;
     1335                const filePhases = { prepared: __( 'Backup preparation', 'rapid-media-reclaim' ), staged: __( 'Backed up — originals still live', 'rapid-media-reclaim' ), quarantining: __( 'Interrupted quarantine — review or restore', 'rapid-media-reclaim' ), quarantined: __( 'Quarantined', 'rapid-media-reclaim' ), restoring: __( 'Recovery needs retry', 'rapid-media-reclaim' ), restored: __( 'Restored', 'rapid-media-reclaim' ), purging: __( 'Authorized deletion needs retry', 'rapid-media-reclaim' ), purged: __( 'Permanently deleted — ZIP required for recovery', 'rapid-media-reclaim' ), discarding: __( 'Discard needs retry', 'rapid-media-reclaim' ) };
     1336                const filePhase = ( job ) => job.imported && job.state === 'staged' ? __( 'Verified private recovery preview', 'rapid-media-reclaim' ) : filePhases[ job.state ] || job.state;
     1337                const rememberFile = ( job ) => {
     1338                        toolJobs.set( 'file:' + job.token, job );
     1339                        let option = Array.from( fileSelect.options ).find( ( o ) => o.value === job.token );
     1340                        if ( ! option ) { option = h( 'option', { value: job.token } ); fileSelect.appendChild( option ); }
     1341                        option.textContent = filePhase( job ) + ' · ' + ( job.files[0] || {} ).path;
     1342                        fileSelect.value = job.token;
     1343                };
     1344                const fileError = ( error ) => {
     1345                        const messages = {
     1346                                file_approval_stale_or_backup_missing: __( 'The review expired, content changed or a saved backup is missing. Download/confirm the backup and run fresh checks.', 'rapid-media-reclaim' ),
     1347                                file_quarantine_watch_required: __( 'Enable request watching and automatic restore in Settings, then verify request routing before quarantine.', 'rapid-media-reclaim' ),
     1348                                file_quarantine_review_blocked: __( 'A current reference, possible owner, recorded request or storage restriction blocks quarantine. Keep this file.', 'rapid-media-reclaim' ),
     1349                                file_backup_download_required: __( 'Download and save this backup before confirming it.', 'rapid-media-reclaim' ),
     1350                                file_recovery_restore_conflict: __( 'A different file occupies the original path, or recovery bytes are missing. Nothing was overwritten. Keep both files and resolve the conflict before retrying.', 'rapid-media-reclaim' ),
     1351                                file_quarantine_source_raced: __( 'The original changed during capture. The replacement and backup were retained. Restore or ask your administrator to resolve the conflict.', 'rapid-media-reclaim' ),
     1352                                file_import_confirmation_required: __( 'Verify this backup and explicitly trust its origin before restoring. Cross-site backups also need adoption confirmation.', 'rapid-media-reclaim' ),
     1353                                file_approval_payload_changed: __( 'The file or its attributes changed. Restore this preparation and create a fresh audit/backup.', 'rapid-media-reclaim' )
     1354                        };
     1355                        return messages[ error.message ] || taskError( error ) + ' ' + __( 'Recovery records are retained. Refresh the list; restore or retry after resolving the problem.', 'rapid-media-reclaim' );
     1356                };
     1357                const fileWork = async ( work ) => {
     1358                        if ( fileBusy ) { fileOutput.textContent = __( 'Wait for the current standalone recovery operation.', 'rapid-media-reclaim' ); return; }
     1359                        fileBusy = true;
     1360                        try { await work(); } catch ( error ) { fileOutput.textContent = fileError( error ); }
     1361                        finally { fileBusy = false; }
     1362                };
     1363                const showFile = ( job ) => {
     1364                        rememberFile( job );
     1365                        const buttons = h( 'div', { class: 'smc-tools__actions' } );
     1366                        const add = ( label, fn, disabled = false ) => {
     1367                                const b = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', disabled, onClick: () => fileWork( async () => { b.disabled = true; try { await fn(); } finally { b.disabled = false; } } ) }, label ); buttons.appendChild( b ); return b;
     1368                        };
     1369                        const notes = h( 'div' );
     1370                        if ( job.state === 'prepared' ) {
     1371                                add( __( 'Resume backup preparation', 'rapid-media-reclaim' ), async () => {
     1372                                        while ( active && job.state === 'prepared' ) { job = await api.post( '/tools/files/step', { token: job.token } ); rememberFile( job ); }
     1373                                        if ( active ) { showFile( job ); }
     1374                                } );
     1375                        }
     1376                        if ( job.state !== 'prepared' && job.state !== 'discarding' && job.state !== 'purged' && job.state !== 'purging' ) {
     1377                                buttons.appendChild( h( 'a', { class: 'smc-btn smc-btn--secondary', href: safeHref( job.download_url ), target: '_blank', rel: 'noopener noreferrer' }, __( 'Download standalone recovery ZIP', 'rapid-media-reclaim' ) ) );
     1378                        }
     1379                        if ( job.imported && ! job.trusted ) {
     1380                                const trust = h( 'input', { type: 'checkbox' } ); const adopt = h( 'input', { type: 'checkbox' } );
     1381                                notes.appendChild( h( 'p', null, h( 'label', null, trust, ' ', __( 'I trust the source of this ZIP and reviewed every destination below.', 'rapid-media-reclaim' ) ) ) );
     1382                                if ( job.cross_site ) { notes.appendChild( h( 'p', null, h( 'label', null, adopt, ' ', __( 'I explicitly approve importing these paths from a different site.', 'rapid-media-reclaim' ) ) ) ); }
     1383                                add( __( 'Trust this backup', 'rapid-media-reclaim' ), async () => {
     1384                                        if ( ! trust.checked || ( job.cross_site && ! adopt.checked ) ) { throw new Error( __( 'Confirm backup trust and any cross-site adoption first.', 'rapid-media-reclaim' ) ); }
     1385                                        showFile( await api.post( '/tools/files/trust', { token: job.token, trusted_backup: true, adopt_site: adopt.checked } ) );
     1386                                }, job.state !== 'staged' );
     1387                                add( __( 'Discard untrusted upload', 'rapid-media-reclaim' ), async () => {
     1388                                        const yes = await SMC.dialog( { title: __( 'Discard this recovery upload?', 'rapid-media-reclaim' ), body: h( 'p', null, __( 'Only this untrusted upload and its private verified copies will be removed. Public files are untouched. Keep your original ZIP.', 'rapid-media-reclaim' ) ), buttons: [ { label: __( 'Discard upload', 'rapid-media-reclaim' ), value: true } ] } );
     1389                                        if ( yes ) { await api.post( '/tools/files/discard', { token: job.token } ); const option = Array.from( fileSelect.options ).find( ( o ) => o.value === job.token ); if ( option ) { option.remove(); } toolJobs.delete( 'file:' + job.token ); fileOutput.textContent = __( 'Untrusted upload discarded. Public files were not changed.', 'rapid-media-reclaim' ); }
     1390                                } );
     1391                        }
     1392                        if ( ! job.imported && job.state === 'staged' ) {
     1393                                const saved = h( 'input', { type: 'checkbox', checked: job.backup_saved } );
     1394                                notes.appendChild( h( 'p', null, h( 'label', null, saved, ' ', __( 'I downloaded and saved this recovery ZIP outside this server.', 'rapid-media-reclaim' ) ) ) );
     1395                                add( __( 'Confirm saved standalone backup', 'rapid-media-reclaim' ), async () => {
     1396                                        if ( ! saved.checked ) { throw new Error( __( 'Save your backup and confirm it first.', 'rapid-media-reclaim' ) ); }
     1397                                        showFile( await api.post( '/tools/files/backup-confirm', { token: job.token, confirmed: true } ) );
     1398                                } );
     1399                                add( job.approval && job.approval.status === 'checking' ? __( 'Resume standalone checks', 'rapid-media-reclaim' ) : __( 'Check before standalone quarantine', 'rapid-media-reclaim' ), async () => {
     1400                                        if ( ! job.approval || job.approval.status !== 'checking' ) { job = await api.post( '/tools/files/approval-start', { token: job.token } ); }
     1401                                        while ( active && job.approval.status === 'checking' ) {
     1402                                                job = await api.post( '/tools/files/approval-step', { token: job.token } ); rememberFile( job );
     1403                                                fileOutput.textContent = sprintf( /* translators: %s: checked stored rows */ __( '%s stored rows checked. Closing pauses; resume this saved recovery job later.', 'rapid-media-reclaim' ), num( job.approval.rows ) );
     1404                                        }
     1405                                        if ( active ) { showFile( job ); }
     1406                                }, ! job.backup_saved );
     1407                                if ( job.approval && job.approval.status === 'ready' ) {
     1408                                        const reviewed = h( 'input', { type: 'checkbox' } );
     1409                                        notes.appendChild( h( 'p', null, h( 'label', null, reviewed, ' ', __( 'I reviewed the public pages, relevant theme/plugin behavior and caches. These checks cannot prove the file is unused.', 'rapid-media-reclaim' ) ) ) );
     1410                                        add( __( 'Quarantine this standalone file', 'rapid-media-reclaim' ), async () => {
     1411                                                if ( ! reviewed.checked ) { throw new Error( __( 'Review the public pages and caches first.', 'rapid-media-reclaim' ) ); }
     1412                                                const yes = await SMC.dialog( { title: __( 'Quarantine this standalone file?', 'rapid-media-reclaim' ), body: h( 'p', null, __( 'Its public URL will become unavailable until restored. A saved ZIP, fresh checks, request watching and verified routing are required. Static/CDN/cache paths may bypass observation. No permanent deletion occurs.', 'rapid-media-reclaim' ) ), buttons: [ { label: __( 'Move file to quarantine', 'rapid-media-reclaim' ), value: true, variant: 'primary' } ] } );
     1413                                                if ( yes ) { showFile( await api.post( '/tools/files/quarantine', { token: job.token, confirmed: true } ) ); }
     1414                                        } );
     1415                                }
     1416                        }
     1417                        if ( ! [ 'restored', 'purged', 'purging' ].includes( job.state ) && ( ! job.imported || job.trusted ) ) {
     1418                                add( __( 'Restore standalone files', 'rapid-media-reclaim' ), async () => { showFile( await api.post( '/tools/files/restore', { token: job.token } ) ); } );
     1419                        }
     1420                        if ( [ 'quarantined', 'purging' ].includes( job.state ) ) {
     1421                                notes.appendChild( h( 'p', null, job.window && job.window.verified_window_complete ? __( 'The routing-check window is complete. This does not prove continuous request capture or non-usage.', 'rapid-media-reclaim' ) : __( 'Permanent deletion is blocked until the routing-check window is complete, with at least 14 days and no recorded requests.', 'rapid-media-reclaim' ) ) );
     1422                                add( __( 'Run fresh checks before permanent deletion', 'rapid-media-reclaim' ), async () => {
     1423                                        job = await api.post( '/tools/files/approval-start', { token: job.token } );
     1424                                        while ( active && job.approval.status === 'checking' ) {
     1425                                                job = await api.post( '/tools/files/approval-step', { token: job.token } ); rememberFile( job );
     1426                                                fileOutput.textContent = sprintf( __( '%s stored rows checked. Closing pauses; resume this saved recovery job later.', 'rapid-media-reclaim' ), num( job.approval.rows ) );
     1427                                        }
     1428                                        if ( active ) { showFile( job ); }
     1429                                }, ! job.window || ! job.window.verified_window_complete );
     1430                                add( __( 'Permanently delete standalone quarantine copies', 'rapid-media-reclaim' ), async () => {
     1431                                        const yes = await SMC.dialog( { title: __( 'Permanently delete this standalone file?', 'rapid-media-reclaim' ), body: h( 'p', null, __( 'Both server recovery copies will be deleted. Recovery will require your downloaded ZIP. Review public pages, dynamic uses and caches first; routing checks cannot prove non-usage. Any replacement at the original public path is kept.', 'rapid-media-reclaim' ) ), buttons: [ { label: __( 'Permanently delete copies', 'rapid-media-reclaim' ), value: true } ] } );
     1432                                        if ( yes ) { showFile( await api.post( '/tools/files/purge', { token: job.token, confirmed: true } ) ); }
     1433                                }, ! job.window || ! job.window.verified_window_complete || ! job.approval || job.approval.status !== 'ready' );
     1434                        }
     1435
     1436                        const reasons = { sources_changed: __( 'Content changed during review. Restart checks.', 'rapid-media-reclaim' ), stored_match: __( 'A possible stored reference or owner blocks quarantine. Keep the file.', 'rapid-media-reclaim' ), source_limit: __( 'Some content could not be fully checked. Resolve the source limit before quarantine.', 'rapid-media-reclaim' ) };
     1437                        replace( fileOutput, h( 'h4', null, filePhase( job ) ), h( 'ul', null, ...job.files.map( ( f ) => h( 'li', null, f.path + ' · ' + bytes( f.bytes ) + ( f.mode !== undefined ? ' · ' + __( 'Permissions:', 'rapid-media-reclaim' ) + ' ' + f.mode.toString( 8 ) : '' ) ) ) ),
     1438                                job.approval ? h( 'p', null, job.approval.status === 'ready' ? __( 'Stored-source checks are current for five minutes. They establish eligibility for manual quarantine, not non-usage or purge permission.', 'rapid-media-reclaim' ) : reasons[ job.approval.reason ] || __( 'Stored-source checks are pending.', 'rapid-media-reclaim' ) ) : null,
     1439                                job.hits ? h( 'p', null, __( 'A request was recorded. This path is protected from re-quarantine.', 'rapid-media-reclaim' ) ) : null,
     1440                                job.state === 'purged' ? h( 'p', null, job.verified_removed_bytes === null ? __( 'Deletion completed. Removed bytes are unknown because a verified receipt was interrupted.', 'rapid-media-reclaim' ) : sprintf( /* translators: %s: logical original bytes removed */ __( 'Verified removal: %s logical original bytes, counted once. Recovery ZIPs and physical allocation are excluded.', 'rapid-media-reclaim' ), bytes( job.verified_removed_bytes ) ) ) : null,
     1441                                notes, buttons );
     1442                };
     1443                const fileUpload = h( 'input', { type: 'file', accept: '.zip,application/zip', 'aria-label': __( 'Standalone recovery ZIP', 'rapid-media-reclaim' ) } );
     1444                const fileSection = h( 'section', { class: 'smc-recovery' }, h( 'h3', null, __( 'Standalone file recovery', 'rapid-media-reclaim' ) ),
     1445                        h( 'p', null, __( 'Standalone files are separate from Media Library counts. Prepare a backup from an uploads-audit row, then select its recovery job here. Archives preserve ordinary file permissions and modification times; ownership, ACLs and directory attributes are not reconstructed. Permanent deletion needs a saved backup, fresh review, a completed routing-check window of at least 14 days and a separate confirmation. Quarantine retains recovery copies and does not free disk space.', 'rapid-media-reclaim' ) ), fileSelect,
     1446                        h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: () => { const job = toolJobs.get( 'file:' + fileSelect.value ); if ( job ) { showFile( job ); } } }, __( 'Open standalone recovery', 'rapid-media-reclaim' ) ), fileUpload,
     1447                        h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: () => fileWork( async () => {
     1448                                const file = fileUpload.files[0]; if ( ! file ) { throw new Error( __( 'Choose a standalone recovery ZIP first.', 'rapid-media-reclaim' ) ); }
     1449                                const data = new FormData(); data.append( 'archive', file );
     1450                                let job = await wp.apiFetch( { path: ( boot.restPath || '/rapid-media-reclaim/v1' ) + '/tools/files/upload', method: 'POST', body: data } ); rememberFile( job );
     1451                                while ( active && job.state === 'prepared' ) { job = await api.post( '/tools/files/step', { token: job.token } ); rememberFile( job ); }
     1452                                if ( active ) { showFile( job ); }
     1453                        } ) }, __( 'Upload standalone recovery ZIP', 'rapid-media-reclaim' ) ), fileOutput );
     1454                let fileBefore = 0;
     1455                const olderFiles = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', hidden: true, onClick: () => fileWork( loadFiles ) }, __( 'Load older standalone recovery records', 'rapid-media-reclaim' ) );
     1456                fileSection.appendChild( olderFiles );
     1457                async function loadFiles() {
     1458                        const result = await api.get( '/tools/files/jobs' + ( fileBefore ? '?before=' + fileBefore : '' ) );
     1459                        if ( ! active ) { return; }
     1460                        result.jobs.slice().reverse().forEach( rememberFile ); fileBefore = result.next; olderFiles.hidden = ! result.limited;
     1461                        if ( result.unreadable ) { fileOutput.textContent = __( 'Some recovery records could not be read. Keep all backups and ask your administrator to review storage; uninstall remains blocked for unresolved data.', 'rapid-media-reclaim' ); }
     1462                }
     1463                loadFiles().catch( ( error ) => { if ( active ) { fileOutput.textContent = fileError( error ); } } );
     1464
     1465                let fileReviewBusy = false;
     1466                const uploadReviewRow = ( job, saved, labels ) => {
     1467                        const row = saved.item;
     1468                        const detail = h( 'div', { role: 'status', 'aria-live': 'polite' } );
     1469                        const check = h( 'button', {
     1470                                type: 'button', class: 'smc-btn smc-btn--secondary smc-btn--sm',
     1471                                disabled: ! /\.(?:jpe?g|png|gif|webp|avif|pdf)$/i.test( row.path ),
     1472                                onClick: async () => {
     1473                                        if ( fileReviewBusy ) { detail.textContent = __( 'Wait for the current live check to finish.', 'rapid-media-reclaim' ); return; }
     1474                                        fileReviewBusy = true; check.disabled = true;
     1475                                        try {
     1476                                                const review = await api.post( '/tools/file-review', { token: job.token, row_id: saved.result_id } );
     1477                                                if ( ! active || ! detail.isConnected ) { return; }
     1478                                                const messages = {
     1479                                                        ownership_match: __( 'Possible current metadata owner found. Keep this file.', 'rapid-media-reclaim' ),
     1480                                                        reference_match: __( 'Possible stored reference found. Keep this file.', 'rapid-media-reclaim' ),
     1481                                                        incomplete: __( 'The live check is incomplete. No cleanup approval was issued.', 'rapid-media-reclaim' ),
     1482                                                        no_match_in_checked_sources: __( 'No match in the checked stored sources. This does not establish that the file is unused.', 'rapid-media-reclaim' )
     1483                                                };
     1484                                                replace( detail,
     1485                                                        h( 'p', null, messages[ review.status ] ),
     1486                                                        h( 'p', null, sprintf( /* translators: %s: inspected database rows */ __( '%s stored rows checked. Checks are bounded and are not an atomic snapshot. Theme/PHP code, custom tables, network options, caches and external usage may remain unchecked. No files were moved.', 'rapid-media-reclaim' ), num( review.coverage.rows ) ) ),
     1487                                                        ...review.coverage.hits.map( ( hit ) => h( 'p', null, hit.source_type + ' #' + hit.source_id + ' · ' + hit.field + ' · ' + hit.match ) ),
     1488                                                        review.coverage.hits_limit ? h( 'p', null, __( 'Additional matches were found; only the first 20 are shown.', 'rapid-media-reclaim' ) ) : null,
     1489                                                        review.coverage.gaps.length ? h( 'p', null, __( 'Coverage limits:', 'rapid-media-reclaim' ) + ' ' + review.coverage.gaps.join( ', ' ) ) : null,
     1490                                                        review.storage.audit_only ? h( 'p', null, __( 'Storage or indexing restrictions also block cleanup.', 'rapid-media-reclaim' ) ) : null
     1491                                                );
     1492                                        } catch ( error ) { detail.textContent = taskError( error ); }
     1493                                        finally { fileReviewBusy = false; check.disabled = false; }
     1494                                }
     1495                        }, __( 'Check current ownership and references', 'rapid-media-reclaim' ) );
     1496                        const prepare = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary smc-btn--sm', disabled: check.disabled, onClick: () => fileWork( async () => { showFile( await api.post( '/tools/files/prepare', { audit: job.token, row: saved.result_id } ) ); fileSection.scrollIntoView( { block: 'start', behavior: 'smooth' } ); } ) }, __( 'Prepare standalone recovery backup', 'rapid-media-reclaim' ) );
     1497                        return h( 'li', { class: 'smc-audit-result' },
     1498                                row.path + ' · ' + bytes( row.bytes ) + ' · ' + ( labels[ row.status ] || __( 'Review required', 'rapid-media-reclaim' ) ) + ( row.owners && row.owners.length ? ' · #' + row.owners.join( ', #' ) : '' ),
     1499                                row.unregistered_size ? h( 'p', null, __( 'An unregistered size is still owned. Do not delete it based on its size name.', 'rapid-media-reclaim' ) ) : null,
     1500                                check, prepare, detail
     1501                        );
     1502                };
     1503                const showUploadResults = async ( job ) => {
     1504                        const labels = { all: __( 'All categories', 'rapid-media-reclaim' ), indexed_original: __( 'Indexed original', 'rapid-media-reclaim' ), indexed_derivative: __( 'Indexed derivative', 'rapid-media-reclaim' ), indexed_shared: __( 'Indexed shared path', 'rapid-media-reclaim' ), possible_derivative_review: __( 'Possible old derivative — review', 'rapid-media-reclaim' ), unindexed_review: __( 'No indexed owner — review', 'rapid-media-reclaim' ), ownership_unavailable: __( 'Ownership unavailable', 'rapid-media-reclaim' ) };
     1505                        const category = h( 'select', { class: 'smc-select', 'aria-label': __( 'Ownership category', 'rapid-media-reclaim' ) }, ...Object.entries( labels ).map( ( [ value, label ] ) => h( 'option', { value }, label ) ) );
     1506                        const extension = h( 'input', { type: 'text', class: 'smc-input', maxLength: 12, placeholder: __( 'Extension, e.g. jpg', 'rapid-media-reclaim' ), 'aria-label': __( 'File extension', 'rapid-media-reclaim' ) } );
     1507                        const minimum = h( 'input', { type: 'number', class: 'smc-input', min: 0, max: 2147483647, value: 0, 'aria-label': __( 'Minimum file bytes', 'rapid-media-reclaim' ) } );
     1508                        const list = h( 'ul' ); const note = h( 'p', { role: 'status', 'aria-live': 'polite' } );
     1509                        const csv = h( 'a', { class: 'smc-btn smc-btn--secondary' }, __( 'Download filtered audit CSV', 'rapid-media-reclaim' ) );
     1510                        let after = 0; let busy = false;
     1511                        const page = async ( reset = false ) => {
     1512                                if ( busy || ! active || ! list.isConnected ) { return; }
     1513                                busy = true; apply.disabled = true; next.disabled = true;
     1514                                try {
     1515                                        const result = await api.get( '/tools/discover-results', { token: job.token, after: reset ? 0 : after, status: category.value, extension: extension.value.trim().toLowerCase(), min_bytes: minimum.value } );
     1516                                        if ( ! active || ! list.isConnected ) { return; }
     1517                                        after = result.next; next.hidden = ! result.has_more;
     1518                                        csv.href = safeHref( result.csv_url );
     1519                                        note.textContent = result.snapshot_current ? __( 'Ownership comes from the saved index generation, not a live usage check. No indexed owner does not mean unused. Each page examines at most 100 saved rows; filtered pages can be empty.', 'rapid-media-reclaim' ) : __( 'The index changed or was unavailable. These ownership hints are stale; start a new scan and audit before reviewing them.', 'rapid-media-reclaim' );
     1520                                        replace( list, ...result.rows.map( ( saved ) => uploadReviewRow( job, saved, labels ) ) );
     1521                                        if ( ! result.rows.length ) { list.appendChild( h( 'li', null, __( 'No matching files in this page. Continue if more rows are available.', 'rapid-media-reclaim' ) ) ); }
     1522                                } catch ( error ) { note.textContent = taskError( error ); }
     1523                                finally { busy = false; apply.disabled = false; next.disabled = false; }
     1524                        };
     1525                        const apply = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: () => page( true ) }, __( 'Apply audit filters', 'rapid-media-reclaim' ) );
     1526                        const next = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: () => page() }, __( 'Next audit page', 'rapid-media-reclaim' ) );
     1527                        replace( output, h( 'h3', null, __( 'Uploads audit — review only', 'rapid-media-reclaim' ) ), h( 'p', null, __( 'This best-effort walk excludes known caches, backups, protected plugin downloads and symlinks. Files may change during the walk. Audit categories never authorize removal. Supported files can begin a separate backup and fresh-review workflow.', 'rapid-media-reclaim' ) ), h( 'div', { class: 'smc-tools__actions' }, category, extension, h( 'label', null, __( 'Minimum bytes', 'rapid-media-reclaim' ), minimum ), apply, csv ), note, list, next );
     1528                        await page( true );
     1529                };
     1530                const visualSelect = h( 'select', { class: 'smc-select', 'aria-label': __( 'Saved visual searches', 'rapid-media-reclaim' ) }, h( 'option', { value: '' }, __( 'Choose a visual search', 'rapid-media-reclaim' ) ) );
     1531                const visualStatus = h( 'p', { role: 'status', 'aria-live': 'polite' } );
     1532                const rememberVisual = ( job ) => {
     1533                        if ( job.kind !== 'similarity' ) { return; }
     1534                        toolJobs.set( 'similarity:' + job.token, job );
     1535                        let option = Array.from( visualSelect.options ).find( ( item ) => item.value === job.token );
     1536                        if ( ! option ) { option = h( 'option', { value: job.token } ); visualSelect.appendChild( option ); }
     1537                        const status = job.status === 'cancelled' ? __( 'Cancelled', 'rapid-media-reclaim' ) : job.status === 'done' ? __( 'Finished', 'rapid-media-reclaim' ) : __( 'Paused or running', 'rapid-media-reclaim' );
     1538                        option.textContent = new Date( job.created * 1000 ).toLocaleString() + ' · ' + status + ' · ' + num( job.processed ); visualSelect.value = job.token;
     1539                };
     1540                const showVisualResults = async ( job ) => {
     1541                        const list = h( 'div' ); const note = h( 'p', { role: 'status', 'aria-live': 'polite' } );
     1542                        const view = h( 'select', { class: 'smc-select', 'aria-label': __( 'Visual results view', 'rapid-media-reclaim' ) }, h( 'option', { value: 'pairs' }, __( 'Review suggestions', 'rapid-media-reclaim' ) ), h( 'option', { value: 'skipped' }, __( 'Skipped images', 'rapid-media-reclaim' ) ) );
     1543                        let after = 0; let busy = false;
     1544                        const page = async ( reset = false ) => {
     1545                                if ( busy || ! active || ! list.isConnected ) { return; }
     1546                                busy = true; next.disabled = true; view.disabled = true;
     1547                                try {
     1548                                        const result = await api.get( '/tools/discover-results', { token: job.token, after: reset ? 0 : after, view: view.value } );
     1549                                        if ( ! active || ! list.isConnected ) { return; }
     1550                                        after = result.next; next.hidden = ! result.has_more;
     1551                                        const coverage = result.job.visual || {};
     1552                                        note.textContent = sprintf( /* translators: 1: checked images, 2: skipped images, 3: suggestions */ __( '%1$s images checked; %2$s skipped; %3$s suggestions saved.', 'rapid-media-reclaim' ), num( result.job.processed ), num( result.job.skipped ), num( coverage.pairs || 0 ) ) + ' ' + ( coverage.complete ? __( 'Search finished within its criteria. Suggestions still need human review.', 'rapid-media-reclaim' ) : __( 'Coverage is partial: the search may be paused, cancelled, skipped images or reached a limit. Matching images may be missing.', 'rapid-media-reclaim' ) );
     1553                                        replace( list, ...result.rows.map( ( saved ) => {
     1554                                                const row = saved.item;
     1555                                                if ( row.type !== 'visual_pair' ) { return h( 'p', null, '#' + row.attachment_id + ' · ' + __( 'This image could not be compared within the local permissions, format or resource limits.', 'rapid-media-reclaim' ), h( 'small', null, ' (' + row.reason + ')' ) ); }
     1556                                                const member = ( item ) => h( 'div', null, item.preview_url ? h( 'img', { src: safeHref( item.preview_url ), alt: item.path, loading: 'lazy', width: 120, height: 90, style: 'object-fit:contain;max-width:100%;' } ) : null, h( 'p', null, h( 'a', { href: safeHref( item.edit_url ), target: '_blank', rel: 'noopener noreferrer' }, '#' + item.id + ' · ' + item.path ) ) );
     1557                                                return h( 'section', { class: 'smc-recovery' }, h( 'div', { class: 'smc-tools__actions' }, member( row.first ), member( row.second ) ), h( 'p', null, sprintf( /* translators: %s: difference score out of 64 */ __( 'Visual difference score: %s / 64. Lower scores suggest closer appearance, not identical files.', 'rapid-media-reclaim' ), num( row.distance.hamming ) ) ) );
     1558                                        } ) );
     1559                                        if ( ! result.rows.length ) { list.appendChild( h( 'p', null, __( 'No results in this page. This does not establish that any media is unused.', 'rapid-media-reclaim' ) ) ); }
     1560                                } catch ( error ) { note.textContent = taskError( error ); }
     1561                                finally { busy = false; next.disabled = false; view.disabled = false; }
     1562                        };
     1563                        view.addEventListener( 'change', () => page( true ) );
     1564                        const next = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: () => page() }, __( 'Next visual results page', 'rapid-media-reclaim' ) );
     1565                        replace( output, h( 'h3', null, __( 'Visually similar images — review only', 'rapid-media-reclaim' ) ), h( 'p', null, __( 'These are captured visual suggestions, not exact duplicates. Re-encoded or resized images can differ in quality and metadata. Media may change during or after the search. Review originals before acting; visual suggestions never authorize merging or deletion.', 'rapid-media-reclaim' ) ), view, note, list, next );
     1566                        await page( true );
     1567                };
     1568                let discoveryBusy = false;
     1569                const discover = async ( kind, fresh = false ) => {
     1570                        if ( discoveryBusy ) { throw new Error( __( 'An audit is already running here. Wait, cancel it or close Tools to pause it.', 'rapid-media-reclaim' ) ); }
     1571                        discoveryBusy = true;
     1572                        try {
     1573                        let job = ( ! fresh && ( kind === 'uploads' ? toolJobs.get( 'uploads:' + uploadSelect.value ) : kind === 'similarity' ? toolJobs.get( 'similarity:' + visualSelect.value ) : toolJobs.get( kind ) ) ) || await api.post( '/tools/discover', { kind } );
     1574                        if ( kind === 'uploads' ) { rememberUpload( job ); }
     1575                        if ( kind === 'similarity' ) { rememberVisual( job ); }
     1576                        toolJobs.set( kind, job );
     1577                        while ( active && job.status === 'running' ) {
     1578                                if ( kind === 'similarity' ) { progress.textContent = sprintf( /* translators: 1: images checked, 2: signatures compared */ __( 'Local visual search: %1$s images checked; %2$s signatures compared. Closing pauses this task.', 'rapid-media-reclaim' ), num( job.processed ), num( ( job.visual || {} ).compared || 0 ) ); } else { progress.textContent = sprintf( /* translators: %s: processed file count */ __( 'Read-only discovery: %s files checked. Closing pauses this task.', 'rapid-media-reclaim' ), num( job.processed ) ); }
     1579                                job = await api.post( '/tools/discover-step', { token: job.token } );
     1580                                toolJobs.set( kind, job );
     1581                                if ( kind === 'uploads' ) { rememberUpload( job ); }
     1582                        if ( kind === 'similarity' ) { rememberVisual( job ); }
     1583                        }
     1584                        if ( ! active ) { return; }
     1585                        if ( kind === 'similarity' ) { visualStatus.textContent = __( 'Visual search saved. Review suggestions and coverage below.', 'rapid-media-reclaim' ); progress.textContent = visualStatus.textContent; await showVisualResults( job ); return; }
     1586                        if ( kind === 'uploads' ) { uploadStatus.textContent = sprintf( /* translators: 1: files, 2: skipped entries */ __( 'Audit saved: %1$s files; %2$s skipped entries. Results expire after 24 hours.', 'rapid-media-reclaim' ), num( job.processed ), num( job.skipped || 0 ) ); progress.textContent = uploadStatus.textContent; await showUploadResults( job ); return; }
     1587                        const result = await api.get( '/tools/discover-results', { token: job.token } );
     1588                        const rows = result.rows || [];
     1589                        progress.textContent = sprintf( /* translators: 1: processed files, 2: skipped entries */ __( 'Checked %1$s files; %2$s entries skipped. Results are for review only. Showing the first 100 rows.', 'rapid-media-reclaim' ), num( job.processed ), num( job.skipped || 0 ) );
     1590                        const lines = rows.map( ( row ) => h( 'li', null, ( row.item.path || '#' + row.item.attachment_id ) + ' — ' + ( row.item.reason || row.item.sha256 || __( 'Ownership review required', 'rapid-media-reclaim' ) ) ) );
     1591                        replace( output, h( 'p', null, sprintf( /* translators: %s: number of duplicate groups */ __( 'Exact duplicate groups found: %s. Shared attachment paths count as one file.', 'rapid-media-reclaim' ), num( ( result.duplicate_groups || [] ).length ) ) ), h( 'ul', null, ...lines ) );
     1592                        } finally { discoveryBusy = false; }
     1593                };
     1594                run( __( 'Find exact duplicates', 'rapid-media-reclaim' ), () => discover( 'duplicates' ) );
     1595                run( __( 'Find visually similar images', 'rapid-media-reclaim' ), () => discover( 'similarity', true ) );
     1596                run( __( 'Compare selected images', 'rapid-media-reclaim' ), async () => {
     1597                        const ids = Array.from( state.selection.keys() );
     1598                        if ( ! ids.length || ids.length > 10 ) { throw new Error( __( 'Select up to ten images before opening Tools.', 'rapid-media-reclaim' ) ); }
     1599                        const result = await api.post( '/tools/visual', { ids } );
     1600                        progress.textContent = __( 'Visual signatures are suggestions only. They never authorize a merge.', 'rapid-media-reclaim' );
     1601                        replace( output, h( 'pre', null, JSON.stringify( result.rows, null, 2 ) ) );
     1602                } );
     1603                run( __( 'Preview selected reference merge', 'rapid-media-reclaim' ), async () => {
     1604                        const ids = Array.from( state.selection.keys() );
     1605                        if ( ids.length < 2 || ids.length > 11 ) { throw new Error( __( 'Select a canonical attachment and up to ten exact duplicates first.', 'rapid-media-reclaim' ) ); }
     1606                        const canonicalInput = h( 'select', { class: 'smc-select' }, ...ids.map( ( id ) => { const item = state.list && state.list.items && state.list.items.find( ( item ) => item.id === id ); return h( 'option', { value: String( id ) }, '#' + id + ( item ? ' · ' + displayName( item ) : '' ) ); } ) );
     1607                        const chosen = await SMC.dialog( { title: __( 'Choose the attachment to keep', 'rapid-media-reclaim' ), body: h( 'div', null, h( 'p', null, __( 'This rewrites supported references only. Original attachments and files are retained. Unsupported sources block the operation; generated builder caches and retirement require separate review.', 'rapid-media-reclaim' ) ), canonicalInput ), buttons: [ { label: __( 'Build read-only preview', 'rapid-media-reclaim' ), value: 'preview', variant: 'primary' } ] } );
     1608                        if ( ! chosen ) { return; }
     1609                        const canonical = Number( canonicalInput.value );
     1610                        const retired = ids.filter( ( id ) => id !== canonical );
     1611                        const preview = await api.post( '/tools/merge-preview', { canonical, retired } );
     1612                        const blocked = preview.blocked || [];
     1613                        progress.textContent = sprintf( /* translators: 1: supported source writes, 2: unsupported references */ __( 'Preview: %1$s supported source writes, %2$s unsupported references. No files will be removed.', 'rapid-media-reclaim' ), num( preview.writes.length ), num( blocked.length ) );
     1614                        const lines = preview.writes.map( ( write ) => h( 'li', null, h( 'details', null, h( 'summary', null, '#' + write.id + ' · ' + write.kind + ( write.key ? ' · ' + write.key : '' ) ), h( 'p', null, __( 'Before', 'rapid-media-reclaim' ) ), h( 'pre', null, typeof write.before === 'string' ? write.before : JSON.stringify( write.before, null, 2 ) ), h( 'p', null, __( 'After', 'rapid-media-reclaim' ) ), h( 'pre', null, typeof write.after === 'string' ? write.after : JSON.stringify( write.after, null, 2 ) ) ) ) );
     1615                        if ( blocked.length || ! lines.length ) { replace( output, h( 'ul', null, ...lines ), h( 'p', null, __( 'The operation is blocked. Unsupported or missing writers must be resolved before any changes.', 'rapid-media-reclaim' ) ) ); return; }
     1616                        const confirmed = await SMC.dialog( { title: __( 'Apply these reference changes?', 'rapid-media-reclaim' ), body: h( 'div', null, h( 'ul', null, ...lines ), h( 'p', null, __( 'A recovery journal retains the original source values. Later editor changes are preserved as conflicts during rollback. The original files stay in place.', 'rapid-media-reclaim' ) ) ), confirmCheck: __( 'I reviewed the canonical attachment and these source changes.', 'rapid-media-reclaim' ), buttons: [ { label: __( 'Apply reference changes', 'rapid-media-reclaim' ), value: 'apply', variant: 'primary' } ] } );
     1617                        if ( ! confirmed ) { return; }
     1618                        let job = await api.post( '/tools/merge-start', { canonical, retired, digest: preview.digest } );
     1619                        rememberMerge( job );
     1620                        while ( active && job.status === 'applying' ) { job = await api.post( '/tools/merge-step', { token: job.token } ); rememberMerge( job ); progress.textContent = sprintf( /* translators: 1: completed source writes, 2: total source writes */ __( 'Reference changes: %1$s of %2$s sources.', 'rapid-media-reclaim' ), num( job.cursor ), num( job.sources ) ); }
     1621                        replace( output, h( 'p', null, __( 'Reference job saved. Original files are retained. Roll back from Tools if needed; complete a fresh scan and cache review before considering retirement.', 'rapid-media-reclaim' ) ) );
     1622                } );
     1623                run( __( 'Roll back last reference merge', 'rapid-media-reclaim' ), async () => {
     1624                        let job = toolJobs.get( 'merge' );
     1625                        if ( ! job && ! mergeSelect.value ) { throw new Error( __( 'There is no reference job to roll back.', 'rapid-media-reclaim' ) ); }
     1626                        if ( mergeSelect.value ) { job = { token: mergeSelect.value }; }
     1627                        const confirmed = await SMC.dialog( { title: __( 'Roll back reference changes?', 'rapid-media-reclaim' ), body: h( 'p', null, __( 'Only sources that still match the saved written values can be restored. Later editor changes will be preserved and reported as conflicts.', 'rapid-media-reclaim' ) ), buttons: [ { label: __( 'Roll back', 'rapid-media-reclaim' ), value: 'rollback', variant: 'primary' } ] } );
     1628                        if ( ! confirmed ) { return; }
     1629                        do { job = await api.post( '/tools/merge-rollback', { token: job.token } ); rememberMerge( job ); } while ( active && job.status === 'rolling_back' );
     1630                        progress.textContent = __( 'Reference rollback saved. Quarantined duplicates were restored first; later editor changes remain protected.', 'rapid-media-reclaim' );
     1631                        await api.get( '/summary' ).then( ( data ) => applySummary( data.summary ) ).catch( () => {} );
     1632                        invalidate();
     1633                } );
     1634
     1635                run( __( 'Regenerate merge caches', 'rapid-media-reclaim' ), async () => {
     1636                        let job = toolJobs.get( 'merge' );
     1637                        if ( mergeSelect.value ) { job = { token: mergeSelect.value }; }
     1638                        if ( ! job ) { throw new Error( __( 'Select a completed reference job first.', 'rapid-media-reclaim' ) ); }
     1639                        job = await api.post( '/tools/merge-cache-start', { token: job.token } );
     1640                        rememberMerge( job );
     1641                        while ( active && job.cache.status === 'running' ) {
     1642                                job = await api.post( '/tools/merge-cache-step', { token: job.token } );
     1643                                rememberMerge( job );
     1644                                progress.textContent = sprintf( /* translators: 1: attempted posts, 2: affected posts */ __( 'Cache generation: %1$s of %2$s posts.', 'rapid-media-reclaim' ), num( job.cache.cursor ), num( job.cache.tasks.length ) );
     1645                        }
     1646                        replace( output, h( 'p', null, job.cache.status === 'not_required' ? __( 'This reference job has no builder caches to regenerate. Original files remain protected.', 'rapid-media-reclaim' ) : job.cache.status === 'regenerated' ? __( 'Supported cache assets regenerated. Review the public pages and run a fresh scan. Original files remain protected. Duplicate quarantine requires a separate saved-backup confirmation.', 'rapid-media-reclaim' ) : __( 'Some caches need manual review. You can retry after resolving the builder or source issue. Reference changes and recovery journals are retained.', 'rapid-media-reclaim' ) ) );
     1647                } );
     1648
     1649                const retirementJob = () => {
     1650                        const job = mergeSelect.value ? { token: mergeSelect.value } : toolJobs.get( 'merge' );
     1651                        if ( ! job ) { throw new Error( __( 'Select a completed reference job first.', 'rapid-media-reclaim' ) ); }
     1652                        return job;
     1653                };
     1654                run( __( 'Prepare duplicate quarantine and rescan', 'rapid-media-reclaim' ), async () => {
     1655                        const job = retirementJob();
     1656                        await api.post( '/tools/merge-retire-prepare', { token: job.token } );
     1657                        progress.textContent = __( 'Preparing a fresh usage scan. No files are being moved.', 'rapid-media-reclaim' );
     1658                        await SMC.sleep( 1100 );
     1659                        if ( ! active ) { return; }
     1660                        let res = await api.post( '/scan' );
     1661                        while ( active && res.scan.status === 'running' ) {
     1662                                res = await api.post( '/scan/step' );
     1663                                progress.textContent = sprintf( /* translators: %s: scan percentage */ __( 'Checking duplicate usage: %s%%.', 'rapid-media-reclaim' ), num( res.scan.percent ) );
     1664                        }
     1665                        state.scan = res.scan;
     1666                        if ( ! active ) { return; }
     1667                        if ( res.scan.status !== 'done' ) { throw new Error( __( 'Complete a fresh scan before backing up duplicates.', 'rapid-media-reclaim' ) ); }
     1668                        invalidate();
     1669                        replace( output, h( 'p', null, __( 'Fresh scan complete. Next use “Back up merged duplicates”, download the ZIP and review the published pages and relevant caches before confirming quarantine.', 'rapid-media-reclaim' ) ) );
     1670                } );
     1671                run( __( 'Back up merged duplicates', 'rapid-media-reclaim' ), async () => {
     1672                        const job = retirementJob();
     1673                        const prepared = await api.post( '/tools/merge-retire-backup', { token: job.token } );
     1674                        let backup = prepared.export;
     1675                        while ( active && backup.status !== 'ready' ) {
     1676                                progress.textContent = sprintf( /* translators: 1: completed files, 2: total files */ __( 'Building duplicate backup: %1$s of %2$s files.', 'rapid-media-reclaim' ), num( backup.completed ), num( backup.total ) );
     1677                                backup = await api.post( '/tools/export-step', { token: backup.token } );
     1678                        }
     1679                        if ( ! active ) { return; }
     1680                        const saved = h( 'input', { type: 'checkbox' } );
     1681                        const reviewed = h( 'input', { type: 'checkbox' } );
     1682                        const move = h( 'button', { type: 'button', class: 'smc-btn smc-btn--primary', disabled: true, onClick: async () => {
     1683                                move.disabled = true;
     1684                                try {
     1685                                        await api.post( '/tools/export-confirm', { token: backup.token, saved_backup: true } );
     1686                                        const confirmed = await SMC.dialog( { title: __( 'Quarantine merged duplicates?', 'rapid-media-reclaim' ), body: h( 'p', null, __( 'Only this job’s duplicate files will move to protected quarantine. The canonical media stays live. Rollback restores these files before restoring references. Permanent deletion remains blocked by the recovery journal.', 'rapid-media-reclaim' ) ), buttons: [ { label: __( 'Move duplicates to quarantine', 'rapid-media-reclaim' ), value: 'quarantine', variant: 'primary' } ] } );
     1687                                        if ( ! confirmed ) { return; }
     1688                                        const result = await api.post( '/tools/merge-retire', { token: job.token, confirmed: true } );
     1689                                        progress.textContent = result.status === 'quarantined' ? __( 'Duplicates moved to quarantine. Use reference rollback to restore files before restoring their references. No media was permanently deleted.', 'rapid-media-reclaim' ) : __( 'Quarantine needs recovery review. Files were restored where possible and the journal was retained. Use reference rollback to resolve the operation.', 'rapid-media-reclaim' );
     1690                                        await api.get( '/summary' ).then( ( data ) => applySummary( data.summary ) ).catch( () => {} );
     1691                                        invalidate();
     1692                                        replace( output, h( 'p', null, progress.textContent ) );
     1693                                } catch ( error ) { progress.textContent = taskError( error ); }
     1694                                finally { move.disabled = ! saved.checked || ! reviewed.checked; }
     1695                        } }, __( 'Confirm backup and quarantine duplicates', 'rapid-media-reclaim' ) );
     1696                        const enable = () => { move.disabled = ! saved.checked || ! reviewed.checked; };
     1697                        saved.addEventListener( 'change', enable ); reviewed.addEventListener( 'change', enable );
     1698                        progress.textContent = __( 'Backup verified. Download and save it before confirming; an archive left on this server expires after 24 hours.', 'rapid-media-reclaim' );
     1699                        replace( output, h( 'a', { class: 'smc-btn smc-btn--secondary', href: safeHref( backup.download_url ), target: '_blank', rel: 'noopener noreferrer' }, __( 'Download duplicate recovery ZIP', 'rapid-media-reclaim' ) ), h( 'p', null, h( 'label', null, saved, ' ', __( 'I downloaded and saved this recovery backup.', 'rapid-media-reclaim' ) ) ), h( 'p', null, h( 'label', null, reviewed, ' ', __( 'I reviewed the published pages and cleared relevant page and CDN caches.', 'rapid-media-reclaim' ) ) ), move );
     1700                } );
     1701
     1702                run( __( 'Start a new uploads audit', 'rapid-media-reclaim' ), () => discover( 'uploads', true ) );
     1703                const resumeUpload = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: async () => { if ( ! uploadSelect.value ) { return; } resumeUpload.disabled = true; try { await discover( 'uploads' ); } catch ( error ) { uploadStatus.textContent = taskError( error ); } finally { resumeUpload.disabled = false; } } }, __( 'Resume or browse audit', 'rapid-media-reclaim' ) );
     1704                const cancelUpload = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: async () => { if ( ! uploadSelect.value ) { return; } cancelUpload.disabled = true; try { const job = await api.post( '/tools/discover-cancel', { token: uploadSelect.value } ); rememberUpload( job ); toolJobs.set( 'uploads', job ); uploadStatus.textContent = __( 'Audit stopped. Saved results remain available until expiry. No media files changed.', 'rapid-media-reclaim' ); } catch ( error ) { uploadStatus.textContent = taskError( error ); } finally { cancelUpload.disabled = false; } } }, __( 'Cancel selected audit', 'rapid-media-reclaim' ) );
     1705                const resumeVisual = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: async () => { if ( ! visualSelect.value ) { return; } resumeVisual.disabled = true; try { await discover( 'similarity' ); } catch ( error ) { visualStatus.textContent = taskError( error ); } finally { resumeVisual.disabled = false; } } }, __( 'Resume or browse visual search', 'rapid-media-reclaim' ) );
     1706                const cancelVisual = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: async () => { if ( ! visualSelect.value ) { return; } cancelVisual.disabled = true; try { rememberVisual( await api.post( '/tools/discover-cancel', { token: visualSelect.value } ) ); visualStatus.textContent = __( 'Visual search stopped. Saved suggestions remain available until expiry. No media was changed.', 'rapid-media-reclaim' ); } catch ( error ) { visualStatus.textContent = taskError( error ); } finally { cancelVisual.disabled = false; } } }, __( 'Cancel selected visual search', 'rapid-media-reclaim' ) );
     1707                const visualJobs = h( 'section', { class: 'smc-recovery' }, h( 'h3', null, __( 'Saved visual searches', 'rapid-media-reclaim' ) ), h( 'div', { class: 'smc-tools__actions' }, visualSelect, resumeVisual, cancelVisual ), visualStatus );
     1708                const uploads = h( 'section', { class: 'smc-recovery' }, h( 'h3', null, __( 'Saved uploads audits', 'rapid-media-reclaim' ) ), h( 'div', { class: 'smc-tools__actions' }, uploadSelect, resumeUpload, cancelUpload ), uploadStatus );
     1709                api.get( '/tools/discover-jobs' ).then( ( result ) => { if ( ! active ) { return; } result.jobs.slice().reverse().forEach( ( job ) => { rememberUpload( job ); rememberVisual( job ); } ); if ( result.limited ) { uploadStatus.textContent = visualStatus.textContent = __( 'Only recent jobs are listed. Saved task tokens still work in WP-CLI until expiry.', 'rapid-media-reclaim' ); } } ).catch( ( error ) => { uploadStatus.textContent = taskError( error ); } );
     1710                run( __( 'Test request routing', 'rapid-media-reclaim' ), async () => {
     1711                        progress.textContent = __( 'Testing one missing-upload route…', 'rapid-media-reclaim' );
     1712                        const result = await api.post( '/tools/probe', {} );
     1713                        showObservation( result );
     1714                        progress.textContent = result.mode === 'verified-PHP' ? __( 'Routing check succeeded. The verification period is separate from quarantine age.', 'rapid-media-reclaim' ) : __( 'Routing was not verified. Review the status and hosting examples.', 'rapid-media-reclaim' );
     1715                } );
     1716                run( __( 'Export selected quarantine', 'rapid-media-reclaim' ), async () => {
     1717                        const ids = Array.from( state.selection ).filter( ( entry ) => entry[1].status === 'quarantined' ).map( ( entry ) => entry[0] );
     1718                        if ( ! ids.length || ids.length > 100 ) { throw new Error( __( 'Select between 1 and 100 quarantined media items, including their shared copies, before opening Tools.', 'rapid-media-reclaim' ) ); }
     1719                        const selectionKey = 'export:' + ids.slice().sort( ( a, b ) => a - b ).join( ',' );
     1720                        exportJob = toolJobs.get( selectionKey ) || await api.post( '/tools/export', { ids } );
     1721                        toolJobs.set( selectionKey, exportJob );
     1722                        while ( active && exportJob.status !== 'ready' ) {
     1723                                progress.textContent = sprintf( /* translators: 1: export phase, 2: completed files, 3: total files */ __( 'Recovery export: %1$s, %2$s of %3$s files. Closing pauses this task.', 'rapid-media-reclaim' ), exportJob.status, num( exportJob.completed ), num( exportJob.total ) );
     1724                                exportJob = await api.post( '/tools/export-step', { token: exportJob.token } );
     1725                                toolJobs.set( selectionKey, exportJob );
     1726                        }
     1727                        if ( ! active ) { return; }
     1728                        progress.textContent = __( 'Archive checksums verified. Download it and confirm you have saved the backup. The private download expires in 24 hours.', 'rapid-media-reclaim' );
     1729                        const link = h( 'a', { class: 'smc-btn smc-btn--primary', href: safeHref( exportJob.download_url ), target: '_blank', rel: 'noopener noreferrer' }, __( 'Download recovery ZIP', 'rapid-media-reclaim' ) );
     1730                        const saved = h( 'input', { type: 'checkbox' } );
     1731                        const confirm = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', disabled: true, onClick: async () => {
     1732                                try {
     1733                                        await api.post( '/tools/export-confirm', { token: exportJob.token, saved_backup: true } );
     1734                                        progress.textContent = __( 'Saved backup confirmed. The minimum waiting period and all usage checks still apply.', 'rapid-media-reclaim' );
     1735                                        confirm.disabled = true;
     1736                                } catch ( error ) { progress.textContent = error.message; }
     1737                        } }, __( 'Confirm saved backup', 'rapid-media-reclaim' ) );
     1738                        saved.addEventListener( 'change', () => { confirm.disabled = ! saved.checked; } );
     1739                        replace( output, link, h( 'p', null, h( 'label', null, saved, ' ', __( 'I downloaded and saved this recovery backup.', 'rapid-media-reclaim' ) ) ), confirm );
     1740                } );
     1741                const importSelect = h( 'select', { class: 'smc-select', 'aria-label': __( 'Saved backup recovery', 'rapid-media-reclaim' ) } );
     1742                const archiveInput = h( 'input', { type: 'file', accept: '.zip,application/zip', 'aria-label': __( 'Recovery ZIP', 'rapid-media-reclaim' ) } );
     1743                const recoveryOutput = h( 'div', { class: 'smc-recovery__preview' } );
     1744                const recoveryProgress = h( 'p', { role: 'status', 'aria-live': 'polite' } );
     1745                const phases = {
     1746                        verifying: __( 'Verifying files', 'rapid-media-reclaim' ),
     1747                        attachments: __( 'Recovering attachment records', 'rapid-media-reclaim' ),
     1748                        registering: __( 'Saving recovery records', 'rapid-media-reclaim' ),
     1749                        copying: __( 'Preparing verified files', 'rapid-media-reclaim' ),
     1750                        restoring: __( 'Restoring media', 'rapid-media-reclaim' ),
     1751                };
     1752                const rememberImport = ( job ) => {
     1753                        toolJobs.set( 'import:' + job.token, job );
     1754                        let option = Array.from( importSelect.options ).find( ( entry ) => entry.value === job.token );
     1755                        if ( ! option ) { option = h( 'option', { value: job.token } ); importSelect.appendChild( option ); }
     1756                        const labels = { verifying: __( 'Verification paused', 'rapid-media-reclaim' ), preview: __( 'Ready to preview', 'rapid-media-reclaim' ), restoring: __( 'Recovery paused', 'rapid-media-reclaim' ), done: __( 'Recovery complete', 'rapid-media-reclaim' ), review: __( 'Manual review needed', 'rapid-media-reclaim' ), rejected: __( 'Unsupported backup', 'rapid-media-reclaim' ), receiving: __( 'Upload incomplete', 'rapid-media-reclaim' ) };
     1757                        option.textContent = sprintf( /* translators: 1: saved recovery number, 2: status, 3: number of media items */ __( 'Backup %1$s · %2$s · %3$s items', 'rapid-media-reclaim' ), num( Array.from( importSelect.options ).indexOf( option ) + 1 ), labels[ job.status ] || __( 'Review needed', 'rapid-media-reclaim' ), num( job.items ) );
     1758                        importSelect.value = job.token;
     1759                };
     1760                const advanceImport = async ( job ) => {
     1761                        rememberImport( job );
     1762                        while ( active && ( job.status === 'verifying' || job.status === 'restoring' ) ) {
     1763                                recoveryProgress.textContent = sprintf( /* translators: 1: recovery phase, 2: completed entries, 3: total entries */ __( '%1$s: %2$s of %3$s. Closing pauses this task; resume here after reloading.', 'rapid-media-reclaim' ), phases[ job.phase ] || phases.verifying, num( job.completed ), num( job.total ) );
     1764                                job = await api.post( '/tools/import-step', { token: job.token } );
     1765                                rememberImport( job );
     1766                        }
     1767                        if ( ! active ) { return; }
     1768                        if ( job.status === 'done' ) {
     1769                                recoveryProgress.textContent = __( 'Recovery complete. Original IDs, file bytes and supported core fields were verified. Existing associations and alt text were preserved; recreated records use verified original contexts. Plugin-specific and taxonomy metadata are not restored. Run a fresh scan.', 'rapid-media-reclaim' );
     1770                                return;
     1771                        }
     1772                        if ( job.status === 'review' ) {
     1773                                if ( job.review_reason === 'preparation' ) { recoveryProgress.textContent = __( 'Recovery preparation needs manual review after an interruption. Your backup and existing media are preserved. Ask your site administrator to review this recovery before continuing.', 'rapid-media-reclaim' ); return; }
     1774                                recoveryProgress.textContent = sprintf( /* translators: %s: unexpected attachment ID */ __( 'An attachment ID was taken during recovery. Review attachment #%s with your site administrator. Files and recovery records were retained.', 'rapid-media-reclaim' ), num( job.review_id ) );
     1775                                return;
     1776                        }
     1777                        if ( job.status !== 'preview' ) { throw new Error( __( 'This upload cannot be restored. Upload a complete supported backup.', 'rapid-media-reclaim' ) ); }
     1778                        const preview = await api.post( '/tools/import-preview', { token: job.token } );
     1779                        const stateLabels = { missing: __( 'Will restore', 'rapid-media-reclaim' ), identical: __( 'Identical file already present', 'rapid-media-reclaim' ), conflict: __( 'Conflict: current file will be kept', 'rapid-media-reclaim' ) };
     1780                        const items = preview.items.map( ( item ) => h( 'li', null, h( 'strong', null, item.title || '#' + item.id ), h( 'p', null, '#' + item.id + ' · ' + item.file + ' · ' + item.mime ), h( 'p', null, item.conflict || ( item.missing ? __( 'Recreate the original attachment ID', 'rapid-media-reclaim' ) : __( 'Repair matching existing attachment', 'rapid-media-reclaim' ) ) ), h( 'p', null, sprintf( /* translators: 1: image width, 2: image height, 3: number of image sizes */ __( 'Metadata: %1$s × %2$s; %3$s sizes.', 'rapid-media-reclaim' ), num( item.width ), num( item.height ), num( item.sizes ) ) ), h( 'p', null, sprintf( /* translators: %s: number of saved edit backups */ __( 'Saved edit backups: %s.', 'rapid-media-reclaim' ), num( item.backups ) ) ), item.owner_id ? h( 'p', null, sprintf( /* translators: %s: shared file owner attachment ID */ __( 'Shared files with attachment #%s.', 'rapid-media-reclaim' ), num( item.owner_id ) ) ) : null ) );
     1781                        const files = preview.files.map( ( file ) => h( 'li', null, file.name + ' · ' + bytes( file.bytes ) + ' · ' + stateLabels[ file.state ] ) );
     1782                        replace( recoveryOutput, h( 'h4', null, __( 'Read-only recovery preview', 'rapid-media-reclaim' ) ), h( 'p', null, __( 'Recovery covers file bytes, core file metadata and supported attachment fields. New backups also preserve original parent, author and alt text for recreated records. Existing records keep their current associations and alt text. Plugin-specific metadata and taxonomies are unsupported. This is not a full site backup.', 'rapid-media-reclaim' ) ), h( 'ul', null, ...items ), h( 'details', null, h( 'summary', null, __( 'Files and current destinations', 'rapid-media-reclaim' ) ), h( 'ul', null, ...files ) ), h( 'ul', { class: 'smc-recovery__conflicts' }, ...preview.conflicts.map( ( conflict ) => h( 'li', null, conflict ) ) ) );
     1783                        recoveryProgress.textContent = preview.conflicts.length ? __( 'Resolve these conflicts, then refresh the preview. Current files and records are preserved.', 'rapid-media-reclaim' ) : __( 'Preview verified. Nothing has been restored yet. Review the files and attachment IDs before confirming.', 'rapid-media-reclaim' );
     1784                        if ( preview.conflicts.length ) { return; }
     1785                        const confirm = h( 'button', { type: 'button', class: 'smc-btn smc-btn--primary', onClick: async () => {
     1786                                confirm.disabled = true;
     1787                                try {
     1788                                        const adoption = h( 'input', { type: 'checkbox' } );
     1789                                        const confirmed = await SMC.dialog( { title: __( 'Restore this trusted backup?', 'rapid-media-reclaim' ), body: h( 'div', null, h( 'p', null, __( 'Only restore a backup you created and trust. Checksums verify file consistency, not its creator. Existing files are never replaced. Recovery keeps the original attachment IDs and does not delete media.', 'rapid-media-reclaim' ) ), preview.adoption_required ? h( 'p', null, h( 'label', null, adoption, ' ', __( 'This is a reinstall of the same site. Adopt the backup identity for this matching site address.', 'rapid-media-reclaim' ) ) ) : null, h( 'p', null, __( 'Files are prepared in protected Quarantine storage. Nginx needs the documented access rules from your host; the ZIP itself remains outside public web storage.', 'rapid-media-reclaim' ) ) ), confirmCheck: __( 'I reviewed this preview and confirm this is my trusted recovery backup.', 'rapid-media-reclaim' ), buttons: [ { label: __( 'Confirm and restore', 'rapid-media-reclaim' ), value: 'restore', variant: 'primary' } ] } );
     1790                                        if ( ! confirmed ) { return; }
     1791                                        if ( preview.adoption_required && ! adoption.checked ) { throw new Error( __( 'Confirm same-site backup identity adoption before restoring.', 'rapid-media-reclaim' ) ); }
     1792                                        const started = await api.post( '/tools/import-confirm', { token: job.token, digest: preview.digest, trusted_backup: true, adopt_site: adoption.checked } );
     1793                                        clear( recoveryOutput );
     1794                                        await advanceImport( started );
     1795                                } catch ( error ) { recoveryProgress.textContent = error.message; }
     1796                                finally { confirm.disabled = false; }
     1797                        } }, __( 'Review and confirm recovery', 'rapid-media-reclaim' ) );
     1798                        recoveryOutput.appendChild( confirm );
     1799                };
     1800                const importAction = ( label, action ) => h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: async ( event ) => {
     1801                        const button = event.currentTarget; button.disabled = true;
     1802                        try { await action(); } catch ( error ) { recoveryProgress.textContent = error.message || __( 'Recovery paused. Resolve the problem and resume this saved backup.', 'rapid-media-reclaim' ); }
     1803                        finally { button.disabled = false; }
     1804                } }, label );
     1805                const uploadButton = importAction( __( 'Upload and verify ZIP', 'rapid-media-reclaim' ), async () => {
     1806                        if ( ! archiveInput.files || archiveInput.files.length !== 1 ) { throw new Error( __( 'Choose one recovery ZIP first.', 'rapid-media-reclaim' ) ); }
     1807                        const data = new FormData(); data.append( 'archive', archiveInput.files[ 0 ] );
     1808                        recoveryProgress.textContent = __( 'Uploading to private recovery storage…', 'rapid-media-reclaim' );
     1809                        const job = await wp.apiFetch( { path: ( boot.restPath || '/rapid-media-reclaim/v1' ) + '/tools/import-upload', method: 'POST', body: data } );
     1810                        archiveInput.value = '';
     1811                        await advanceImport( job );
     1812                } );
     1813                const resumeButton = importAction( __( 'Resume or refresh preview', 'rapid-media-reclaim' ), async () => {
     1814                        const job = toolJobs.get( 'import:' + importSelect.value );
     1815                        if ( ! job ) { throw new Error( __( 'Upload a backup or choose a saved recovery first.', 'rapid-media-reclaim' ) ); }
     1816                        await advanceImport( job );
     1817                } );
     1818                const recovery = h( 'section', { class: 'smc-recovery', 'aria-label': __( 'Recover from a backup ZIP', 'rapid-media-reclaim' ) }, h( 'h3', null, __( 'Recover from a backup ZIP', 'rapid-media-reclaim' ) ), h( 'p', null, __( 'Upload → verify → preview → confirm → restore. Idle previews expire after 24 hours. Confirmed recovery remains available after closing or reloading.', 'rapid-media-reclaim' ) ), archiveInput, h( 'div', { class: 'smc-tools__actions' }, uploadButton, importSelect, resumeButton ), recoveryProgress, recoveryOutput );
     1819                api.get( '/tools/import-jobs' ).then( ( jobs ) => { if ( active ) { jobs.slice().reverse().forEach( rememberImport ); } } ).catch( ( error ) => { recoveryProgress.textContent = error.message; } );
     1820
     1821                const modal = SMC.dialog( { returnFocus: '#smc-tools-button', title: __( 'Media tools', 'rapid-media-reclaim' ), body: h( 'div', null, h( 'p', null, __( 'Discovery results never delete or merge files. Request routing verification covers one path; CDN and browser caches remain outside observation.', 'rapid-media-reclaim' ) ), actions, uploads, visualJobs, fileSection, savings, observation, mergeSelect, progress, output, recovery ), cancelLabel: __( 'Close', 'rapid-media-reclaim' ), buttons: [] } );
     1822                api.get( '/tools/status' ).then( ( status ) => {
     1823                        if ( ! active ) { return; }
     1824                        progress.textContent = status.storage.audit_only ? status.storage.reasons.join( ' ' ) : __( 'Local storage available. Advanced mutation features remain subject to recovery checks.', 'rapid-media-reclaim' );
     1825                        showObservation( status.observation );
     1826                        showSavings( status.ledger );
     1827                        if ( status.operations_csv_url ) { savings.appendChild( h( 'a', { class: 'smc-btn smc-btn--secondary', href: safeHref( status.operations_csv_url ) }, __( 'Download operation CSV', 'rapid-media-reclaim' ) ) ); }
     1828                        if ( status.configuration ) {
     1829                                const config = status.configuration;
     1830                                actions.after( h( 'details', null, h( 'summary', null, __( 'Server setup examples (for your hosting administrator)', 'rapid-media-reclaim' ) ), h( 'p', null, config.guidance ), config.nginx ? h( 'pre', null, config.nginx ) : null, config.apache ? h( 'pre', null, config.apache ) : null ) );
     1831                        }
     1832                        ( status.merge_jobs || [] ).slice().reverse().forEach( rememberMerge );
     1833                        if ( status.csv_url ) { actions.appendChild( h( 'a', { class: 'smc-btn smc-btn--secondary', href: safeHref( status.csv_url ) }, __( 'Download inventory CSV', 'rapid-media-reclaim' ) ) ); }
     1834                } ).catch( ( error ) => { progress.textContent = error.message; } );
     1835                await modal;
     1836                active = false;
     1837                clearTimeout( observationTimer );
     1838        }
     1839
    11981840        // Notices (between the header and the summary tiles).
    11991841        // ------------------------------------------------------------------
    … …  
    12251867                const summary = state.summary || {};
    12261868                const last = summary.last_scan;
     1869                if ( summary.storage && summary.storage.audit_only ) {
     1870                        const database = ( summary.last_scan && summary.last_scan.coverage || [] ).find( ( entry ) => entry.id === 'database_adapter' );
     1871                        const examples = database && database.detail && database.detail.examples || [];
     1872                        items.push( notice( {
     1873                                tone: 'warning', title: __( 'Audit-only mode: cleanup is disabled', 'rapid-media-reclaim' ), text: summary.storage.reasons.join( ' ' ),
     1874                                extra: examples.length ? h( 'details', null, h( 'summary', null, __( 'Show affected sources', 'rapid-media-reclaim' ) ), h( 'ul', null, ...examples.map( ( source ) => {
     1875                                        const label = { posts: __( 'Post / page', 'rapid-media-reclaim' ), terms: __( 'Term', 'rapid-media-reclaim' ), users: __( 'User', 'rapid-media-reclaim' ), options: __( 'Setting', 'rapid-media-reclaim' ) }[ source.phase ] || source.phase;
     1876                                        return h( 'li', null, label + ( source.id ? ' #' + source.id : '' ) + ( source.key ? ' · ' + source.key : '' ) );
     1877                                } ) ) ) : null,
     1878                        } ) );
     1879                }
    12271880
    12281881                // Interrupted permanent deletion that can be finished safely.
    … …  
    12321885                                tone: 'error',
    12331886                                title: sprintf( /* translators: %s: number of files */ _n( 'Deleting %s file was interrupted', 'Deleting %s files was interrupted', recoveryIds.length, 'rapid-media-reclaim' ), num( recoveryIds.length ) ),
    1234                                 text: __( 'A permanent delete stopped before it finished. Retry to complete it; nothing else is affected.', 'rapid-media-reclaim' ),
     1887                                text: __( 'A previously authorized permanent deletion stopped before it finished. Routing verification may be incomplete or browser-only. Retry continues that authorization; it does not complete a verified window.', 'rapid-media-reclaim' ),
    12351888                                actions: [ h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary smc-btn--sm', onClick: async () => {
    12361889                                        try {
    1237                                                 const res = await api.post( '/purge', { ids: recoveryIds, force: true, retry_only: true } );
    1238                                                 applySummary( res.summary );
     1890                                                const res = await runBulk( '/purge', recoveryIds, { force: true, retry_only: true }, 'purged', ( done, total ) => done + ' / ' + total );
     1891                                                if ( res.error ) { throw res.error; }
    12391892                                                SMC.toast( { type: res.failed.length ? 'error' : 'success', message: res.failed.length ? res.failed[0].message : __( 'Interrupted cleanup completed.', 'rapid-media-reclaim' ) } );
    12401893                                        } catch ( error ) {
    … …  
    17022355                }
    17032356                if ( q.purge_ready || ! days ) {
    1704                         return __( 'Ready to delete', 'rapid-media-reclaim' );
     2357                        return __( 'Waiting period met', 'rapid-media-reclaim' );
    17052358                }
    17062359                /* translators: 1: current day, 2: total days, e.g. "Day 3 of 14" */
    … …  
    19182571                }
    19192572                const copy = {
    1920                         unused: [ 'sparkle', __( 'No unused media found', 'rapid-media-reclaim' ), __( 'Your library is clean. Every file is used somewhere or marked Keep.', 'rapid-media-reclaim' ) ],
     2573                        unused: [ 'sparkle', __( 'No unused media found', 'rapid-media-reclaim' ), __( 'Other files may be in use, marked Keep, or in quarantine.', 'rapid-media-reclaim' ) ],
    19212574                        quarantined: [ 'box', __( 'Quarantine is empty', 'rapid-media-reclaim' ), __( 'Files you move to quarantine wait here, ready to restore with one click.', 'rapid-media-reclaim' ) ],
    19222575                        used: [ 'shield', __( 'No files in use yet', 'rapid-media-reclaim' ), __( 'Files that are used on your site appear here with proof of where.', 'rapid-media-reclaim' ) ],
    … …  
    22222875                }
    22232876                writeHash();
     2877                const cached = details.get( id ) || listItem( id );
     2878                if ( cached && cached.status === 'quarantined' ) { details.delete( id ); }
    22242879                renderDrawer();
    22252880                if ( ! wasOpen || ! ( opts && opts.keepFocus ) ) {
    … …  
    22342889                }
    22352890                const id = drawer.id;
     2891                clearTimeout( drawer.observationTimer );
    22362892                drawer.id = null;
    22372893                drawer.token++;
    … …  
    22802936
    22812937        function renderDrawer() {
     2938                clearTimeout( drawer.observationTimer );
    22822939                const id = drawer.id;
    22832940                if ( id === null ) {
    … …  
    23082965
    23092966                const full = detail && ! detail.error ? detail : null;
     2967                if ( full && item.status === 'quarantined' ) {
     2968                        const expires = item.quarantine && item.quarantine.observation && item.quarantine.observation.expires_at || 0;
     2969                        drawer.observationTimer = setTimeout( () => {
     2970                                if ( drawer.id !== id ) { return; }
     2971                                details.delete( id );
     2972                                loadDetail( id );
     2973                        }, expires * 1000 > Date.now() ? Math.max( 1000, Math.min( 60000, expires * 1000 - Date.now() ) ) : 60000 );
     2974                }
     2975
    23102976                replace(
    23112977                        drawer.body,
    … …  
    23252991                replace(
    23262992                        drawer.foot,
    2327                         ACTION_ORDER.filter( ( name ) => ACTIONS[ name ].eligible( selInfo( item ) ) ).map( ( name ) =>
     2993                        ACTION_ORDER.filter( ( name ) => eligibleIds( name, statusEntry ).length ).map( ( name ) =>
    23282994                                h(
    23292995                                        'button',
    … …  
    24113077                                                since ? sprintf( /* translators: %s: date */ __( 'In quarantine since %s.', 'rapid-media-reclaim' ), since ) + ' ' : '',
    24123078                                                q.purge_ready || ! days
    2413                                                         ? __( 'It can be deleted permanently whenever you’re ready.', 'rapid-media-reclaim' )
    2414                                                         : sprintf( /* translators: 1: "Day 3 of 14", 2: date */ __( '%1$s. It can be deleted permanently from %2$s.', 'rapid-media-reclaim' ), quarantineLabel( item ), readyAt )
     3079                                                        ? __( 'The waiting period has passed. A saved recovery backup, usage checks and explicit confirmation are still required.', 'rapid-media-reclaim' )
     3080                                                        : sprintf( /* translators: 1: "Day 3 of 14", 2: date */ __( '%1$s. The waiting period ends on %2$s; all other safety checks still apply.', 'rapid-media-reclaim' ), quarantineLabel( item ), readyAt )
    24153081                                        )
    24163082                                ),
     3083                                h( 'p', { class: 'smc-callout smc-callout--info' }, full && q.observation && q.observation.verified_window_complete && q.observation.expires_at * 1000 > Date.now() ? __( 'At the last check, the verified window was complete with no known interruption in routing verification. This does not prove disuse or grant deletion permission.', 'rapid-media-reclaim' ) : sprintf( /* translators: 1: elapsed routing-check days, 2: required days */ __( 'Verified routing period: %1$s of %2$s days. Incomplete, unknown or paused verification is separate from waiting age. Manual deletion still requires every existing check.', 'rapid-media-reclaim' ), num( Math.floor( ( full && q.observation && q.observation.elapsed_seconds || 0 ) / 86400 ) ), num( days ) ) ),
    24173084                                used
    24183085                                        ? h(
    … …  
    24893156                const recent = Date.now() - Date.parse( full.date ) < 86400000;
    24903157                let text;
    2491                 if ( confidence === 'high' ) {
     3158                const unread = ( full.checked || [] ).some( ( source ) => source.id === 'database_adapter' && source.detail && source.detail.partial );
     3159                if ( full.index_fault || ( state.summary && state.summary.index_fault ) ) {
     3160                        text = __( 'Some usage updates could not be saved. Run a complete scan before relying on this result or cleaning up.', 'rapid-media-reclaim' );
     3161                } else if ( full.index_pending || ( state.summary && state.summary.index_pending ) ) {
     3162                        text = __( 'Usage updates are waiting for background indexing. This result may be stale; cleanup is paused until indexing finishes.', 'rapid-media-reclaim' );
     3163                } else if ( unread ) {
     3164                        text = __( 'Some stored content could not be checked within scan limits. This file may still be in use. Resolve the affected sources and rescan before cleaning up.', 'rapid-media-reclaim' );
     3165                } else if ( confidence === 'high' ) {
    24923166                        text = __( 'No trace of this file was found anywhere we checked.', 'rapid-media-reclaim' );
    24933167                } else if ( confidence === 'low' ) {
    … …  
    25243198                                                'span',
    25253199                                                { class: 'smc-checklist__count' },
    2526                                                 c.detail && Object.prototype.hasOwnProperty.call( c.detail, 'partial' ) ? ( c.detail.partial ? __( 'Checked · some values read as plain data', 'rapid-media-reclaim' ) : __( 'Checked', 'rapid-media-reclaim' ) ) : c.id === 'frontend' && c.detail ? crawlSummary( c.detail ) : c.count
     3200                                                c.id === 'database_adapter' ? __( 'Incomplete · stored values exceeded scan limits', 'rapid-media-reclaim' ) : c.detail && Object.prototype.hasOwnProperty.call( c.detail, 'partial' ) ? ( c.detail.partial ? __( 'Checked · some values read as plain data', 'rapid-media-reclaim' ) : __( 'Checked', 'rapid-media-reclaim' ) ) : c.id === 'frontend' && c.detail ? crawlSummary( c.detail ) : c.count
    25273201                                                        ? sprintf( /* translators: %s: number of items */ _n( 'Not found in %s checked', 'Not found in %s checked', c.count, 'rapid-media-reclaim' ), num( c.count ) )
    25283202                                                        : __( 'Not found', 'rapid-media-reclaim' )
    … …  
    26883362        function openSettings() {
    26893363                const s = state.settings;
    2690                 const days = h( 'input', { type: 'number', class: 'smc-input', id: 'smc-set-days', min: '0', max: '365', step: '1', value: String( s.quarantine_days ), 'aria-describedby': 'smc-set-days-help' } );
     3364                const days = h( 'input', { type: 'number', class: 'smc-input', id: 'smc-set-days', min: '14', max: '365', step: '1', value: String( s.quarantine_days ), 'aria-describedby': 'smc-set-days-help' } );
    26913365                const toggle = ( id, label, help, checked ) => {
    26923366                        const input = h( 'input', { type: 'checkbox', class: 'smc-switch__input', id, checked, 'aria-describedby': id + '-help', role: 'switch' } );
    … …  
    27023376                };
    27033377                const drafts = toggle( 'smc-set-drafts', __( 'Count drafts as use', 'rapid-media-reclaim' ), __( 'Files used only in drafts, private or scheduled posts are treated as in use.', 'rapid-media-reclaim' ), !! s.include_drafts );
     3378                const aliases = h( 'textarea', { class: 'smc-input', rows: '3', maxlength: '20480', id: 'smc-upload-aliases' }, ( s.upload_aliases || [] ).join( '\n' ) );
    27043379                const trash = toggle( 'smc-set-trash', __( 'Count trashed posts as weak evidence', 'rapid-media-reclaim' ), __( 'Files used only in trashed posts get lower confidence instead of high.', 'rapid-media-reclaim' ), !! s.include_trash );
    27053380
    … …  
    27163391                                h( 'label', { class: 'smc-field__label', for: 'smc-set-days' }, __( 'Quarantine period', 'rapid-media-reclaim' ) ),
    27173392                                h( 'div', { class: 'smc-input-group' }, days, h( 'span', null, __( 'days', 'rapid-media-reclaim' ) ) ),
    2718                                 h( 'p', { class: 'smc-field__help', id: 'smc-set-days-help' }, __( 'How long files wait in quarantine before they can be deleted permanently without an extra warning.', 'rapid-media-reclaim' ) )
     3393                                h( 'p', { class: 'smc-field__help', id: 'smc-set-days-help' }, __( 'How long files wait in quarantine before they can be deleted permanently. A verified, saved recovery backup is also required.', 'rapid-media-reclaim' ) )
    27193394                        ),
     3395                        h( 'label', { for: 'smc-upload-aliases' }, __( 'Old or CDN uploads roots (one URL per line, up to 10)', 'rapid-media-reclaim' ) ), aliases,
    27203396                        drafts.el,
    27213397                        trash.el, watch.el, restore.el, crawl.el,
    … …  
    27303406                        onSubmit: async () => {
    27313407                                const value = parseInt( days.value, 10 );
    2732                                 if ( isNaN( value ) || value < 0 || value > 365 ) {
     3408                                if ( isNaN( value ) || value < 14 || value > 365 ) {
    27333409                                        days.focus();
    2734                                         throw { message: __( 'Enter a number of days between 0 and 365.', 'rapid-media-reclaim' ) };
     3410                                        throw { message: __( 'Enter a number of days between 14 and 365.', 'rapid-media-reclaim' ) };
    27353411                                }
    27363412                                const limit = Number( crawlLimit.value );
    27373413                                if ( ! Number.isInteger( limit ) || limit < 1 || limit > 500 ) { crawlLimit.focus(); throw { message: __( 'Enter a page limit between 1 and 500.', 'rapid-media-reclaim' ) }; }
    2738                                 const res = await api.post( '/settings', { quarantine_days: value, include_drafts: drafts.input.checked, include_trash: trash.input.checked, request_watch: watch.input.checked, auto_restore: restore.input.checked, frontend_crawl: crawl.input.checked, crawl_limit: limit } );
     3414                                const res = await api.post( '/settings', { quarantine_days: value, upload_aliases: aliases.value.split( /\r?\n/ ).map( ( value ) => value.trim() ).filter( Boolean ), include_drafts: drafts.input.checked, include_trash: trash.input.checked, request_watch: watch.input.checked, auto_restore: restore.input.checked, frontend_crawl: crawl.input.checked, crawl_limit: limit } );
    27393415                                const daysChanged = res.settings.quarantine_days !== state.settings.quarantine_days;
    27403416                                state.settings = res.settings;
  • rapid-media-reclaim/tags/1.1.0/assets/js/ui.js

    r3794616 r3814937  
    230230                                el.close();
    231231                                el.remove();
    232                                 if ( previous && previous.isConnected && typeof previous.focus === 'function' ) {
    233                                         previous.focus();
     232                                // Header refreshes may replace the opener while a long tool runs.
     233                                const returnTo = ( opts.returnFocus && document.querySelector( opts.returnFocus ) ) || ( previous && previous.isConnected ? previous : previous && Array.from( document.querySelectorAll( 'button, a, input, select' ) ).find( ( node ) => node.tagName === previous.tagName && node.textContent === previous.textContent && node.getAttribute( 'aria-label' ) === previous.getAttribute( 'aria-label' ) && node.getClientRects().length && ! node.disabled ) );
     234                                if ( returnTo && typeof returnTo.focus === 'function' ) {
     235                                        returnTo.focus();
    234236                                }
    235237                                resolve( value );
  • rapid-media-reclaim/tags/1.1.0/includes/admin/class-admin.php

    r3794616 r3814937  
    123123
    124124                return array(
    125                         'version'   => SAFE_MEDIA_CLEANER_VERSION,
    126                         'restPath'  => '/' . Controller::NS,
    127                         'locale'    => str_replace( '_', '-', get_user_locale() ),
    128                         'pageUrl'   => self::page_url(),
    129                         'reviewUrl' => 'https://wordpress.org/support/plugin/rapid-media-reclaim/reviews/#new-post',
    130                         'sourceUrl' => 'https://wordpress.org/plugins/rapid-media-reclaim/',
    131                         'maxIds'    => Controller::MAX_IDS,
    132                         'maxSelect' => Controller::MAX_SELECT,
    133                         'summary'   => $payload['summary'],
    134                         'scan'      => $payload['scan'],
    135                         'settings'  => $payload['settings'],
    136                         'initial'   => $initial,
     125                        'version'    => SAFE_MEDIA_CLEANER_VERSION,
     126                        'restPath'   => '/' . Controller::NS,
     127                        'locale'     => str_replace( '_', '-', get_user_locale() ),
     128                        'pageUrl'    => self::page_url(),
     129                        'reviewUrl'  => 'https://wordpress.org/support/plugin/rapid-media-reclaim/reviews/#new-post',
     130                        'sourceUrl'  => 'https://wordpress.org/plugins/rapid-media-reclaim/',
     131                        'maxIds'     => Controller::MAX_IDS,
     132                        'maxFileIds' => Controller::MAX_FILE_IDS,
     133                        'maxSelect'  => Controller::MAX_SELECT,
     134                        'summary'    => $payload['summary'],
     135                        'scan'       => $payload['scan'],
     136                        'settings'   => $payload['settings'],
     137                        'initial'    => $initial,
    137138                );
    138139        }
  • rapid-media-reclaim/tags/1.1.0/includes/class-index.php

    r3794616 r3814937  
    2929
    3030                $last = get_option( 'safe_media_cleaner_last_scan', null );
    31                 $base = self::base_sql();
     31                $base = self::base_sql( array(), false );
    3232
    3333                // One pass over the library: status, confidence and size per attachment.
    … …  
    3838                        "SELECT s.status, s.confidence, COUNT(*) AS items, COALESCE(SUM(s.bytes), 0) AS bytes
    3939                        FROM ( SELECT {$base['status']} AS status, {$base['confidence']} AS confidence,
    40                                 COALESCE(fb.b, 0) AS bytes, {$base['shared']} AS is_copy
     40                                {$base['bytes']} AS bytes, {$base['shared']} AS is_copy
    4141                                {$base['from']} ) s
    4242                        WHERE s.is_copy = 0
    … …  
    7575                return array(
    7676                        'scanned'                 => self::generation() > 0,
     77                        'storage'                 => Storage::status(),
     78                        'index_pending'           => Deferred_Index::pending(),
     79                        'index_fault'             => (bool) Deferred_Index::fault_token(),
    7780                        'recovery_ids'            => Quarantine::orphan_ids( true ),
    7881                        'unresolved_recovery_ids' => Quarantine::orphan_ids(),
    … …  
    9396
    9497                $args = self::normalize_args( $args );
    95                 $base = self::base_sql();
     98                $base = self::base_sql( $args['ids'], '' !== $args['search'] || 'name' === $args['orderby'] );
    9699
    97100                $where = array();
    … …  
    130133
    131134                $inner = "SELECT p.ID AS id, p.post_title AS title, p.post_mime_type AS mime, p.post_date_gmt AS date,
    132                                 COALESCE(f.meta_value, '') AS file,
    133                                 {$base['status']} AS status, {$base['confidence']} AS confidence, COALESCE(fb.b, 0) AS bytes,
     135                                {$base['file']} AS file,
     136                                {$base['status']} AS status, {$base['confidence']} AS confidence, {$base['bytes']} AS bytes,
    134137                                {$base['shared']} AS is_copy
    135138                                {$base['from']}";
    … …  
    184187                }
    185188
    186                 $item            = $result['items'][0];
    187                 $refs            = self::refs( $id );
    188                 $item['refs']    = $refs['strong'];
    189                 $item['weak']    = $refs['weak'];
    190                 $last            = get_option( 'safe_media_cleaner_last_scan', null );
    191                 $item['checked'] = \SafeMediaCleaner\Scan\Adapter_Coverage::append( is_array( $last ) ? (array) ( $last['coverage'] ?? array() ) : array(), self::generation() );
    192                 $item['files']   = self::files( $id );
     189                $item                  = $result['items'][0];
     190                $refs                  = self::refs( $id );
     191                $item['refs']          = $refs['strong'];
     192                $item['weak']          = $refs['weak'];
     193                $last                  = get_option( 'safe_media_cleaner_last_scan', null );
     194                $item['checked']       = \SafeMediaCleaner\Scan\Adapter_Coverage::append( is_array( $last ) ? (array) ( $last['coverage'] ?? array() ) : array(), self::generation() );
     195                $item['files']         = self::files( $id );
     196                $item['index_pending'] = Deferred_Index::pending();
     197                $item['index_fault']   = (bool) Deferred_Index::fault_token();
    193198
    194199                return $item;
    … …  
    352357         * Evidence and sizes are aggregated once per query in derived tables rather
    353358         * than per row, so listing stays fast on large libraries.
    354          */
    355         private static function base_sql(): array {
     359         *
     360         * @param array $ids Optional attachment scope, applied before aggregation.
     361         * @param bool  $include_file Include filename metadata for search/name ordering.
     362         */
     363        private static function base_sql( array $ids = array(), bool $include_file = true ): array {
    356364                $quarantine_table = Installer::table( 'quarantine' );
    357365                global $wpdb;
    … …  
    360368                $files      = Installer::table( 'files' );
    361369                $generation = self::generation();
     370                $id_list    = implode( ',', array_map( 'absint', $ids ) );
     371                $scope      = $ids ? ' AND attachment_id IN (' . $id_list . ')' : '';
    362372                $new_after  = gmdate( 'Y-m-d H:i:s', time() - self::NEW_UPLOAD_SECONDS );
    363373
    364                 // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table names only.
     374                $file_join = $include_file ? "LEFT JOIN {$wpdb->postmeta} f ON f.post_id=p.ID AND f.meta_key='_wp_attached_file'" : '';
     375                // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table names and internal join fragments only.
    365376                $from = $wpdb->prepare(
    366377                        "FROM {$wpdb->posts} p
    367                         LEFT JOIN {$wpdb->postmeta} f ON f.post_id = p.ID AND f.meta_key = '_wp_attached_file'
    368                         LEFT JOIN {$wpdb->postmeta} k ON k.post_id = p.ID AND k.meta_key = '_safe_media_cleaner_keep'
    369                         LEFT JOIN ( SELECT attachment_id AS post_id, MAX(id) AS meta_value FROM {$quarantine_table} WHERE status = 'quarantined' GROUP BY attachment_id ) q ON q.post_id = p.ID
     378                        {$file_join}
     379                        LEFT JOIN (SELECT DISTINCT post_id,1 AS meta_value FROM {$wpdb->postmeta} WHERE meta_key='_safe_media_cleaner_keep' LIMIT 18446744073709551615) k ON k.post_id=p.ID
     380                        LEFT JOIN ( SELECT attachment_id AS post_id, MAX(id) AS meta_value FROM {$quarantine_table} WHERE status = 'quarantined' {$scope} GROUP BY attachment_id LIMIT 18446744073709551615 ) q ON q.post_id = p.ID
    370381                        LEFT JOIN (
    371382                                SELECT attachment_id,
    … …  
    373384                                        MAX( strength = 'weak' AND match_type IN ('id','url') ) AS weak_ref,
    374385                                        MAX( strength = 'weak' AND match_type = 'filename' ) AS weak_name
    375                                 FROM {$refs} WHERE generation = %d GROUP BY attachment_id
     386                                FROM {$refs} WHERE generation = %d {$scope} GROUP BY attachment_id LIMIT 18446744073709551615
    376387                        ) r ON r.attachment_id = p.ID
    377                         LEFT JOIN ( SELECT attachment_id, SUM(bytes) AS b FROM {$files} WHERE generation = %d GROUP BY attachment_id ) fb ON fb.attachment_id = p.ID",
     388                        LEFT JOIN ( SELECT attachment_id, SUM(bytes) AS b FROM {$files} WHERE generation = %d {$scope} GROUP BY attachment_id LIMIT 18446744073709551615 ) fb ON fb.attachment_id = p.ID",
    378389                        $generation,
    379390                        $generation
    380391                );
     392                // A non-restrictive LIMIT keeps full-library aggregates materialized instead
     393                // of a lateral aggregate lookup for each attachment on MariaDB. Values remain
     394                // live per query; no persistent status cache can outlive an evidence mutation.
     395                $copy_scope = $ids ? ' AND o2.attachment_id IN (' . $id_list . ')' : '';
    381396                // Copies: attachments whose original file also belongs to a lower ID.
    382397                $from .= $wpdb->prepare(
    … …  
    384399                                SELECT DISTINCT o2.attachment_id FROM {$files} o1
    385400                                JOIN {$files} o2 ON o2.path = o1.path AND o2.attachment_id > o1.attachment_id AND o2.generation = %d AND o2.kind = 'original'
    386                                 WHERE o1.generation = %d AND o1.kind = 'original'
     401                                WHERE o1.generation = %d AND o1.kind = 'original' {$copy_scope}
     402                                LIMIT 18446744073709551615
    387403                        ) cp ON cp.attachment_id = p.ID",
    388404                        $generation,
    … …  
    391407                // phpcs:enable
    392408                $from .= " WHERE p.post_type = 'attachment' AND p.post_status IN ('inherit','private','publish')";
     409                if ( $ids ) {
     410                        $from .= ' AND p.ID IN (' . $id_list . ')';
     411                }
    393412
    394413                $status = "CASE
    … …  
    408427                );
    409428
     429                if ( Deferred_Index::pending() || Deferred_Index::fault_token() || get_option( 'safe_media_cleaner_adapter_gap_' . $generation . '_database', false ) ) {
     430                        $confidence = "'low'"; }
     431
    410432                // True when a lower-ID attachment has the same original file (a translation copy).
    411433                $shared = '( cp.attachment_id IS NOT NULL )';
    412434
     435                $bytes = 'COALESCE(fb.b, 0)';
     436                if ( ! $ids && Status_Index::usable( $generation ) ) {
     437                        // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Only internal table identifiers; values are prepared.
     438                        $table  = Installer::table( 'status' );
     439                        $from   = $wpdb->prepare(
     440                                "FROM {$wpdb->posts} p
     441                        {$file_join}
     442                        LEFT JOIN (SELECT DISTINCT post_id,1 AS meta_value FROM {$wpdb->postmeta} WHERE meta_key='_safe_media_cleaner_keep' LIMIT 18446744073709551615) k ON k.post_id=p.ID
     443                        LEFT JOIN (SELECT attachment_id AS post_id,MAX(id) AS meta_value FROM {$quarantine_table} WHERE status='quarantined' GROUP BY attachment_id) q ON q.post_id=p.ID
     444                        LEFT JOIN {$table} r ON r.attachment_id=p.ID AND r.generation=%d
     445                        WHERE p.post_type='attachment' AND p.post_status IN ('inherit','private','publish')",
     446                                $generation
     447                        ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Internal identifiers only, generation prepared.
     448                        $bytes  = 'COALESCE(r.bytes,0)';
     449                        $shared = 'COALESCE(r.is_copy,0)';
     450                }
    413451                return array(
     452                        'file'       => $include_file ? "COALESCE(f.meta_value,'')" : 'NULL',
     453                        'bytes'      => $bytes,
    414454                        'from'       => $from,
    415455                        'status'     => $status,
    … …  
    511551                $ids = array_map( 'intval', wp_list_pluck( $rows, 'id' ) );
    512552                _prime_post_caches( $ids, false, true );
     553                update_meta_cache( 'post', $ids );
    513554                $quarantine = Quarantine::records_for( $ids );
    514555                $counts     = self::ref_counts( $ids );
    … …  
    520561                        $id   = (int) $row['id'];
    521562                        $mime = (string) $row['mime'];
    522                         $file = (string) $row['file'];
     563                        $file = (string) ( $row['file'] ?? get_post_meta( $id, '_wp_attached_file', true ) );
    523564                        $q    = $quarantine[ $id ] ?? null;
    524565
    … …  
    535576                                $age             = max( 0, time() - (int) strtotime( $q['created_at'] . ' UTC' ) );
    536577                                $quarantine_info = array(
    537                                         'id'          => (int) $q['id'],
    538                                         'batch'       => (string) $q['batch'],
    539                                         'since'       => gmdate( 'c', (int) strtotime( $q['created_at'] . ' UTC' ) ),
    540                                         'days'        => (int) floor( $age / DAY_IN_SECONDS ),
    541                                         'purge_ready' => $age >= $days * DAY_IN_SECONDS,
    542                                         'hits'        => (int) $q['hits'],
     578                                        'id'                => (int) $q['id'],
     579                                        'batch'             => (string) $q['batch'],
     580                                        'since'             => gmdate( 'c', (int) strtotime( $q['created_at'] . ' UTC' ) ),
     581                                        'days'              => (int) floor( $age / DAY_IN_SECONDS ),
     582                                        'purge_ready'       => $age >= $days * DAY_IN_SECONDS,
     583                                        'age_wait_complete' => $age >= $days * DAY_IN_SECONDS,
     584                                        'observation'       => Quarantine::observation( $id ),
     585                                        'hits'              => (int) $q['hits'],
    543586                                );
    544587                        }
    … …  
    607650                // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    608651
     652                $post_ids = array();
     653                foreach ( (array) $rows as $row ) {
     654                        if ( in_array( $row['source_type'], array( 'frontend', 'post_content', 'post_excerpt', 'featured_image', 'post_meta', 'builder', 'acf', 'woocommerce' ), true ) && $row['source_id'] ) {
     655                                $post_ids[] = (int) $row['source_id'];
     656                        }
     657                }
     658                if ( $post_ids ) {
     659                        _prime_post_caches( array_unique( $post_ids ), false, false );
     660                }
    609661                $out = array(
    610662                        'strong' => array(),
    … …  
    696748                        $source = array(
    697749                                'kind'     => 'media',
    698                                 'title'    => get_the_title( $sid ) ? get_the_title( $sid ) : sprintf( /* translators: %d: media ID */ __( 'Media #%d', 'rapid-media-reclaim' ), $sid ),
     750                                'title'    => get_the_title( $sid ) ? get_the_title( $sid ) : sprintf( /* translators: %d: attachment ID */ __( 'Media #%d', 'rapid-media-reclaim' ), $sid ),
    699751                                'subtitle' => __( 'Same file, used elsewhere (for example a translation)', 'rapid-media-reclaim' ),
    700752                                'edit_url' => get_edit_post_link( $sid, 'raw' ),
  • rapid-media-reclaim/tags/1.1.0/includes/class-installer.php

    r3794616 r3814937  
    1515final class Installer {
    1616
    17         const DB_VERSION = '5';
     17        const DB_VERSION = '9';
    1818
    1919        /**
    2020         * Install plugin storage on activation.
    21          */
    22         public static function activate(): void {
     21         *
     22         * @param bool|null $network_wide Activate every network site.
     23         */
     24        public static function activate( ?bool $network_wide = false ): void {
     25                if ( $network_wide && is_multisite() ) {
     26                        self::network( 'activate' );
     27                        return;
     28                }
    2329                self::install();
     30                Routing_Window::interrupt( 'activation' );
     31                Routing_Window::repair();
    2432                Quarantine::ensure_dir();
     33                Deferred_Index::repair();
    2534        }
    2635
    2736        /**
    2837         * Unschedule plugin background work.
    29          */
    30         public static function deactivate(): void {
     38         *
     39         * @param bool|null $network_wide Deactivate every network site.
     40         */
     41        public static function deactivate( ?bool $network_wide = false ): void {
     42                if ( $network_wide && is_multisite() ) {
     43                        self::network( 'deactivate' );
     44                        return;
     45                }
    3146                wp_clear_scheduled_hook( Scan_Runner::CRON_HOOK );
     47                wp_clear_scheduled_hook( Scan_Runner::CLEANUP_HOOK );
     48                wp_clear_scheduled_hook( Status_Index::HOOK );
     49                wp_clear_scheduled_hook( Deferred_Index::HOOK );
     50                wp_clear_scheduled_hook( Maintenance::HOOK );
     51                wp_clear_scheduled_hook( Routing_Window::HOOK );
     52                Routing_Window::interrupt( 'deactivation' );
     53                // Legacy shared slot only; current challenges expire under their own ticket keys.
     54                delete_transient( Server_Watch::PROBE );
    3255                Scan_Runner::cancel();
    3356                delete_option( Request_Watcher::RATE_OPTION );
     57        }
     58
     59        /**
     60         * Run a fixed lifecycle method on every current network site in bounded pages.
     61         *
     62         * @param string $method Internal activate/deactivate method.
     63         * @throws \RuntimeException Failed network inventory.
     64         */
     65        private static function network( string $method ): void {
     66                global $wpdb;
     67                $after = 0;
     68                do {
     69                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Fresh keyset network lifecycle enumeration, at most one hundred IDs.
     70                        $ids = $wpdb->get_col( $wpdb->prepare( "SELECT blog_id FROM {$wpdb->blogs} WHERE blog_id>%d ORDER BY blog_id LIMIT 100", $after ) );
     71                        if ( $wpdb->last_error || ! is_array( $ids ) ) {
     72                                throw new \RuntimeException( 'safe_media_cleaner_network_inventory_failed' );
     73                        }
     74                        foreach ( $ids as $id ) {
     75                                $after = (int) $id;
     76                                switch_to_blog( $after );
     77                                try {
     78                                        self::$method( false );
     79                                } finally {
     80                                        restore_current_blog();
     81                                }
     82                        }
     83                        $count = count( $ids );
     84                } while ( 100 === $count );
     85        }
     86
     87        /**
     88         * Initialize a newly provisioned site only while this plugin is network active.
     89         *
     90         * @param \WP_Site $site Newly initialized site.
     91         */
     92        public static function new_site( \WP_Site $site ): void {
     93                if ( ! is_multisite() || ! array_key_exists( plugin_basename( SAFE_MEDIA_CLEANER_PATH . 'rapid-media-reclaim.php' ), (array) get_site_option( 'active_sitewide_plugins', array() ) ) ) {
     94                        return;
     95                }
     96                switch_to_blog( (int) $site->blog_id );
     97                try {
     98                        self::activate();
     99                } finally {
     100                        restore_current_blog();
     101                }
    34102        }
    35103
    … …  
    97165                global $wpdb;
    98166                return array(
    99                         'files'      => $wpdb->prefix . 'safe_media_cleaner_files',
    100                         'refs'       => $wpdb->prefix . 'safe_media_cleaner_refs',
    101                         'quarantine' => $wpdb->prefix . 'safe_media_cleaner_quarantine',
     167                        'ledger_payloads' => $wpdb->prefix . 'safe_media_cleaner_ledger_payloads',
     168                        'ledger_events'   => $wpdb->prefix . 'safe_media_cleaner_ledger_events',
     169                        'pending'         => $wpdb->prefix . 'safe_media_cleaner_pending',
     170                        'status'          => $wpdb->prefix . 'safe_media_cleaner_status',
     171                        'discovery'       => $wpdb->prefix . 'safe_media_cleaner_discovery',
     172                        'files'           => $wpdb->prefix . 'safe_media_cleaner_files',
     173                        'refs'            => $wpdb->prefix . 'safe_media_cleaner_refs',
     174                        'quarantine'      => $wpdb->prefix . 'safe_media_cleaner_quarantine',
    102175                );
    103176        }
    … …  
    135208                        KEY attachment (attachment_id,generation),
    136209                        KEY path (path(191)),
     210                        KEY shared_path (generation,kind,path(128),attachment_id),
    137211                        KEY name (generation,name),
    138212                        KEY generation (generation)
    … …  
    164238                        owner_id bigint(20) unsigned NOT NULL DEFAULT 0,
    165239                        purge_intent tinyint(1) unsigned NOT NULL DEFAULT 0,
     240                        ledger_pending tinyint(1) unsigned NOT NULL DEFAULT 0,
    166241                        status varchar(12) NOT NULL DEFAULT 'quarantined',
    167242                        files longtext NOT NULL,
    … …  
    177252                        KEY owner_id (owner_id,status),
    178253                        KEY status (status),
     254                        KEY ledger_pending (ledger_pending),
    179255                        KEY batch (batch)
    180256                        ) $charset;"
    181257                );
     258
     259                dbDelta(
     260                        "CREATE TABLE {$t['status']} (
     261                        generation int(10) unsigned NOT NULL,
     262                        attachment_id bigint(20) unsigned NOT NULL,
     263                        used tinyint(1) unsigned NOT NULL DEFAULT 0,
     264                        weak_ref tinyint(1) unsigned NOT NULL DEFAULT 0,
     265                        weak_name tinyint(1) unsigned NOT NULL DEFAULT 0,
     266                        bytes bigint(20) unsigned NOT NULL DEFAULT 0,
     267                        is_copy tinyint(1) unsigned NOT NULL DEFAULT 0,
     268                        PRIMARY KEY  (generation,attachment_id),
     269                        KEY flags (generation,is_copy,used,bytes)
     270                        ) $charset;"
     271                );
     272
     273                dbDelta(
     274                        "CREATE TABLE {$t['pending']} (
     275                        phase varchar(12) NOT NULL,
     276                        source_id bigint(20) unsigned NOT NULL,
     277                        revision char(32) NOT NULL,
     278                        queued_at datetime NOT NULL,
     279                        attempts int(10) unsigned NOT NULL DEFAULT 0,
     280                        PRIMARY KEY  (phase,source_id),
     281                        KEY queued (queued_at),
     282                        KEY attempts (attempts)
     283                        ) $charset;"
     284                );
     285
     286                dbDelta(
     287                        "CREATE TABLE {$t['ledger_payloads']} (
     288                        id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
     289                        version tinyint(3) unsigned NOT NULL DEFAULT 1,
     290                        payload_key char(64) NOT NULL,
     291                        root_key char(64) NOT NULL,
     292                        record_id bigint(20) unsigned NOT NULL,
     293                        attachment_id bigint(20) unsigned NOT NULL,
     294                        bytes bigint(20) unsigned NOT NULL DEFAULT 0,
     295                        manifest_files int(10) unsigned NOT NULL DEFAULT 0,
     296                        origin varchar(12) NOT NULL,
     297                        storage_state varchar(12) NOT NULL DEFAULT 'unknown',
     298                        updated_at datetime NOT NULL,
     299                        PRIMARY KEY  (id),
     300                        UNIQUE KEY payload_key (payload_key),
     301                        KEY root_key (root_key),
     302                        KEY record_id (record_id),
     303                        KEY storage (storage_state,bytes,updated_at)
     304                        ) $charset;"
     305                );
     306                dbDelta(
     307                        "CREATE TABLE {$t['ledger_events']} (
     308                        id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
     309                        version tinyint(3) unsigned NOT NULL DEFAULT 1,
     310                        payload_key char(64) NOT NULL,
     311                        record_id bigint(20) unsigned NOT NULL,
     312                        attachment_id bigint(20) unsigned NOT NULL,
     313                        operation varchar(12) NOT NULL,
     314                        result varchar(12) NOT NULL DEFAULT 'pending',
     315                        bytes bigint(20) unsigned NOT NULL DEFAULT 0,
     316                        coverage varchar(12) NOT NULL,
     317                        created_at datetime NOT NULL,
     318                        updated_at datetime NOT NULL,
     319                        PRIMARY KEY  (id),
     320                        UNIQUE KEY operation_payload (payload_key,operation),
     321                        KEY result (result,operation,bytes),
     322                        KEY record_id (record_id)
     323                        ) $charset;"
     324                );
     325                // No legacy statuses are imported as historical events.
     326                add_option( Operation_Ledger::STARTED, current_time( 'mysql', true ), '', false );
    182327
    183328                // Read on every request: keep these two tiny options autoloaded.
  • rapid-media-reclaim/tags/1.1.0/includes/class-plugin.php

    r3794616 r3814937  
    2020        public static function boot(): void {
    2121                Installer::maybe_upgrade();
     22                add_action( 'wp_initialize_site', array( Installer::class, 'new_site' ), 200, 1 );
    2223                Scan_Runner::init();
     24                Status_Index::init();
    2325                Quarantine::init();
     26                Merge::init();
    2427                Request_Watcher::init();
     28                Recovery_Export::init();
     29                Recovery_Import::init();
     30                Csv_Export::init();
     31                Discovery_Jobs::init();
     32                Discovery_Csv::init();
     33                File_Epoch::init();
     34                File_Archive::init();
     35                Rest\File_Controller::init();
     36                Maintenance::init();
     37                Deferred_Index::init();
     38                Server_Watch::init();
     39                Routing_Window::init();
     40                Rest\Tools_Controller::init();
     41                Rest\Recovery_Controller::init();
     42                if ( defined( 'WP_CLI' ) && WP_CLI ) {
     43                        Cli::init();
     44                }
    2545
    2646                if ( class_exists( Scan\Incremental::class ) ) {
  • rapid-media-reclaim/tags/1.1.0/includes/class-quarantine.php

    r3794616 r3814937  
    126126
    127127        /**
    128          * Quarantine eligible attachments under the operation lock.
    129          *
    130          * @param array $ids Ids.
    131          */
    132         public static function move( array $ids ): array {
     128         * Run imported recovery under the SAME lock and process guard as move/restore/purge.
     129         *
     130         * @param callable $callback Internal recovery operation.
     131         * @return mixed Operation result.
     132         * @throws \RuntimeException A concurrent/reentrant operation is running.
     133         */
     134        public static function recovery_operation( callable $callback ) {
    133135                global $wpdb;
    134136                $key = 'smc:' . md5( DB_NAME . ':' . $wpdb->prefix );
    135                 if ( self::$operating || self::core_deleting() || doing_action( 'delete_attachment' ) || doing_action( 'deleted_post' ) || '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $key ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
     137                if ( self::is_operating() || self::core_deleting() || doing_action( 'delete_attachment' ) || doing_action( 'deleted_post' ) || '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s,0)', $key ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Shared live media-operation lock.
     138                        throw new \RuntimeException( __( 'Another media operation is running. Retry shortly.', 'rapid-media-reclaim' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Encoded at presentation.
     139                }
     140                self::$operating = true;
     141                try {
     142                        return $callback();
     143                } finally {
     144                        self::$operating = false;
     145                        $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $key ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Release shared operation lock.
     146                }
     147        }
     148
     149        /**
     150         * Register imported payloads BEFORE copying, preserving existing matching records.
     151         *
     152         * @param array  $item Validated attachment plan.
     153         * @param string $batch Durable import batch.
     154         * @return array|\WP_Error Registered recovery row.
     155         */
     156        public static function recovery_record( array $item, string $batch ) {
     157                if ( ! self::$operating ) {
     158                        return new \WP_Error( 'safe_media_cleaner_lock', __( 'Recovery requires the media operation lock.', 'rapid-media-reclaim' ) );
     159                }
     160                $id  = $item['attachment_id'];
     161                $row = self::records_for( array( $id ) )[ $id ] ?? null;
     162                if ( $row ) {
     163                        $files    = self::manifest( $row );
     164                        $expected = array();
     165                        foreach ( $item['files'] as $file ) {
     166                                $expected[ $file['from'] ] = array( $file['bytes'], $file['sha256'] );
     167                        }
     168                        if ( is_wp_error( $files ) || count( $files ) !== count( $expected ) || (int) $row['owner_id'] !== $item['owner_id'] ) {
     169                                return new \WP_Error( 'safe_media_cleaner_conflict', __( 'Existing quarantine recovery differs from this backup. Review it in Quarantine first.', 'rapid-media-reclaim' ) );
     170                        }
     171                        foreach ( $files as $file ) {
     172                                if ( ( $expected[ $file['from'] ] ?? null ) !== array( (int) $file['bytes'], $file['sha256'] ?? '' ) ) {
     173                                        return new \WP_Error( 'safe_media_cleaner_conflict', __( 'Existing quarantine files differ from this backup.', 'rapid-media-reclaim' ) );
     174                                }
     175                        }
     176                        return $row;
     177                }
     178                $files = array();
     179                foreach ( $item['files'] as $file ) {
     180                        $files[] = array(
     181                                'from'   => $file['from'],
     182                                'to'     => $batch . '/' . $file['from'],
     183                                'bytes'  => $file['bytes'],
     184                                'sha256' => $file['sha256'],
     185                        );
     186                }
     187                if ( ! self::insert_record( $id, $batch, $files, array_sum( array_column( $files, 'bytes' ) ), $item['owner_id'] ) ) {
     188                        return new \WP_Error( 'safe_media_cleaner_manifest', __( 'Could not save recovery data. Retry before copying files.', 'rapid-media-reclaim' ) );
     189                }
     190                return self::records_for( array( $id ) )[ $id ];
     191        }
     192
     193        /**
     194         * Use normal identity-checked restore only inside the shared operation wrapper.
     195         *
     196         * @param int $id Registered payload owner.
     197         * @return int|\WP_Error Normal recovery result.
     198         */
     199        public static function recovery_restore( int $id ) {
     200                return self::$operating ? self::restore_one( $id ) : new \WP_Error( 'safe_media_cleaner_lock', __( 'Recovery requires the media operation lock.', 'rapid-media-reclaim' ) );
     201        }
     202
     203        /**
     204         * Check live ownership of imported file names using the normal ownership guard.
     205         *
     206         * @param array $files Payload entries.
     207         * @param array $ids Complete shared group.
     208         * @return true|\WP_Error Ownership result.
     209         */
     210        public static function recovery_ownership( array $files, array $ids ) {
     211                $folders = array();
     212                foreach ( $files as $file ) {
     213                        $dir               = dirname( $file['from'] );
     214                        $dir               = '.' === $dir ? '' : $dir . '/';
     215                        $folders[ $dir ][] = basename( $file['from'] );
     216                }
     217                foreach ( $folders as $dir => $names ) {
     218                        $claimed = self::claimed_names( $dir, $ids, $names );
     219                        if ( is_wp_error( $claimed ) ) {
     220                                return $claimed;
     221                        }
     222                        if ( $claimed ) {
     223                                return new \WP_Error( 'safe_media_cleaner_ownership', __( 'Another attachment owns a backup file name. Review that media before retrying.', 'rapid-media-reclaim' ) );
     224                        }
     225                }
     226                return true;
     227        }
     228
     229        /** Whether a quarantine/restore/purge operation owns this request. */
     230        public static function is_operating(): bool {
     231                return self::$operating || File_Recovery::is_operating(); }
     232
     233        /** Move selected files using existing guarded recovery manifests.
     234         *
     235         * @param array $ids Attachment IDs.
     236         * @return array Move results.
     237         */
     238        public static function move( array $ids ): array {
     239                foreach ( $ids as $id ) {
     240                        if ( Recovery_Import::is_protected( (int) $id ) ) {
     241                                return array(
     242                                        'moved'  => array(),
     243                                        'failed' => array( self::failure( (int) $id, __( 'Resume the pending backup recovery in Tools before changing this media.', 'rapid-media-reclaim' ) ) ),
     244                                        'bytes'  => 0,
     245                                );
     246                        }
     247                }
     248                foreach ( $ids as $id ) {
     249                        if ( Merge::is_protected( (int) $id ) && ! Merge_Retirement::allows( (int) $id ) ) {
     250                                return array(
     251                                        'moved'  => array(),
     252                                        'failed' => array( self::failure( (int) $id, __( 'This file is protected by a reference recovery journal. Roll back or finish reviewing that operation first.', 'rapid-media-reclaim' ), 'merge_protected' ) ),
     253                                        'bytes'  => 0,
     254                                );
     255                        }
     256                }
     257
     258                $storage_error = Storage::mutation_error();
     259                if ( $storage_error ) {
     260                        return array(
     261                                'moved'  => array(),
     262                                'failed' => array( self::failure( 0, $storage_error->get_error_message(), 'audit_only' ) ),
     263                                'bytes'  => 0,
     264                        );
     265                }
     266
     267                global $wpdb;
     268                $key = 'smc:' . md5( DB_NAME . ':' . $wpdb->prefix );
     269                if ( self::is_operating() || self::core_deleting() || doing_action( 'delete_attachment' ) || doing_action( 'deleted_post' ) || '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $key ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
    136270                        return array(
    137271                                'moved'  => array(),
    … …  
    156290         */
    157291        private static function move_locked( array $ids ): array {
     292                foreach ( $ids as $id ) {
     293                        if ( Merge::is_protected( (int) $id ) && ! Merge_Retirement::allows( (int) $id ) ) {
     294                                return array(
     295                                        'moved'  => array(),
     296                                        'failed' => array( self::failure( (int) $id, 'merge_protected', 'merge_protected' ) ),
     297                                        'bytes'  => 0,
     298                                );
     299                        }
     300                }
     301                foreach ( $ids as $id ) {
     302                        if ( Recovery_Import::is_protected( (int) $id ) ) {
     303                                return array(
     304                                        'moved'  => array(),
     305                                        'failed' => array( self::failure( (int) $id, __( 'Resume pending recovery in Tools first.', 'rapid-media-reclaim' ) ) ),
     306                                        'bytes'  => 0,
     307                                );
     308                        }
     309                }
    158310                $ids    = self::clean_ids( $ids );
    159                 $batch  = strtolower( wp_generate_password( 12, false ) );
     311                $batch  = Merge_Retirement::batch( $ids );
     312                $batch  = '' !== $batch ? $batch : strtolower( wp_generate_password( 12, false ) );
    160313                $result = array(
    161314                        'batch'  => $batch,
    … …  
    233386         */
    234387        public static function restore( array $ids ): array {
     388                foreach ( $ids as $id ) {
     389                        if ( Recovery_Import::is_protected( (int) $id ) ) {
     390                                return array(
     391                                        'restored' => array(),
     392                                        'failed'   => array( self::failure( (int) $id, __( 'Resume the pending backup recovery in Tools before changing this media.', 'rapid-media-reclaim' ) ) ),
     393                                        'bytes'    => 0,
     394                                );
     395                        }
     396                }
    235397                global $wpdb;
    236398                $key = 'smc:' . md5( DB_NAME . ':' . $wpdb->prefix );
    237                 if ( self::$operating || self::core_deleting() || doing_action( 'delete_attachment' ) || doing_action( 'deleted_post' ) || '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $key ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
     399                if ( self::is_operating() || self::core_deleting() || doing_action( 'delete_attachment' ) || doing_action( 'deleted_post' ) || '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $key ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
    238400                        return array(
    239401                                'restored' => array(),
    … …  
    258420         */
    259421        private static function restore_locked( array $ids ): array {
     422                foreach ( $ids as $id ) {
     423                        if ( Recovery_Import::is_protected( (int) $id ) ) {
     424                                return array(
     425                                        'restored' => array(),
     426                                        'failed'   => array( self::failure( (int) $id, __( 'Resume pending recovery in Tools first.', 'rapid-media-reclaim' ) ) ),
     427                                        'bytes'    => 0,
     428                                );
     429                        }
     430                }
    260431                $result  = array(
    261432                        'restored' => array(),
    … …  
    286457         *
    287458         * @param string $batch Batch.
    288          */
    289         public static function restore_batch( string $batch ): array {
     459         * @param int    $limit Optional attachment count per call.
     460         * @throws \RuntimeException Recovery batch state could not be verified.
     461         */
     462        public static function restore_batch( string $batch, int $limit = 0 ): array {
    290463                global $wpdb;
    291464                $batch = preg_replace( '/[^a-z0-9]/', '', strtolower( $batch ) );
    292465                // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    293                 $ids = $batch ? $wpdb->get_col(
    294                         $wpdb->prepare( 'SELECT attachment_id FROM ' . self::table() . ' WHERE batch = %s AND status = %s', $batch, 'quarantined' ) // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
     466                $limit_sql = $limit > 0 ? ' LIMIT ' . min( 500, $limit ) : '';
     467                $ids       = $batch ? $wpdb->get_col(
     468                        $wpdb->prepare( 'SELECT attachment_id FROM ' . self::table() . ' WHERE batch = %s AND status = %s ORDER BY id' . $limit_sql, $batch, 'quarantined' ) // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    295469                ) : array();
    296470                // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    297                 return self::restore( array_map( 'intval', (array) $ids ) );
     471                if ( $wpdb->last_error ) {
     472                        throw new \RuntimeException( __( 'Could not read the recovery batch. Retry the batch.', 'rapid-media-reclaim' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- REST JSON encodes the message.
     473                }
     474                $result = self::restore( array_map( 'intval', (array) $ids ) );
     475                if ( $limit > 0 ) {
     476                        $result['remaining'] = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM ' . self::table() . " WHERE batch=%s AND status='quarantined'", $batch ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Internal table and prepared batch value.
     477                        if ( $wpdb->last_error ) {
     478                                throw new \RuntimeException( __( 'Could not verify the remaining recovery records. Retry the batch.', 'rapid-media-reclaim' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- REST JSON encodes the message.
     479                        }
     480                }
     481                return $result;
    298482        }
    299483
    … …  
    302486         *
    303487         * @param array $ids Ids.
    304          * @param bool  $force Force.
     488         * @param bool  $force Deprecated; never bypasses waiting or backup requirements.
    305489         * @param bool  $retry_only Retry only.
    306490         */
    307491        public static function purge( array $ids, bool $force = false, bool $retry_only = false ): array {
     492                foreach ( $ids as $id ) {
     493                        if ( Recovery_Import::is_protected( (int) $id ) ) {
     494                                return array(
     495                                        'purged' => array(),
     496                                        'failed' => array( self::failure( (int) $id, __( 'Resume the pending backup recovery in Tools before changing this media.', 'rapid-media-reclaim' ) ) ),
     497                                        'bytes'  => 0,
     498                                );
     499                        }
     500                }
     501                $storage_error = Storage::mutation_error();
     502                if ( $storage_error ) {
     503                        return array(
     504                                'purged' => array(),
     505                                'failed' => array( self::failure( 0, $storage_error->get_error_message(), 'audit_only' ) ),
     506                                'bytes'  => 0,
     507                        );
     508                }
     509
    308510                global $wpdb;
    309511                $key = 'smc:' . md5( DB_NAME . ':' . $wpdb->prefix );
    310                 if ( self::$operating || self::core_deleting() || doing_action( 'delete_attachment' ) || doing_action( 'deleted_post' ) || '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $key ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
     512                if ( self::is_operating() || self::core_deleting() || doing_action( 'delete_attachment' ) || doing_action( 'deleted_post' ) || '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $key ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
    311513                        return array(
    312514                                'purged' => array(),
    … …  
    318520                try {
    319521                        do_action( 'safe_media_cleaner_operation_locked', 'purge', $ids );
    320                         return self::purge_locked( $ids, $force, $retry_only );
     522                        return self::purge_locked( $ids, $retry_only );
    321523                } finally {
    322524                        self::$operating = false;
    … …  
    329531         *
    330532         * @param array $ids Ids.
    331          * @param bool  $force Force.
    332533         * @param bool  $retry_only Retry only.
    333534         */
    334         private static function purge_locked( array $ids, bool $force = false, bool $retry_only = false ): array {
    335                 $result  = array(
     535        private static function purge_locked( array $ids, bool $retry_only = false ): array {
     536                foreach ( $ids as $id ) {
     537                        if ( Recovery_Import::is_protected( (int) $id ) ) {
     538                                return array(
     539                                        'purged' => array(),
     540                                        'failed' => array( self::failure( (int) $id, __( 'Resume pending recovery in Tools first.', 'rapid-media-reclaim' ) ) ),
     541                                        'bytes'  => 0,
     542                                );
     543                        }
     544                }
     545                $result                        = array(
    336546                        'purged' => array(),
    337547                        'failed' => array(),
    338548                        'bytes'  => 0,
    339549                );
    340                 $days    = (int) Settings::get()['quarantine_days'];
     550                $result['observation_warning'] = self::observation_warning();
     551                $result['observation']         = array();
     552                foreach ( self::clean_ids( $ids ) as $selected ) {
     553                        $result['observation'][ $selected ] = self::observation( $selected );
     554                }
    341555                $records = self::records_for( self::clean_ids( $ids ) );
    342556
    … …  
    351565                                continue;
    352566                        }
    353                         $age = time() - (int) strtotime( $record['created_at'] . ' UTC' );
    354                         if ( ! $force && $age < $days * DAY_IN_SECONDS ) {
    355                                 $result['failed'][] = self::failure(
    356                                         $id,
    357                                         sprintf(
    358                                                 /* translators: %d: number of days */
    359                                                 _n( 'This file has been in quarantine for less than %d day.', 'This file has been in quarantine for less than %d days.', $days, 'rapid-media-reclaim' ),
    360                                                 $days
    361                                         ),
    362                                         'too_recent'
    363                                 );
    364                                 continue;
    365                         }
    366567
    367568                        // The item may have come back into use after it was quarantined (for
    368569                        // example set as a featured image). Never delete it then, even when forced.
    369                         if ( ! $retry_only && get_post( $id ) && self::in_use_now( $id, $record ) ) {
     570                        if ( (int) ( $record['hits'] ?? 0 ) > 0 || ( get_post( $id ) && self::in_use_now( $id, $record ) ) ) {
    370571                                $result['failed'][] = self::failure( $id, __( 'This file is in use again (for example as a featured image or in content). Restore it instead of deleting it.', 'rapid-media-reclaim' ), 'in_use' );
    371572                                continue;
    … …  
    411612                        }
    412613
     614                        // Core translation callbacks may delete every sibling at once. Verify
     615                        // all members before any deletion intent is persisted or posts deleted.
     616                        $members = self::group_records( $id );
     617                        if ( ! isset( $members[ $id ] ) ) {
     618                                $result['failed'][] = self::failure( $id, __( 'Could not verify the complete recovery group. Nothing was deleted.', 'rapid-media-reclaim' ), 'recovery_unavailable' );
     619                                continue;
     620                        }
     621                        $eligible = true;
     622                        foreach ( $members as $member => $member_record ) {
     623                                if ( (int) ( $member_record['hits'] ?? 0 ) > 0 || ( get_post( $member ) && self::in_use_now( $member, $member_record ) ) ) {
     624                                        $result['failed'][] = self::failure( $id, __( 'A shared file is in use again. Restore the group instead of deleting it.', 'rapid-media-reclaim' ), 'in_use' );
     625                                        $eligible           = false;
     626                                        break;
     627                                }
     628                                $requirement = self::purge_requirement( $member, $member_record, $retry_only );
     629                                if ( $requirement ) {
     630                                        $result['failed'][] = self::failure( $id, $requirement->get_error_message(), $requirement->get_error_code() );
     631                                        $eligible           = false;
     632                                        break;
     633                                }
     634                        }
     635                        if ( ! $eligible ) {
     636                                continue;
     637                        }
    413638                        $purged = self::purge_one( $record, $retry_only );
    414639                        if ( is_wp_error( $purged ) ) {
    … …  
    420645                }
    421646                return $result;
     647        }
     648
     649        /**
     650         * Enforce immutable waiting and current recovery-backup requirements.
     651         *
     652         * An already authorized interrupted cleanup may resume without rebuilding a
     653         * backup from payloads it has already removed. Force is deliberately absent.
     654         *
     655         * @param int   $id Attachment ID.
     656         * @param array $record Current quarantine record under the operation lock.
     657         * @param bool  $retry_only Resume a previously authorized cleanup only.
     658         * @return \WP_Error|null A policy refusal, or null when requirements pass.
     659         */
     660        private static function purge_requirement( int $id, array $record, bool $retry_only ): ?\WP_Error {
     661                if ( $retry_only && ! empty( $record['purge_intent'] ) ) {
     662                        return null;
     663                }
     664                $days    = max( 14, min( 365, (int) Settings::get()['quarantine_days'] ) );
     665                $created = strtotime( (string) $record['created_at'] . ' UTC' );
     666                if ( false === $created || time() - $created < $days * DAY_IN_SECONDS ) {
     667                        return new \WP_Error(
     668                                'too_recent',
     669                                sprintf(
     670                                        /* translators: %d: minimum quarantine days. */
     671                                        __( 'Keep this file in quarantine for at least %d days before permanent deletion.', 'rapid-media-reclaim' ),
     672                                        $days
     673                                )
     674                        );
     675                }
     676                if ( ! Recovery_Export::is_backed_up( $id, $record ) ) {
     677                        return new \WP_Error( 'backup_required', __( 'Download and confirm a current recovery archive before permanent deletion.', 'rapid-media-reclaim' ) );
     678                }
     679                return null;
     680        }
     681
     682        /**
     683         * Fresh group observation facts. This never grants or removes manual purge permission.
     684         *
     685         * @param int $id Attachment ID.
     686         * @return array Conservative verification period.
     687         */
     688        public static function observation( int $id ): array {
     689                global $wpdb;
     690                $record = self::records_for( array( $id ) )[ $id ] ?? null;
     691                $failed = (bool) $wpdb->last_error || ! $record;
     692                wp_cache_delete( $id, 'post_meta' );
     693                $siblings = self::shared_with( $id );
     694                $failed   = $failed || (bool) $wpdb->last_error || count( $siblings ) > 500;
     695                $root     = (int) ( $record['owner_id'] ?? 0 );
     696                $root     = $root ? $root : $id;
     697                $ids      = self::clean_ids( array_merge( array( $id, $root ), $siblings ) );
     698                $table    = self::table();
     699                $rows     = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE status=%s AND (owner_id=%d OR attachment_id IN (" . implode( ',', $ids ) . ')) ORDER BY id LIMIT 501', 'quarantined', $root ), ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Bounded current group, internal table and integer-only IDs; never a scan cache.
     700                $failed   = $failed || (bool) $wpdb->last_error || ! is_array( $rows ) || count( (array) $rows ) > 500;
     701                $records  = array();
     702                foreach ( (array) $rows as $row ) {
     703                        $member                 = (int) $row['attachment_id'];
     704                        $row['recognized_seen'] = Request_Watcher::seen( $member );
     705                        $failed                 = $failed || (bool) $wpdb->last_error;
     706                        $records[ $member ]     = $row;
     707                }
     708                $failed = $failed || (bool) array_diff( $ids, array_keys( $records ) );
     709                if ( $failed ) {
     710                        Routing_Window::interrupt( 'group_unavailable' );
     711                        $records = array();
     712                }
     713                return Routing_Window::group( $records, Routing_Window::status(), time(), (int) Settings::get()['quarantine_days'] );
     714        }
     715
     716        /** Warning shared by manual deletion clients, irrespective of the age gate. */
     717        public static function observation_warning(): string {
     718                return __( 'Manual deletion may proceed with incomplete or browser-only routing verification. Quarantine age is separate from the verified window. No recognized requests does not prove that a file is unused. The minimum waiting period, usage and ownership checks, saved-backup confirmation and permissions still apply.', 'rapid-media-reclaim' );
    422719        }
    423720
    … …  
    573870         */
    574871        public static function guard_external_delete( $delete, $post, $force ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- Signature follows the pre_delete_attachment filter contract.
     872                if ( Recovery_Import::is_protected( (int) $post->ID ) ) {
     873                        return false;
     874                }
    575875                if ( isset( self::$purging[ (int) $post->ID ] ) ) {
    576876                        return $delete; }
    … …  
    625925
    626926                $files = self::attachment_files( $id );
     927                if ( is_wp_error( $files ) ) {
     928                        return $files; }
    627929                if ( ! $files ) {
    628930                        return new \WP_Error( 'safe_media_cleaner_no_files', __( 'No files were found for this media item.', 'rapid-media-reclaim' ) );
    … …  
    652954                        return new \WP_Error( 'safe_media_cleaner_manifest', __( 'Could not save recovery data. No files were moved.', 'rapid-media-reclaim' ) );
    653955                }
    654                 // Phase 1: link every file into quarantine. The public files are untouched,
    655                 // so any failure (no hard links on this filesystem, file owned by another
    656                 // user, disk full) is undone by removing only the links created here.
    657                 $linked = array();
     956                $ledger_record = self::records_for( array( $id ) )[ $id ];
    658957                foreach ( $moved as $file ) {
    659                         $from = $uploads . '/' . $file['from'];
    660                         $to   = $target . '/' . $file['to'];
    661                         if ( ! wp_mkdir_p( dirname( $to ) ) || ! self::link_file( $from, $to ) ) {
    662                                 self::abandon_move( $id, $linked, $target );
    663                                 return new \WP_Error( 'safe_media_cleaner_move_failed', __( 'This media item could not be moved (the server did not allow it). Recovery data has been retained if cleanup could not finish. Review this item before retrying.', 'rapid-media-reclaim' ) );
    664                         }
    665                         $linked[] = $file;
    666                 }
    667                 // Phase 2: remove the originals. If one cannot be removed, put back the
    668                 // ones already removed so the live site never loses a file.
    669                 $removed = array();
    670                 foreach ( $moved as $file ) {
    671                         if ( ! self::unlink_file( $uploads . '/' . $file['from'] ) ) {
    672                                 foreach ( $removed as $back ) {
    673                                         self::link_file( $target . '/' . $back['to'], $uploads . '/' . $back['from'] );
     958                        if ( ! Operation_Ledger::begin( $ledger_record, $file, 'quarantine' ) ) {
     959                                return Operation_Ledger::error();
     960                        }
     961                }
     962                $ledger_complete = false;
     963                try {
     964                        // Phase 1: link every file into quarantine. The public files are untouched,
     965                        // so any failure (no hard links on this filesystem, file owned by another
     966                        // user, disk full) is undone by removing only the links created here.
     967                        $linked = array();
     968                        foreach ( $moved as $file ) {
     969                                $from = $uploads . '/' . $file['from'];
     970                                $to   = $target . '/' . $file['to'];
     971                                if ( ! wp_mkdir_p( dirname( $to ) ) || ! self::link_file( $from, $to ) ) {
     972                                        self::abandon_move( $id, $linked, $target );
     973                                        return new \WP_Error( 'safe_media_cleaner_move_failed', __( 'This media item could not be moved (the server did not allow it). Recovery data has been retained if cleanup could not finish. Review this item before retrying.', 'rapid-media-reclaim' ) );
    674974                                }
    675                                 self::abandon_move( $id, $linked, $target );
    676                                 return new \WP_Error( 'safe_media_cleaner_move_failed', __( 'This media item could not be moved (a file could not be removed). Recovery data has been retained if cleanup could not finish. Review this item before retrying.', 'rapid-media-reclaim' ) );
    677                         }
    678                         $removed[] = $file;
    679                 }
    680 
     975                                $linked[] = $file;
     976                        }
     977                        // Phase 2: remove the originals. If one cannot be removed, put back the
     978                        // ones already removed so the live site never loses a file.
     979                        $removed = array();
     980                        foreach ( $moved as $file ) {
     981                                if ( ! self::unlink_file( $uploads . '/' . $file['from'] ) ) {
     982                                        foreach ( $removed as $back ) {
     983                                                self::link_file( $target . '/' . $back['to'], $uploads . '/' . $back['from'] );
     984                                        }
     985                                        self::abandon_move( $id, $linked, $target );
     986                                        return new \WP_Error( 'safe_media_cleaner_move_failed', __( 'This media item could not be moved (a file could not be removed). Recovery data has been retained if cleanup could not finish. Review this item before retrying.', 'rapid-media-reclaim' ) );
     987                                }
     988                                $removed[] = $file;
     989                        }
     990
     991                        $ledger_complete = true;
     992                } finally {
     993                        $ledger_saved = true;
     994                        foreach ( $moved as $file ) {
     995                                $ledger_saved = Operation_Ledger::finish( $ledger_record, $file, 'quarantine', $ledger_complete ? 'verified' : 'failed' ) && $ledger_saved;
     996                        }
     997                }
     998                if ( ! $ledger_saved ) {
     999                        return Operation_Ledger::error();
     1000                }
    6811001                do_action( 'safe_media_cleaner_quarantined', $id, $moved );
    6821002                return $bytes;
    … …  
    8261146                }
    8271147
    828                 $missing = array();
     1148                $ledger_saved = Operation_Ledger::mark( $record, true );
     1149                $missing      = array();
    8291150                foreach ( $files as $file ) {
    830                         $from = $source . '/' . $file['to'];
    831                         $to   = $uploads . '/' . $file['from'];
    832                         if ( ! self::inside( $from, self::uploads_dir() ) || ! self::inside( $to, $uploads ) ) {
    833                                 return new \WP_Error( 'safe_media_cleaner_path', __( 'Unsafe recovery path. Recovery data was retained.', 'rapid-media-reclaim' ) );
    834                         }
    835                         // A write-ahead identity makes interrupted moves/restores idempotent.
    836                         if ( is_file( $to ) && ! empty( $file['sha256'] ) && hash_equals( $file['sha256'], (string) hash_file( 'sha256', $to ) ) ) {
    837                                 if ( is_file( $from ) && ( ! hash_equals( $file['sha256'], (string) hash_file( 'sha256', $from ) ) || ! self::unlink_file( $from ) ) ) {
    838                                         return new \WP_Error( 'safe_media_cleaner_cleanup', __( 'Recovery cleanup incomplete. Retry restore.', 'rapid-media-reclaim' ) );
     1151                        $ledger_ready    = Operation_Ledger::begin( $record, $file, 'restore' );
     1152                        $ledger_source   = 'present' === Operation_Ledger::storage_state( $record, $file );
     1153                        $ledger_complete = false;
     1154                        try {
     1155
     1156                                $from = $source . '/' . $file['to'];
     1157                                $to   = $uploads . '/' . $file['from'];
     1158                                if ( ! self::inside( $from, self::uploads_dir() ) || ! self::inside( $to, $uploads ) ) {
     1159                                        return new \WP_Error( 'safe_media_cleaner_path', __( 'Unsafe recovery path. Recovery data was retained.', 'rapid-media-reclaim' ) );
    8391160                                }
    840                                 continue;
    841                         }
    842                         if ( file_exists( $to ) || ! is_file( $from ) || ( ! empty( $file['sha256'] ) && ! hash_equals( $file['sha256'], (string) hash_file( 'sha256', $from ) ) ) ) {
    843                                 return new \WP_Error( 'safe_media_cleaner_conflict', __( 'A recovery file is missing, changed, or its destination is occupied. Recovery data was retained.', 'rapid-media-reclaim' ) );
    844                         }
    845                         if ( ! wp_mkdir_p( dirname( $to ) ) || ! self::move_file( $from, $to ) ) {
    846                                 return new \WP_Error( 'safe_media_cleaner_restore_failed', __( 'Restore incomplete. Recovery data was retained; retry restore.', 'rapid-media-reclaim' ) );
    847                         }
     1161                                // A write-ahead identity makes interrupted moves/restores idempotent.
     1162                                if ( is_file( $to ) && (int) filesize( $to ) === (int) $file['bytes'] && ! empty( $file['sha256'] ) && hash_equals( $file['sha256'], (string) hash_file( 'sha256', $to ) ) ) {
     1163                                        if ( is_file( $from ) && ( ! hash_equals( $file['sha256'], (string) hash_file( 'sha256', $from ) ) || ! self::unlink_file( $from ) ) ) {
     1164                                                return new \WP_Error( 'safe_media_cleaner_cleanup', __( 'Recovery cleanup incomplete. Retry restore.', 'rapid-media-reclaim' ) );
     1165                                        }
     1166                                        $ledger_complete = true;
     1167                                        continue;
     1168                                }
     1169                                if ( file_exists( $to ) || ! is_file( $from ) || ( ! empty( $file['sha256'] ) && ! hash_equals( $file['sha256'], (string) hash_file( 'sha256', $from ) ) ) ) {
     1170                                        return new \WP_Error( 'safe_media_cleaner_conflict', __( 'A recovery file is missing, changed, or its destination is occupied. Recovery data was retained.', 'rapid-media-reclaim' ) );
     1171                                }
     1172                                if ( ! wp_mkdir_p( dirname( $to ) ) || ! self::move_file( $from, $to ) ) {
     1173                                        return new \WP_Error( 'safe_media_cleaner_restore_failed', __( 'Restore incomplete. Recovery data was retained; retry restore.', 'rapid-media-reclaim' ) );
     1174                                }
     1175                                $ledger_complete = true;
     1176                        } finally {
     1177                                $ledger_saved = $ledger_ready && Operation_Ledger::finish( $record, $file, 'restore', $ledger_complete ? ( $ledger_source ? 'verified' : 'unknown' ) : 'failed' ) && $ledger_saved;
     1178                        }
     1179                }
     1180                if ( ! $ledger_saved ) {
     1181                        return Operation_Ledger::error();
    8481182                }
    8491183
    … …  
    8671201                if ( get_post_meta( $id, self::META, true ) ) {
    8681202                        return new \WP_Error( 'safe_media_cleaner_meta', __( 'Could not clear recovery metadata. Retry restore.', 'rapid-media-reclaim' ) ); }
     1203                if ( ! Operation_Ledger::mark( $record, false ) ) {
     1204                        return Operation_Ledger::error();
     1205                }
    8691206                if ( ! self::update_record( (int) $record['id'], 'restored' ) ) {
    8701207                        return new \WP_Error( 'safe_media_cleaner_record', __( 'Files restored but recovery state could not be saved. Retry restore.', 'rapid-media-reclaim' ) ); }
    … …  
    9371274                                return new \WP_Error( 'safe_media_cleaner_purge_intent', __( 'Could not save permanent deletion authorization. Nothing was deleted.', 'rapid-media-reclaim' ) ); }
    9381275                }
     1276                foreach ( $files as $file ) {
     1277                        if ( ! Operation_Ledger::begin( $record, $file, 'remove' ) ) {
     1278                                return Operation_Ledger::error();
     1279                        }
     1280                }
     1281                if ( $files && ! Operation_Ledger::mark( $record, true ) ) {
     1282                        return Operation_Ledger::error();
     1283                }
    9391284                $group     = array_unique( array_merge( array( $id ), array_keys( $group_records ), self::shared_with( $id ) ) );
    9401285                $protected = array();
    … …  
    9581303                if ( ! self::delete_quarantined_files( $record ) ) {
    9591304                        return new \WP_Error( 'safe_media_cleaner_cleanup', __( 'Payload cleanup failed. Recovery record retained for retry.', 'rapid-media-reclaim' ) );
     1305                }
     1306                if ( $files && ! Operation_Ledger::mark( $record, false ) ) {
     1307                        return Operation_Ledger::error();
    9601308                }
    9611309                if ( ! self::update_record( (int) $record['id'], 'purged' ) ) {
    … …  
    10321380                $source = self::dir() . '/' . (int) $record['attachment_id'];
    10331381                foreach ( $files as $file ) {
    1034                         $path = $source . '/' . $file['to'];
    1035                         if ( ! self::inside( $path, self::uploads_dir() ) || ( file_exists( $path ) && ! self::unlink_file( $path ) ) ) {
    1036                                 return false; }
     1382                        if ( ! Operation_Ledger::begin( $record, $file, 'remove' ) ) {
     1383                                return false;
     1384                        }
     1385                        $path     = $source . '/' . $file['to'];
     1386                        $present  = 'present' === Operation_Ledger::storage_state( $record, $file );
     1387                        $unlinked = false;
     1388                        $removed  = self::inside( $path, self::uploads_dir() ) && ( ! file_exists( $path ) || ( $present && self::unlink_file( $path, $unlinked ) ) );
     1389                        $saved    = Operation_Ledger::finish( $record, $file, 'remove', $removed ? ( $present && $unlinked ? 'verified' : 'unknown' ) : 'failed' );
     1390                        if ( ! $removed || ! $saved ) {
     1391                                return false;
     1392                        }
    10371393                }
    10381394                self::remove_empty_dirs( $source );
    … …  
    10461402         *
    10471403         * @param int $id Id.
    1048          */
    1049         private static function attachment_files( int $id ): array {
     1404         * @return array|\WP_Error Files or a failed ownership check.
     1405         */
     1406        public static function attachment_files( int $id ) {
    10501407                $uploads  = self::uploads_dir();
    10511408                $attached = get_post_meta( $id, '_wp_attached_file', true );
    … …  
    10651422                // Files that belong to any other attachment in this folder are never ours,
    10661423                // even when their names look like one of our WebP/AVIF siblings.
    1067                 $claimed = self::claimed_names( $dir, array_merge( array( $id ), self::shared_with( $id ) ) );
     1424                $possible = array();
     1425                foreach ( $names as $name ) {
     1426                        $possible[] = $name;
     1427                        $stem       = preg_replace( '/\.[^.]+$/', '', $name );
     1428                        foreach ( array( 'webp', 'avif' ) as $ext ) {
     1429                                $possible[] = $name . '.' . $ext;
     1430                                $possible[] = $stem . '.' . $ext; }
     1431                }
     1432                $claimed = self::claimed_names( $dir, array_merge( array( $id ), self::shared_with( $id ) ), $possible );
     1433                if ( is_wp_error( $claimed ) ) {
     1434                        return $claimed; }
    10681435
    10691436                $files = array();
    … …  
    11391506         * @param string $dir     Relative folder with trailing slash, or ''.
    11401507         * @param array  $exclude Attachment IDs to ignore (the item and its copies).
    1141          */
    1142         private static function claimed_names( string $dir, array $exclude ): array {
     1508         * @param array  $candidates Optional names to retain.
     1509         * @return array|\WP_Error Ownership failure blocks the move.
     1510         */
     1511        private static function claimed_names( string $dir, array $exclude, array $candidates = array() ) {
    11431512                global $wpdb;
    1144                 $like = '' === $dir ? '%' : $wpdb->esc_like( $dir ) . '%';
    1145                 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Live ownership check before moving files; must not be cached.
    1146                 $rows    = $wpdb->get_results( $wpdb->prepare( "SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attached_file' AND meta_value LIKE %s", $like ) );
     1513                $like    = '' === $dir ? '%' : $wpdb->esc_like( $dir ) . '%';
    11471514                $exclude = array_flip( array_map( 'intval', $exclude ) );
     1515                $wanted  = array_flip( array_map( 'strtolower', $candidates ) );
    11481516                $claimed = array();
    1149                 foreach ( (array) $rows as $row ) {
    1150                         $other = (int) $row->post_id;
    1151                         $path  = ltrim( str_replace( '\\', '/', (string) $row->meta_value ), '/' );
    1152                         $odir  = dirname( $path );
    1153                         $odir  = '.' === $odir ? '' : $odir . '/';
    1154                         if ( isset( $exclude[ $other ] ) || $odir !== $dir ) {
    1155                                 continue;
    1156                         }
    1157                         foreach ( self::owned_names( $other, $path ) as $name ) {
    1158                                 $claimed[ strtolower( $name ) ] = true;
    1159                         }
    1160                 }
     1517                $cursor  = 0;
     1518                do {
     1519                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Live bounded ownership reads must not use the scan projection or a stale ownership cache.
     1520                        $rows = $wpdb->get_results( $wpdb->prepare( "SELECT meta_id,post_id,meta_value FROM {$wpdb->postmeta} WHERE meta_key='_wp_attached_file' AND meta_id>%d AND meta_value LIKE %s ORDER BY meta_id LIMIT 200", $cursor, $like ) );
     1521                        if ( $wpdb->last_error ) {
     1522                                return new \WP_Error( 'safe_media_cleaner_ownership', __( 'Could not verify file ownership. No files were moved.', 'rapid-media-reclaim' ) ); }
     1523                        $paths = array();
     1524                        foreach ( (array) $rows as $row ) {
     1525                                $cursor = (int) $row->meta_id;
     1526                                $other  = (int) $row->post_id;
     1527                                $path   = ltrim( str_replace( '\\', '/', (string) $row->meta_value ), '/' );
     1528                                $odir   = dirname( $path );
     1529                                $odir   = '.' === $odir ? '' : $odir . '/';
     1530                                if ( ! isset( $exclude[ $other ] ) && $odir === $dir ) {
     1531                                        $paths[ $other ] = $path; }
     1532                        }
     1533                        // Prime one bounded window, preserve metadata filters, and evict only
     1534                        // entries introduced here so root-level uploads cannot fill request memory.
     1535                        $introduced = array();
     1536                        foreach ( array_keys( $paths ) as $other ) {
     1537                                $found = false;
     1538                                wp_cache_get( $other, 'post_meta', false, $found );
     1539                                if ( ! $found ) {
     1540                                        $introduced[] = $other; }
     1541                        }
     1542                        try {
     1543                                if ( $paths ) {
     1544                                        update_meta_cache( 'post', array_keys( $paths ) ); }
     1545                                if ( $wpdb->last_error ) {
     1546                                        return new \WP_Error( 'safe_media_cleaner_ownership', __( 'Could not verify file ownership. No files were moved.', 'rapid-media-reclaim' ) ); }
     1547                                foreach ( $paths as $other => $path ) {
     1548                                        foreach ( self::owned_names( $other, $path ) as $name ) {
     1549                                                $name = strtolower( $name );
     1550                                                if ( ! $wanted || isset( $wanted[ $name ] ) ) {
     1551                                                        $claimed[ $name ] = true; }
     1552                                        }
     1553                                }
     1554                        } finally {
     1555                                foreach ( $introduced as $other ) {
     1556                                        wp_cache_delete( $other, 'post_meta' ); }
     1557                        }
     1558                        $count = count( (array) $rows );
     1559                } while ( 200 === $count );
    11611560                return $claimed;
    11621561        }
    … …  
    12101609        private static function in_use_now( int $id, array $record ): bool {
    12111610                global $wpdb;
    1212                 if ( (int) ( $record['hits'] ?? 0 ) > 0 || Index::usage_count( $id ) > 0 ) {
     1611                if ( (int) ( $record['hits'] ?? 0 ) > 0 || Request_Watcher::seen( $id ) > 0 || Index::usage_count( $id ) > 0 ) {
    12131612                        return true;
    12141613                }
    … …  
    12811680         *
    12821681         * @param string $path Path.
    1283          */
    1284         private static function unlink_file( string $path ): bool {
     1682         * @param bool   $unlinked Native syscall success receipt for accounting.
     1683         */
     1684        private static function unlink_file( string $path, bool &$unlinked = false ): bool {
     1685                $unlinked = false;
    12851686                if ( false === apply_filters( 'safe_media_cleaner_unlink_file_allowed', true, $path ) ) {
    12861687                        return false; }
    12871688                if ( ! self::inside( $path, self::uploads_dir() ) ) {
    12881689                        return false; }
    1289                 @unlink( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.unlink_unlink -- Delete the exact validated manifest path without third-party path filters; verify removal below.
     1690                $unlinked = @unlink( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.unlink_unlink -- Delete the exact validated manifest path without third-party path filters; verify removal below.
    12901691                clearstatcache( true, $path );
    12911692                return ! file_exists( $path );
  • rapid-media-reclaim/tags/1.1.0/includes/class-request-watcher.php

    r3794616 r3814937  
    140140                $lock = 'safe_media_cleaner_watch_' . md5( DB_NAME . ':' . $wpdb->prefix );
    141141                if ( '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s,0)', $lock ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
     142                        Server_Watch::gap( 'browser_lock' );
    142143                        return $reply; }
    143144                try {
    … …  
    147148                        $count  = (int) ( ( $rate['minute'] ?? 0 ) === $minute ? ( $rate['count'] ?? 0 ) : 0 );
    148149                        if ( $count >= 60 || ! self::client_allowed() ) {
     150                                Server_Watch::gap( 'browser_rate' );
    149151                                return $reply; }
    150152                        $new_rate = array(
    … …  
    155157                        wp_cache_delete( self::RATE_OPTION, 'options' );
    156158                        if ( get_option( self::RATE_OPTION ) !== $new_rate ) {
     159                                Server_Watch::gap( 'browser_rate_persistence' );
    157160                                return $reply; }
    158161                        $ids           = array();
    159162                        $manifest_rows = self::manifest_rows();
    160163                        foreach ( array_keys( $paths ) as $path ) {
     164                                File_Quarantine::requested( $path );
    161165                                $ids = array_merge( $ids, self::matching_ids( $path, $manifest_rows ) ); }
     166                        if ( count( array_unique( $ids ) ) > 100 ) {
     167                                Server_Watch::gap( 'browser_owner_bound' );
     168                        }
    162169                        // Anonymous reports only count for media a visitor could actually see.
    163170                        $ids = array_values( array_filter( array_slice( array_unique( $ids ), 0, 100 ), array( __CLASS__, 'is_public' ) ) );
    … …  
    166173                        foreach ( $ids as $id ) {
    167174                                update_post_meta( $id, self::SEEN_META, time() );
     175                                if ( ! self::seen( $id ) ) {
     176                                        Server_Watch::gap( 'browser_hit_persistence' );
     177                                }
    168178                        }
    169179                        foreach ( array_unique( array_filter( array( Scan_Runner::current_generation(), Scan_Runner::building_generation() ) ) ) as $generation ) {
    170180                                self::write_evidence( $ids, (int) $generation ); }
    171181                        foreach ( $ids as $id ) {
    172                                 $wpdb->query( $wpdb->prepare( 'UPDATE ' . Installer::table( 'quarantine' ) . " SET hits=hits+1,last_hit_at=%s WHERE attachment_id=%d AND status='quarantined'", gmdate( 'Y-m-d H:i:s' ), $id ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     182                                $written = $wpdb->query( $wpdb->prepare( 'UPDATE ' . Installer::table( 'quarantine' ) . " SET hits=hits+1,last_hit_at=%s WHERE attachment_id=%d AND status='quarantined'", gmdate( 'Y-m-d H:i:s' ), $id ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     183                                if ( false === $written || $wpdb->last_error ) {
     184                                        Server_Watch::gap( 'browser_hit_sql' );
     185                                }
    173186                        }
    174187                        if ( ! empty( $settings['auto_restore'] ) && $ids ) {
    … …  
    176189                } catch ( \Throwable $error ) {
    177190                        // Public callers receive no database details or quarantine state.
     191                        Server_Watch::gap( 'browser_worker' );
    178192                        return $reply;
    179193                } finally {
    180                         $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock ) ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
     194                        if ( '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- A failed unlock is a known interruption, never a cached result.
     195                                Server_Watch::gap( 'browser_unlock' );
     196                        }
     197                }
    181198                return $reply;
    182199        }
    … …  
    188205         */
    189206        public static function seen( int $id ): int {
     207                wp_cache_delete( $id, 'post_meta' );
    190208                return (int) get_post_meta( $id, self::SEEN_META, true );
    191209        }
    … …  
    221239                }
    222240                set_transient( $key, $count + 1, MINUTE_IN_SECONDS );
     241                if ( (int) get_transient( $key ) !== $count + 1 ) {
     242                        Server_Watch::gap( 'browser_client_rate_persistence' );
     243                        return false;
     244                }
    223245                return true;
    224246        }
    … …  
    231253                $table = Installer::table( 'quarantine' );
    232254                $rows  = $wpdb->get_results( $wpdb->prepare( "SELECT attachment_id,bytes,LEFT(files,%d) AS files FROM {$table} WHERE status=%s ORDER BY id DESC LIMIT 500", 16385, 'quarantined' ), ARRAY_A ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     255                if ( $wpdb->last_error || ! is_array( $rows ) || count( $rows ) >= 500 ) {
     256                        Server_Watch::gap( 'browser_manifest_sql_or_bound' );
     257                }
    233258                $out   = array();
    234259                $bytes = 0;
    … …  
    236261                        $length = strlen( $row['files'] );
    237262                        if ( $length > 16384 ) {
     263                                Server_Watch::gap( 'browser_manifest_bound' );
    238264                                continue; }
    239265                        if ( $bytes + $length > 1048576 ) {
     266                                Server_Watch::gap( 'browser_manifest_bound' );
    240267                                break; }
    241268                        $bytes          += $length;
    242                         $row['manifest'] = json_decode( $row['files'], true );
     269                        $row['manifest'] = json_decode( $row['files'], true, 32 );
     270                        if ( ! Server_Watch::valid_manifest( (string) $row['files'] ) ) {
     271                                Server_Watch::gap( 'browser_manifest_invalid' );
     272                                continue;
     273                        }
    243274                        unset( $row['files'] );
    244275                        if ( is_array( $row['manifest'] ) ) {
    … …  
    289320                $generation = Scan_Runner::current_generation();
    290321                $ids        = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT attachment_id FROM {$files} WHERE path = %s AND generation=%d LIMIT 100", strtolower( $path ), $generation ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     322                if ( $wpdb->last_error || count( (array) $ids ) >= 100 ) {
     323                        Server_Watch::gap( 'browser_lookup_sql_or_bound' );
     324                }
    291325                // Quarantined files can be absent from a later file map. Bound manifest work.
    292326                foreach ( $rows as $row ) {
    … …  
    339373         */
    340374        private static function write_evidence( array $ids, int $generation ): void {
     375                Status_Index::write(
     376                        array( $generation ),
     377                        static function () use ( $ids, $generation ) {
     378                                self::write_evidence_rows( $ids, $generation );
     379                        }
     380                );
     381        }
     382
     383        /**
     384         * Write observed evidence.
     385         *
     386         * @param array $ids IDs.
     387         * @param int   $generation Generation.
     388         * @throws \RuntimeException Evidence write failed.
     389         */
     390        private static function write_evidence_rows( array $ids, int $generation ): void {
    341391                global $wpdb;
    342392                if ( $generation < 1 ) {
  • rapid-media-reclaim/tags/1.1.0/includes/class-scan-runner.php

    r3794616 r3814937  
    2020final class Scan_Runner {
    2121
    22         const OPTION    = 'safe_media_cleaner_scan_state';
    23         const LOCK      = 'safe_media_cleaner_scan_lock';
    24         const CRON_HOOK = 'safe_media_cleaner_scan_continue';
     22        const OPTION         = 'safe_media_cleaner_scan_state';
     23        const LOCK           = 'safe_media_cleaner_scan_lock';
     24        const CRON_HOOK      = 'safe_media_cleaner_scan_continue';
     25        const CLEANUP_HOOK   = 'safe_media_cleaner_index_cleanup';
     26        const CLEANUP_CURSOR = 'safe_media_cleaner_index_cleanup_cursor';
    2527
    2628        /** Seconds of work per step. */
    … …  
    3537        public static function init(): void {
    3638                add_action( self::CRON_HOOK, array( __CLASS__, 'cron_step' ) );
     39                add_action( self::CLEANUP_HOOK, array( __CLASS__, 'cleanup_old_index' ) );
    3740        }
    3841
    … …  
    130133
    131134                $state = array(
    132                         'status'      => 'running',
    133                         'generation'  => $generation,
    134                         'phases'      => $phases,
    135                         'phase_index' => 0,
    136                         'cursor'      => null,
    137                         'phase_done'  => 0,
    138                         'started_at'  => time(),
    139                         'finished_at' => null,
    140                         'error'       => null,
     135                        'status'            => 'running',
     136                        'generation'        => $generation,
     137                        'phases'            => $phases,
     138                        'phase_index'       => 0,
     139                        'cursor'            => null,
     140                        'phase_done'        => 0,
     141                        'started_at'        => time(),
     142                        'finished_at'       => null,
     143                        'error'             => null,
     144                        'incremental_fault' => Deferred_Index::fault_token(),
    141145                );
    142146                self::save( $state );
    … …  
    218222        public static function cron_step(): void {
    219223                // The admin screen may also be stepping; the lock keeps them apart.
    220                 self::step();
     224                try {
     225                        self::step();
     226                } finally {
     227                        self::repair_continuation();
     228                }
    221229        }
    222230
    … …  
    259267                                return self::abandon( (int) $state['generation'] );
    260268                        }
    261                         $state = self::finish( $state, $engine );
     269                        $state = self::finish( $state, $engine, $deadline );
    262270                }
    263271
    … …  
    282290         * @param array  $state State.
    283291         * @param Engine $engine Engine.
    284          */
    285         private static function finish( array $state, Engine $engine ): array {
     292         * @param float  $deadline Step deadline.
     293         */
     294        private static function finish( array $state, Engine $engine, float $deadline ): array {
    286295                $generation = (int) $state['generation'];
    287                 $previous   = self::current_generation();
    288 
    289                 Request_Watcher::replay( $generation );
    290                 self::link_shared_files( $generation );
     296
     297                if ( microtime( true ) >= $deadline ) {
     298                        return $state;
     299                }
     300                if ( empty( $state['watch_replayed'] ) ) {
     301                        Request_Watcher::replay( $generation );
     302                        $state['watch_replayed'] = true;
     303                }
     304                do {
     305                        $shared                 = self::link_shared_files( $generation, (int) ( $state['shared_cursor'] ?? 0 ) );
     306                        $state['shared_cursor'] = $shared['cursor'];
     307                        self::save( $state );
     308                        if ( ! self::still_running( $generation ) ) {
     309                                return self::abandon( $generation );
     310                        }
     311                } while ( ! $shared['done'] && microtime( true ) < $deadline );
     312                if ( ! $shared['done'] ) {
     313                        return $state;
     314                }
    291315                update_option( 'safe_media_cleaner_index_generation', $generation, false );
    292316                update_option(
    … …  
    306330                self::save( $state );
    307331
    308                 if ( $previous && $previous !== $generation ) {
    309                         self::delete_generation_rows( $previous );
    310                 }
    311                 self::delete_stale_rows( $generation );
     332                Deferred_Index::clear_fault( (string) ( $state['incremental_fault'] ?? '' ) );
     333                self::schedule_cleanup();
     334                Status_Index::schedule();
    312335
    313336                return $state;
    … …  
    319342         *
    320343         * @param int $generation Generation.
    321          */
    322         private static function link_shared_files( int $generation ): void {
     344         * @param int $after Last processed file-row ID.
     345         * @throws \RuntimeException Database read/write failure.
     346         */
     347        private static function link_shared_files( int $generation, int $after ): array {
    323348                global $wpdb;
    324349                $files = Installer::table( 'files' );
    325350                $refs  = Installer::table( 'refs' );
    326                 // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table names only.
    327                 // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    328                 $wpdb->query(
     351                // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Internal table identifiers; live cursor batches, values prepared.
     352                $ids = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM {$files} WHERE generation=%d AND kind='original' AND id>%d ORDER BY id LIMIT 500", $generation, $after ) );
     353                if ( $wpdb->last_error ) {
     354                        throw new \RuntimeException( 'Could not read shared-file inventory.' );
     355                }
     356                if ( ! $ids ) {
     357                        return array(
     358                                'cursor' => $after,
     359                                'done'   => true,
     360                        );
     361                }
     362                $list    = implode( ',', array_map( 'intval', $ids ) );
     363                $written = $wpdb->query(
    329364                        $wpdb->prepare(
    330                                 "INSERT INTO {$refs} (attachment_id, strength, source_type, source_id, source_key, context, match_type, generation)
    331                                 SELECT DISTINCT other.attachment_id, 'strong', 'shared_file', used.attachment_id, '', %s, 'id', %d
    332                                 FROM {$files} used
    333                                 JOIN {$files} other ON other.path = used.path AND other.attachment_id <> used.attachment_id
    334                                         AND other.generation = %d AND other.kind = 'original'
    335                                 WHERE used.generation = %d AND used.kind = 'original'
    336                                         AND EXISTS ( SELECT 1 FROM {$refs} r WHERE r.attachment_id = used.attachment_id AND r.generation = %d
    337                                                 AND r.strength = 'strong' AND r.source_type <> 'shared_file' )",
     365                                "INSERT INTO {$refs} (attachment_id,strength,source_type,source_id,source_key,context,match_type,generation)
     366                        SELECT DISTINCT other.attachment_id,'strong','shared_file',used.attachment_id,'',%s,'id',%d
     367                        FROM {$files} used
     368                        STRAIGHT_JOIN {$files} other ON other.generation=%d AND other.kind='original' AND other.path=used.path AND other.attachment_id<>used.attachment_id
     369                        WHERE used.id IN ({$list}) AND used.generation=%d AND used.kind='original'
     370                        AND EXISTS (SELECT 1 FROM {$refs} r WHERE r.attachment_id=used.attachment_id AND r.generation=%d AND r.strength='strong' AND r.source_type<>'shared_file')
     371                        AND NOT EXISTS (SELECT 1 FROM {$refs} r WHERE r.attachment_id=other.attachment_id AND r.generation=%d AND r.source_type='shared_file' AND r.source_id=used.attachment_id)",
    338372                                __( 'Shares its file with another media item', 'rapid-media-reclaim' ),
     373                                $generation,
    339374                                $generation,
    340375                                $generation,
    … …  
    343378                        )
    344379                );
    345                 // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    346                 // phpcs:enable
     380                // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
     381                if ( false === $written ) {
     382                        throw new \RuntimeException( 'Could not preserve shared-file usage evidence.' );
     383                }
     384                return array(
     385                        'cursor' => (int) max( $ids ),
     386                        'done'   => count( $ids ) < 500,
     387                );
    347388        }
    348389
    … …  
    359400                delete_option( 'safe_media_cleaner_adapter_gap_' . $generation . '_elementor' );
    360401                delete_option( 'safe_media_cleaner_adapter_gap_' . $generation . '_acf' );
    361                 foreach ( array( 'files', 'refs' ) as $name ) {
     402                delete_option( 'safe_media_cleaner_adapter_gap_' . $generation . '_database' );
     403                foreach ( array( 'files', 'refs', 'status' ) as $name ) {
    362404                        $table = Installer::table( $name );
    363405                        do {
    … …  
    367409        }
    368410
    369         /**
    370          * Remove rows left over from any generation other than the current one.
    371          *
    372          * @param int $generation Generation.
    373          */
    374         private static function delete_stale_rows( int $generation ): void {
     411        /** Queue cleanup separately from publishing a completed scan. */
     412        private static function schedule_cleanup(): void {
     413                if ( ! wp_next_scheduled( self::CLEANUP_HOOK ) ) {
     414                        wp_schedule_single_event( time() + 5, self::CLEANUP_HOOK );
     415                }
     416        }
     417
     418        /**
     419         * Delete obsolete index data with a two-second cooperative budget and four-query cap.
     420         *
     421         * Each SQL delete is limited to 1,000 rows. The scan lock protects publication
     422         * and generation reuse. Failed or busy work is retried without changing scan status.
     423         * A single database operation cannot be interrupted by the PHP deadline.
     424         *
     425         * @return array Cleanup progress, never a media deletion result.
     426         */
     427        public static function cleanup_old_index(): array {
    375428                global $wpdb;
    376                 // Per-generation bookkeeping of earlier, cancelled or abandoned scans.
    377                 $names = $wpdb->get_col( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'safe\\_media\\_cleaner\\_scan\\_coverage\\_%' OR option_name LIKE 'safe\\_media\\_cleaner\\_crawl\\_%' OR option_name LIKE 'safe\\_media\\_cleaner\\_adapter\\_%'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Option names by prefix; no API lists them.
    378                 foreach ( (array) $names as $name ) {
    379                         // Match generation numbers in scan coverage, crawl and adapter bookkeeping names.
    380                         if ( preg_match( '/_(?:coverage|crawl|gap)_(\d+)(?:_[a-z]+)?$/', $name, $m ) && (int) $m[1] !== $generation ) {
    381                                 delete_option( $name );
    382                         }
    383                 }
    384                 foreach ( array( 'files', 'refs' ) as $name ) {
    385                         $table = Installer::table( $name );
    386                         do {
    387                                 $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE generation <> %d LIMIT 5000", $generation ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    388                         } while ( $deleted > 0 );
    389                 }
     429                $result = array(
     430                        'deleted' => 0,
     431                        'pending' => false,
     432                        'error'   => false,
     433                );
     434                if ( ! self::lock() ) {
     435                        self::schedule_cleanup();
     436                        $result['pending'] = true;
     437                        return $result;
     438                }
     439                try {
     440                        wp_cache_delete( 'safe_media_cleaner_index_generation', 'options' );
     441                        wp_cache_delete( self::OPTION, 'options' );
     442                        $generation = self::current_generation();
     443                        $state      = self::raw();
     444                        $building   = 'running' === $state['status'] ? (int) $state['generation'] : $generation;
     445                        $deadline   = microtime( true ) + 2.0;
     446                        // Both protected generations are reread only after acquiring the scan lock.
     447                        // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Internal table names, prepared values, fresh bounded maintenance queries.
     448                        $delete_queries = 0;
     449                        foreach ( array( 'files', 'refs', 'status' ) as $name ) {
     450                                $table = Installer::table( $name );
     451                                for ( $batch = 0; $batch < 2; ++$batch ) {
     452                                        if ( microtime( true ) >= $deadline || $delete_queries >= 4 ) {
     453                                                $result['pending'] = true;
     454                                                break 2;
     455                                        }
     456                                        ++$delete_queries;
     457                                        $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE generation NOT IN (%d,%d) LIMIT 1000", $generation, $building ) );
     458                                        if ( false === $deleted ) {
     459                                                $result['error']   = true;
     460                                                $result['pending'] = true;
     461                                                break 2;
     462                                        }
     463                                        $result['deleted'] += $deleted;
     464                                        if ( $deleted < 1000 ) {
     465                                                break;
     466                                        }
     467                                        $result['pending'] = true;
     468                                }
     469                        }
     470                        if ( microtime( true ) >= $deadline ) {
     471                                $result['pending'] = true;
     472                        } else {
     473                                $cursor = (string) get_option( self::CLEANUP_CURSOR, '' );
     474                                $names  = $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE (option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s) AND option_name>%s ORDER BY option_name LIMIT 50", $wpdb->esc_like( 'safe_media_cleaner_scan_coverage_' ) . '%', $wpdb->esc_like( 'safe_media_cleaner_crawl_' ) . '%', $wpdb->esc_like( 'safe_media_cleaner_adapter_' ) . '%', $cursor ) );
     475                                if ( $wpdb->last_error ) {
     476                                        $result['error']   = true;
     477                                        $result['pending'] = true;
     478                                } else {
     479                                        foreach ( $names as $name ) {
     480                                                if ( microtime( true ) >= $deadline ) {
     481                                                        $result['pending'] = true;
     482                                                        break;
     483                                                }
     484                                                $cursor = $name;
     485                                                if ( preg_match( '/_(?:coverage|crawl|gap)_(\d+)(?:_[a-z]+)?$/', $name, $match ) && ! in_array( (int) $match[1], array( $generation, $building ), true ) ) {
     486                                                        delete_option( $name );
     487                                                }
     488                                        }
     489                                        $complete = ! $names || end( $names ) === $cursor;
     490                                        update_option( self::CLEANUP_CURSOR, $complete && 50 > count( $names ) ? '' : $cursor, false );
     491                                        $result['pending'] = $result['pending'] || ! $complete || 50 === count( $names );
     492                                }
     493                        }
     494                        // phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
     495                } finally {
     496                        self::unlock();
     497                }
     498                if ( $result['pending'] ) {
     499                        self::schedule_cleanup();
     500                }
     501                return $result;
    390502        }
    391503
    … …  
    402514        }
    403515
     516        /** Repair a missing event without running scan work in the maintenance request. */
     517        public static function repair_continuation(): void {
     518                wp_cache_delete( self::OPTION, 'options' );
     519                if ( 'running' === self::raw()['status'] ) {
     520                        self::schedule_cron();
     521                }
     522        }
     523
    404524        /**
    405525         * Schedule the next background scan step.
    … …  
    407527        private static function schedule_cron(): void {
    408528                if ( ! wp_next_scheduled( self::CRON_HOOK ) ) {
    409                         wp_schedule_single_event( time() + 60, self::CRON_HOOK );
     529                        wp_schedule_single_event( time() + 5, self::CRON_HOOK );
    410530                }
    411531        }
    … …  
    488608                        'status'      => $state['status'],
    489609                        'phase'       => $current ? $current['id'] : null,
    490                         'phase_label' => $current ? $current['label'] : null,
     610                        'phase_label' => 'running' === $state['status'] && $state['phase_index'] >= count( $phases ) ? __( 'Finalizing shared-file evidence', 'rapid-media-reclaim' ) : ( $current ? $current['label'] : null ),
    491611                        'phase_index' => (int) $state['phase_index'],
    492612                        'phase_count' => count( $phases ),
  • rapid-media-reclaim/tags/1.1.0/includes/class-settings.php

    r3794616 r3814937  
    2929                        'frontend_crawl'  => false,
    3030                        'crawl_limit'     => 100,
     31                        'upload_aliases'  => array(),
    3132                );
    3233        }
    … …  
    5960                $values = array_merge( self::defaults(), array_intersect_key( $values, self::defaults() ) );
    6061                return array(
    61                         'quarantine_days' => max( 0, min( 365, (int) $values['quarantine_days'] ) ),
     62                        'quarantine_days' => max( 14, min( 365, (int) $values['quarantine_days'] ) ),
    6263                        'include_drafts'  => (bool) $values['include_drafts'],
    6364                        'include_trash'   => (bool) $values['include_trash'],
    … …  
    6667                        'frontend_crawl'  => rest_sanitize_boolean( $values['frontend_crawl'] ),
    6768                        'crawl_limit'     => max( 1, min( 500, (int) $values['crawl_limit'] ) ),
     69                        'upload_aliases'  => self::aliases( $values['upload_aliases'] ),
    6870                );
    6971        }
     72        /**
     73         * Validate explicit old/CDN upload roots; aliases never authorize network requests.
     74         *
     75         * @param mixed $values User-supplied roots.
     76         */
     77        public static function aliases( $values ): array {
     78                $out = array();
     79                foreach ( is_array( $values ) ? array_slice( $values, 0, 10 ) : array() as $value ) {
     80                        if ( ! is_string( $value ) || strlen( $value ) > 2048 ) {
     81                                continue;
     82                        }
     83                        $parts = wp_parse_url( $value );
     84                        if ( ! is_array( $parts ) || ! in_array( strtolower( $parts['scheme'] ?? '' ), array( 'http', 'https' ), true ) || empty( $parts['host'] ) || isset( $parts['user'] ) || isset( $parts['pass'] ) || isset( $parts['query'] ) || isset( $parts['fragment'] ) || preg_match( '~[\\\\\x00-\x20]|(?:^|/)\.{1,2}(?:/|$)~', $value ) ) {
     85                                continue;
     86                        }
     87                        $out[] = rtrim( esc_url_raw( $value, array( 'http', 'https' ) ), '/' );
     88                }
     89                return array_values( array_unique( array_filter( $out ) ) );
     90        }
    7091}
  • rapid-media-reclaim/tags/1.1.0/includes/rest/class-controller.php

    r3794616 r3814937  
    2929
    3030        /** Most IDs accepted by one bulk request. */
    31         const MAX_IDS = 500;
     31        const MAX_IDS      = 500;
     32        const MAX_FILE_IDS = 10;
    3233
    3334        /** Most IDs returned by "select all matching". */
    … …  
    7273                );
    7374                $this->route( '/usage', $read, 'get_usage', array( 'ids' => $this->ids_arg( true ) ) );
    74                 $this->route( '/quarantine', $write, 'quarantine', array( 'ids' => $this->ids_arg( true ) ) );
     75                $this->route( '/quarantine', $write, 'quarantine', array( 'ids' => $this->ids_arg( true, self::MAX_FILE_IDS ) ) );
    7576                $this->route(
    7677                        '/restore',
    … …  
    7879                        'restore',
    7980                        array(
    80                                 'ids'   => $this->ids_arg( false ),
     81                                'ids'   => $this->ids_arg( false, self::MAX_FILE_IDS ),
    8182                                'batch' => array(
    8283                                        'type'      => 'string',
    … …  
    9596                                        'default' => false,
    9697                                ),
    97                                 'ids'        => $this->ids_arg( true ),
     98                                'ids'        => $this->ids_arg( true, self::MAX_FILE_IDS ),
    9899                                'force'      => array(
    99100                                        'type'    => 'boolean',
    … …  
    131132                                                'quarantine_days' => array(
    132133                                                        'type'    => 'integer',
    133                                                         'minimum' => 0,
     134                                                        'minimum' => 14,
    134135                                                        'maximum' => 365,
     136                                                ),
     137                                                'upload_aliases'  => array(
     138                                                        'type'     => 'array',
     139                                                        'maxItems' => 10,
     140                                                        'items'    => array(
     141                                                                'type'      => 'string',
     142                                                                'maxLength' => 2048,
     143                                                                'pattern'   => '^https?://',
     144                                                        ),
    135145                                                ),
    136146                                                'include_drafts'  => array( 'type' => 'boolean' ),
    … …  
    174184         */
    175185        public static function summary_payload(): array {
    176                 return array(
    177                         'summary'  => Index::summary(),
     186                $summary = Index::summary();
     187                \SafeMediaCleaner\Savings_Report::remember_estimate( $summary );
     188                return array(
     189                        'summary'  => $summary,
    178190                        'scan'     => Scan_Runner::state(),
    179191                        'settings' => Settings::get(),
    … …  
    337349                $ids   = (array) $request['ids'];
    338350                if ( '' !== $batch ) {
    339                         $result = Quarantine::restore_batch( $batch );
     351                        $result = Quarantine::restore_batch( $batch, self::MAX_FILE_IDS );
    340352                } elseif ( $ids ) {
    341353                        $result = Quarantine::restore( Index::with_copies( $ids ) );
    … …  
    409421                }
    410422                $values = array();
    411                 foreach ( array( 'quarantine_days', 'include_drafts', 'include_trash', 'request_watch', 'auto_restore', 'frontend_crawl', 'crawl_limit' ) as $key ) {
     423                foreach ( array( 'quarantine_days', 'include_drafts', 'include_trash', 'request_watch', 'auto_restore', 'frontend_crawl', 'crawl_limit', 'upload_aliases' ) as $key ) {
    412424                        if ( null !== $request->get_param( $key ) ) {
    413425                                $values[ $key ] = $request->get_param( $key );
    … …  
    420432                        'settings'     => $settings,
    421433                        // Changing what counts as use only takes effect after a new scan.
    422                         'needs_rescan' => $before['include_drafts'] !== $settings['include_drafts'] || $before['include_trash'] !== $settings['include_trash'] || $before['frontend_crawl'] !== $settings['frontend_crawl'] || $before['crawl_limit'] !== $settings['crawl_limit'],
     434                        'needs_rescan' => $before['include_drafts'] !== $settings['include_drafts'] || $before['include_trash'] !== $settings['include_trash'] || $before['frontend_crawl'] !== $settings['frontend_crawl'] || $before['crawl_limit'] !== $settings['crawl_limit'] || $before['upload_aliases'] !== $settings['upload_aliases'],
    423435                        'summary'      => Index::summary(),
    424436                );
    … …  
    488500         *
    489501         * @param bool $required Required.
    490          */
    491         private function ids_arg( bool $required ): array {
     502         * @param int  $limit Maximum request IDs.
     503         */
     504        private function ids_arg( bool $required, int $limit = self::MAX_IDS ): array {
    492505                return array(
    493506                        'type'              => 'array',
    … …  
    497510                        ),
    498511                        'minItems'          => $required ? 1 : 0,
    499                         'maxItems'          => self::MAX_IDS,
     512                        'maxItems'          => $limit,
    500513                        'required'          => $required,
    501                         'sanitize_callback' => static function ( $value ) {
    502                                 return array_slice( array_values( array_unique( array_filter( wp_parse_id_list( $value ) ) ) ), 0, self::MAX_IDS );
     514                        'sanitize_callback' => static function ( $value ) use ( $limit ) {
     515                                return array_slice( array_values( array_unique( array_filter( wp_parse_id_list( $value ) ) ) ), 0, $limit );
    503516                        },
    504517                        'validate_callback' => 'rest_validate_request_arg',
  • rapid-media-reclaim/tags/1.1.0/includes/scan/class-acf-adapter.php

    r3794616 r3814937  
    1717         * Extract media evidence. Limits apply across the complete input walk.
    1818         *
    19          * @param mixed  $value Stored metadata value.
    20          * @param array  $field Trusted persisted field definition.
    21          * @param string $path Actual metadata storage key.
     19         * @param mixed      $value Stored metadata value.
     20         * @param array      $field Trusted persisted field definition.
     21         * @param string     $path Actual metadata storage key.
     22         * @param array|null $budget Shared owner counters.
    2223         * @return array References and distinct coverage issue reasons.
    2324         */
    24         public static function extract( $value, array $field, string $path = '' ): array {
    25                 $result  = array(
     25        public static function extract( $value, array $field, string $path = '', ?array &$budget = null ): array {
     26                if ( null === $budget ) {
     27                        $budget = array(
     28                                'nodes' => 0,
     29                                'bytes' => 0,
     30                                'refs'  => 0,
     31                        );
     32                }
     33                $result = array(
    2634                        'refs'   => array(),
    2735                        'issues' => array(),
    2836                );
    29                 $type    = isset( $field['type'] ) && is_string( $field['type'] ) ? $field['type'] : '';
     37                $type   = isset( $field['type'] ) && is_string( $field['type'] ) ? $field['type'] : '';
     38                if ( ! empty( $field['_structural_validated'] ) && in_array( $type, array( 'group', 'repeater', 'flexible_content' ), true ) ) {
     39                        return $result; // Owner validator consumed selectors; they are never references.
     40                }
    3041                $media   = in_array( $type, array( 'image', 'file', 'gallery' ), true );
    3142                $known   = in_array( $type, array( 'text', 'textarea', 'number', 'range', 'email', 'url', 'password', 'select', 'checkbox', 'radio', 'button_group', 'true_false', 'post_object', 'relationship', 'taxonomy', 'user', 'date_picker', 'date_time_picker', 'time_picker', 'color_picker', 'message', 'tab', 'accordion' ), true );
    … …  
    4152                        list( $item, $depth, $eligible ) = array_pop( $stack );
    4253                        ++$nodes;
    43                         if ( $depth > 24 || $nodes > 5000 || $bytes > 524288 ) {
     54                        ++$budget['nodes'];
     55                        if ( $depth > 24 || $nodes > 5000 || $bytes > 524288 || $budget['nodes'] > 5000 || $budget['bytes'] > 4194304 ) {
    4456                                $result['issues'][] = 'acf_budget_exceeded';
    4557                                break;
    … …  
    6476                                continue;
    6577                        }
    66                         $text   = trim( (string) $item );
    67                         $bytes += strlen( $text );
     78                        $text             = trim( (string) $item );
     79                        $bytes           += strlen( $text );
     80                        $budget['bytes'] += strlen( $text );
    6881                        if ( $bytes > 524288 ) {
    6982                                $result['issues'][] = 'acf_budget_exceeded';
    … …  
    112125                        }
    113126                        if ( $match ) {
    114                                 if ( count( $result['refs'] ) >= 1000 ) {
     127                                if ( $budget['refs'] >= 1000 ) {
    115128                                        $result['issues'][] = 'acf_reference_limit_exceeded';
    116129                                        break;
    117130                                }
     131                                ++$budget['refs'];
    118132                                $result['refs'][] = array(
    119133                                        'value'      => $item,
  • rapid-media-reclaim/tags/1.1.0/includes/scan/class-adapter-coverage.php

    r3794616 r3814937  
    2626                $option = 'safe_media_cleaner_adapter_coverage_' . $generation;
    2727                $state  = get_option( $option, array() );
    28                 foreach ( array( 'elementor', 'acf' ) as $adapter ) {
     28                foreach ( array( 'elementor', 'acf', 'database' ) as $adapter ) {
    2929                        if ( empty( $reports[ $adapter ] ) ) {
    3030                                continue;
    … …  
    3535                        }
    3636                        $state[ $adapter ]['sources'] = min( 1000000, (int) ( $state[ $adapter ]['sources'] ?? 0 ) + (int) $reports[ $adapter ]['sources'] );
     37                        if ( 'database' === $adapter ) {
     38                                $examples = (array) ( $state[ $adapter ]['examples'] ?? array() );
     39                                foreach ( $reports[ $adapter ]['examples'] ?? array() as $sample ) {
     40                                        $sample = array(
     41                                                'phase' => sanitize_key( $sample['phase'] ?? '' ),
     42                                                'id'    => max( 0, (int) ( $sample['id'] ?? 0 ) ),
     43                                                'key'   => substr( sanitize_text_field( $sample['key'] ?? '' ), 0, 191 ),
     44                                        );
     45                                        if ( count( $examples ) < 20 && ! in_array( $sample, $examples, true ) ) {
     46                                                $examples[] = $sample; }
     47                                }
     48                                $state[ $adapter ]['examples'] = $examples;
     49                        }
    3750                        foreach ( $reports[ $adapter ]['issues'] as $reason => $count ) {
    3851                                // Reasons are adapter constants, never source text. Retain at most 16 keys.
    … …  
    5871                        'elementor' => __( 'Elementor structured media', 'rapid-media-reclaim' ),
    5972                        'acf'       => __( 'ACF typed fields', 'rapid-media-reclaim' ),
     73                        'database'  => __( 'Database source limits', 'rapid-media-reclaim' ),
    6074                );
    6175                $out    = array();
    … …  
    7488                                ),
    7589                        );
     90                        if ( 'database' === $adapter ) {
     91                                $examples = (array) ( $state[ $adapter ]['examples'] ?? array() );
     92                                $first    = get_option( 'safe_media_cleaner_adapter_gap_' . $generation . '_database', array() );
     93                                if ( ! $examples && is_array( $first ) && isset( $first['phase'] ) ) {
     94                                        $examples = array( $first ); }
     95                                $out[ count( $out ) - 1 ]['detail']['examples'] = $examples; }
    7696                }
    7797                return $out;
    … …  
    104124                        $coverage,
    105125                        static function ( $entry ) {
    106                                 return ! in_array( $entry['id'] ?? '', array( 'elementor_adapter', 'acf_adapter' ), true );
     126                                return ! in_array( $entry['id'] ?? '', array( 'elementor_adapter', 'acf_adapter', 'database_adapter' ), true );
    107127                        }
    108128                );
  • rapid-media-reclaim/tags/1.1.0/includes/scan/class-database-scanner.php

    r3794616 r3814937  
    125125         */
    126126        private function eligible(): string {
     127                if ( 'options' === $this->phase ) {
     128                        global $wpdb;
     129                        return $wpdb->prepare( 'option_name NOT LIKE %s AND option_name NOT LIKE %s', $wpdb->esc_like( '_transient_' ) . '%', $wpdb->esc_like( '_site_transient_' ) . '%' );
     130                }
    127131                if ( 'posts' !== $this->phase ) {
    128132                        return '1=1';
    … …  
    149153         */
    150154        public static function option_allowed( string $name ): bool {
     155                if ( 'elementor_log' === $name ) {
     156                        return false;
     157                }
    151158                if ( preg_match( '/^(?:_transient_|_site_transient_|safe_media_cleaner_|_?connectors_)|^(?:cron|rewrite_rules|active_plugins)$|_user_roles$|(?:^|[_-])(?:api[_-]?keys?|access[_-]?tokens?|refresh[_-]?tokens?|tokens?|secrets?|passwords?|credentials?|private[_-]?keys?)(?:$|[_-])/i', $name ) ) {
    152159                        return false;
    … …  
    173180        public function scan( $cursor, int $limit, Ref_Collector $refs ) {
    174181                global $wpdb;
     182                if ( 'options' === $this->phase ) {
     183                        $limit = min( 2, $limit );
     184                }
    175185                list( $table, $pk ) = $this->table_info();
    176186                $where              = $this->eligible();
    … …  
    237247         * @param bool   $weak Weak.
    238248         * @param bool   $force_ids Force ids.
    239          */
    240         private function evidence( $value, string $type, int $id, string $key, string $context, bool $weak = false, bool $force_ids = false ): void {
    241                 $items = Extractor::extract( $value, $force_ids ? 'attachment_id' : $key, $context );
    242                 foreach ( $items as $item ) {
     249         * @param array  $budget Optional extraction budget shared by one stored record.
     250         * @param bool   $structural Whether this source contains structural selectors, never media IDs.
     251         * @throws \RuntimeException The cleanup restriction for a partly read value could not be saved.
     252         */
     253        private function evidence( $value, string $type, int $id, string $key, string $context, bool $weak = false, bool $force_ids = false, ?array &$budget = null, bool $structural = false ): void {
     254                $result = Extractor::extract_result( $value, $force_ids ? 'attachment_id' : $key, $context, $budget );
     255                if ( ! $result['complete'] ) {
     256                        // Evidence found before the limit is kept; the unread remainder pauses cleanup.
     257                        $this->source_gap( $id, $key, (string) array_key_first( $result['issues'] ) );
     258                }
     259                foreach ( $result['refs'] as $item ) {
     260                        if ( $structural && 'id' === $item['match_type'] ) {
     261                                continue; // A generic image-like name cannot turn a row count into media.
     262                        }
    243263                        $item['source_type'] = $type;
    244264                        $item['source_id']   = $id;
    … …  
    269289                        $field = 1 === count( $fields ) ? $fields[0] : null;
    270290                        // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Bounded stored definition, class hydration disabled.
    271                         $config            = $field && is_string( $field->post_content ) ? @unserialize(
     291                        $config = $field && is_string( $field->post_content ) ? @unserialize(
    272292                                $field->post_content,
    273293                                array(
    … …  
    276296                                )
    277297                        ) : array(); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Decode bounded existing field definitions with object hydration disabled.
     298                        // Read only definitions already registered by active ACF. Never include PHP
     299                        // files or ask ACF to load arbitrary paths while scanning.
     300                        if ( function_exists( 'acf_get_local_field' ) ) {
     301                                $local = acf_get_local_field( $key );
     302                                if ( is_array( $local ) && isset( $local['type'] ) && is_string( $local['type'] ) ) {
     303                                        $this->acf[ $key ] = array(
     304                                                'label' => isset( $local['label'] ) && is_string( $local['label'] ) ? substr( $local['label'], 0, 500 ) : '',
     305                                                'type'  => $local['type'],
     306                                        );
     307                                        return $this->acf[ $key ];
     308                                }
     309                        }
    278310                        $this->acf[ $key ] = array(
    279311                                'label' => $field ? $field->post_title : '',
    … …  
    282314                }
    283315                return $this->acf[ $key ];
     316        }
     317
     318        /**
     319         * Read a saved template without object hydration or unbounded metadata values.
     320         *
     321         * @param int $id Template ID.
     322         * @return array|null Bounded document, null if missing, ambiguous or unreadable.
     323         */
     324        private static function elementor_document( int $id ): ?array {
     325                global $wpdb;
     326                $rows = $wpdb->get_results( $wpdb->prepare( "SELECT m.meta_key,IF(OCTET_LENGTH(m.meta_value)<=524288,m.meta_value,NULL) AS meta_value FROM {$wpdb->postmeta} m INNER JOIN {$wpdb->posts} p ON p.ID=m.post_id WHERE p.ID=%d AND p.post_type='elementor_library' AND p.post_status NOT IN ('trash','auto-draft') AND m.meta_key IN ('_elementor_data','_elementor_page_settings') LIMIT 3", $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Prepared, byte-bounded dependency metadata lookup; no object hydration.
     327                $data = array();
     328                foreach ( $rows as $row ) {
     329                        if ( null === $row->meta_value || isset( $data[ $row->meta_key ] ) ) {
     330                                return null;
     331                        }
     332                        $data[ $row->meta_key ] = $row->meta_value;
     333                }
     334                if ( $wpdb->last_error || ! isset( $data['_elementor_data'] ) ) {
     335                        return null;
     336                }
     337                $settings = array();
     338                if ( ! empty( $data['_elementor_page_settings'] ) ) {
     339                        // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Bounded stored settings; object hydration disabled.
     340                        $settings = @unserialize(
     341                                $data['_elementor_page_settings'],
     342                                array(
     343                                        'allowed_classes' => false,
     344                                        'max_depth'       => 24,
     345                                )
     346                        );
     347                }
     348                $content = json_decode( $data['_elementor_data'], true, 25 );
     349                if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $content ) ) {
     350                        return null;
     351                }
     352                return array(
     353                        'content'       => $content,
     354                        'page_settings' => $settings,
     355                );
    284356        }
    285357
    … …  
    317389                        $this->pending[] = $ref;
    318390                }
     391        }
     392
     393        /**
     394         * Index Beaver Builder storage, including its stdClass nodes, without class hydration.
     395         *
     396         * Layout keys get typed photo, background and gallery evidence. Every Beaver value
     397         * that cannot be decoded completely (custom or incomplete classes, cycles, malformed
     398         * bytes, budgets) is a database source gap, which pauses mutations.
     399         *
     400         * @param string $value Raw stored value.
     401         * @param int    $id Post ID.
     402         * @param string $key Exact metadata key.
     403         * @param bool   $weak Whether source status requires weak evidence.
     404         * @return mixed Value for the generic walk: the plain decoded array when available.
     405         */
     406        private function beaver_evidence( string $value, int $id, string $key, bool $weak ) {
     407                $layout = in_array( $key, array( '_fl_builder_data', '_fl_builder_draft' ), true );
     408                if ( ! $layout && ! preg_match( '/^(?:a|O):[0-9]+:/', $value ) ) {
     409                        return $value;
     410                }
     411                $decoded = Builder_Adapter::beaver_decode( $value );
     412                $issues  = $decoded['issues'];
     413                if ( $layout ) {
     414                        $result = null === $decoded['value'] ? array(
     415                                'refs'   => array(),
     416                                'issues' => $issues,
     417                        ) : Builder_Adapter::extract( $decoded['value'], 'Beaver Builder' );
     418                        $this->adapter_evidence( $result, 'builders', 'builder', $id, $key, $weak );
     419                        $issues = $result['issues'];
     420                }
     421                // Unknown controls still reach the generic walk; any other issue left values unread.
     422                if ( array_diff( $issues, array( 'builder_custom_controls_not_resolved' ) ) ) {
     423                        $this->source_gap( $id, $key, 'beaver_source_unreadable' );
     424                }
     425                // Never send rejected serialized graphs to the generic decoder a second time.
     426                // The durable gap above preserves the restriction; only normalized arrays are safe.
     427                return $decoded['value'] ?? array();
     428        }
     429
     430        /**
     431         * Keep unread database values visible, even if a later worker is interrupted.
     432         *
     433         * @param int    $id Source ID.
     434         * @param string $key Metadata key or option name; values are never retained.
     435         * @param string $reason Machine reason constant, never source text.
     436         * @throws \RuntimeException The durable cleanup restriction could not be saved.
     437         */
     438        private function source_gap( int $id = 0, string $key = '', string $reason = 'database_source_budget_exceeded' ): void {
     439                $report = $this->adapter_reports['database'] ?? array(
     440                        'sources'  => 1,
     441                        'issues'   => array(),
     442                        'examples' => array(),
     443                );
     444                $sample = array(
     445                        'phase' => $this->phase,
     446                        'id'    => $id,
     447                        'key'   => substr( $key, 0, 191 ),
     448                );
     449                $option = 'safe_media_cleaner_adapter_gap_' . $this->generation . '_database';
     450                add_option( $option, $sample, '', false );
     451                if ( ! get_option( $option, false ) ) {
     452                        throw new \RuntimeException( __( 'Could not save the cleanup restriction for unread content. The scan was stopped.', 'rapid-media-reclaim' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Error data is encoded by REST/CLI and escaped at the admin boundary.
     453                }
     454                if ( count( $report['examples'] ) < 20 && ! in_array( $sample, $report['examples'], true ) ) {
     455                        $report['examples'][] = $sample; }
     456                $report['issues'][ $reason ]       = 1;
     457                $this->adapter_reports['database'] = $report;
    319458        }
    320459
    … …  
    363502                                }
    364503                                if ( null === $row->option_value ) {
     504                                        $this->source_gap( 0, $name );
    365505                                        continue;
    366506                                }
    … …  
    376516                                }
    377517                                if ( 0 === strpos( $name, 'theme_mods_' ) ) {
    378                                         $data = @unserialize( $row->option_value, array( 'allowed_classes' => false ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Read existing WordPress serialized metadata with object creation disabled; malformed stored values are ignored.
     518                                        // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Read existing WordPress serialized metadata with object creation disabled and bounded depth.
     519                                        $data = @unserialize(
     520                                                $row->option_value,
     521                                                array(
     522                                                        'allowed_classes' => false,
     523                                                        'max_depth'       => Extractor::MAX_DEPTH,
     524                                                )
     525                                        );
    379526                                        if ( is_array( $data ) ) {
     527                                                // One budget for the whole option: aliases can span several theme mods.
     528                                                $budget = Extractor::budget( array( 'source_bytes' => strlen( $row->option_value ) ) );
    380529                                                foreach ( $data as $key => $value ) {
    381                                                         $this->evidence( $value, 'theme_mod', 0, $name, __( 'Theme', 'rapid-media-reclaim' ) . ' · ' . ucwords( str_replace( '_', ' ', $key ) ), false, 'custom_logo' === $key );
     530                                                        $this->evidence( $value, 'theme_mod', 0, $name, __( 'Theme', 'rapid-media-reclaim' ) . ' · ' . ucwords( str_replace( '_', ' ', (string) $key ) ), false, 'custom_logo' === $key, $budget );
    382531                                                }
     532                                        } elseif ( preg_match( '/^a:\d+:/', $row->option_value ) ) {
     533                                                // Corrupt or too deep: read it as text, but never as fully checked.
     534                                                $this->source_gap( 0, $name, 'database_value_unreadable' );
     535                                                $this->evidence( $row->option_value, 'theme_mod', 0, $name, __( 'Theme', 'rapid-media-reclaim' ) );
    383536                                        }
    384537                                } else {
    … …  
    409562                                $mt     = $wpdb->{$kind . 'meta'};
    410563                                $column = $kind . '_id';
    411                                 $values = $wpdb->get_results( $wpdb->prepare( "SELECT {$column} AS owner_id,meta_key,meta_value FROM {$mt} WHERE {$column} IN (" . implode( ',', array_fill( 0, count( $ids ), '%d' ) ) . ')', $ids ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Bounded source inventory requires fresh reads; table/column fragments are internal allowlists and values use placeholders.
    412                                 if ( $wpdb->last_error ) {
    413                                         throw new \RuntimeException( 'Could not read source metadata.' );
    414                                 }
     564                                $in     = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
     565                                // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Metadata table/owner column are internal allowlists; IDs are prepared; payload reads are bounded.
     566                                $stats = $wpdb->get_row( $wpdb->prepare( "SELECT COUNT(*) AS n,COALESCE(SUM(OCTET_LENGTH(meta_value)),0) AS bytes FROM {$mt} WHERE {$column} IN ({$in})", $ids ) );
     567                                if ( $wpdb->last_error || ! $stats ) {
     568                                        throw new \RuntimeException( 'Could not measure source metadata.' );
     569                                }
     570                                if ( ( (int) $stats->n > 2000 || (int) $stats->bytes > 4194304 ) && count( $rows ) > 1 ) {
     571                                        // Split before fetching payloads; never load 25 large owners together.
     572                                        foreach ( $rows as $single ) {
     573                                                $this->process( array( $single ), $refs );
     574                                                $refs->flush(); }
     575                                        return;
     576                                }
     577                                $values = array();
     578                                if ( (int) $stats->n > 2000 || (int) $stats->bytes > 4194304 ) {
     579                                        $this->source_gap( (int) $ids[0] );
     580                                } else {
     581                                        // Recheck the combined budget inside the payload statement. A value
     582                                        // growing between measurement and fetch becomes NULL, not an OOM.
     583                                        $values = $wpdb->get_results( $wpdb->prepare( "SELECT m.{$column} AS owner_id,m.meta_key,IF(b.n<=2000 AND b.bytes<=4194304 AND OCTET_LENGTH(m.meta_value)<=2097152,m.meta_value,NULL) AS meta_value FROM {$mt} m CROSS JOIN (SELECT COUNT(*) AS n,COALESCE(SUM(OCTET_LENGTH(meta_value)),0) AS bytes FROM {$mt} WHERE {$column} IN ({$in})) b WHERE m.{$column} IN ({$in}) LIMIT 2001", array_merge( $ids, $ids ) ) );
     584                                        if ( $wpdb->last_error ) {
     585                                                throw new \RuntimeException( 'Could not read source metadata.' ); }
     586                                }
     587                                // phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, PluginCheck.Security.DirectDB.UnescapedDBParameter
     588
    415589                                foreach ( $values as $value ) {
     590                                        if ( null === $value->meta_value ) {
     591                                                $this->source_gap( (int) $value->owner_id, (string) $value->meta_key );
     592                                                continue; }
    416593                                        $meta[ $value->owner_id ][ $value->meta_key ][] = $value->meta_value;
    417594                                }
    418595                        }
     596                        $acf_catalog = 'posts' === $this->phase ? Acf_Structure::catalog() : array();
    419597                        foreach ( $rows as $row ) {
    420598                                $id   = (int) ( 'terms' === $this->phase ? $row->term_id : $row->ID );
    … …  
    427605                                        $weak    = 'trash' === $row->post_status || ( ! $settings['include_drafts'] && in_array( $row->post_status, array( 'draft', 'pending', 'future', 'private' ), true ) );
    428606                                        $builder = preg_match( '/\[(?:et_pb_|vc_)/', $row->post_content );
     607                                        if ( $builder ) {
     608                                                $shortcodes = Builder_Adapter::extract( $row->post_content, 'Divi / WPBakery' );
     609                                                $this->adapter_evidence( $shortcodes, 'shortcode_builders', 'builder', $id, '', $weak );
     610                                                if ( array_diff( $shortcodes['issues'], array( 'builder_custom_controls_not_resolved' ) ) ) {
     611                                                        $this->source_gap( $id, 'post_content', 'shortcode_source_unreadable' );
     612                                                }
     613                                        }
    429614                                        $this->evidence( $row->post_content, $builder ? 'builder' : 'post_content', $id, '', $builder ? __( 'Divi / WPBakery', 'rapid-media-reclaim' ) : __( 'Post content', 'rapid-media-reclaim' ), $weak );
    430615                                        $this->evidence( $row->post_excerpt, 'post_excerpt', $id, '', __( 'Post excerpt', 'rapid-media-reclaim' ), $weak );
    … …  
    434619                                                $this->evidence( $description, 'term_meta', $id, 'description', __( 'Term description', 'rapid-media-reclaim' ) );
    435620                                        }
     621                                }
     622                                $structure  = 'posts' === $this->phase ? Acf_Structure::inspect( $acf_catalog, $meta[ $id ] ?? array() ) : array(
     623                                        'fields' => array(),
     624                                        'issues' => array(),
     625                                );
     626                                $acf_budget = array(
     627                                        'nodes' => $structure['work'] ?? 0,
     628                                        'bytes' => 0,
     629                                        'refs'  => 0,
     630                                );
     631                                if ( $structure['issues'] ) {
     632                                        $this->source_gap( $id, '', 'database_acf_structure_incomplete' );
     633                                        $this->adapter_evidence(
     634                                                array(
     635                                                        'refs'   => array(),
     636                                                        'issues' => $structure['issues'],
     637                                                ),
     638                                                'acf',
     639                                                'acf',
     640                                                $id,
     641                                                '',
     642                                                $weak
     643                                        );
    436644                                }
    437645                                foreach ( $meta[ $id ] ?? array() as $key => $values ) {
    … …  
    473681
    474682                                        $field_key = $meta[ $id ][ '_' . $key ][0] ?? '';
    475                                         $acf       = is_string( $field_key ) && 0 === strpos( $field_key, 'field_' ) ? $this->acf_field( $field_key ) : null;
     683                                        $acf       = isset( $structure['fields'][ $key ] ) ? $structure['fields'][ $key ] : ( is_string( $field_key ) && 0 === strpos( $field_key, 'field_' ) ? $this->acf_field( $field_key ) : null );
     684                                        if ( isset( $structure['fields'][ $key ] ) ) {
     685                                                $structural_field = $structure['fields'][ $key ];
     686                                                // Registered local fields keep their existing reader precedence.
     687                                                if ( ! function_exists( 'acf_get_local_field' ) || ! acf_get_local_field( $structural_field['key'] ) ) {
     688                                                        $acf = $structural_field;
     689                                                } else {
     690                                                        $acf = $this->acf_field( $structural_field['key'] );
     691                                                }
     692                                        }
    476693                                        if ( $acf && 'posts' === $this->phase ) {
    477694                                                $type    = 'acf';
    … …  
    482699                                                // Adapters only add precise evidence. The generic walk below always
    483700                                                // runs too, so anything an adapter cannot model is still found.
     701                                                $generic = $value;
    484702                                                if ( 'posts' === $this->phase && '_elementor_data' === $key ) {
    485                                                         $this->adapter_evidence( Elementor_Adapter::extract( $value ), 'elementor', 'builder', $id, $key, $weak );
     703                                                        $result = Elementor_Dependencies::extract(
     704                                                                $value,
     705                                                                static function ( int $template ) {
     706                                                                        return self::elementor_document( $template );
     707                                                                },
     708                                                                $id
     709                                                        );
     710                                                        delete_post_meta( $id, '_safe_media_cleaner_elementor_dependency' );
     711                                                        foreach ( $result['dependencies'] as $dependency ) {
     712                                                                add_post_meta( $id, '_safe_media_cleaner_elementor_dependency', $dependency );
     713                                                        }
     714                                                        $this->adapter_evidence( $result, 'elementor', 'builder', $id, $key, $weak );
     715                                                } elseif ( in_array( $key, array( '_bricks_page_content_2', '_bricks_page_header_2', '_bricks_page_footer_2' ), true ) ) {
     716                                                        $this->adapter_evidence( Builder_Adapter::extract( $value, $context ), 'builders', 'builder', $id, $key, $weak );
     717                                                } elseif ( 'posts' === $this->phase && 0 === strpos( $key, '_fl_builder' ) && is_string( $value ) ) {
     718                                                        // The generic walk drops objects; give it Beaver's decoded plain arrays.
     719                                                        $generic = $this->beaver_evidence( $value, $id, $key, $weak );
    486720                                                } elseif ( $acf ) {
    487                                                         $this->adapter_evidence( Acf_Adapter::extract( $value, $acf, $key ), 'acf', 'posts' === $this->phase ? 'acf' : $type, $id, $key, $weak );
     721                                                        $result = Acf_Adapter::extract( $value, $acf, $key, $acf_budget );
     722                                                        if ( $result['issues'] && ( isset( $structure['fields'][ $key ] ) || in_array( $acf['type'], array( 'group', 'repeater', 'flexible_content' ), true ) ) ) {
     723                                                                $this->source_gap( $id, $key, 'database_acf_structure_incomplete' );
     724                                                        }
     725                                                        $this->adapter_evidence( $result, 'acf', 'posts' === $this->phase ? 'acf' : $type, $id, $key, $weak );
    488726                                                }
    489                                                 $this->evidence( $value, $type, $id, $key, $context, $weak, $force );
     727                                                $generic_budget = null;
     728                                                $selector       = $acf && in_array( $acf['type'], array( 'group', 'repeater', 'flexible_content' ), true );
     729                                                $this->evidence( $generic, $type, $id, $key, $context, $weak, $force, $generic_budget, $selector );
    490730                                        }
    491731                                }
  • rapid-media-reclaim/tags/1.1.0/includes/scan/class-extractor.php

    r3794616 r3814937  
    1212}
    1313
    14 /** Extractor service. */
     14/**
     15 * Extractor service.
     16 *
     17 * Every top-level extraction runs under one shared work budget (values visited,
     18 * bytes inspected, unique evidence records, nested decodes and nesting depth).
     19 * Shared or cyclic decoded graphs, deep nesting and decode bombs exhaust that
     20 * budget; the result then reports why it is incomplete instead of looking fully
     21 * checked. See docs/EXTRACTION-LIMITS.md.
     22 */
    1523final class Extractor {
     24        /** Values (arrays and scalars) visited per extraction, at most. */
     25        const MAX_NODES = 1000000;
     26        /** Scalar and decoded bytes inspected per extraction, at most. */
     27        const MAX_BYTES = 16777216;
     28        /** Unique evidence records per extraction. */
     29        const MAX_REFS = 50000;
     30        /** Nested JSON/serialized decodes per extraction. */
     31        const MAX_DECODES = 20000;
     32        /** Nesting levels, including decoded strings and nested blocks. */
     33        const MAX_DEPTH = 40;
     34        /** Largest single string that is decoded as JSON or serialized data. */
     35        const MAX_DECODE_BYTES = 4194304;
     36        /** Largest scalar inspected; reject before normalization or regex allocation. */
     37        const MAX_STRING_BYTES = 4194304;
     38        /**
     39         * Raw string input amplification: inspected bytes may not exceed this multiple
     40         * of the top-level string length (plus a small floor). Nested encodings re-read
     41         * their substrings, so a few nesting levels fit; aliased large strings do not.
     42         */
     43        const AMPLIFICATION = 8;
     44        /**
     45         * Visited values per raw input byte. Unaliased JSON needs at least two bytes per
     46         * value and serialized data four, even across several nesting levels; alias
     47         * fan-out needs almost none.
     48         */
     49        const NODE_AMPLIFICATION = 2;
     50        /** Work floor for tiny string inputs. */
     51        const FLOOR = 1024;
     52        /** Short scalars are read once per extraction for each key and context. */
     53        const MEMO_BYTES = 512;
     54
    1655        /**
    1756         * Walk structured content and return unresolved evidence.
     57         *
     58         * Compatibility wrapper: the evidence may be partial. Callers that decide whether
     59         * media is unused or that verify a rewrite must use extract_result() instead.
    1860         *
    1961         * @param mixed  $value Value.
    … …  
    2466         */
    2567        public static function extract( $value, string $key = '', string $context = '', int $depth = 0 ): array {
    26                 if ( $depth > 40 || is_object( $value ) ) {
    27                         return array();
    28                 }
    29                 $out    = array();
    30                 $strong = (bool) preg_match( '/^(attachment_?id|image_?id|media_?id|backgroundMediaId|background_image_id|photo_id|photo|bg_image|thumbnail_id|_thumbnail_id|custom_logo|logo|site_icon|woocommerce_placeholder_image|ids|images|_product_image_gallery)$/i', $key );
    31                 if ( is_array( $value ) ) {
    32                         $paired = isset( $value['url'] ) || isset( $value['src'] );
    33                         foreach ( $value as $k => $v ) {
    34                                 $child_key = is_int( $k ) ? $key : (string) $k;
    35                                 if ( 'id' === $child_key && $paired && self::is_upload_url( (string) ( $value['url'] ?? $value['src'] ?? '' ) ) ) {
    36                                         $child_key = 'attachment_id';
    37                                 }
    38                                 $out = array_merge( $out, self::extract( $v, $child_key, $context, $depth + 1 ) );
    39                         }
    40                         return $out;
    41                 }
    42                 if ( ! is_scalar( $value ) ) {
    43                         return $out;
    44                 }
    45                 $s = str_replace( '\\/', '/', (string) $value );
    46                 if ( preg_match( '/^\d+(?:\s*,\s*\d+)*$/', $s ) && ( $strong || 'id' === $key ) ) {
    47                         foreach ( explode( ',', $s ) as $id ) {
    48                                 $out[] = self::ref( (int) $id, $strong ? 'strong' : 'weak', 'id', $context );
    49                         }
    50                 }
    51                 if ( strlen( $s ) < 2 ) {
    52                         return $out;
    53                 }
    54                 $decoded = json_decode( $s, true );
    55                 if ( is_array( $decoded ) ) {
    56                         return array_merge( $out, self::extract( $decoded, $key, $context, $depth + 1 ) );
    57                 }
    58                 if ( preg_match( '/^(a|s|i|b|d|N):|^N;/', $s ) ) {
    59                         $decoded = @unserialize( $s, array( 'allowed_classes' => false ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Read existing WordPress serialized metadata with object creation disabled; malformed stored values are ignored.
    60                         if ( false !== $decoded && $decoded !== $value ) {
    61                                 return array_merge( $out, self::extract( $decoded, $key, $context, $depth + 1 ) );
     68                $budget = self::budget();
     69                return self::run( $value, $key, $context, max( 0, $depth ), $budget )['refs'];
     70        }
     71
     72        /**
     73         * Walk structured content under a bounded budget and say whether it was complete.
     74         *
     75         * @param mixed      $value Stored value.
     76         * @param string     $key Field key.
     77         * @param string     $context Evidence context.
     78         * @param array|null $budget Optional shared budget from budget(); a fresh one when null.
     79         * @return array `refs`, `complete` (bool), `issues` (reason => count) and `work` counters.
     80         */
     81        public static function extract_result( $value, string $key = '', string $context = '', ?array &$budget = null ): array {
     82                if ( null === $budget ) {
     83                        $budget = self::budget();
     84                }
     85                return self::run( $value, $key, $context, 0, $budget );
     86        }
     87
     88        /**
     89         * Create a budget that several extractions of one source record can share.
     90         *
     91         * Limits can only be lowered (for tests and stricter callers); values above the
     92         * built-in maxima, non-integers and values below one are clamped.
     93         *
     94         * `source_bytes` is the raw length of the stored record the shared budget reads;
     95         * it applies the raw-input amplification limit to already decoded values too.
     96         *
     97         * @param array $limits Optional `nodes`, `bytes`, `refs`, `decodes`, `depth`, `source_bytes`.
     98         * @return array Budget state.
     99         */
     100        public static function budget( array $limits = array() ): array {
     101                if ( isset( $limits['source_bytes'] ) && is_int( $limits['source_bytes'] ) ) {
     102                        $raw  = max( 0, min( self::MAX_BYTES, $limits['source_bytes'] ) );
     103                        $work = array(
     104                                'nodes' => self::NODE_AMPLIFICATION * $raw + self::FLOOR,
     105                                'bytes' => self::AMPLIFICATION * $raw + self::FLOOR,
     106                        );
     107                        foreach ( $work as $name => $cap ) {
     108                                $limits[ $name ] = isset( $limits[ $name ] ) && is_int( $limits[ $name ] ) ? min( $cap, $limits[ $name ] ) : $cap;
     109                        }
     110                }
     111                $max = array(
     112                        'nodes'   => self::MAX_NODES,
     113                        'bytes'   => self::MAX_BYTES,
     114                        'refs'    => self::MAX_REFS,
     115                        'decodes' => self::MAX_DECODES,
     116                        'depth'   => self::MAX_DEPTH,
     117                );
     118                foreach ( $max as $name => $ceiling ) {
     119                        if ( isset( $limits[ $name ] ) && is_int( $limits[ $name ] ) ) {
     120                                $max[ $name ] = max( 1, min( $ceiling, $limits[ $name ] ) );
    62121                        }
    63122                }
    … …  
    67126                        $base_path = rtrim( (string) wp_parse_url( $uploads['baseurl'], PHP_URL_PATH ), '/' ) . '/';
    68127                }
    69                 $pattern = '~(?:https?://|//)[^\s<>"\'()]+|(?:/?[a-zA-Z0-9_.%-]+/)*uploads/[^\s<>"\'()]+|' . preg_quote( $base_path, '~' ) . '[^\s<>"\'()]+|(?<![\w/])\d{4}/\d{2}/[^\s<>"\'()]+~i';
    70                 if ( preg_match_all( $pattern, html_entity_decode( $s, ENT_QUOTES, 'UTF-8' ), $m ) ) {
     128                return array(
     129                        'max'       => $max,
     130                        'nodes'     => 0,
     131                        'bytes'     => 0,
     132                        'refs'      => 0,
     133                        'decodes'   => 0,
     134                        'objects'   => 0,
     135                        'issues'    => array(),
     136                        'stop'      => false,
     137                        'cap'       => null,
     138                        'base_path' => $base_path,
     139                );
     140        }
     141
     142        /**
     143         * Run one top-level extraction against a (possibly shared) budget.
     144         *
     145         * @param mixed  $value Stored value.
     146         * @param string $key Field key.
     147         * @param string $context Evidence context.
     148         * @param int    $depth Starting depth.
     149         * @param array  $budget Budget state.
     150         * @return array Result.
     151         */
     152        private static function run( $value, string $key, string $context, int $depth, array &$budget ): array {
     153                $before = $budget['issues'];
     154                $used   = array(
     155                        'nodes'   => $budget['nodes'],
     156                        'bytes'   => $budget['bytes'],
     157                        'objects' => $budget['objects'],
     158                );
     159                // A short raw string cannot legitimately expand into a huge graph.
     160                $cap = null;
     161                if ( is_string( $value ) ) {
     162                        $cap = array(
     163                                'nodes' => $budget['nodes'] + self::NODE_AMPLIFICATION * strlen( $value ) + self::FLOOR,
     164                                'bytes' => $budget['bytes'] + self::AMPLIFICATION * strlen( $value ) + self::FLOOR,
     165                        );
     166                }
     167                $saved         = $budget['cap'];
     168                $budget['cap'] = $cap;
     169                $out           = array();
     170                $seen          = array();
     171                if ( $budget['stop'] ) {
     172                        self::issue( $budget, 'extractor_budget_exhausted' );
     173                } else {
     174                        self::collect( $value, $key, $context, $depth, $budget, $out, $seen );
     175                }
     176                $budget['cap'] = $saved;
     177                $issues        = array();
     178                foreach ( $budget['issues'] as $reason => $count ) {
     179                        $delta = $count - (int) ( $before[ $reason ] ?? 0 );
     180                        if ( $delta > 0 ) {
     181                                $issues[ $reason ] = $delta;
     182                        }
     183                }
     184                return array(
     185                        'refs'     => $out,
     186                        'complete' => ! $issues,
     187                        'issues'   => $issues,
     188                        'work'     => array(
     189                                'nodes'   => $budget['nodes'] - $used['nodes'],
     190                                'bytes'   => $budget['bytes'] - $used['bytes'],
     191                                'refs'    => count( $out ),
     192                                'objects' => $budget['objects'] - $used['objects'],
     193                        ),
     194                );
     195        }
     196
     197        /**
     198         * Record an incomplete-extraction reason. Exhausted budgets stop all later work.
     199         *
     200         * @param array  $budget Budget state.
     201         * @param string $reason Machine reason constant.
     202         * @param bool   $stop Whether the shared budget is exhausted.
     203         */
     204        private static function issue( array &$budget, string $reason, bool $stop = false ): void {
     205                $budget['issues'][ $reason ] = (int) ( $budget['issues'][ $reason ] ?? 0 ) + 1;
     206                if ( $stop ) {
     207                        $budget['stop'] = true;
     208                }
     209        }
     210
     211        /**
     212         * Charge visited values and inspected bytes; false once a limit is exceeded.
     213         *
     214         * @param array $budget Budget state.
     215         * @param int   $nodes Values.
     216         * @param int   $bytes Bytes.
     217         * @return bool Whether work may continue.
     218         */
     219        private static function charge( array &$budget, int $nodes, int $bytes ): bool {
     220                $budget['nodes'] += $nodes;
     221                $budget['bytes'] += $bytes;
     222                $cap              = $budget['cap'];
     223                if ( $budget['nodes'] > $budget['max']['nodes'] || ( $cap && $budget['nodes'] > $cap['nodes'] ) ) {
     224                        self::issue( $budget, 'extractor_node_limit', true );
     225                        return false;
     226                }
     227                if ( $budget['bytes'] > $budget['max']['bytes'] || ( $cap && $budget['bytes'] > $cap['bytes'] ) ) {
     228                        self::issue( $budget, 'extractor_byte_limit', true );
     229                        return false;
     230                }
     231                return true;
     232        }
     233
     234        /**
     235         * Append evidence without copying the growing result for every nested value.
     236         *
     237         * @param mixed  $value Stored value.
     238         * @param string $key Field key.
     239         * @param string $context Evidence context.
     240         * @param int    $depth Recursion depth.
     241         * @param array  $budget Shared budget.
     242         * @param array  $out Evidence accumulator.
     243         * @param array  $seen Evidence already in $out.
     244         */
     245        private static function collect( $value, string $key, string $context, int $depth, array &$budget, array &$out, array &$seen ): void {
     246                if ( $budget['stop'] ) {
     247                        return;
     248                }
     249                if ( $depth > $budget['max']['depth'] ) {
     250                        // Deep or self-referencing data is never silently truncated.
     251                        self::issue( $budget, 'extractor_depth_limit' );
     252                        return;
     253                }
     254                if ( is_object( $value ) ) {
     255                        // Objects are never hydrated or walked. Their unread properties are a gap;
     256                        // builder adapters must normalize supported formats before the generic walk.
     257                        ++$budget['objects'];
     258                        self::issue( $budget, 'extractor_object_unread' );
     259                        return;
     260                }
     261                if ( is_array( $value ) ) {
     262                        if ( ! self::charge( $budget, 1 + count( $value ), 0 ) ) {
     263                                return;
     264                        }
     265                        // Each child is charged above and again when visited; refund the pre-charge.
     266                        $budget['nodes'] -= count( $value );
     267                        $paired           = isset( $value['url'] ) || isset( $value['src'] );
     268                        foreach ( $value as $k => $v ) {
     269                                if ( $budget['stop'] ) {
     270                                        return;
     271                                }
     272                                if ( ! self::charge( $budget, 0, strlen( (string) $k ) ) ) {
     273                                        return;
     274                                }
     275                                $child_key = is_int( $k ) ? $key : (string) $k;
     276                                if ( 'id' === $child_key && $paired && self::is_upload_url( (string) ( is_scalar( $value['url'] ?? null ) ? $value['url'] : ( is_scalar( $value['src'] ?? null ) ? $value['src'] : '' ) ), $budget ) ) {
     277                                        $child_key = 'attachment_id';
     278                                }
     279                                self::collect( $v, $child_key, $context, $depth + 1, $budget, $out, $seen );
     280                        }
     281                        return;
     282                }
     283                if ( ! is_scalar( $value ) ) {
     284                        return;
     285                }
     286                $raw = (string) $value;
     287                $cap = $budget['cap'];
     288                if ( strlen( $raw ) > self::MAX_STRING_BYTES || strlen( $raw ) > $budget['max']['bytes'] - $budget['bytes'] || ( $cap && strlen( $raw ) > $cap['bytes'] - $budget['bytes'] ) ) {
     289                        self::issue( $budget, 'extractor_byte_limit', true );
     290                        return;
     291                }
     292                $s = str_replace( '\\/', '/', $raw );
     293                if ( strlen( $raw ) <= self::MEMO_BYTES ) {
     294                        // Aliases revisit identical scalars: their evidence is already in $out.
     295                        $memo = "\0" . $key . "\0" . $context . "\0" . ( is_string( $value ) ? 's' : 'o' ) . $raw;
     296                        if ( isset( $seen[ $memo ] ) ) {
     297                                self::charge( $budget, 1, 0 );
     298                                return;
     299                        }
     300                        $seen[ $memo ] = true;
     301                }
     302                if ( ! self::charge( $budget, 1, strlen( $s ) ) ) {
     303                        return;
     304                }
     305                $strong = (bool) preg_match( '/^(attachment_?id|image_?id|media_?id|backgroundMediaId|background_image_id|photo_id|photo|bg_image|thumbnail_id|_thumbnail_id|custom_logo|logo|site_icon|woocommerce_placeholder_image|ids|images|_product_image_gallery)$/i', $key );
     306                if ( ( $strong || 'id' === $key ) && preg_match( '/^\d+(?:\s*,\s*\d+)*$/', $s ) ) {
     307                        foreach ( explode( ',', $s ) as $id ) {
     308                                self::add( $budget, $out, $seen, (int) $id, $strong ? 'strong' : 'weak', 'id', $context );
     309                        }
     310                }
     311                if ( strlen( $s ) < 2 ) {
     312                        return;
     313                }
     314                // PHP serialization counts original bytes, including JSON's escaped slashes.
     315                $decoded = self::decode( $raw, $depth, $budget );
     316                if ( $budget['stop'] ) {
     317                        return;
     318                }
     319                if ( null !== $decoded && $decoded !== $value ) {
     320                        self::collect( $decoded, $key, $context, $depth + 1, $budget, $out, $seen );
     321                        return;
     322                }
     323                $base_path = $budget['base_path'];
     324                $pattern   = '~(?:https?://|//)[^\s<>"\'()]+|(?<![a-zA-Z0-9_.%-])uploads/[^\s<>"\'()]+|' . preg_quote( $base_path, '~' ) . '[^\s<>"\'()]+|(?<![\w/])\d{4}/\d{2}/[^\s<>"\'()]+~i';
     325                $text      = html_entity_decode( $s, ENT_QUOTES, 'UTF-8' );
     326                if ( self::matches( $pattern, $text, $m, $budget ) ) {
    71327                        foreach ( $m[0] as $url ) {
    72                                 $out[] = self::ref( rtrim( $url, ',;]' ), 'strong', 'url', $context );
    73                         }
    74                 }
    75                 if ( preg_match_all( '/wp-image-(\d+)/', $s, $m ) ) {
     328                                self::add( $budget, $out, $seen, rtrim( $url, ',;]' ), 'strong', 'url', $context );
     329                                // The literal uploads marker avoids scanning an arbitrary prefix at
     330                                // every character. Retain both interpretations for ambiguous relative
     331                                // paths so an actual uploads/uploads directory is still protected.
     332                                if ( 0 === stripos( $url, 'uploads/' ) ) {
     333                                        self::add( $budget, $out, $seen, rtrim( rtrim( $base_path, '/' ) . '/' . substr( $url, 8 ), ',;]' ), 'strong', 'url', $context );
     334                                }
     335                        }
     336                }
     337                if ( self::matches( '/wp-image-(\d+)/', $s, $m, $budget ) ) {
    76338                        foreach ( $m[1] as $id ) {
    77                                 $out[] = self::ref( (int) $id, 'strong', 'id', $context );
    78                         }
    79                 }
    80                 if ( preg_match_all( '/\[(gallery|playlist|vc_gallery|vc_single_image|et_pb_\w+|video|audio)\b([^\]]*)\]/i', $s, $m, PREG_SET_ORDER ) ) {
     339                                self::add( $budget, $out, $seen, (int) $id, 'strong', 'id', $context );
     340                        }
     341                }
     342                if ( self::matches( '/\[(gallery|playlist|vc_gallery|vc_single_image|et_pb_\w+|video|audio)\b([^\]]*)\]/i', $s, $m, $budget, PREG_SET_ORDER ) ) {
    81343                        foreach ( $m as $shortcode ) {
    82                                 if ( preg_match_all( '/\b(ids|images|image|attachment_id)=["\']([\d, ]+)["\']/', $shortcode[2], $attrs, PREG_SET_ORDER ) ) {
     344                                if ( self::matches( '/\b(ids|images|image|attachment_id)=["\']([\d, ]+)["\']/', $shortcode[2], $attrs, $budget, PREG_SET_ORDER ) ) {
    83345                                        foreach ( $attrs as $attr ) {
    84346                                                foreach ( explode( ',', $attr[2] ) as $id ) {
    85                                                         $out[] = self::ref( (int) $id, 'strong', 'id', 'Shortcode · ' . $shortcode[1] );
     347                                                        self::add( $budget, $out, $seen, (int) $id, 'strong', 'id', 'Shortcode · ' . $shortcode[1] );
    86348                                                }
    87349                                        }
    … …  
    90352                }
    91353                if ( false !== strpos( $s, '<!-- wp:' ) && function_exists( 'parse_blocks' ) ) {
    92                         $out = array_merge( $out, self::blocks( parse_blocks( $s ) ) );
    93                 }
    94                 if ( preg_match_all( '~(?<![\w/])([\w%.-]+\.(?:jpe?g|png|gif|webp|avif|svg|pdf|mp4|mp3|woff2?))(?![\w])~i', $s, $m ) ) {
     354                        self::blocks( parse_blocks( $s ), $depth + 1, $budget, $out, $seen );
     355                }
     356                if ( self::matches( '~(?<![\w%./-])(\.*+[\w%-]++(?:\.++[\w%-]++)*\.++(?:jpe?g|png|gif|webp|avif|svg|pdf|mp4|mp3|woff2?))(?![\w])~i', $s, $m, $budget ) ) {
    95357                        foreach ( $m[1] as $name ) {
    96                                 $out[] = self::ref( $name, 'weak', 'filename', $context );
    97                         }
    98                 }
    99                 return $out;
    100         }
     358                                self::add( $budget, $out, $seen, $name, 'weak', 'filename', $context );
     359                        }
     360                }
     361        }
     362
     363        /**
     364         * Decode a JSON or serialized string without object hydration.
     365         *
     366         * @param string $s String.
     367         * @param int    $depth Current depth.
     368         * @param array  $budget Budget state.
     369         * @return mixed Decoded value, or null when the string is not decodable data.
     370         */
     371        private static function decode( string $s, int $depth, array &$budget ) {
     372                $start      = strspn( $s, " \t\n\r" );
     373                $json       = isset( $s[ $start ] ) && ( '[' === $s[ $start ] || '{' === $s[ $start ] );
     374                $serialized = (bool) preg_match( '/^(?:[asOC]:[0-9]+:|i:-?[0-9]+;|b:[01];|d:(?:[+\-]?(?:[0-9.]+(?:[eE][+\-]?[0-9]+)?|INF)|NAN);|N;)/', $s );
     375                if ( ! $json && ! $serialized ) {
     376                        return null;
     377                }
     378                if ( strlen( $s ) > self::MAX_DECODE_BYTES ) {
     379                        self::issue( $budget, 'extractor_decode_limit' );
     380                        return null;
     381                }
     382                if ( ++$budget['decodes'] > $budget['max']['decodes'] ) {
     383                        self::issue( $budget, 'extractor_decode_limit', true );
     384                        return null;
     385                }
     386                // Decoded children are deeper than the string itself.
     387                $levels = max( 1, $budget['max']['depth'] - $depth );
     388                if ( $json ) {
     389                        $decoded = json_decode( $s, true, $levels + 1 );
     390                        if ( JSON_ERROR_DEPTH === json_last_error() ) {
     391                                self::issue( $budget, 'extractor_depth_limit' );
     392                                return null;
     393                        }
     394                        if ( is_array( $decoded ) ) {
     395                                return $decoded;
     396                        }
     397                        if ( ! $serialized ) {
     398                                return null;
     399                        }
     400                }
     401                // A depth refusal is followed by a generic offset notice, so error_get_last()
     402                // cannot tell it apart from malformed text. Watch every decoder warning instead.
     403                $too_deep = false;
     404                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_set_error_handler -- Scoped to one decode; restored immediately; distinguishes a depth refusal from malformed text.
     405                set_error_handler(
     406                        static function ( $number, $message ) use ( &$too_deep ) {
     407                                if ( false !== stripos( (string) $message, 'depth' ) ) {
     408                                        $too_deep = true;
     409                                }
     410                                return true;
     411                        }
     412                );
     413                try {
     414                        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Read existing WordPress serialized metadata with object creation disabled and bounded depth; malformed stored values are read as text.
     415                        $decoded = unserialize(
     416                                $s,
     417                                array(
     418                                        'allowed_classes' => false,
     419                                        'max_depth'       => $levels + 1,
     420                                )
     421                        );
     422                } finally {
     423                        restore_error_handler();
     424                }
     425                if ( $too_deep ) {
     426                        self::issue( $budget, 'extractor_depth_limit' );
     427                        return null;
     428                }
     429                if ( false === $decoded ) {
     430                        // The recognition check above already excludes ordinary prose/CSS.
     431                        // Every recognized serialization prefix must report a failed decode.
     432                        if ( 'b:0;' !== $s ) {
     433                                self::issue( $budget, 'extractor_malformed_data' );
     434                        }
     435                        return null;
     436                }
     437                return $decoded;
     438        }
     439
     440        /**
     441         * Run a bounded pattern; a PCRE failure is reported instead of reading as "no match".
     442         *
     443         * @param string $pattern Pattern.
     444         * @param string $subject Subject.
     445         * @param mixed  $matches Matches.
     446         * @param array  $budget Budget state.
     447         * @param int    $flags Flags.
     448         * @return bool Whether anything matched.
     449         */
     450        private static function matches( string $pattern, string $subject, &$matches, array &$budget, int $flags = PREG_PATTERN_ORDER ): bool {
     451                $matches = array();
     452                $found   = preg_match_all( $pattern, $subject, $matches, $flags );
     453                if ( false === $found ) {
     454                        self::issue( $budget, 'extractor_pattern_error' );
     455                        return false;
     456                }
     457                return $found > 0;
     458        }
     459
    101460        /**
    102461         * Recognize an uploads URL without trusting its host.
    103462         *
    104463         * @param string $value Value.
     464         * @param array  $budget Budget state with the uploads path.
    105465         * @return bool Result.
    106466         */
    107         private static function is_upload_url( string $value ): bool {
     467        private static function is_upload_url( string $value, array $budget ): bool {
    108468                $value = str_replace( '\\/', '/', $value );
    109                 $path  = '/wp-content/uploads/';
    110                 if ( function_exists( 'wp_upload_dir' ) ) {
    111                         $uploads = wp_upload_dir();
    112                         $path    = rtrim( (string) wp_parse_url( $uploads['baseurl'], PHP_URL_PATH ), '/' ) . '/';
    113                 }
    114                 return false !== strpos( $value, $path ) || false !== strpos( $value, 'uploads/' );
    115         }
     469                return false !== strpos( $value, $budget['base_path'] ) || false !== strpos( $value, 'uploads/' );
     470        }
     471
    116472        /**
    117473         * Visit nested Gutenberg blocks with their block context.
    118474         *
    119475         * @param array $blocks Blocks.
    120          * @return array Result.
    121          */
    122         private static function blocks( array $blocks ): array {
    123                 $out = array();
     476         * @param int   $depth Nesting depth.
     477         * @param array $budget Shared budget.
     478         * @param array $out Evidence accumulator.
     479         * @param array $seen Evidence already in $out.
     480         */
     481        private static function blocks( array $blocks, int $depth, array &$budget, array &$out, array &$seen ): void {
     482                if ( $depth > $budget['max']['depth'] ) {
     483                        self::issue( $budget, 'extractor_depth_limit' );
     484                        return;
     485                }
    124486                foreach ( $blocks as $block ) {
    125                         $out = array_merge( $out, self::extract( $block['attrs'] ?? array(), '', 'Gutenberg · ' . ( $block['blockName'] ?? '' ) ), self::blocks( $block['innerBlocks'] ?? array() ) );
    126                         if ( isset( $block['attrs']['id'] ) ) {
    127                                 $out[] = self::ref( (int) $block['attrs']['id'], 'strong', 'id', 'Gutenberg · ' . $block['blockName'] );
    128                         }
    129                 }
    130                 return $out;
    131         }
    132         /**
    133          * Build one unresolved evidence record.
    134          *
     487                        if ( $budget['stop'] || ! self::charge( $budget, 1, 0 ) ) {
     488                                return;
     489                        }
     490                        $name = (string) ( $block['blockName'] ?? '' );
     491                        self::collect( $block['attrs'] ?? array(), '', 'Gutenberg · ' . $name, $depth + 1, $budget, $out, $seen );
     492                        self::blocks( $block['innerBlocks'] ?? array(), $depth + 1, $budget, $out, $seen );
     493                        if ( isset( $block['attrs']['id'] ) && is_scalar( $block['attrs']['id'] ) ) {
     494                                self::add( $budget, $out, $seen, (int) $block['attrs']['id'], 'strong', 'id', 'Gutenberg · ' . $name );
     495                        }
     496                }
     497        }
     498
     499        /**
     500         * Add one unique unresolved evidence record within the evidence budget.
     501         *
     502         * @param array  $budget Budget state.
     503         * @param array  $out Evidence accumulator.
     504         * @param array  $seen Evidence already in $out.
    135505         * @param mixed  $value Value.
    136506         * @param string $strength Strength.
    137507         * @param string $type Type.
    138508         * @param string $context Context.
    139          * @return array Result.
    140          */
    141         private static function ref( $value, string $strength, string $type, string $context ): array {
    142                 return array(
     509         */
     510        private static function add( array &$budget, array &$out, array &$seen, $value, string $strength, string $type, string $context ): void {
     511                if ( $budget['stop'] ) {
     512                        return;
     513                }
     514                $id = $strength . '|' . $type . '|' . $context . '|' . ( is_int( $value ) ? 'i' : 's' ) . $value;
     515                if ( isset( $seen[ $id ] ) ) {
     516                        return;
     517                }
     518                if ( ++$budget['refs'] > $budget['max']['refs'] ) {
     519                        self::issue( $budget, 'extractor_reference_limit', true );
     520                        return;
     521                }
     522                $seen[ $id ] = true;
     523                $out[]       = array(
    143524                        'value'      => $value,
    144525                        'strength'   => $strength,
  • rapid-media-reclaim/tags/1.1.0/includes/scan/class-file-map.php

    r3794616 r3814937  
    2323         */
    2424        public static function refresh( array $ids, array $generations ): void {
     25                if ( class_exists( \SafeMediaCleaner\Status_Index::class ) ) {
     26                        \SafeMediaCleaner\Status_Index::write(
     27                                $generations,
     28                                static function () use ( $ids, $generations ) {
     29                                        self::write_refresh( $ids, $generations );
     30                                }
     31                        );
     32                } else {
     33                        self::write_refresh( $ids, $generations ); }
     34        }
     35
     36        /**
     37         * Replace authoritative file rows.
     38         *
     39         * @param array $ids IDs.
     40         * @param array $generations Generations.
     41         * @throws \RuntimeException Inventory read/write failed.
     42         */
     43        private static function write_refresh( array $ids, array $generations ): void {
    2544                global $wpdb;
    2645                if ( ! $ids || ! $generations ) {
  • rapid-media-reclaim/tags/1.1.0/includes/scan/class-frontend-scanner.php

    r3794616 r3814937  
    11<?php
    22/**
    3  * Bounded anonymous HTML coverage of public posts and pages.
     3 * Bounded sitemap-led anonymous HTML and linked stylesheet coverage.
    44 *
    55 * @package SafeMediaCleaner
    … …  
    8585                $query    = new \WP_Query(
    8686                        array(
    87                                 'post_type'           => array( 'post', 'page' ),
     87                                'post_type'           => array_values( get_post_types( array( 'public' => true ) ) ),
    8888                                'post_status'         => 'publish',
    8989                                'has_password'        => false,
    … …  
    9898                );
    9999                $state    = array(
    100                         'ids'     => array_slice( $query->posts, 0, $limit ),
    101                         'limited' => count( $query->posts ) > $limit,
    102                         'results' => array(),
    103                         'limit'   => $limit,
     100                        'ids'             => array_slice( $query->posts, 0, $limit ),
     101                        'limited'         => count( $query->posts ) > $limit,
     102                        'results'         => array(),
     103                        'limit'           => $limit,
     104                        'urls'            => array(),
     105                        'sitemaps'        => array( home_url( '/wp-sitemap.xml' ), home_url( '/sitemap_index.xml' ) ),
     106                        'visited'         => array(),
     107                        'sitemap_failed'  => 0,
     108                        'sitemap_skipped' => 0,
     109                        'styles'          => array(),
     110                        'style_results'   => array(),
     111                        'external_styles' => 0,
    104112                );
    105113                if ( ! add_option( $this->option(), $state, '', false ) ) {
    … …  
    117125         */
    118126        public function total(): int {
    119                 return count( $this->state()['ids'] ); }
     127                $state = $this->state();
     128                return min( $state['limit'], count( $state['ids'] ) + count( $state['urls'] ?? array() ) ); }
    120129        /**
    121130         * Reject query permalinks, alternate origins, credentials and ambiguous paths.
    … …  
    134143                                return false; }
    135144                }
     145                $path = rawurldecode( $parts['path'] ?? '/' );
     146                if ( preg_match( '~(?:^|/)(?:wp-admin|wp-login\.php|wp-json|xmlrpc\.php)(?:/|$)|(?:^|/)\.\.(?:/|$)~i', $path ) || preg_match( '/[\\\\\x00-\x20\x7f]/', $path ) ) {
     147                        return false;
     148                }
    136149                $scheme      = strtolower( $parts['scheme'] ?? '' );
    137150                $home_scheme = strtolower( $home['scheme'] ?? '' );
    … …  
    153166                $state           = $this->state();
    154167                $offset          = max( 0, (int) $cursor );
    155                 if ( $offset >= count( $state['ids'] ) ) {
     168                if ( $limit > 0 && ! empty( $state['sitemaps'] ) ) {
     169                        $this->discover( $state );
     170                        if ( empty( $state['sitemaps'] ) ) {
     171                                $state['ids'] = array_values(
     172                                        array_filter(
     173                                                $state['ids'],
     174                                                static function ( $id ) use ( $state ) {
     175                                                        return ! in_array( (string) get_permalink( $id ), $state['urls'], true );
     176                                                }
     177                                        )
     178                                );
     179                                $state['ids'] = array_slice( $state['ids'], 0, max( 0, $state['limit'] - count( $state['urls'] ) ) );
     180                        }
     181                        $this->save( $state );
     182                        return $offset;
     183                }
     184                if ( $limit > 0 && ! empty( $state['styles'] ) ) {
     185                        $this->scan_style( $state, $refs );
     186                        $this->save( $state );
     187                        return $offset;
     188                }
     189                $inventory = array_merge( $state['urls'] ?? array(), $state['ids'] );
     190                if ( $offset >= count( $inventory ) ) {
    156191                        return null; }
    157192                if ( $limit < 1 ) {
    158193                        return $offset; }
    159                 $id = (int) $state['ids'][ $offset ];
     194                $entry = $inventory[ $offset ];
     195                $id    = is_int( $entry ) || ctype_digit( (string) $entry ) ? (int) $entry : (int) url_to_postid( $entry );
     196                $key   = is_string( $entry ) && ! ctype_digit( $entry ) ? $entry : $id;
    160197                // A committed coverage result also makes replay after a cursor-write failure safe.
    161                 if ( isset( $state['results'][ $id ] ) ) {
     198                if ( isset( $state['results'][ $key ] ) ) {
    162199                        $this->processed = 1;
    163                         return $offset + 1 >= count( $state['ids'] ) ? null : $offset + 1;
     200                        return $offset + 1 >= count( $inventory ) && empty( $state['styles'] ) ? null : $offset + 1;
    164201                }
    165202                $post   = get_post( $id );
    166                 $url    = (string) get_permalink( $id );
     203                $url    = is_string( $entry ) && ! ctype_digit( $entry ) ? $entry : (string) get_permalink( $id );
    167204                $result = 'skipped';
    168                 if ( $post && 'publish' === $post->post_status && '' === $post->post_password && in_array( $post->post_type, array( 'post', 'page' ), true ) && self::allowed_url( $url ) ) {
     205                if ( ( ! $id || ( $post && 'publish' === $post->post_status && '' === $post->post_password && is_post_type_viewable( $post->post_type ) ) ) && self::allowed_url( $url ) ) {
    169206                        $response = wp_safe_remote_get(
    170207                                $url,
    … …  
    188225                                $type = strtolower( (string) wp_remote_retrieve_header( $response, 'content-type' ) );
    189226                                if ( 200 === $code && 0 === strpos( $type, 'text/html' ) && strlen( $body ) < 1048576 ) {
    190                                         $items    = array_values(
     227                                        $extracted = Extractor::extract_result( $body );
     228                                        $items     = array_values(
    191229                                                array_filter(
    192                                                         Extractor::extract( $body ),
     230                                                        $extracted['refs'],
    193231                                                        static function ( $item ) {
    194232                                                                return 'url' === $item['match_type'];
    … …  
    196234                                                )
    197235                                        );
     236                                        if ( count( $items ) > 2000 ) {
     237                                                $state['limited'] = true;
     238                                                $items            = array_slice( $items, 0, 2000 );
     239                                        }
    198240                                        $resolved = $this->resolver->resolve_many( $items );
    199241                                        foreach ( $items as $index => $item ) {
    … …  
    201243                                                        $refs->add( $attachment, 'strong', 'frontend', $id, $url, __( 'Anonymous public HTML', 'rapid-media-reclaim' ), 'url' ); }
    202244                                        }
     245                                        $this->queue_styles( $state, $body, $url, $id );
    203246                                        // Evidence must be durable before the successful coverage marker.
    204247                                        $refs->flush();
    205                                         $result = 'success';
    206                                 }
    207                         }
    208                 }
    209                 $state['results'][ $id ] = $result;
     248                                        // URLs found before an extraction limit still protect media, but the
     249                                        // page is reported as partially read, never as a successful check.
     250                                        $result = $extracted['complete'] ? 'success' : 'partial';
     251                                        if ( ! $extracted['complete'] ) {
     252                                                $state['limited'] = true;
     253                                        }
     254                                }
     255                        }
     256                }
     257                $state['results'][ $key ] = $result;
    210258                update_option( $this->option(), $state, false );
    211259                if ( get_option( $this->option() ) !== $state ) {
    212260                        throw new \RuntimeException( __( 'Could not persist crawl progress.', 'rapid-media-reclaim' ) ); } // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception messages are data; REST JSON or the admin render boundary escapes output.
    213261                $this->processed = 1;
    214                 return $offset + 1 >= count( $state['ids'] ) ? null : $offset + 1;
    215         }
     262                return $offset + 1 >= count( $inventory ) && empty( $state['styles'] ) ? null : $offset + 1;
     263        }
     264
     265        /**
     266         * Queue bounded same-origin stylesheets linked from successfully fetched HTML.
     267         *
     268         * @param array  $state State.
     269         * @param string $html Public HTML.
     270         * @param string $page Page URL.
     271         * @param int    $id Source post ID, or zero for an archive.
     272         */
     273        private function queue_styles( array &$state, string $html, string $page, int $id ): void {
     274                if ( ! class_exists( '\DOMDocument' ) ) {
     275                        return;
     276                }
     277                $previous = libxml_use_internal_errors( true );
     278                $document = new \DOMDocument();
     279                $document->loadHTML( $html, LIBXML_NONET );
     280                libxml_clear_errors();
     281                libxml_use_internal_errors( $previous );
     282                $state['styles']          = $state['styles'] ?? array();
     283                $state['style_results']   = $state['style_results'] ?? array();
     284                $state['external_styles'] = $state['external_styles'] ?? 0;
     285                foreach ( $document->getElementsByTagName( 'link' ) as $link ) {
     286                        if ( ! in_array( 'stylesheet', preg_split( '/\s+/', strtolower( trim( $link->getAttribute( 'rel' ) ) ) ), true ) ) {
     287                                continue;
     288                        }
     289                        $url = \WP_Http::make_absolute_url( $link->getAttribute( 'href' ), $page );
     290                        // Stylesheet version queries are stripped, never forwarded to endpoints.
     291                        $url = preg_replace( '/[?#].*$/', '', $url );
     292                        if ( ! self::allowed_url( $url ) ) {
     293                                ++$state['external_styles'];
     294                                continue;
     295                        }
     296                        if ( isset( $state['styles'][ $url ] ) || isset( $state['style_results'][ $url ] ) ) {
     297                                continue;
     298                        }
     299                        if ( count( $state['styles'] ) + count( $state['style_results'] ) >= 20 ) {
     300                                $state['limited'] = true;
     301                                break;
     302                        }
     303                        $state['styles'][ $url ] = $id;
     304                }
     305        }
     306
     307        /**
     308         * Fetch one stylesheet; imports and JavaScript remain explicitly excluded.
     309         *
     310         * @param array         $state State.
     311         * @param Ref_Collector $refs Evidence collector.
     312         */
     313        private function scan_style( array &$state, Ref_Collector $refs ): void {
     314                $url = array_key_first( $state['styles'] );
     315                $id  = $state['styles'][ $url ];
     316                unset( $state['styles'][ $url ] );
     317                $state['style_results'][ $url ] = 'failed';
     318                if ( ! self::allowed_url( $url ) ) {
     319                        return;
     320                }
     321                $response = wp_safe_remote_get(
     322                        $url,
     323                        array(
     324                                'timeout'             => 5,
     325                                'redirection'         => 0,
     326                                'limit_response_size' => 1048576,
     327                                'cookies'             => array(),
     328                                'headers'             => array(
     329                                        'Accept'        => 'text/css',
     330                                        'Cookie'        => '',
     331                                        'Authorization' => '',
     332                                ),
     333                                'user-agent'          => 'Rapid Media Reclaim anonymous coverage crawler',
     334                        )
     335                );
     336                if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) || 0 !== strpos( strtolower( (string) wp_remote_retrieve_header( $response, 'content-type' ) ), 'text/css' ) ) {
     337                        return;
     338                }
     339                $body = wp_remote_retrieve_body( $response );
     340                if ( strlen( $body ) >= 1048576 ) {
     341                        return;
     342                }
     343                if ( preg_match_all( '~url\(\s*["\']?([^\s)"\']+)~i', $body, $matches ) ) {
     344                        $items = array();
     345                        foreach ( array_slice( $matches[1], 0, 2000 ) as $image ) {
     346                                $absolute = \WP_Http::make_absolute_url( $image, $url );
     347                                $items[]  = array(
     348                                        'value'      => $absolute,
     349                                        'match_type' => 'url',
     350                                        'strength'   => 'strong',
     351                                        'context'    => $url,
     352                                );
     353                        }
     354                        $resolved = $this->resolver->resolve_many( $items );
     355                        foreach ( $resolved as $attachments ) {
     356                                foreach ( $attachments as $attachment ) {
     357                                        $refs->add( $attachment, 'strong', 'frontend', $id, $url, __( 'Anonymous linked stylesheet', 'rapid-media-reclaim' ), 'url' );
     358                                }
     359                        }
     360                        $refs->flush();
     361                }
     362                $state['style_results'][ $url ] = 'success';
     363        }
     364
     365        /**
     366         * Persist progress before advancing the caller's cursor.
     367         *
     368         * @param array $state State.
     369         * @throws \RuntimeException When progress cannot be saved.
     370         */
     371        private function save( array $state ): void {
     372                update_option( $this->option(), $state, false );
     373                if ( get_option( $this->option() ) !== $state ) {
     374                        throw new \RuntimeException( __( 'Could not persist crawl progress.', 'rapid-media-reclaim' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- JSON data escaped by render boundary.
     375                }
     376        }
     377
     378        /**
     379         * Discover one sitemap per tick, with a twenty-document hard budget.
     380         *
     381         * XML is parsed without entity substitution, DTD loading or network access.
     382         *
     383         * @param array $state Durable state, modified by reference.
     384         */
     385        private function discover( array &$state ): void {
     386                $url                = array_shift( $state['sitemaps'] );
     387                $state['visited'][] = $url;
     388                if ( ! self::allowed_url( $url ) || ! class_exists( '\DOMDocument' ) ) {
     389                        ++$state['sitemap_failed'];
     390                        return;
     391                }
     392                $response = wp_safe_remote_get(
     393                        $url,
     394                        array(
     395                                'timeout'             => 5,
     396                                'redirection'         => 0,
     397                                'limit_response_size' => 1048576,
     398                                'cookies'             => array(),
     399                                'headers'             => array(
     400                                        'Accept'        => 'application/xml,text/xml',
     401                                        'Cookie'        => '',
     402                                        'Authorization' => '',
     403                                ),
     404                                'user-agent'          => 'Rapid Media Reclaim anonymous coverage crawler',
     405                        )
     406                );
     407                $body     = is_wp_error( $response ) ? '' : wp_remote_retrieve_body( $response );
     408                if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) || strlen( $body ) >= 1048576 || preg_match( '/<!DOCTYPE|<!ENTITY/i', $body ) ) {
     409                        ++$state['sitemap_failed'];
     410                        return;
     411                }
     412                $previous = libxml_use_internal_errors( true );
     413                $document = new \DOMDocument();
     414                $loaded   = $document->loadXML( $body, LIBXML_NONET );
     415                libxml_clear_errors();
     416                libxml_use_internal_errors( $previous );
     417                $root = $loaded && $document->documentElement ? $document->documentElement->localName : ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native DOM API property names.
     418                if ( ! in_array( $root, array( 'urlset', 'sitemapindex' ), true ) ) {
     419                        ++$state['sitemap_failed'];
     420                        return;
     421                }
     422                foreach ( $document->documentElement->childNodes as $node ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native DOM API property names.
     423                        if ( ! $node instanceof \DOMElement || ! in_array( $node->localName, array( 'url', 'sitemap' ), true ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native DOM API property names.
     424                                continue;
     425                        }
     426                        $location = '';
     427                        foreach ( $node->childNodes as $child ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native DOM API property names.
     428                                if ( $child instanceof \DOMElement && 'loc' === $child->localName ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native DOM API property names.
     429                                        $location = trim( $child->textContent ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native DOM API property names.
     430                                        break;
     431                                }
     432                        }
     433                        if ( strlen( $location ) > 2048 || ! self::allowed_url( $location ) ) {
     434                                ++$state['sitemap_skipped'];
     435                                continue;
     436                        }
     437                        if ( 'sitemapindex' === $root ) {
     438                                if ( in_array( $location, $state['visited'], true ) || in_array( $location, $state['sitemaps'], true ) ) {
     439                                        continue;
     440                                }
     441                                if ( count( $state['visited'] ) + count( $state['sitemaps'] ) >= 20 ) {
     442                                        $state['limited'] = true;
     443                                        continue;
     444                                }
     445                                $state['sitemaps'][] = $location;
     446                        } elseif ( ! in_array( $location, $state['urls'], true ) ) {
     447                                if ( count( $state['urls'] ) >= $state['limit'] ) {
     448                                        $state['limited'] = true;
     449                                        break;
     450                                }
     451                                $state['urls'][] = $location;
     452                        }
     453                }
     454        }
     455
    216456        /**
    217457         * Coverage.
    218458         *
    219          * @return array Explicit successful, failed, skipped, limited and pending coverage.
     459         * @return array Explicit successful, failed, skipped, partial, limited and pending coverage.
    220460         */
    221461        public function coverage(): array {
    222                 $state  = $this->state();
    223                 $counts = array_count_values( $state['results'] );
     462                $state     = $this->state();
     463                $inventory = array_merge( $state['urls'] ?? array(), $state['ids'] );
     464                $counts    = array_count_values( $state['results'] );
    224465                return array(
    225                         'total'   => count( $state['ids'] ),
    226                         'success' => $counts['success'] ?? 0,
    227                         'failed'  => $counts['failed'] ?? 0,
    228                         'skipped' => $counts['skipped'] ?? 0,
    229                         'pending' => count( $state['ids'] ) - count( $state['results'] ),
    230                         'limited' => (bool) $state['limited'],
    231                         'limit'   => $state['limit'],
     466                        'total'             => count( $inventory ),
     467                        'success'           => $counts['success'] ?? 0,
     468                        'failed'            => $counts['failed'] ?? 0,
     469                        'skipped'           => $counts['skipped'] ?? 0,
     470                        'partial'           => $counts['partial'] ?? 0,
     471                        'pending'           => count( $inventory ) - count( $state['results'] ),
     472                        'limited'           => (bool) $state['limited'],
     473                        'limit'             => $state['limit'],
     474                        'sitemap_pending'   => count( $state['sitemaps'] ?? array() ),
     475                        'sitemap_attempted' => count( $state['visited'] ?? array() ),
     476                        'sitemap_failed'    => $state['sitemap_failed'] ?? 0,
     477                        'sitemap_skipped'   => $state['sitemap_skipped'] ?? 0,
     478                        'javascript'        => false,
     479                        'style_pending'     => count( $state['styles'] ?? array() ),
     480                        'style_results'     => array_count_values( $state['style_results'] ?? array() ),
     481                        'external_styles'   => $state['external_styles'] ?? 0,
     482                        'css_imports'       => false,
    232483                );
    233484        }
  • rapid-media-reclaim/tags/1.1.0/includes/scan/class-incremental.php

    r3794616 r3814937  
    1616/** Incremental service. */
    1717final class Incremental {
     18        /** Initialized request-owned queues; no extra database reads on page loads.
     19         *
     20         * @var array
     21         */
     22        private static $instances = array();
     23
     24        /** Flush known buffered source changes before an explicit retirement fence. */
     25        public static function flush_pending(): void {
     26                foreach ( self::$instances as $instance ) {
     27                        $instance->flush(); }
     28        }
     29
    1830        /**
    1931         * Coalesced incremental work.
    … …  
    2638         */
    2739        public function init(): void {
     40                self::$instances[ spl_object_hash( $this ) ] = $this;
    2841                add_action( 'save_post', array( $this, 'post' ), 10, 1 );
    2942                add_action( 'wp_after_insert_post', array( $this, 'post' ), 10, 1 );
    … …  
    3346                        'post_updated',
    3447                        function ( $id, $after, $before ) {
    35                                 if ( 'acf-field' === $before->post_type ) {
     48                                if ( in_array( $before->post_type, array( 'acf-field', 'acf-field-group' ), true ) ) {
    3649                                        $this->acf_definition_changed();
    3750                                }
    … …  
    5770                                $event . '_option',
    5871                                function ( $name ) {
    59                                         // Media settings change in the admin, the REST API or WP-CLI; front-end
    60                                         // requests update caches and counters only.
     72                                        // Option hooks retain their existing editing-context scope. Visitor
     73                                        // deferral covers post, term, user and attachment source changes.
    6174                                        if ( self::editing_context() && Database_Scanner::option_allowed( $name ) ) {
    6275                                                $this->enqueue( 'options', $name );
    … …  
    110123        }
    111124        /**
    112          * True for requests that can change which media is used (admin, REST, cron, WP-CLI).
     125         * Contexts retaining immediate indexing; visitor changes use the durable queue.
    113126         */
    114127        private static function editing_context(): bool {
    … …  
    129142         */
    130143        public function post( $id ): void {
    131                 if ( 'acf-field' === get_post_type( $id ) ) {
     144                if ( in_array( get_post_type( $id ), array( 'acf-field', 'acf-field-group' ), true ) ) {
    132145                        $this->acf_definition_changed();
    133146                }
    134147                if ( ! wp_is_post_revision( $id ) && ! wp_is_post_autosave( $id ) ) {
    135148                        $this->enqueue( 'posts', $id );
     149                }
     150        }
     151        /**
     152         * Refresh bounded owners of a saved Elementor document, including transitive edges.
     153         *
     154         * @param int $id Changed dependency ID.
     155         */
     156        private function dependents( int $id ): void {
     157                global $wpdb;
     158                if ( ! $this->generations() ) {
     159                        return;
     160                }
     161                $owners = self::read_ids( $wpdb->prepare( "SELECT DISTINCT post_id FROM {$wpdb->postmeta} WHERE meta_key=%s AND meta_value=%s LIMIT 101", '_safe_media_cleaner_elementor_dependency', (string) $id ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Prepared bounded dependency lookup; postmeta key is indexed.
     162                foreach ( array_slice( $owners, 0, 100 ) as $owner ) {
     163                        $this->enqueue( 'posts', (int) $owner );
     164                }
     165                if ( count( $owners ) > 100 || $wpdb->last_error ) {
     166                        foreach ( $this->generations() as $generation ) {
     167                                Adapter_Coverage::merge(
     168                                        $generation,
     169                                        array(
     170                                                'elementor' => array(
     171                                                        'sources' => 0,
     172                                                        'issues'  => array( 'elementor_dependency_refresh_requires_rescan' => 1 ),
     173                                                ),
     174                                        )
     175                                );
     176                        }
    136177                }
    137178        }
    … …  
    144185                                $generation,
    145186                                array(
    146                                         'acf' => array(
     187                                        'acf'      => array(
    147188                                                'sources' => 0,
    148189                                                'issues'  => array( 'acf_definition_changed' => 1 ),
    149190                                        ),
     191                                        'database' => array(
     192                                                'sources' => 0,
     193                                                'issues'  => array( 'database_acf_definition_changed' => 1 ),
     194                                        ),
    150195                                )
    151196                        );
    … …  
    165210        }
    166211        /**
    167          * * Write buffered work and clear the in-memory queue.
     212         * Write buffered work, retaining durable protection on a failed immediate edit.
     213         *
     214         * @throws \Throwable Immediate indexing could not finish.
    168215         */
    169216        public function flush(): void {
     217                if ( ! $this->queue ) {
     218                        return;
     219                }
     220                if ( ! self::editing_context() ) {
     221                        \SafeMediaCleaner\Deferred_Index::enqueue( $this->queue );
     222                        $this->queue = array();
     223                        return;
     224                }
     225                $snapshot = $this->queue;
     226                try {
     227                        $this->write_queue();
     228                } catch ( \Throwable $error ) {
     229                        // A failed immediate edit must not expose a partially rewritten index.
     230                        \SafeMediaCleaner\Deferred_Index::enqueue( $snapshot );
     231                        throw $error;
     232                }
     233        }
     234
     235        /** Write the buffered queue inside projection invalidation. */
     236        private function write_queue(): void {
     237                if ( ! $this->queue ) {
     238                        return; }
     239                if ( class_exists( \SafeMediaCleaner\Status_Index::class ) ) {
     240                        \SafeMediaCleaner\Status_Index::write(
     241                                $this->generations(),
     242                                function () {
     243                                        $this->flush_index();
     244                                }
     245                        );
     246                } else {
     247                        $this->flush_index(); }
     248        }
     249
     250        /**
     251         * Apply an internal durable source snapshot synchronously in the worker.
     252         *
     253         * @param array $sources Numeric IDs grouped by scanner phase.
     254         * @throws \InvalidArgumentException Invalid source kind.
     255         */
     256        public static function refresh_sources( array $sources ): void {
     257                $worker = new self();
     258                foreach ( $sources as $phase => $ids ) {
     259                        if ( ! in_array( $phase, array( 'posts', 'terms', 'users', 'files' ), true ) ) {
     260                                throw new \InvalidArgumentException( 'Invalid deferred source kind.' );
     261                        }
     262                        foreach ( $ids as $id ) {
     263                                $worker->enqueue( $phase, absint( $id ) );
     264                        }
     265                }
     266                $worker->write_queue();
     267        }
     268
     269        /**
     270         * Execute a prepared authoritative mutation and never mask a failure.
     271         *
     272         * @param string $sql Prepared internal SQL.
     273         * @throws \RuntimeException Evidence write failed.
     274         */
     275        private static function execute( string $sql ): void {
     276                global $wpdb;
     277                if ( false === $wpdb->query( $sql ) ) { // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared -- Callers prepare values against internal table identifiers.
     278                        throw new \RuntimeException( 'Could not update incremental evidence.' );
     279                }
     280        }
     281
     282        /**
     283         * Read an authoritative ID set or retain the pending source for retry.
     284         *
     285         * @param string $sql Prepared internal SQL.
     286         * @return array IDs.
     287         * @throws \RuntimeException Evidence read failed.
     288         */
     289        private static function read_ids( string $sql ): array {
     290                global $wpdb;
     291                $ids = $wpdb->get_col( $sql ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared -- Callers prepare values; no cached read can authorize acknowledging a job.
     292                if ( $wpdb->last_error ) {
     293                        throw new \RuntimeException( 'Could not read incremental evidence.' );
     294                }
     295                return $ids;
     296        }
     297
     298        /**
     299         * Distinguish a missing post from a failed core post lookup.
     300         *
     301         * @param int $id Source ID.
     302         * @return string|false Post type.
     303         * @throws \RuntimeException Core source identity could not be read.
     304         */
     305        private static function post_type( int $id ) {
     306                global $wpdb;
     307                $type = get_post_type( $id );
     308                if ( $wpdb->last_error ) {
     309                        throw new \RuntimeException( 'Could not read incremental source identity.' );
     310                }
     311                return $type;
     312        }
     313
     314        /** Refresh authoritative evidence and shared groups. */
     315        private function flush_index(): void {
     316                if ( ! $this->queue ) {
     317                        return;
     318                }
    170319                global $wpdb;
    171320                $generations = $this->generations();
     321                // Resolve saved-template owners once per changed post per flush, after all
     322                // metadata writes have settled. Never rescan dependency ownership per field.
     323                foreach ( $this->queue['posts'] ?? array() as $id ) {
     324                        $this->dependents( (int) $id );
     325                }
    172326                $queue       = $this->queue;
    173327                $this->queue = array();
    … …  
    178332                $files = $queue['files'] ?? array();
    179333                foreach ( $queue['posts'] ?? array() as $id ) {
    180                         if ( 'attachment' === get_post_type( $id ) ) {
     334                        if ( 'attachment' === self::post_type( (int) $id ) ) {
    181335                                $files[ $id ] = $id;
    182336                        }
    … …  
    184338                foreach ( $files as $id ) {
    185339                        File_Map::refresh( array( (int) $id ), $generations );
    186                         if ( 'attachment' !== get_post_type( $id ) ) {
     340                        if ( 'attachment' !== self::post_type( (int) $id ) ) {
    187341                                foreach ( $generations as $g ) {
    188342                                        foreach ( array( 'files', 'refs' ) as $name ) {
    189343                                                $table = Installer::table( $name );
    190                                                 $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE attachment_id=%d AND generation=%d", $id, $g ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     344                                                self::execute( $wpdb->prepare( "DELETE FROM {$table} WHERE attachment_id=%d AND generation=%d", $id, $g ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    191345                                        }
    192346                                }
    … …  
    210364                                        $args      = array_merge( array( $generation, $id ), $types[ $phase ] );
    211365                                        $in        = implode( ',', array_fill( 0, count( $types[ $phase ] ), '%s' ) );
    212                                         foreach ( $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT attachment_id FROM {$table} WHERE generation=%d AND {$condition} AND source_type IN ({$in})", $args ) ) as $before ) { // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     366                                        foreach ( self::read_ids( $wpdb->prepare( "SELECT DISTINCT attachment_id FROM {$table} WHERE generation=%d AND {$condition} AND source_type IN ({$in})", $args ) ) as $before ) { // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    213367                                                $affected[ (int) $before ] = true;
    214368                                        }
    215                                         $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE generation=%d AND {$condition} AND source_type IN (" . implode( ',', array_fill( 0, count( $types[ $phase ] ), '%s' ) ) . ')', $args ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     369                                        self::execute( $wpdb->prepare( "DELETE FROM {$table} WHERE generation=%d AND {$condition} AND source_type IN (" . implode( ',', array_fill( 0, count( $types[ $phase ] ), '%s' ) ) . ')', $args ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    216370                                        $scanner->one( $id, $refs );
    217371                                        $refs->flush();
    218                                         foreach ( $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT attachment_id FROM {$table} WHERE generation=%d AND {$condition} AND source_type IN ({$in})", $args ) ) as $after ) { // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     372                                        foreach ( self::read_ids( $wpdb->prepare( "SELECT DISTINCT attachment_id FROM {$table} WHERE generation=%d AND {$condition} AND source_type IN ({$in})", $args ) ) as $after ) { // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    219373                                                $affected[ (int) $after ] = true;
    220374                                        }
    … …  
    245399                                'intval',
    246400                                // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    247                                 $wpdb->get_col(
     401                                self::read_ids(
    248402                                        $wpdb->prepare(
    249403                                                "SELECT DISTINCT other.attachment_id FROM {$files} changed
    … …  
    259413                        foreach ( array_chunk( $group, 500 ) as $chunk ) {
    260414                                $list = implode( ',', $chunk );
    261                                 $wpdb->query( $wpdb->prepare( "DELETE FROM {$refs} WHERE generation=%d AND source_type='shared_file' AND attachment_id IN ({$list})", $generation ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     415                                self::execute( $wpdb->prepare( "DELETE FROM {$refs} WHERE generation=%d AND source_type='shared_file' AND attachment_id IN ({$list})", $generation ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    262416                                // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    263                                 $wpdb->query(
     417                                self::execute(
    264418                                        $wpdb->prepare(
    265419                                                "INSERT INTO {$refs} (attachment_id,strength,source_type,source_id,source_key,context,match_type,generation)
  • rapid-media-reclaim/tags/1.1.0/includes/scan/class-ref-collector.php

    r3794616 r3814937  
    7474         */
    7575        public function flush(): void {
     76                if ( class_exists( \SafeMediaCleaner\Status_Index::class ) ) {
     77                        \SafeMediaCleaner\Status_Index::write(
     78                                $this->generations,
     79                                function () {
     80                                        $this->write_flush();
     81                                }
     82                        );
     83                } else {
     84                        $this->write_flush(); }
     85        }
     86
     87        /**
     88         * Flush authoritative evidence rows.
     89         *
     90         * @throws \RuntimeException Evidence write failed.
     91         */
     92        private function write_flush(): void {
    7693                global $wpdb;
    7794                $table = Installer::table( 'refs' );
  • rapid-media-reclaim/tags/1.1.0/includes/scan/class-theme-scanner.php

    r3794616 r3814937  
    2121        private $resolver;
    2222        /**
     23         * Target generation for durable coverage.
     24         *
     25         * @var int
     26         */
     27        private $generation;
     28        /**
    2329         * Sorted theme file inventory.
    2430         *
    … …  
    3844         */
    3945        public function __construct( int $generation ) {
    40                 $this->resolver = new Url_Resolver( $generation );
     46                $this->generation = $generation;
     47                $this->resolver   = new Url_Resolver( $generation );
    4148        }
    4249        /**
    … …  
    119126                                throw new \RuntimeException( 'Could not read theme file: ' . $key ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Error data is escaped by the REST JSON or admin rendering boundary.
    120127                        }
    121                         $items    = Extractor::extract( $content );
     128                        $result = Extractor::extract_result( $content );
     129                        if ( ! $result['complete'] ) {
     130                                $this->gap( $key, (string) array_key_first( $result['issues'] ) );
     131                        }
     132                        $items    = $result['refs'];
    122133                        $resolved = $this->resolver->resolve_many( $items );
    123134                        foreach ( $items as $i => $ref ) {
    … …  
    132143                return $next >= $this->total() ? null : $next;
    133144        }
     145
     146        /**
     147         * Keep a partly read theme file visible and pause cleanup, like an unread database value.
     148         *
     149         * @param string $key Theme-relative file path; contents are never retained.
     150         * @param string $reason Machine reason constant.
     151         * @throws \RuntimeException The durable cleanup restriction could not be saved.
     152         */
     153        private function gap( string $key, string $reason ): void {
     154                $sample = array(
     155                        'phase' => 'theme_files',
     156                        'id'    => 0,
     157                        'key'   => substr( $key, 0, 191 ),
     158                );
     159                $option = 'safe_media_cleaner_adapter_gap_' . $this->generation . '_database';
     160                add_option( $option, $sample, '', false );
     161                if ( ! get_option( $option, false ) ) {
     162                        throw new \RuntimeException( __( 'Could not save the cleanup restriction for unread content. The scan was stopped.', 'rapid-media-reclaim' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Error data is encoded by REST/CLI and escaped at the admin boundary.
     163                }
     164                Adapter_Coverage::merge(
     165                        $this->generation,
     166                        array(
     167                                'database' => array(
     168                                        'sources'  => 1,
     169                                        'issues'   => array( $reason => 1 ),
     170                                        'examples' => array( $sample ),
     171                                ),
     172                        )
     173                );
     174        }
    134175}
  • rapid-media-reclaim/tags/1.1.0/includes/scan/class-url-resolver.php

    r3794616 r3814937  
    4040         * @param string $url Url.
    4141         * @param string $base_path Base path.
     42         * @param array  $aliases Explicit CDN/old upload roots.
    4243         * @return string Result.
    4344         */
    44         public static function normalize( string $url, string $base_path = '/wp-content/uploads' ): string {
    45                 $url = rawurldecode( html_entity_decode( str_replace( '\\/', '/', $url ), ENT_QUOTES, 'UTF-8' ) );
    46                 $url = preg_split( '/[?#]/', $url )[0];
     45        public static function normalize( string $url, string $base_path = '/wp-content/uploads', array $aliases = array() ): string {
     46                $url      = rawurldecode( html_entity_decode( str_replace( '\\/', '/', $url ), ENT_QUOTES, 'UTF-8' ) );
     47                $url      = preg_split( '/[?#]/', $url )[0];
     48                $rootless = preg_replace( '~^https?:~i', '', $url );
     49                usort(
     50                        $aliases,
     51                        static function ( $a, $b ) {
     52                                return strlen( $b ) <=> strlen( $a );
     53                        }
     54                );
     55                foreach ( $aliases as $alias ) {
     56                        $prefix = preg_replace( '~^https?:~i', '', rtrim( rawurldecode( $alias ), '/' ) ) . '/';
     57                        if ( 0 === strncasecmp( $rootless, $prefix, strlen( $prefix ) ) ) {
     58                                return strtolower( substr( $rootless, strlen( $prefix ) ) );
     59                        }
     60                }
    4761                $url = preg_replace( '~^(?:https?:)?//[^/]+~i', '', $url );
    4862                $url = str_replace( '\\', '/', $url );
    … …  
    87101                $base    = wp_parse_url( $uploads['baseurl'], PHP_URL_PATH );
    88102                $base    = $base ? $base : '/wp-content/uploads';
     103                $aliases = \SafeMediaCleaner\Settings::get()['upload_aliases'];
    89104                $paths   = array();
    90105                $ids     = array();
    … …  
    100115                                $ids[ (int) $ref['value'] ][] = $key;
    101116                        } elseif ( 'filename' !== $ref['match_type'] ) {
    102                                 foreach ( self::variants( self::normalize( (string) $ref['value'], $base ) ) as $p ) {
     117                                foreach ( self::variants( self::normalize( (string) $ref['value'], $base, $aliases ) ) as $p ) {
    103118                                        $paths[ $p ][] = $key;
    104119                                }
  • rapid-media-reclaim/tags/1.1.0/languages/rapid-media-reclaim.pot

    r3794616 r3814937  
    33msgid ""
    44msgstr ""
    5 "Project-Id-Version: Rapid Media Reclaim 1.0.0\n"
    6 "Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/source\n"
     5"Project-Id-Version: Rapid Media Reclaim 1.1.0\n"
     6"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/rapid-media-reclaim\n"
    77"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
    88"Language-Team: LANGUAGE <LL@li.org>\n"
    … …  
    1010"Content-Type: text/plain; charset=UTF-8\n"
    1111"Content-Transfer-Encoding: 8bit\n"
    12 "POT-Creation-Date: 2026-10-22T10:56:31+00:00\n"
     12"POT-Creation-Date: 2026-11-21T06:46:51+00:00\n"
    1313"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
    1414"X-Generator: WP-CLI 2.12.0\n"
    … …  
    2020#: includes/admin/class-admin.php:55
    2121#: includes/admin/class-admin.php:56
    22 #: assets/js/app.js:1190
     22#: assets/js/app.js:1207
    2323msgid "Rapid Media Reclaim"
    24 msgstr ""
    25 
    26 #. Plugin URI of the plugin
    27 #: rapid-media-reclaim.php
    28 msgid "https://wordpress.org/plugins/rapid-media-reclaim/"
    2924msgstr ""
    3025
    3126#. Description of the plugin
    3227#: rapid-media-reclaim.php
    33 msgid "Find unused media with proof of where every file is used, move it to a reversible quarantine, and clean up only when you are sure."
     28msgid "Review potentially unused media with usage evidence, reversible quarantine and one-click restore before reclaiming storage."
    3429msgstr ""
    3530
    … …  
    6156
    6257#: includes/admin/class-media-library.php:71
    63 #: assets/js/app.js:1701
     58#: assets/js/app.js:2354
    6459msgid "In quarantine"
    6560msgstr ""
    … …  
    7873
    7974#: includes/admin/class-media-library.php:89
    80 #: assets/js/app.js:27
    81 #: assets/js/app.js:1465
    82 #: assets/js/app.js:1728
     75#: assets/js/app.js:28
     76#: assets/js/app.js:2118
     77#: assets/js/app.js:2381
    8378msgid "Kept"
    8479msgstr ""
    … …  
    8883msgstr ""
    8984
     85#: includes/class-acf-context.php:330
     86msgid "ACF definitions or hidden field keys changed. Restore the approved context or resolve this journal manually; later edits and the merge lease were preserved."
     87msgstr ""
     88
     89#: includes/class-cli.php:48
     90msgid "Supply positive attachment IDs separated by commas."
     91msgstr ""
     92
     93#: includes/class-cli.php:52
     94msgid "At most 100 attachments may be selected per command."
     95msgstr ""
     96
     97#: includes/class-cli.php:56
     98msgid "An attachment ID is outside the supported range."
     99msgstr ""
     100
     101#: includes/class-cli.php:74
     102msgid "Use --user=<administrator> with the plugin management capability."
     103msgstr ""
     104
     105#: includes/class-cli.php:77
     106msgid "Force operations are not supported."
     107msgstr ""
     108
     109#: includes/class-cli.php:85
     110msgid "You cannot manage one of the selected attachments."
     111msgstr ""
     112
     113#: includes/class-cli.php:120
     114msgid "Quarantine the approved duplicates after reviewing public pages/caches and saving the current backup? No permanent deletion."
     115msgstr ""
     116
     117#: includes/class-cli.php:164
     118msgid "Operation history is unavailable. Check database access and retry with the last CSV cursor."
     119msgstr ""
     120
     121#: includes/class-cli.php:185
     122msgid "You cannot permanently delete one of the selected attachments."
     123msgstr ""
     124
     125#: includes/class-cli.php:231
     126msgid "Unsupported command."
     127msgstr ""
     128
     129#: includes/class-csv-export.php:62
     130msgid "You cannot export this media inventory."
     131msgstr ""
     132
     133#: includes/class-discovery-csv.php:71
     134msgid "Review only; no deletion authorization. Best-effort walk of changing uploads. Ownership is an index snapshot, not live proof. Unindexed files may still be used. Excluded/skipped trees are not covered. At most 10000 examined rows and 30 seconds per export; continuation is in the completion row."
     135msgstr ""
     136
     137#: includes/class-discovery-csv.php:79
     138msgid "Index changed or unavailable; ownership snapshot is stale."
     139msgstr ""
     140
     141#: includes/class-discovery-csv.php:79
     142msgid "Unregistered size remains owned; not a deletion candidate."
     143msgstr ""
     144
     145#: includes/class-discovery-csv.php:79
     146msgid "Requires independent usage and ownership review."
     147msgstr ""
     148
     149#: includes/class-discovery-csv.php:112
     150msgid "You cannot download this uploads audit."
     151msgstr ""
     152
     153#: includes/class-discovery-csv.php:123
     154msgid "This audit is unavailable, expired or belongs to another user."
     155msgstr ""
     156
     157#: includes/class-discovery-csv.php:133
     158msgid "Export interrupted; do not treat this partial CSV as complete."
     159msgstr ""
     160
     161#: includes/class-discovery-jobs.php:72
     162msgid "Unsupported discovery task."
     163msgstr ""
     164
     165#: includes/class-discovery-jobs.php:90
     166msgid "Could not save discovery task."
     167msgstr ""
     168
     169#: includes/class-discovery-jobs.php:129
     170msgid "This discovery task is busy."
     171msgstr ""
     172
     173#: includes/class-discovery-jobs.php:159
     174msgid "Could not save discovery results. Retry this step."
     175msgstr ""
     176
     177#: includes/class-discovery-jobs.php:167
     178msgid "Could not advance discovery cursor."
     179msgstr ""
     180
     181#: includes/class-discovery-jobs.php:192
     182msgid "Could not read discovery results."
     183msgstr ""
     184
     185#: includes/class-discovery-jobs.php:330
     186msgid "Invalid discovery task."
     187msgstr ""
     188
     189#: includes/class-discovery-jobs.php:335
     190msgid "Discovery task expired or belongs to another user."
     191msgstr ""
     192
     193#: includes/class-discovery-jobs.php:362
     194msgid "You cannot run media discovery tasks."
     195msgstr ""
     196
     197#: includes/class-duplicate-scanner.php:268
     198msgid "Could not read attachment inventory."
     199msgstr ""
     200
     201#: includes/class-file-archive.php:160
     202msgid "This backup is unavailable or could not be verified. Refresh Tools and retry with the owning account."
     203msgstr ""
     204
    90205#. translators: %d: post ID
    91 #: includes/class-index.php:644
     206#: includes/class-index.php:696
    92207#, php-format
    93208msgid "(no title) #%d"
    94209msgstr ""
    95210
    96 #: includes/class-index.php:670
     211#: includes/class-index.php:722
    97212msgid "User profile"
    98213msgstr ""
    99214
    100 #: includes/class-index.php:686
    101 #: includes/scan/class-database-scanner.php:332
     215#: includes/class-index.php:738
     216#: includes/scan/class-database-scanner.php:508
    102217msgid "Site setting"
    103218msgstr ""
    104219
    105 #: includes/class-index.php:687
     220#: includes/class-index.php:739
    106221msgid "Theme setting"
    107222msgstr ""
    108223
    109 #: includes/class-index.php:688
    110 #: includes/scan/class-database-scanner.php:335
     224#: includes/class-index.php:740
     225#: includes/scan/class-database-scanner.php:511
    111226msgid "Widget"
    112227msgstr ""
    113228
    114 #: includes/class-index.php:689
    115 #: assets/js/app.js:70
     229#: includes/class-index.php:741
     230#: assets/js/app.js:71
    116231msgid "Site identity"
    117232msgstr ""
    118233
    119 #. translators: %d: media ID
    120234#. translators: %d: attachment ID
    121 #: includes/class-index.php:698
    122 #: assets/js/app.js:205
     235#: includes/class-index.php:750
     236#: assets/js/app.js:206
    123237#, php-format,js-format
    124238msgid "Media #%d"
    125239msgstr ""
    126240
    127 #. translators: %d: media ID
    128 #: includes/class-index.php:699
     241#. translators: %d: attachment ID
     242#: includes/class-index.php:751
    129243msgid "Same file, used elsewhere (for example a translation)"
    130244msgstr ""
    131245
    132 #: includes/class-index.php:707
     246#: includes/class-index.php:759
    133247msgid "Anonymous browser media error"
    134248msgstr ""
    135249
    136 #: includes/class-index.php:708
     250#: includes/class-index.php:760
    137251msgid "Conservative observation; page and visitor details are not stored."
    138252msgstr ""
    139253
    140 #: includes/class-index.php:717
     254#: includes/class-index.php:769
    141255msgid "Theme file"
    142256msgstr ""
    143257
     258#: includes/class-merge.php:68
     259msgid "Resolve existing reference journals before creating another merge."
     260msgstr ""
     261
     262#: includes/class-merge.php:71
     263msgid "Could not protect the merge payloads. Nothing was rewritten."
     264msgstr ""
     265
     266#: includes/class-merge.php:90
     267msgid "Select one canonical image and up to ten duplicates after a complete scan."
     268msgstr ""
     269
     270#: includes/class-merge.php:111
     271msgid "Every merge item must be editable, local and outside quarantine."
     272msgstr ""
     273
     274#: includes/class-merge.php:114
     275msgid "Translation/shared-file reference merges need a language mapping and are not supported yet. No references were changed."
     276msgstr ""
     277
     278#: includes/class-merge.php:118
     279msgid "A selected original cannot be fingerprinted safely."
     280msgstr ""
     281
     282#: includes/class-merge.php:122
     283msgid "Only distinct paths with byte-identical originals can be rewritten."
     284msgstr ""
     285
     286#: includes/class-merge.php:147
     287msgid "Merge references exceed the preview budget or could not be read."
     288msgstr ""
     289
     290#: includes/class-merge.php:393
     291msgid "Merge journal exceeds its bounded storage limit."
     292msgstr ""
     293
     294#: includes/class-merge.php:411
     295msgid "Preview changed, has unsupported references or contains no supported writes. Nothing was changed."
     296msgstr ""
     297
     298#: includes/class-merge.php:426
     299msgid "Could not save the merge recovery journal."
     300msgstr ""
     301
     302#: includes/class-merge.php:446
     303msgid "Another media operation is running."
     304msgstr ""
     305
     306#: includes/class-merge.php:504
     307msgid "ACF scan coverage is incomplete. Resolve unsupported sources and complete a new scan before applying this merge. The journal was retained."
     308msgstr ""
     309
     310#: includes/class-merge.php:512
     311msgid "A merge payload changed. Roll back before retrying."
     312msgstr ""
     313
     314#: includes/class-merge.php:527
     315msgid "Restore missing or changed merge payloads before rolling references back."
     316msgstr ""
     317
     318#: includes/class-merge.php:534
     319msgid "You can no longer edit a merge source."
     320msgstr ""
     321
     322#: includes/class-merge.php:540
     323msgid "A source changed after preview. Its edits were preserved; review the conflict before retrying."
     324msgstr ""
     325
     326#: includes/class-merge.php:545
     327msgid "A reference write did not persist. The journal was retained."
     328msgstr ""
     329
     330#: includes/class-merge.php:757
     331msgid "Complete or roll back the pending reference operation before starting another."
     332msgstr ""
     333
     334#: includes/class-merge.php:968
     335msgid "Repeated or missing metadata cannot be merged safely."
     336msgstr ""
     337
     338#: includes/class-merge.php:990
     339msgid "A source changed during the write. Its edits were preserved and the merge journal was retained."
     340msgstr ""
     341
     342#: includes/class-merge.php:1002
     343msgid "Could not save merge progress. Retry; the recovery journal is retained."
     344msgstr ""
     345
     346#: includes/class-merge.php:1013
     347msgid "Invalid merge journal."
     348msgstr ""
     349
     350#: includes/class-merge.php:1016
     351msgid "Merge journal is unavailable or belongs to another user."
     352msgstr ""
     353
     354#: includes/class-merge.php:1046
     355msgid "Only administrators can merge references."
     356msgstr ""
     357
     358#: includes/class-operation-ledger.php:213
     359msgid "Operation accounting is pending. Files and recovery manifests were retained. Retry in Quarantine; check database writes if this persists. Available originals can still be restored."
     360msgstr ""
     361
    144362#: includes/class-quarantine.php:138
    145 #: includes/class-quarantine.php:240
    146 #: includes/class-quarantine.php:313
     363#: includes/class-quarantine.php:272
     364#: includes/class-quarantine.php:402
     365#: includes/class-quarantine.php:515
    147366msgid "Another media operation is running. Retry shortly."
    148367msgstr ""
    149368
     369#: includes/class-quarantine.php:158
     370#: includes/class-quarantine.php:200
     371msgid "Recovery requires the media operation lock."
     372msgstr ""
     373
    150374#: includes/class-quarantine.php:169
     375msgid "Existing quarantine recovery differs from this backup. Review it in Quarantine first."
     376msgstr ""
     377
     378#: includes/class-quarantine.php:173
     379msgid "Existing quarantine files differ from this backup."
     380msgstr ""
     381
     382#: includes/class-quarantine.php:188
     383msgid "Could not save recovery data. Retry before copying files."
     384msgstr ""
     385
     386#: includes/class-quarantine.php:223
     387msgid "Another attachment owns a backup file name. Review that media before retrying."
     388msgstr ""
     389
     390#: includes/class-quarantine.php:243
     391#: includes/class-quarantine.php:392
     392#: includes/class-quarantine.php:496
     393msgid "Resume the pending backup recovery in Tools before changing this media."
     394msgstr ""
     395
     396#: includes/class-quarantine.php:252
     397msgid "This file is protected by a reference recovery journal. Roll back or finish reviewing that operation first."
     398msgstr ""
     399
     400#: includes/class-quarantine.php:305
     401#: includes/class-quarantine.php:426
     402#: includes/class-quarantine.php:540
     403msgid "Resume pending recovery in Tools first."
     404msgstr ""
     405
     406#: includes/class-quarantine.php:322
    151407msgid "The quarantine folder could not be created. Check that the uploads folder is writable."
    152408msgstr ""
    153409
    154 #: includes/class-quarantine.php:179
     410#: includes/class-quarantine.php:332
    155411msgid "Shared group operation incomplete. Restore the group before retrying."
    156412msgstr ""
    157413
    158414#. translators: %s: comma-separated media IDs
    159 #: includes/class-quarantine.php:189
     415#: includes/class-quarantine.php:342
    160416#, php-format
    161417msgid "This file is shared with media item %s (for example a translation). Select them together to quarantine them."
    162418msgstr ""
    163419
    164 #: includes/class-quarantine.php:203
     420#: includes/class-quarantine.php:356
    165421msgid "Could not save the shared recovery record."
    166422msgstr ""
    167423
    168 #: includes/class-quarantine.php:346
     424#: includes/class-quarantine.php:472
     425msgid "Could not read the recovery batch. Retry the batch."
     426msgstr ""
     427
     428#: includes/class-quarantine.php:478
     429msgid "Could not verify the remaining recovery records. Retry the batch."
     430msgstr ""
     431
     432#: includes/class-quarantine.php:560
    169433msgid "Only quarantined files can be deleted permanently."
    170434msgstr ""
    171435
    172 #: includes/class-quarantine.php:350
     436#: includes/class-quarantine.php:564
    173437msgid "No verified permanent deletion intent exists. Restore or review this recovery record; its payload was retained."
    174438msgstr ""
    175439
    176 #. translators: %d: number of days
    177 #: includes/class-quarantine.php:359
    178 #, php-format
    179 msgid "This file has been in quarantine for less than %d day."
    180 msgid_plural "This file has been in quarantine for less than %d days."
    181 msgstr[0] ""
    182 msgstr[1] ""
    183 
    184 #: includes/class-quarantine.php:370
     440#: includes/class-quarantine.php:571
    185441msgid "This file is in use again (for example as a featured image or in content). Restore it instead of deleting it."
    186442msgstr ""
    187443
    188444#. translators: %s: comma-separated media IDs
    189 #: includes/class-quarantine.php:389
     445#: includes/class-quarantine.php:590
    190446#, php-format
    191447msgid "Media item %s still uses this file and is not in quarantine. Restore this item, or quarantine that one too."
    … …  
    193449
    194450#. translators: %s: comma-separated media IDs
    195 #: includes/class-quarantine.php:404
     451#: includes/class-quarantine.php:605
    196452#, php-format
    197453msgid "This file is shared with quarantined media item %s. Delete them together."
    198454msgstr ""
    199455
    200 #: includes/class-quarantine.php:491
     456#: includes/class-quarantine.php:618
     457msgid "Could not verify the complete recovery group. Nothing was deleted."
     458msgstr ""
     459
     460#: includes/class-quarantine.php:624
     461msgid "A shared file is in use again. Restore the group instead of deleting it."
     462msgstr ""
     463
     464#. translators: %d: minimum quarantine days.
     465#: includes/class-quarantine.php:671
     466#, php-format
     467msgid "Keep this file in quarantine for at least %d days before permanent deletion."
     468msgstr ""
     469
     470#: includes/class-quarantine.php:677
     471msgid "Download and confirm a current recovery archive before permanent deletion."
     472msgstr ""
     473
     474#: includes/class-quarantine.php:718
     475msgid "Manual deletion may proceed with incomplete or browser-only routing verification. Quarantine age is separate from the verified window. No recognized requests does not prove that a file is unused. The minimum waiting period, usage and ownership checks, saved-backup confirmation and permissions still apply."
     476msgstr ""
     477
     478#: includes/class-quarantine.php:788
    201479msgid "Invalid quarantine directory setting. Recovery data retained."
    202480msgstr ""
    203481
    204 #: includes/class-quarantine.php:533
     482#: includes/class-quarantine.php:835
    205483msgid "Sorry, you are not allowed to view this file."
    206484msgstr ""
    207485
    208 #: includes/class-quarantine.php:615
     486#: includes/class-quarantine.php:920
    209487msgid "This media item no longer exists."
    210488msgstr ""
    211489
    212 #: includes/class-quarantine.php:618
     490#: includes/class-quarantine.php:923
    213491msgid "This file is already in quarantine."
    214492msgstr ""
    215493
    216 #: includes/class-quarantine.php:623
     494#: includes/class-quarantine.php:930
    217495msgid "No files were found for this media item."
    218496msgstr ""
    219497
    220 #: includes/class-quarantine.php:634
     498#: includes/class-quarantine.php:941
    221499msgid "Could not verify file identity."
    222500msgstr ""
    223501
    224 #: includes/class-quarantine.php:647
     502#: includes/class-quarantine.php:954
    225503msgid "Could not save recovery data. No files were moved."
    226504msgstr ""
    227505
    228 #: includes/class-quarantine.php:658
     506#: includes/class-quarantine.php:973
    229507msgid "This media item could not be moved (the server did not allow it). Recovery data has been retained if cleanup could not finish. Review this item before retrying."
    230508msgstr ""
    231509
    232 #: includes/class-quarantine.php:671
     510#: includes/class-quarantine.php:986
    233511msgid "This media item could not be moved (a file could not be removed). Recovery data has been retained if cleanup could not finish. Review this item before retrying."
    234512msgstr ""
    235513
    236 #: includes/class-quarantine.php:767
     514#: includes/class-quarantine.php:1092
    237515msgid "This file is not in quarantine."
    238516msgstr ""
    239517
    240 #: includes/class-quarantine.php:784
     518#: includes/class-quarantine.php:1109
    241519msgid "Shared recovery owner is missing. Recovery data was retained."
    242520msgstr ""
    243521
    244 #: includes/class-quarantine.php:795
     522#: includes/class-quarantine.php:1120
    245523msgid "Legacy recovery identity is missing or ambiguous. No files were moved; recovery data was retained."
    246524msgstr ""
    247525
    248 #: includes/class-quarantine.php:799
     526#: includes/class-quarantine.php:1124
    249527msgid "Legacy recovery payload could not be verified."
    250528msgstr ""
    251529
    252 #: includes/class-quarantine.php:819
     530#: includes/class-quarantine.php:1144
    253531msgid "Could not save verified legacy recovery identities. No files were moved."
    254532msgstr ""
    255533
    256 #: includes/class-quarantine.php:828
     534#: includes/class-quarantine.php:1159
    257535msgid "Unsafe recovery path. Recovery data was retained."
    258536msgstr ""
    259537
    260 #: includes/class-quarantine.php:833
     538#: includes/class-quarantine.php:1164
    261539msgid "Recovery cleanup incomplete. Retry restore."
    262540msgstr ""
    263541
    264 #: includes/class-quarantine.php:838
     542#: includes/class-quarantine.php:1170
    265543msgid "A recovery file is missing, changed, or its destination is occupied. Recovery data was retained."
    266544msgstr ""
    267545
    268 #: includes/class-quarantine.php:841
     546#: includes/class-quarantine.php:1173
    269547msgid "Restore incomplete. Recovery data was retained; retry restore."
    270548msgstr ""
    271549
    272 #: includes/class-quarantine.php:853
     550#: includes/class-quarantine.php:1192
    273551msgid "Could not clear shared recovery metadata. Retry restore."
    274552msgstr ""
    275553
    276 #: includes/class-quarantine.php:855
     554#: includes/class-quarantine.php:1194
    277555msgid "Could not save shared recovery state. Retry restore."
    278556msgstr ""
    279557
    280 #: includes/class-quarantine.php:863
     558#: includes/class-quarantine.php:1202
    281559msgid "Could not clear recovery metadata. Retry restore."
    282560msgstr ""
    283561
    284 #: includes/class-quarantine.php:865
     562#: includes/class-quarantine.php:1207
    285563msgid "Files restored but recovery state could not be saved. Retry restore."
    286564msgstr ""
    287565
    288 #: includes/class-quarantine.php:892
     566#: includes/class-quarantine.php:1234
    289567msgid "Shared recovery owner is missing. Restore the group before deleting."
    290568msgstr ""
    291569
    292 #: includes/class-quarantine.php:898
     570#: includes/class-quarantine.php:1240
    293571msgid "Quarantine is incomplete. Restore before deleting."
    294572msgstr ""
    295573
    296 #: includes/class-quarantine.php:904
     574#: includes/class-quarantine.php:1246
    297575msgid "Quarantine payload changed. Recovery data retained."
    298576msgstr ""
    299577
    300 #: includes/class-quarantine.php:912
     578#: includes/class-quarantine.php:1254
    301579msgid "A shared recovery record has no verified deletion intent. Restore or review the group first."
    302580msgstr ""
    303581
    304 #: includes/class-quarantine.php:932
     582#: includes/class-quarantine.php:1274
    305583msgid "Could not save permanent deletion authorization. Nothing was deleted."
    306584msgstr ""
    307585
    308 #: includes/class-quarantine.php:947
     586#: includes/class-quarantine.php:1297
    309587msgid "WordPress could not delete this media item."
    310588msgstr ""
    311589
    312 #: includes/class-quarantine.php:954
     590#: includes/class-quarantine.php:1304
    313591msgid "Payload cleanup failed. Recovery record retained for retry."
    314592msgstr ""
    315593
    316 #: includes/class-quarantine.php:957
     594#: includes/class-quarantine.php:1310
    317595msgid "Could not save cleanup state."
    318596msgstr ""
    319597
    320 #: includes/class-quarantine.php:999
     598#: includes/class-quarantine.php:1352
    321599msgid "Recovery manifest is corrupt. Data was retained."
    322600msgstr ""
    323601
    324 #: includes/class-quarantine.php:1003
     602#: includes/class-quarantine.php:1356
    325603msgid "Recovery manifest is unsafe. Data was retained."
    326604msgstr ""
    327605
    328 #: includes/class-request-watcher.php:315
     606#: includes/class-quarantine.php:1522
     607#: includes/class-quarantine.php:1546
     608msgid "Could not verify file ownership. No files were moved."
     609msgstr ""
     610
     611#: includes/class-recovery-archive.php:277
     612msgid "This archive is incomplete, unsafe or outside the supported recovery limits. No media was changed."
     613msgstr ""
     614
     615#: includes/class-recovery-attachments.php:118
     616msgid "WordPress inserted a different attachment ID. Recovery is paused for manual review. No files or posts were deleted."
     617msgstr ""
     618
     619#: includes/class-recovery-attachments.php:156
     620msgid "Another writer occupied the original attachment ID during recovery. WordPress created a different ID. Recovery is paused for manual review; no posts or files were deleted."
     621msgstr ""
     622
     623#: includes/class-recovery-attachments.php:232
     624msgid "An attachment ID, permission, or metadata changed, or reconstruction could not be verified. Recovery data was retained. Resolve the conflict and retry in Tools."
     625msgstr ""
     626
     627#: includes/class-recovery-export.php:35
     628msgid "Select between 1 and 100 recovery items."
     629msgstr ""
     630
     631#: includes/class-recovery-export.php:40
     632msgid "Some selected items no longer have recovery records."
     633msgstr ""
     634
     635#: includes/class-recovery-export.php:48
     636msgid "Include the payload owner and all shared media items in the export."
     637msgstr ""
     638
     639#: includes/class-recovery-export.php:52
     640msgid "Export shared media items together."
     641msgstr ""
     642
     643#: includes/class-recovery-export.php:57
     644msgid "Recovery manifest is incomplete. Restore or review this item first."
     645msgstr ""
     646
     647#: includes/class-recovery-export.php:61
     648msgid "Export requires verified manifests and files no larger than 64 MiB."
     649msgstr ""
     650
     651#: includes/class-recovery-export.php:65
     652msgid "Export at most 512 MiB per archive; use smaller selections."
     653msgstr ""
     654
     655#: includes/class-recovery-export.php:76
     656msgid "Export at most 5,000 payload files at once."
     657msgstr ""
     658
     659#: includes/class-recovery-export.php:106
     660msgid "Recovery metadata exceeds the bounded export limit."
     661msgstr ""
     662
     663#: includes/class-recovery-export.php:135
     664msgid "The PHP ZIP extension is required for recovery exports."
     665msgstr ""
     666
     667#: includes/class-recovery-export.php:142
     668msgid "Could not create private recovery archive."
     669msgstr ""
     670
     671#: includes/class-recovery-export.php:149
     672msgid "Could not save recovery manifest."
     673msgstr ""
     674
     675#: includes/class-recovery-export.php:166
     676msgid "Could not save export progress."
     677msgstr ""
     678
     679#: includes/class-recovery-export.php:184
     680msgid "This export is busy. Retry shortly."
     681msgstr ""
     682
     683#: includes/class-recovery-export.php:190
     684msgid "Recovery state changed. Start a new export."
     685msgstr ""
     686
     687#: includes/class-recovery-export.php:204
     688msgid "Could not save archive verification progress."
     689msgstr ""
     690
     691#: includes/class-recovery-export.php:210
     692msgid "Recovery archive is missing or damaged."
     693msgstr ""
     694
     695#: includes/class-recovery-export.php:217
     696msgid "A recovery payload is missing, changed or unreadable. Nothing was deleted."
     697msgstr ""
     698
     699#: includes/class-recovery-export.php:225
     700msgid "Archive write failed. Check private temporary storage."
     701msgstr ""
     702
     703#: includes/class-recovery-export.php:232
     704msgid "Could not save export progress. Retry this step."
     705msgstr ""
     706
     707#: includes/class-recovery-export.php:249
     708msgid "Could not verify archive."
     709msgstr ""
     710
     711#: includes/class-recovery-export.php:255
     712msgid "Archive payload is missing."
     713msgstr ""
     714
     715#: includes/class-recovery-export.php:262
     716msgid "Archive checksum verification failed."
     717msgstr ""
     718
     719#: includes/class-recovery-export.php:281
     720msgid "Download a current, complete recovery archive before confirming your saved backup."
     721msgstr ""
     722
     723#: includes/class-recovery-export.php:299
     724msgid "Could not save the backup receipt."
     725msgstr ""
     726
     727#: includes/class-recovery-export.php:387
     728msgid "Could not save the recovery delivery or confirmation receipt. Retry before deleting media."
     729msgstr ""
     730
     731#: includes/class-recovery-export.php:518
     732msgid "Invalid recovery export."
     733msgstr ""
     734
     735#: includes/class-recovery-export.php:522
     736msgid "Recovery export expired or belongs to another user."
     737msgstr ""
     738
     739#: includes/class-recovery-export.php:538
     740msgid "The original private export storage is unavailable. Restore that storage before retrying cleanup or downloading."
     741msgstr ""
     742
     743#: includes/class-recovery-export.php:544
     744msgid "Export storage is inside a public web root. Download and cleanup were refused."
     745msgstr ""
     746
     747#: includes/class-recovery-export.php:558
     748msgid "Private temporary storage must resolve to a local non-symlink directory."
     749msgstr ""
     750
     751#: includes/class-recovery-export.php:567
     752msgid "Recovery export storage must be outside every configured public web root."
     753msgstr ""
     754
     755#: includes/class-recovery-export.php:571
     756msgid "Private temporary storage is unavailable."
     757msgstr ""
     758
     759#: includes/class-recovery-export.php:575
     760msgid "Recovery export storage must be private."
     761msgstr ""
     762
     763#: includes/class-recovery-export.php:587
     764msgid "You cannot export recovery data."
     765msgstr ""
     766
     767#: includes/class-recovery-export.php:631
     768msgid "This export is busy. Retry the download shortly."
     769msgstr ""
     770
     771#: includes/class-recovery-export.php:635
     772msgid "Recovery export is not ready."
     773msgstr ""
     774
     775#: includes/class-recovery-export.php:639
     776msgid "Recovery export is unavailable."
     777msgstr ""
     778
     779#: includes/class-recovery-format.php:262
     780msgid "This backup contains unsupported attachment fields or metadata. No recovery changes were made."
     781msgstr ""
     782
     783#: includes/class-recovery-import-plan.php:34
     784msgid "This backup belongs to a different site. Recovery is not a migration tool."
     785msgstr ""
     786
     787#: includes/class-recovery-import-plan.php:47
     788msgid "This older backup lacks original association and alt-text context. It can only repair existing attachment records."
     789msgstr ""
     790
     791#: includes/class-recovery-import-plan.php:50
     792msgid "The original ID is occupied, its file or metadata differs, or you cannot edit it. Review the existing media first."
     793msgstr ""
     794
     795#: includes/class-recovery-import-plan.php:53
     796msgid "The original parent or author is missing, changed, or cannot be edited by you. Recovery cannot detach or reassign this attachment."
     797msgstr ""
     798
     799#. translators: 1: attachment ID, 2: recovery conflict
     800#: includes/class-recovery-import-plan.php:56
     801#, php-format
     802msgid "Attachment #%1$d: %2$s"
     803msgstr ""
     804
     805#: includes/class-recovery-import-plan.php:88
     806msgid "Existing edit backups are not covered by this archive. Preserve and review them before recovery."
     807msgstr ""
     808
     809#. translators: %s: upload-relative file name
     810#: includes/class-recovery-import-plan.php:102
     811#, php-format
     812msgid "File %s is occupied or has an unsafe parent directory. Keep the current file and resolve the conflict before retrying."
     813msgstr ""
     814
     815#. translators: %d: attachment ID
     816#: includes/class-recovery-import-plan.php:127
     817#, php-format
     818msgid "Attachment #%d has different or incomplete quarantine recovery data. Review it in Quarantine before importing."
     819msgstr ""
     820
     821#: includes/class-recovery-import-store.php:149
     822msgid "Recovery is unavailable, expired, belongs to another user, or its progress could not be saved. Retry from Tools with an authorized account."
     823msgstr ""
     824
     825#: includes/class-recovery-import.php:44
     826msgid "Choose a valid recovery ZIP upload within the server upload limit. Filesystem paths and incomplete uploads are not accepted."
     827msgstr ""
     828
     829#: includes/class-recovery-import.php:48
     830msgid "Too many recovery uploads remain. Finish active recovery or allow expired previews to be cleaned up before uploading again."
     831msgstr ""
     832
     833#: includes/class-recovery-import.php:52
     834msgid "The uploaded ZIP could not be read safely. Upload it again."
     835msgstr ""
     836
     837#: includes/class-recovery-import.php:72
     838msgid "The private recovery upload could not be saved. No media was changed."
     839msgstr ""
     840
     841#: includes/class-recovery-import.php:113
     842#: includes/class-recovery-import.php:279
     843msgid "Recovery finished but its protection could not be released. Retry from Tools."
     844msgstr ""
     845
     846#: includes/class-recovery-import.php:130
     847msgid "Finish verifying this ZIP before previewing recovery."
     848msgstr ""
     849
     850#: includes/class-recovery-import.php:150
     851msgid "Review a verified preview and explicitly confirm that this is your trusted backup."
     852msgstr ""
     853
     854#: includes/class-recovery-import.php:155
     855msgid "Recovery conditions changed or conflicts remain. Refresh the preview, resolve conflicts and confirm again."
     856msgstr ""
     857
     858#: includes/class-recovery-import.php:159
     859msgid "Finish the active recovery job before confirming another backup."
     860msgstr ""
     861
     862#: includes/class-recovery-import.php:162
     863msgid "Could not reserve recovery. Retry confirmation."
     864msgstr ""
     865
     866#: includes/class-recovery-import.php:193
     867msgid "Recovery ownership changed. Progress was retained for review."
     868msgstr ""
     869
     870#: includes/class-recovery-import.php:204
     871msgid "The backup site identity no longer matches. Recovery was paused."
     872msgstr ""
     873
     874#: includes/class-recovery-import.php:243
     875msgid "Recovery manifest is incomplete. All data was retained."
     876msgstr ""
     877
     878#: includes/class-recovery-import.php:270
     879msgid "Recovery files are available but quarantine state still needs review. Retry to finish."
     880msgstr ""
     881
     882#: includes/class-recovery-import.php:311
     883msgid "A recovered file failed its final identity check. Progress was retained; retry recovery."
     884msgstr ""
     885
     886#: includes/class-recovery-payload.php:201
     887msgid "A recovery file is changed, occupied, unsafe, or could not be copied or cleaned up. All recovery progress was retained. Resolve the conflict and retry."
     888msgstr ""
     889
     890#: includes/class-request-watcher.php:349
    329891msgid "Browser evidence is busy; retry the scan."
    330892msgstr ""
    331893
    332 #: includes/class-request-watcher.php:348
     894#: includes/class-request-watcher.php:398
    333895msgid "Public browser media error report"
    334896msgstr ""
    335897
    336 #: includes/class-request-watcher.php:349
     898#: includes/class-request-watcher.php:399
    337899msgid "Could not preserve browser usage evidence."
    338900msgstr ""
    339901
    340 #: includes/class-scan-runner.php:88
     902#: includes/class-savings-report.php:47
     903msgid "A media operation is running. Refresh the report after it finishes; totals are currently unknown."
     904msgstr ""
     905
     906#: includes/class-savings-report.php:48
     907msgid "Refresh Tools to retry the report."
     908msgstr ""
     909
     910#: includes/class-savings-report.php:93
     911msgid "Tracking starts with this ledger. Earlier statuses do not prove deletion. Storage is the last identity-checked observation; external changes may remain unknown until reconciliation. Backups and physical disk allocation are not measured."
     912msgstr ""
     913
     914#: includes/class-savings-report.php:94
     915msgid "Retry incomplete operations in Quarantine. Database failures require checking writes; hourly maintenance observes up to 20 tracked payloads under the media lock. Large or unsafe payloads remain unknown. Unknown historical removals cannot be reconstructed."
     916msgstr ""
     917
     918#: includes/class-scan-runner.php:91
    341919msgid "The scan engine is not available."
    342920msgstr ""
    343921
    344 #: includes/class-scan-runner.php:96
     922#: includes/class-scan-runner.php:99
    345923msgid "The previous scan is still stopping. Try again in a few seconds."
    346924msgstr ""
    347925
    348 #: includes/class-scan-runner.php:338
    349 #: includes/scan/class-incremental.php:272
     926#: includes/class-scan-runner.php:372
     927#: includes/scan/class-incremental.php:426
    350928msgid "Shares its file with another media item"
    351929msgstr ""
    352930
    353 #: includes/rest/class-controller.php:163
     931#: includes/class-scan-runner.php:610
     932msgid "Finalizing shared-file evidence"
     933msgstr ""
     934
     935#: includes/class-server-watch.php:102
     936msgid "Same-origin missing uploads that reach WordPress; periodic GIF canary only."
     937msgstr ""
     938
     939#: includes/class-server-watch.php:106
     940msgid "Routing canary checks only. No known interruption in routing verification does not mean continuous traffic capture. Other extensions, CDN and browser caches, upstream requests and encoded paths can bypass observation. A total database outage cannot promise durable knowledge of interruptions."
     941msgstr ""
     942
     943#: includes/class-server-watch.php:117
     944msgid "This site uses a custom uploads or installation path. Ask your host to route missing uploads to the WordPress front controller and deny every quarantine path, then run the routing test."
     945msgstr ""
     946
     947#: includes/class-server-watch.php:122
     948msgid "Have your hosting administrator adapt these examples to existing rules, validate the configuration and rerun the routing test. Never overwrite a live configuration. A GIF canary does not verify every static/CDN rule."
     949msgstr ""
     950
     951#: includes/class-storage.php:22
     952msgid "Uploads storage is unavailable, not local, symlinked or not writable."
     953msgstr ""
     954
     955#. translators: %s: storage provider
     956#: includes/class-storage.php:32
     957#, php-format
     958msgid "%s requires audit-only mode; remote media mutations are unsupported."
     959msgstr ""
     960
     961#: includes/class-storage.php:39
     962msgid "An offloaded-media plugin is active. Cleanup is limited to read-only auditing."
     963msgstr ""
     964
     965#: includes/class-storage.php:44
     966msgid "Some stored content exceeded scan limits. Resolve these values and run a complete scan before cleaning up."
     967msgstr ""
     968
     969#: includes/class-storage.php:47
     970msgid "Some usage updates could not be saved. Run a complete scan before cleaning up."
     971msgstr ""
     972
     973#: includes/class-storage.php:52
     974msgid "Background usage indexing could not finish. Cleanup is paused. Check scheduled tasks or ask your hosting provider for help."
     975msgstr ""
     976
     977#: includes/class-storage.php:53
     978msgid "Usage updates are pending. Cleanup is paused until background indexing finishes."
     979msgstr ""
     980
     981#: includes/rest/class-controller.php:173
    354982msgid "Sorry, you are not allowed to manage media cleanup on this site."
    355983msgstr ""
    356984
    357 #: includes/rest/class-controller.php:292
     985#: includes/rest/class-controller.php:304
    358986msgid "This file no longer exists in the Media Library."
    359987msgstr ""
    360988
    361 #: includes/rest/class-controller.php:343
     989#: includes/rest/class-controller.php:355
    362990msgid "Choose at least one file to restore."
    363991msgstr ""
    364992
    365 #: includes/rest/class-controller.php:366
     993#: includes/rest/class-controller.php:378
    366994msgid "You are not allowed to delete this media item."
    367995msgstr ""
    368996
    369 #: includes/rest/class-controller.php:408
     997#: includes/rest/class-controller.php:420
    370998msgid "Only administrators can change these settings."
    371999msgstr ""
    3721000
    373 #: includes/rest/class-controller.php:465
     1001#: includes/rest/class-controller.php:477
    3741002msgid "Something went wrong on the server. Please try again."
    3751003msgstr ""
    3761004
    377 #: includes/scan/class-adapter-coverage.php:58
     1005#: includes/rest/class-recovery-controller.php:89
     1006msgid "You need media recovery permission and a current session. Reload this page and try again."
     1007msgstr ""
     1008
     1009#: includes/rest/class-recovery-controller.php:96
     1010msgid "The recovery request is invalid. Upload a ZIP through Tools and use its saved preview."
     1011msgstr ""
     1012
     1013#: includes/rest/class-tools-controller.php:63
     1014msgid "Select up to ten images for visual review."
     1015msgstr ""
     1016
     1017#: includes/rest/class-tools-controller.php:67
     1018msgid "Visual review requires attachment IDs."
     1019msgstr ""
     1020
     1021#: includes/rest/class-tools-controller.php:100
     1022msgid "Confirm that you saved the recovery backup."
     1023msgstr ""
     1024
     1025#: includes/scan/class-adapter-coverage.php:71
    3781026msgid "Elementor structured media"
    3791027msgstr ""
    3801028
    381 #: includes/scan/class-adapter-coverage.php:59
     1029#: includes/scan/class-adapter-coverage.php:72
    3821030msgid "ACF typed fields"
     1031msgstr ""
     1032
     1033#: includes/scan/class-adapter-coverage.php:73
     1034msgid "Database source limits"
    3831035msgstr ""
    3841036
    … …  
    3991051msgstr ""
    4001052
    401 #: includes/scan/class-database-scanner.php:339
     1053#: includes/scan/class-database-scanner.php:452
     1054#: includes/scan/class-theme-scanner.php:162
     1055msgid "Could not save the cleanup restriction for unread content. The scan was stopped."
     1056msgstr ""
     1057
     1058#: includes/scan/class-database-scanner.php:515
    4021059msgid "Site icon"
    4031060msgstr ""
    4041061
    405 #: includes/scan/class-database-scanner.php:345
     1062#: includes/scan/class-database-scanner.php:530
     1063#: includes/scan/class-database-scanner.php:535
    4061064msgid "Theme"
    4071065msgstr ""
    4081066
    409 #: includes/scan/class-database-scanner.php:393
     1067#: includes/scan/class-database-scanner.php:614
    4101068msgid "Divi / WPBakery"
    4111069msgstr ""
    4121070
    413 #: includes/scan/class-database-scanner.php:393
     1071#: includes/scan/class-database-scanner.php:614
    4141072msgid "Post content"
    4151073msgstr ""
    4161074
    417 #: includes/scan/class-database-scanner.php:394
     1075#: includes/scan/class-database-scanner.php:615
    4181076msgid "Post excerpt"
    4191077msgstr ""
    4201078
    421 #: includes/scan/class-database-scanner.php:398
     1079#: includes/scan/class-database-scanner.php:619
    4221080msgid "Term description"
    4231081msgstr ""
    4241082
    425 #: includes/scan/class-database-scanner.php:415
     1083#: includes/scan/class-database-scanner.php:659
    4261084msgid "Featured image"
    4271085msgstr ""
    4281086
    429 #: includes/scan/class-database-scanner.php:420
     1087#: includes/scan/class-database-scanner.php:664
    4301088msgid "WooCommerce · Product images"
    4311089msgstr ""
    … …  
    4391097msgstr ""
    4401098
    441 #: includes/scan/class-frontend-scanner.php:108
     1099#: includes/scan/class-frontend-scanner.php:116
    4421100msgid "Could not persist crawl inventory."
    4431101msgstr ""
    4441102
    445 #: includes/scan/class-frontend-scanner.php:201
     1103#: includes/scan/class-frontend-scanner.php:243
    4461104msgid "Anonymous public HTML"
    4471105msgstr ""
    4481106
    449 #: includes/scan/class-frontend-scanner.php:212
     1107#: includes/scan/class-frontend-scanner.php:260
     1108#: includes/scan/class-frontend-scanner.php:374
    4501109msgid "Could not persist crawl progress."
    4511110msgstr ""
    4521111
    453 #: includes/scan/class-theme-scanner.php:56
     1112#: includes/scan/class-frontend-scanner.php:357
     1113msgid "Anonymous linked stylesheet"
     1114msgstr ""
     1115
     1116#: includes/scan/class-theme-scanner.php:63
    4541117msgid "Active theme and parent theme files"
    4551118msgstr ""
    4561119
    4571120#: uninstall.php:31
    458 #: uninstall.php:61
     1121#: uninstall.php:75
    4591122msgid "Another Rapid Media Reclaim operation is running. Try again in a minute."
    4601123msgstr ""
    4611124
    462 #: uninstall.php:39
     1125#: uninstall.php:35
     1126msgid "Resume pending backup recovery in Tools before uninstalling. Its files, journals and protections were retained."
     1127msgstr ""
     1128
     1129#: uninstall.php:38
     1130msgid "Standalone file recovery is incomplete. Its manifests, payloads and guards were retained."
     1131msgstr ""
     1132
     1133#: uninstall.php:50
    4631134msgid "The database could not be read."
    4641135msgstr ""
    4651136
    466 #: uninstall.php:42
     1137#: uninstall.php:53
    4671138msgid "Some quarantined media could not be restored automatically."
    4681139msgstr ""
    4691140
    470 #: uninstall.php:45
     1141#: uninstall.php:56
     1142msgid "Complete or roll back pending reference merges before uninstalling."
     1143msgstr ""
     1144
     1145#: uninstall.php:59
    4711146msgid "The quarantine folder still contains files."
    4721147msgstr ""
    4731148
    4741149#: uninstall.php:85
     1150msgid "Private recovery archives could not be removed. Retry cleanup before uninstalling."
     1151msgstr ""
     1152
     1153#: uninstall.php:102
    4751154msgid "The quarantine folder could not be removed. Recovery data was retained."
    4761155msgstr ""
    4771156
    478 #: uninstall.php:129
     1157#: uninstall.php:144
     1158msgid "Network recovery inventory could not be verified. All remaining recovery data was retained."
     1159msgstr ""
     1160
     1161#: uninstall.php:172
    4791162msgid "Rapid Media Reclaim was not deleted, so your quarantined media stays recoverable."
    4801163msgstr ""
    4811164
    482 #: uninstall.php:129
     1165#: uninstall.php:172
    4831166msgid "Activate the plugin, restore or delete the items in its Quarantine tab, then delete the plugin again."
    4841167msgstr ""
    4851168
    486 #: uninstall.php:130
    487 #: uninstall.php:150
     1169#: uninstall.php:173
     1170#: uninstall.php:193
    4881171msgid "Plugin not deleted"
    4891172msgstr ""
    4901173
    491 #: assets/js/app.js:24
    492 #: assets/js/app.js:1453
    493 #: assets/js/app.js:1721
     1174#: assets/js/app.js:25
     1175#: assets/js/app.js:2106
     1176#: assets/js/app.js:2374
    4941177msgid "Unused"
    4951178msgstr ""
    4961179
    497 #: assets/js/app.js:25
    498 #: assets/js/app.js:1301
     1180#: assets/js/app.js:26
     1181#: assets/js/app.js:1235
     1182#: assets/js/app.js:1954
    4991183msgid "Quarantine"
    5001184msgstr ""
    5011185
    502 #: assets/js/app.js:26
    503 #: assets/js/app.js:1458
     1186#: assets/js/app.js:27
     1187#: assets/js/app.js:2111
    5041188msgid "In use"
    5051189msgstr ""
    5061190
    507 #: assets/js/app.js:28
     1191#: assets/js/app.js:29
    5081192msgid "All"
    5091193msgstr ""
    5101194
    511 #: assets/js/app.js:33
     1195#: assets/js/app.js:34
    5121196msgid "All types"
    5131197msgstr ""
    5141198
    515 #: assets/js/app.js:34
     1199#: assets/js/app.js:35
    5161200msgid "Images"
    5171201msgstr ""
    5181202
    519 #: assets/js/app.js:35
     1203#: assets/js/app.js:36
    5201204msgid "Video"
    5211205msgstr ""
    5221206
    523 #: assets/js/app.js:36
     1207#: assets/js/app.js:37
    5241208msgid "Audio"
    5251209msgstr ""
    5261210
    527 #: assets/js/app.js:37
     1211#: assets/js/app.js:38
    5281212msgid "Documents"
    5291213msgstr ""
    5301214
    531 #: assets/js/app.js:38
     1215#: assets/js/app.js:39
    5321216msgid "Other"
    5331217msgstr ""
    5341218
    535 #: assets/js/app.js:42
     1219#: assets/js/app.js:43
    5361220msgid "Largest first"
    5371221msgstr ""
    5381222
    539 #: assets/js/app.js:43
     1223#: assets/js/app.js:44
    5401224msgid "Newest first"
    5411225msgstr ""
    5421226
    543 #: assets/js/app.js:44
     1227#: assets/js/app.js:45
    5441228msgid "Oldest first"
    5451229msgstr ""
    5461230
    547 #: assets/js/app.js:45
     1231#: assets/js/app.js:46
    5481232msgid "Name (A–Z)"
    5491233msgstr ""
    5501234
    551 #: assets/js/app.js:49
     1235#: assets/js/app.js:50
    5521236msgid "High confidence"
    5531237msgstr ""
    5541238
    555 #: assets/js/app.js:50
     1239#: assets/js/app.js:51
    5561240msgid "Medium confidence"
    5571241msgstr ""
    5581242
    559 #: assets/js/app.js:51
     1243#: assets/js/app.js:52
    5601244msgid "Low confidence"
    5611245msgstr ""
    5621246
    563 #: assets/js/app.js:55
     1247#: assets/js/app.js:56
    5641248msgid "Post and page content"
    5651249msgstr ""
    5661250
    567 #: assets/js/app.js:56
     1251#: assets/js/app.js:57
    5681252msgid "Excerpts"
    5691253msgstr ""
    5701254
    571 #: assets/js/app.js:57
     1255#: assets/js/app.js:58
    5721256msgid "Featured images"
    5731257msgstr ""
    5741258
    575 #: assets/js/app.js:58
     1259#: assets/js/app.js:59
    5761260msgid "Custom fields"
    5771261msgstr ""
    5781262
    579 #: assets/js/app.js:59
     1263#: assets/js/app.js:60
    5801264msgid "Page builders"
    5811265msgstr ""
    5821266
    583 #: assets/js/app.js:60
     1267#: assets/js/app.js:61
    5841268msgid "ACF fields"
    5851269msgstr ""
    5861270
    587 #: assets/js/app.js:61
     1271#: assets/js/app.js:62
    5881272msgid "WooCommerce"
    5891273msgstr ""
    5901274
    591 #: assets/js/app.js:62
     1275#: assets/js/app.js:63
    5921276msgid "Site settings"
    5931277msgstr ""
    5941278
    595 #: assets/js/app.js:63
     1279#: assets/js/app.js:64
    5961280msgid "Customizer"
    5971281msgstr ""
    5981282
    599 #: assets/js/app.js:64
     1283#: assets/js/app.js:65
    6001284msgid "Widgets"
    6011285msgstr ""
    6021286
    603 #: assets/js/app.js:65
     1287#: assets/js/app.js:66
    6041288msgid "Categories and terms"
    6051289msgstr ""
    6061290
    607 #: assets/js/app.js:66
     1291#: assets/js/app.js:67
    6081292msgid "User profiles"
    6091293msgstr ""
    6101294
    611 #: assets/js/app.js:67
     1295#: assets/js/app.js:68
    6121296msgid "Theme files"
    6131297msgstr ""
    6141298
    615 #: assets/js/app.js:68
     1299#: assets/js/app.js:69
    6161300msgid "Public HTML crawl"
    6171301msgstr ""
    6181302
    619 #: assets/js/app.js:69
     1303#: assets/js/app.js:70
    6201304msgid "Browser error report"
    6211305msgstr ""
    6221306
    623 #: assets/js/app.js:71
     1307#: assets/js/app.js:72
    6241308msgid "Shared file (translations and copies)"
    6251309msgstr ""
    6261310
    627 #: assets/js/app.js:88
     1311#: assets/js/app.js:89
    6281312msgid "Matched by ID"
    6291313msgstr ""
    6301314
    631 #: assets/js/app.js:89
     1315#: assets/js/app.js:90
    6321316msgid "Matched by URL"
    6331317msgstr ""
    6341318
    635 #: assets/js/app.js:90
     1319#: assets/js/app.js:91
    6361320msgid "Matched by file name"
    6371321msgstr ""
    6381322
    639 #: assets/js/app.js:94
     1323#: assets/js/app.js:95
    6401324msgid "Draft"
    6411325msgstr ""
    6421326
    643 #: assets/js/app.js:95
     1327#: assets/js/app.js:96
    6441328msgid "Pending review"
    6451329msgstr ""
    6461330
    647 #: assets/js/app.js:96
     1331#: assets/js/app.js:97
    6481332msgid "Private"
    6491333msgstr ""
    6501334
    651 #: assets/js/app.js:97
     1335#: assets/js/app.js:98
    6521336msgid "Scheduled"
    6531337msgstr ""
    6541338
    655 #: assets/js/app.js:98
     1339#: assets/js/app.js:99
    6561340msgid "In trash"
    6571341msgstr ""
    6581342
    659 #: assets/js/app.js:99
     1343#: assets/js/app.js:100
    6601344msgid "Auto draft"
    6611345msgstr ""
    6621346
    663 #: assets/js/app.js:100
     1347#: assets/js/app.js:101
    6641348msgid "Revision"
    6651349msgstr ""
    6661350
    667 #: assets/js/app.js:105
    668 #: assets/js/app.js:622
     1351#: assets/js/app.js:106
     1352#: assets/js/app.js:624
    6691353msgid "Move to quarantine"
    6701354msgstr ""
    6711355
    672 #: assets/js/app.js:111
     1356#: assets/js/app.js:112
     1357#: assets/js/app.js:1235
    6731358msgid "Restore"
    6741359msgstr ""
    6751360
    676 #: assets/js/app.js:117
     1361#: assets/js/app.js:118
    6771362msgid "Keep"
    6781363msgstr ""
    6791364
    680 #: assets/js/app.js:123
     1365#: assets/js/app.js:124
    6811366msgid "Unkeep"
    6821367msgstr ""
    6831368
    684 #: assets/js/app.js:129
    685 #: assets/js/app.js:668
     1369#: assets/js/app.js:130
     1370#: assets/js/app.js:667
    6861371msgid "Delete permanently"
    6871372msgstr ""
    6881373
    689 #: assets/js/app.js:339
    690 #: assets/js/app.js:1342
    691 #: assets/js/app.js:1952
    692 #: assets/js/app.js:2364
     1374#: assets/js/app.js:340
     1375#: assets/js/app.js:1995
     1376#: assets/js/app.js:2605
     1377#: assets/js/app.js:3030
    6931378msgid "Try again"
    6941379msgstr ""
    6951380
    6961381#. translators: 1: number selected, 2: total matching
    697 #: assets/js/app.js:511
     1382#: assets/js/app.js:512
    6981383#, js-format
    6991384msgid "Selected the first %1$s of %2$s files. Act on these, then select the rest."
    … …  
    7011386
    7021387#. translators: %s: number of files
    703 #: assets/js/app.js:573
    704 #: assets/js/app.js:2017
     1388#: assets/js/app.js:575
     1389#: assets/js/app.js:2670
    7051390#, js-format
    7061391msgid "%s file"
    … …  
    7101395
    7111396#. translators: 1: number of files, 2: size, e.g. "12 files (48.2 MB)"
    712 #: assets/js/app.js:576
     1397#: assets/js/app.js:578
    7131398#, js-format
    7141399msgid "%1$s file (%2$s)"
    … …  
    7171402msgstr[1] ""
    7181403
    719 #: assets/js/app.js:586
     1404#: assets/js/app.js:588
    7201405msgid "Files are moved out of the public uploads folder. Pages that still use them would show a missing image. Restore anytime from the Quarantine tab."
    7211406msgstr ""
    7221407
    723 #: assets/js/app.js:590
     1408#: assets/js/app.js:592
    7241409msgid "Nothing is deleted. Media Library entries stay in place."
    7251410msgstr ""
    7261411
    727 #: assets/js/app.js:591
     1412#: assets/js/app.js:593
    7281413msgid "One click restores every file and image size."
    7291414msgstr ""
    7301415
    7311416#. translators: %s: number of files
    732 #: assets/js/app.js:603
     1417#: assets/js/app.js:605
    7331418#, js-format
    7341419msgid "%s of these files has medium or low confidence. Open it to review the evidence if you are unsure."
    … …  
    7381423
    7391424#. translators: %s: "12 files (48.2 MB)"
    740 #: assets/js/app.js:618
     1425#: assets/js/app.js:620
    7411426#, js-format
    7421427msgid "Move %s to quarantine?"
    7431428msgstr ""
    7441429
    745 #: assets/js/app.js:632
     1430#: assets/js/app.js:634
    7461431msgid "The files are deleted from the server and their Media Library entries are removed. This can’t be undone."
    7471432msgstr ""
    7481433
     1434#: assets/js/app.js:635
     1435msgid "Routing verification may be incomplete, expired or browser-only. Quarantine age is separate from the verified window. No recognized requests does not prove that a file is unused. Saved-backup confirmation and all deletion checks still apply."
     1436msgstr ""
     1437
    7491438#. translators: 1: number of files, 2: number of days
    750 #: assets/js/app.js:646
     1439#: assets/js/app.js:649
    7511440#, js-format
    7521441msgid "%1$s of these files has been in quarantine for less than %2$s days. Waiting gives you time to notice anything that breaks."
    … …  
    7561445
    7571446#. translators: %s: number of files
    758 #: assets/js/app.js:659
    759 #, js-format
    760 msgid "Delete all %s anyway"
    761 msgstr ""
    762 
    763 #: assets/js/app.js:659
    764 msgid "Delete anyway"
    765 msgstr ""
    766 
    767 #. translators: %s: number of files
    768 #: assets/js/app.js:667
     1447#: assets/js/app.js:666
    7691448#, js-format
    7701449msgid "Delete %s ready file"
    … …  
    7741453
    7751454#. translators: %s: "5 files (12 MB)"
    776 #: assets/js/app.js:677
     1455#: assets/js/app.js:676
    7771456#, js-format
    7781457msgid "Delete %s permanently?"
    7791458msgstr ""
    7801459
    781 #: assets/js/app.js:682
     1460#: assets/js/app.js:681
    7821461msgid "I understand this can’t be undone"
    7831462msgstr ""
    7841463
    7851464#. translators: 1: "3 files couldn't be moved", 2: reason
    786 #: assets/js/app.js:773
     1465#: assets/js/app.js:769
    7871466#, js-format
    7881467msgid "%1$s: %2$s"
    … …  
    7901469
    7911470#. translators: 1: done, 2: total
    792 #: assets/js/app.js:816
     1471#: assets/js/app.js:812
    7931472#, js-format
    7941473msgid "Working… %1$s of %2$s files"
    … …  
    7961475
    7971476#. translators: %s: "12 files (48.2 MB)"
    798 #: assets/js/app.js:825
     1477#: assets/js/app.js:821
    7991478#, js-format
    8001479msgid "Moved %s to quarantine"
    8011480msgstr ""
    8021481
    803 #: assets/js/app.js:828
    804 #: assets/js/app.js:888
     1482#: assets/js/app.js:824
     1483#: assets/js/app.js:884
    8051484msgid "Undo"
    8061485msgstr ""
    8071486
    808 #: assets/js/app.js:836
     1487#: assets/js/app.js:832
    8091488msgid "Some files are shared with other media items, for example translations. They can only be quarantined together."
    8101489msgstr ""
    8111490
    812 #: assets/js/app.js:838
     1491#: assets/js/app.js:834
    8131492msgid "Move them together"
    8141493msgstr ""
    8151494
    816 #: assets/js/app.js:843
    817 #: assets/js/app.js:845
     1495#. translators: %s: number of files
     1496#: assets/js/app.js:839
     1497#: assets/js/app.js:841
    8181498#, js-format
    8191499msgid "%s file couldn’t be moved"
    … …  
    8231503
    8241504#. translators: %s: "3 files (12 MB)"
    825 #: assets/js/app.js:853
     1505#: assets/js/app.js:849
    8261506#, js-format
    8271507msgid "Restored %s"
    8281508msgstr ""
    8291509
    830 #: assets/js/app.js:858
     1510#. translators: %s: number of files
     1511#: assets/js/app.js:854
    8311512#, js-format
    8321513msgid "%s file couldn’t be restored"
    … …  
    8361517
    8371518#. translators: %s: "5 files (12 MB)"
    838 #: assets/js/app.js:867
     1519#: assets/js/app.js:863
    8391520#, js-format
    8401521msgid "Deleted %s permanently"
    8411522msgstr ""
    8421523
    843 #: assets/js/app.js:872
     1524#. translators: %s: number of files
     1525#: assets/js/app.js:868
    8441526#, js-format
    8451527msgid "%s file couldn’t be deleted"
    … …  
    8491531
    8501532#. translators: %s: number of files
    851 #: assets/js/app.js:886
     1533#: assets/js/app.js:882
    8521534#, js-format
    8531535msgid "Kept %s file. It won’t be listed as unused."
    … …  
    8571539
    8581540#. translators: %s: number of files
    859 #: assets/js/app.js:887
     1541#: assets/js/app.js:883
    8601542#, js-format
    8611543msgid "%s file is no longer kept."
    … …  
    8641546msgstr[1] ""
    8651547
    866 #: assets/js/app.js:891
     1548#. translators: %s: number of files
     1549#: assets/js/app.js:887
    8671550#, js-format
    8681551msgid "%s file couldn’t be updated"
    … …  
    8721555
    8731556#. translators: %s: number of files
    874 #: assets/js/app.js:922
     1557#: assets/js/app.js:935
    8751558#, js-format
    8761559msgid "Undone for %s file."
    … …  
    8801563
    8811564#. translators: %s: "12 files (48.2 MB)"
    882 #: assets/js/app.js:1025
     1565#: assets/js/app.js:1040
    8831566#, js-format
    8841567msgid "Scan complete. Found %s that look unused."
    8851568msgstr ""
    8861569
    887 #: assets/js/app.js:1028
     1570#: assets/js/app.js:1043
    8881571msgid "Scan complete. No unused media found."
    8891572msgstr ""
    8901573
    891 #: assets/js/app.js:1050
     1574#: assets/js/app.js:1065
    8921575msgid "Scan cancelled. Your previous results are unchanged."
    8931576msgstr ""
    8941577
    8951578#. translators: %s: seconds
    896 #: assets/js/app.js:1086
     1579#: assets/js/app.js:1101
    8971580#, js-format
    8981581msgid "Connection lost. Retrying in %s s…"
    8991582msgstr ""
    9001583
    901 #: assets/js/app.js:1101
     1584#: assets/js/app.js:1116
    9021585msgid "Summary"
    9031586msgstr ""
    9041587
    905 #: assets/js/app.js:1102
     1588#: assets/js/app.js:1117
    9061589msgid "Views"
    9071590msgstr ""
    9081591
    909 #: assets/js/app.js:1107
     1592#: assets/js/app.js:1122
    9101593msgid "Selection"
    9111594msgstr ""
    9121595
    913 #: assets/js/app.js:1112
     1596#: assets/js/app.js:1127
    9141597msgid "Free and open source"
    9151598msgstr ""
    9161599
    917 #: assets/js/app.js:1114
     1600#: assets/js/app.js:1129
    9181601msgid "Leave a review"
    9191602msgstr ""
    9201603
    921 #: assets/js/app.js:1159
     1604#: assets/js/app.js:1175
    9221605msgid "Scanning…"
    9231606msgstr ""
    9241607
    9251608#. translators: %s: relative time, e.g. "3 minutes ago"
    926 #: assets/js/app.js:1164
     1609#: assets/js/app.js:1180
    9271610#, js-format
    9281611msgid "Last scanned %s"
    9291612msgstr ""
    9301613
    931 #: assets/js/app.js:1176
     1614#: assets/js/app.js:1185
     1615msgid "Tools"
     1616msgstr ""
     1617
     1618#: assets/js/app.js:1193
    9321619msgid "Rescan"
    9331620msgstr ""
    9341621
    935 #: assets/js/app.js:1181
    936 #: assets/js/app.js:2726
     1622#: assets/js/app.js:1198
     1623#: assets/js/app.js:3402
    9371624msgid "Settings"
    9381625msgstr ""
    9391626
     1627#: assets/js/app.js:1226
     1628msgid "Loading storage and observation status…"
     1629msgstr ""
     1630
     1631#: assets/js/app.js:1228
     1632#: assets/js/app.js:1246
     1633msgid "Space saved report"
     1634msgstr ""
     1635
     1636#: assets/js/app.js:1234
     1637msgid "Operation history unavailable. Check database access."
     1638msgstr ""
     1639
     1640#: assets/js/app.js:1235
     1641msgid "Permanent removal"
     1642msgstr ""
     1643
     1644#: assets/js/app.js:1235
     1645msgid "Verified"
     1646msgstr ""
     1647
     1648#: assets/js/app.js:1235
     1649msgid "Failed"
     1650msgstr ""
     1651
     1652#: assets/js/app.js:1235
     1653msgid "Pending"
     1654msgstr ""
     1655
     1656#: assets/js/app.js:1235
     1657#: assets/js/app.js:1243
     1658#: assets/js/app.js:1248
     1659#: assets/js/app.js:1249
     1660#: assets/js/app.js:1256
     1661#: assets/js/app.js:1259
     1662msgid "Unknown"
     1663msgstr ""
     1664
     1665#: assets/js/app.js:1235
     1666msgid "Tracked"
     1667msgstr ""
     1668
     1669#: assets/js/app.js:1235
     1670msgid "Legacy"
     1671msgstr ""
     1672
     1673#: assets/js/app.js:1235
     1674msgid "Imported backup"
     1675msgstr ""
     1676
     1677#: assets/js/app.js:1236
     1678msgid "No tracked operations yet. Earlier activity is unknown."
     1679msgstr ""
     1680
     1681#: assets/js/app.js:1241
     1682msgid "Load operation history"
     1683msgstr ""
     1684
     1685#: assets/js/app.js:1245
     1686msgid "Estimated reclaimable"
     1687msgstr ""
     1688
     1689#: assets/js/app.js:1245
     1690msgid "Media Library quarantine storage"
     1691msgstr ""
     1692
     1693#: assets/js/app.js:1245
     1694msgid "Media Library verified removed"
     1695msgstr ""
     1696
     1697#: assets/js/app.js:1247
     1698msgid "Logical bytes only. Physical disk allocation: not measured. Estimated reclaimable bytes do not authorize deletion."
     1699msgstr ""
     1700
     1701#. translators: 1: tracking start UTC, 2: pending file operations, 3: unknown operations, 4: untracked active recovery records
     1702#: assets/js/app.js:1248
     1703#, js-format
     1704msgid "Tracking started: %1$s UTC. Pending: %2$s. Unknown operations: %3$s. Untracked active records: %4$s."
     1705msgstr ""
     1706
     1707#. translators: 1: inventory estimate observation UTC, 2: oldest storage observation UTC
     1708#: assets/js/app.js:1249
     1709#, js-format
     1710msgid "Inventory estimate observed: %1$s UTC. Oldest storage observation: %2$s UTC."
     1711msgstr ""
     1712
     1713#: assets/js/app.js:1251
     1714#: assets/js/app.js:1257
     1715msgid "Routing verification"
     1716msgstr ""
     1717
     1718#: assets/js/app.js:1254
     1719msgid "PHP routing checked"
     1720msgstr ""
     1721
     1722#: assets/js/app.js:1254
     1723msgid "Browser reports only"
     1724msgstr ""
     1725
     1726#: assets/js/app.js:1254
     1727msgid "Unavailable"
     1728msgstr ""
     1729
     1730#: assets/js/app.js:1258
     1731msgid "No known interruption in routing verification"
     1732msgstr ""
     1733
     1734#: assets/js/app.js:1258
     1735msgid "Routing verification incomplete, expired or paused"
     1736msgstr ""
     1737
     1738#. translators: 1: mode, 2: start date, 3: last success date, 4: expiry date, 5: interruptions
     1739#: assets/js/app.js:1259
     1740#, js-format
     1741msgid "Mode: %1$s. Window start: %2$s. Last successful check: %3$s. Expires: %4$s. Interruptions: %5$s."
     1742msgstr ""
     1743
     1744#. translators: 1: elapsed verification days, 2: required days
     1745#: assets/js/app.js:1260
     1746#, js-format
     1747msgid "Site routing period: %1$s of %2$s days. Each quarantined group also starts no earlier than its latest member."
     1748msgstr ""
     1749
     1750#. translators: %s: most recent interruption date
     1751#: assets/js/app.js:1261
     1752#, js-format
     1753msgid "Latest known interruption: %s. Any interruption restarts the period after a new successful routing check."
     1754msgstr ""
     1755
     1756#: assets/js/app.js:1267
     1757msgid "Routing status unavailable. Refresh Tools before relying on a previous check."
     1758msgstr ""
     1759
     1760#: assets/js/app.js:1271
     1761msgid "Reference job"
     1762msgstr ""
     1763
     1764#: assets/js/app.js:1279
     1765msgid "This audit selection is stale or unfinished. Run a fresh scan and uploads audit."
     1766msgstr ""
     1767
     1768#: assets/js/app.js:1280
     1769msgid "This saved row cannot be reviewed. Choose a supported image or PDF in a fresh audit."
     1770msgstr ""
     1771
     1772#: assets/js/app.js:1281
     1773msgid "The file changed, disappeared or exceeds the 16 MiB live-review limit. Start a fresh audit or review it manually."
     1774msgstr ""
     1775
     1776#: assets/js/app.js:1282
     1777msgid "Your server needs the PHP GD imaging extension for local visual search."
     1778msgstr ""
     1779
     1780#: assets/js/app.js:1283
     1781msgid "The media inventory could not be read. Check database access and retry this step."
     1782msgstr ""
     1783
     1784#: assets/js/app.js:1284
     1785msgid "Saved visual search data is unreadable. Start a new search; originals were not changed."
     1786msgstr ""
     1787
     1788#: assets/js/app.js:1285
     1789msgid "Visual results could not be read. Retry after checking database access."
     1790msgstr ""
     1791
     1792#: assets/js/app.js:1286
     1793msgid "Saved visual results are invalid. Start a new search; originals were not changed."
     1794msgstr ""
     1795
     1796#: assets/js/app.js:1287
     1797msgid "Uploads storage changed or this is an older audit. Start a new uploads audit; no files were changed."
     1798msgstr ""
     1799
     1800#: assets/js/app.js:1288
     1801msgid "Choose a valid category, alphanumeric extension and minimum byte count."
     1802msgstr ""
     1803
     1804#: assets/js/app.js:1289
     1805msgid "The audit is finishing a step. Retry cancellation shortly."
     1806msgstr ""
     1807
     1808#: assets/js/app.js:1290
     1809msgid "Cancellation could not be saved. Retry after checking database access."
     1810msgstr ""
     1811
     1812#: assets/js/app.js:1291
     1813msgid "Prepare duplicate quarantine and complete its new scan before continuing."
     1814msgstr ""
     1815
     1816#: assets/js/app.js:1292
     1817msgid "Wait for the current scan to finish, then prepare duplicate quarantine."
     1818msgstr ""
     1819
     1820#: assets/js/app.js:1293
     1821msgid "Usage evidence still references a duplicate. Review it and keep the file available."
     1822msgstr ""
     1823
     1824#: assets/js/app.js:1294
     1825msgid "Regenerate this reference job’s supported builder caches first. Unsupported builder caches keep quarantine blocked."
     1826msgstr ""
     1827
     1828#: assets/js/app.js:1295
     1829msgid "Generated cache files changed. Regenerate them, prepare duplicate quarantine again and complete a new scan."
     1830msgstr ""
     1831
     1832#: assets/js/app.js:1296
     1833msgid "Download and confirm a current duplicate backup before quarantine."
     1834msgstr ""
     1835
     1836#: assets/js/app.js:1297
     1837msgid "Image variants or edit backups could not be matched safely. Originals remain available for review."
     1838msgstr ""
     1839
     1840#: assets/js/app.js:1298
     1841msgid "Completion could not be saved. Refresh Quarantine and use reference rollback; recovery data was retained."
     1842msgstr ""
     1843
     1844#: assets/js/app.js:1299
     1845msgid "Recovery ownership changed. Review the quarantine records before restoring this reference job."
     1846msgstr ""
     1847
     1848#: assets/js/app.js:1300
     1849msgid "This duplicate group exceeds the current limit of 100 files or 64 MiB. Originals remain available."
     1850msgstr ""
     1851
     1852#: assets/js/app.js:1301
     1853msgid "Another reference recovery journal protects this media. Resolve that operation first."
     1854msgstr ""
     1855
     1856#: assets/js/app.js:1302
     1857msgid "A duplicate is kept, shared, already quarantined or unavailable. Review its recovery state first."
     1858msgstr ""
     1859
     1860#: assets/js/app.js:1303
     1861msgid "Storage or usage indexing needs review. Complete pending work before quarantine."
     1862msgstr ""
     1863
     1864#: assets/js/app.js:1304
     1865msgid "A source changed after this merge. Resolve its reference recovery job before quarantine."
     1866msgstr ""
     1867
     1868#: assets/js/app.js:1306
     1869msgid "The task could not finish. No media was deleted."
     1870msgstr ""
     1871
     1872#: assets/js/app.js:1320
     1873#: assets/js/app.js:1708
     1874msgid "Saved uploads audits"
     1875msgstr ""
     1876
     1877#: assets/js/app.js:1320
     1878msgid "Choose a saved uploads audit"
     1879msgstr ""
     1880
     1881#: assets/js/app.js:1327
     1882#: assets/js/app.js:1537
     1883msgid "Paused or running"
     1884msgstr ""
     1885
     1886#: assets/js/app.js:1327
     1887msgid "Walk finished"
     1888msgstr ""
     1889
     1890#: assets/js/app.js:1327
     1891#: assets/js/app.js:1537
     1892msgid "Cancelled"
     1893msgstr ""
     1894
     1895#: assets/js/app.js:1332
     1896msgid "Standalone recovery job"
     1897msgstr ""
     1898
     1899#: assets/js/app.js:1332
     1900msgid "Choose standalone recovery"
     1901msgstr ""
     1902
     1903#: assets/js/app.js:1335
     1904msgid "Backup preparation"
     1905msgstr ""
     1906
     1907#: assets/js/app.js:1335
     1908msgid "Backed up — originals still live"
     1909msgstr ""
     1910
     1911#: assets/js/app.js:1335
     1912msgid "Interrupted quarantine — review or restore"
     1913msgstr ""
     1914
     1915#: assets/js/app.js:1335
     1916#: assets/js/app.js:2114
     1917msgid "Quarantined"
     1918msgstr ""
     1919
     1920#: assets/js/app.js:1335
     1921msgid "Recovery needs retry"
     1922msgstr ""
     1923
     1924#: assets/js/app.js:1335
     1925msgid "Restored"
     1926msgstr ""
     1927
     1928#: assets/js/app.js:1335
     1929msgid "Authorized deletion needs retry"
     1930msgstr ""
     1931
     1932#: assets/js/app.js:1335
     1933msgid "Permanently deleted — ZIP required for recovery"
     1934msgstr ""
     1935
     1936#: assets/js/app.js:1335
     1937msgid "Discard needs retry"
     1938msgstr ""
     1939
     1940#: assets/js/app.js:1336
     1941msgid "Verified private recovery preview"
     1942msgstr ""
     1943
     1944#: assets/js/app.js:1346
     1945msgid "The review expired, content changed or a saved backup is missing. Download/confirm the backup and run fresh checks."
     1946msgstr ""
     1947
     1948#: assets/js/app.js:1347
     1949msgid "Enable request watching and automatic restore in Settings, then verify request routing before quarantine."
     1950msgstr ""
     1951
     1952#: assets/js/app.js:1348
     1953msgid "A current reference, possible owner, recorded request or storage restriction blocks quarantine. Keep this file."
     1954msgstr ""
     1955
     1956#: assets/js/app.js:1349
     1957msgid "Download and save this backup before confirming it."
     1958msgstr ""
     1959
     1960#: assets/js/app.js:1350
     1961msgid "A different file occupies the original path, or recovery bytes are missing. Nothing was overwritten. Keep both files and resolve the conflict before retrying."
     1962msgstr ""
     1963
     1964#: assets/js/app.js:1351
     1965msgid "The original changed during capture. The replacement and backup were retained. Restore or ask your administrator to resolve the conflict."
     1966msgstr ""
     1967
     1968#: assets/js/app.js:1352
     1969msgid "Verify this backup and explicitly trust its origin before restoring. Cross-site backups also need adoption confirmation."
     1970msgstr ""
     1971
     1972#: assets/js/app.js:1353
     1973msgid "The file or its attributes changed. Restore this preparation and create a fresh audit/backup."
     1974msgstr ""
     1975
     1976#: assets/js/app.js:1355
     1977msgid "Recovery records are retained. Refresh the list; restore or retry after resolving the problem."
     1978msgstr ""
     1979
     1980#: assets/js/app.js:1358
     1981msgid "Wait for the current standalone recovery operation."
     1982msgstr ""
     1983
     1984#: assets/js/app.js:1371
     1985msgid "Resume backup preparation"
     1986msgstr ""
     1987
     1988#: assets/js/app.js:1377
     1989msgid "Download standalone recovery ZIP"
     1990msgstr ""
     1991
     1992#: assets/js/app.js:1381
     1993msgid "I trust the source of this ZIP and reviewed every destination below."
     1994msgstr ""
     1995
     1996#: assets/js/app.js:1382
     1997msgid "I explicitly approve importing these paths from a different site."
     1998msgstr ""
     1999
     2000#: assets/js/app.js:1383
     2001msgid "Trust this backup"
     2002msgstr ""
     2003
     2004#: assets/js/app.js:1384
     2005msgid "Confirm backup trust and any cross-site adoption first."
     2006msgstr ""
     2007
     2008#: assets/js/app.js:1387
     2009msgid "Discard untrusted upload"
     2010msgstr ""
     2011
     2012#: assets/js/app.js:1388
     2013msgid "Discard this recovery upload?"
     2014msgstr ""
     2015
     2016#: assets/js/app.js:1388
     2017msgid "Only this untrusted upload and its private verified copies will be removed. Public files are untouched. Keep your original ZIP."
     2018msgstr ""
     2019
     2020#: assets/js/app.js:1388
     2021msgid "Discard upload"
     2022msgstr ""
     2023
     2024#: assets/js/app.js:1389
     2025msgid "Untrusted upload discarded. Public files were not changed."
     2026msgstr ""
     2027
     2028#: assets/js/app.js:1394
     2029msgid "I downloaded and saved this recovery ZIP outside this server."
     2030msgstr ""
     2031
     2032#: assets/js/app.js:1395
     2033msgid "Confirm saved standalone backup"
     2034msgstr ""
     2035
     2036#: assets/js/app.js:1396
     2037msgid "Save your backup and confirm it first."
     2038msgstr ""
     2039
     2040#: assets/js/app.js:1399
     2041msgid "Resume standalone checks"
     2042msgstr ""
     2043
     2044#: assets/js/app.js:1399
     2045msgid "Check before standalone quarantine"
     2046msgstr ""
     2047
     2048#. translators: %s: checked stored rows
     2049#: assets/js/app.js:1403
     2050#: assets/js/app.js:1426
     2051#, js-format
     2052msgid "%s stored rows checked. Closing pauses; resume this saved recovery job later."
     2053msgstr ""
     2054
     2055#: assets/js/app.js:1409
     2056msgid "I reviewed the public pages, relevant theme/plugin behavior and caches. These checks cannot prove the file is unused."
     2057msgstr ""
     2058
     2059#: assets/js/app.js:1410
     2060msgid "Quarantine this standalone file"
     2061msgstr ""
     2062
     2063#: assets/js/app.js:1411
     2064msgid "Review the public pages and caches first."
     2065msgstr ""
     2066
     2067#: assets/js/app.js:1412
     2068msgid "Quarantine this standalone file?"
     2069msgstr ""
     2070
     2071#: assets/js/app.js:1412
     2072msgid "Its public URL will become unavailable until restored. A saved ZIP, fresh checks, request watching and verified routing are required. Static/CDN/cache paths may bypass observation. No permanent deletion occurs."
     2073msgstr ""
     2074
     2075#: assets/js/app.js:1412
     2076msgid "Move file to quarantine"
     2077msgstr ""
     2078
     2079#: assets/js/app.js:1418
     2080msgid "Restore standalone files"
     2081msgstr ""
     2082
     2083#: assets/js/app.js:1421
     2084msgid "The routing-check window is complete. This does not prove continuous request capture or non-usage."
     2085msgstr ""
     2086
     2087#: assets/js/app.js:1421
     2088msgid "Permanent deletion is blocked until the routing-check window is complete, with at least 14 days and no recorded requests."
     2089msgstr ""
     2090
     2091#: assets/js/app.js:1422
     2092msgid "Run fresh checks before permanent deletion"
     2093msgstr ""
     2094
     2095#: assets/js/app.js:1430
     2096msgid "Permanently delete standalone quarantine copies"
     2097msgstr ""
     2098
     2099#: assets/js/app.js:1431
     2100msgid "Permanently delete this standalone file?"
     2101msgstr ""
     2102
     2103#: assets/js/app.js:1431
     2104msgid "Both server recovery copies will be deleted. Recovery will require your downloaded ZIP. Review public pages, dynamic uses and caches first; routing checks cannot prove non-usage. Any replacement at the original public path is kept."
     2105msgstr ""
     2106
     2107#: assets/js/app.js:1431
     2108msgid "Permanently delete copies"
     2109msgstr ""
     2110
     2111#: assets/js/app.js:1436
     2112msgid "Content changed during review. Restart checks."
     2113msgstr ""
     2114
     2115#: assets/js/app.js:1436
     2116msgid "A possible stored reference or owner blocks quarantine. Keep the file."
     2117msgstr ""
     2118
     2119#: assets/js/app.js:1436
     2120msgid "Some content could not be fully checked. Resolve the source limit before quarantine."
     2121msgstr ""
     2122
     2123#: assets/js/app.js:1437
     2124msgid "Permissions:"
     2125msgstr ""
     2126
     2127#: assets/js/app.js:1438
     2128msgid "Stored-source checks are current for five minutes. They establish eligibility for manual quarantine, not non-usage or purge permission."
     2129msgstr ""
     2130
     2131#: assets/js/app.js:1438
     2132msgid "Stored-source checks are pending."
     2133msgstr ""
     2134
     2135#: assets/js/app.js:1439
     2136msgid "A request was recorded. This path is protected from re-quarantine."
     2137msgstr ""
     2138
     2139#: assets/js/app.js:1440
     2140msgid "Deletion completed. Removed bytes are unknown because a verified receipt was interrupted."
     2141msgstr ""
     2142
     2143#. translators: %s: logical original bytes removed
     2144#: assets/js/app.js:1440
     2145#, js-format
     2146msgid "Verified removal: %s logical original bytes, counted once. Recovery ZIPs and physical allocation are excluded."
     2147msgstr ""
     2148
     2149#: assets/js/app.js:1443
     2150msgid "Standalone recovery ZIP"
     2151msgstr ""
     2152
     2153#: assets/js/app.js:1444
     2154msgid "Standalone file recovery"
     2155msgstr ""
     2156
     2157#: assets/js/app.js:1445
     2158msgid "Standalone files are separate from Media Library counts. Prepare a backup from an uploads-audit row, then select its recovery job here. Archives preserve ordinary file permissions and modification times; ownership, ACLs and directory attributes are not reconstructed. Permanent deletion needs a saved backup, fresh review, a completed routing-check window of at least 14 days and a separate confirmation. Quarantine retains recovery copies and does not free disk space."
     2159msgstr ""
     2160
     2161#: assets/js/app.js:1446
     2162msgid "Open standalone recovery"
     2163msgstr ""
     2164
     2165#: assets/js/app.js:1448
     2166msgid "Choose a standalone recovery ZIP first."
     2167msgstr ""
     2168
     2169#: assets/js/app.js:1453
     2170msgid "Upload standalone recovery ZIP"
     2171msgstr ""
     2172
     2173#: assets/js/app.js:1455
     2174msgid "Load older standalone recovery records"
     2175msgstr ""
     2176
     2177#: assets/js/app.js:1461
     2178msgid "Some recovery records could not be read. Keep all backups and ask your administrator to review storage; uninstall remains blocked for unresolved data."
     2179msgstr ""
     2180
     2181#: assets/js/app.js:1473
     2182msgid "Wait for the current live check to finish."
     2183msgstr ""
     2184
     2185#: assets/js/app.js:1479
     2186msgid "Possible current metadata owner found. Keep this file."
     2187msgstr ""
     2188
     2189#: assets/js/app.js:1480
     2190msgid "Possible stored reference found. Keep this file."
     2191msgstr ""
     2192
     2193#: assets/js/app.js:1481
     2194msgid "The live check is incomplete. No cleanup approval was issued."
     2195msgstr ""
     2196
     2197#: assets/js/app.js:1482
     2198msgid "No match in the checked stored sources. This does not establish that the file is unused."
     2199msgstr ""
     2200
     2201#. translators: %s: inspected database rows
     2202#: assets/js/app.js:1486
     2203#, js-format
     2204msgid "%s stored rows checked. Checks are bounded and are not an atomic snapshot. Theme/PHP code, custom tables, network options, caches and external usage may remain unchecked. No files were moved."
     2205msgstr ""
     2206
     2207#: assets/js/app.js:1488
     2208msgid "Additional matches were found; only the first 20 are shown."
     2209msgstr ""
     2210
     2211#: assets/js/app.js:1489
     2212msgid "Coverage limits:"
     2213msgstr ""
     2214
     2215#: assets/js/app.js:1490
     2216msgid "Storage or indexing restrictions also block cleanup."
     2217msgstr ""
     2218
     2219#: assets/js/app.js:1495
     2220msgid "Check current ownership and references"
     2221msgstr ""
     2222
     2223#: assets/js/app.js:1496
     2224msgid "Prepare standalone recovery backup"
     2225msgstr ""
     2226
     2227#: assets/js/app.js:1498
     2228msgid "Review required"
     2229msgstr ""
     2230
     2231#: assets/js/app.js:1499
     2232msgid "An unregistered size is still owned. Do not delete it based on its size name."
     2233msgstr ""
     2234
     2235#: assets/js/app.js:1504
     2236msgid "All categories"
     2237msgstr ""
     2238
     2239#: assets/js/app.js:1504
     2240msgid "Indexed original"
     2241msgstr ""
     2242
     2243#: assets/js/app.js:1504
     2244msgid "Indexed derivative"
     2245msgstr ""
     2246
     2247#: assets/js/app.js:1504
     2248msgid "Indexed shared path"
     2249msgstr ""
     2250
     2251#: assets/js/app.js:1504
     2252msgid "Possible old derivative — review"
     2253msgstr ""
     2254
     2255#: assets/js/app.js:1504
     2256msgid "No indexed owner — review"
     2257msgstr ""
     2258
     2259#: assets/js/app.js:1504
     2260msgid "Ownership unavailable"
     2261msgstr ""
     2262
     2263#: assets/js/app.js:1505
     2264msgid "Ownership category"
     2265msgstr ""
     2266
     2267#: assets/js/app.js:1506
     2268msgid "Extension, e.g. jpg"
     2269msgstr ""
     2270
     2271#: assets/js/app.js:1506
     2272msgid "File extension"
     2273msgstr ""
     2274
     2275#: assets/js/app.js:1507
     2276msgid "Minimum file bytes"
     2277msgstr ""
     2278
     2279#: assets/js/app.js:1509
     2280msgid "Download filtered audit CSV"
     2281msgstr ""
     2282
     2283#: assets/js/app.js:1519
     2284msgid "Ownership comes from the saved index generation, not a live usage check. No indexed owner does not mean unused. Each page examines at most 100 saved rows; filtered pages can be empty."
     2285msgstr ""
     2286
     2287#: assets/js/app.js:1519
     2288msgid "The index changed or was unavailable. These ownership hints are stale; start a new scan and audit before reviewing them."
     2289msgstr ""
     2290
     2291#: assets/js/app.js:1521
     2292msgid "No matching files in this page. Continue if more rows are available."
     2293msgstr ""
     2294
     2295#: assets/js/app.js:1525
     2296msgid "Apply audit filters"
     2297msgstr ""
     2298
     2299#: assets/js/app.js:1526
     2300msgid "Next audit page"
     2301msgstr ""
     2302
     2303#: assets/js/app.js:1527
     2304msgid "Uploads audit — review only"
     2305msgstr ""
     2306
     2307#: assets/js/app.js:1527
     2308msgid "This best-effort walk excludes known caches, backups, protected plugin downloads and symlinks. Files may change during the walk. Audit categories never authorize removal. Supported files can begin a separate backup and fresh-review workflow."
     2309msgstr ""
     2310
     2311#: assets/js/app.js:1527
     2312msgid "Minimum bytes"
     2313msgstr ""
     2314
     2315#: assets/js/app.js:1530
     2316#: assets/js/app.js:1707
     2317msgid "Saved visual searches"
     2318msgstr ""
     2319
     2320#: assets/js/app.js:1530
     2321msgid "Choose a visual search"
     2322msgstr ""
     2323
     2324#: assets/js/app.js:1537
     2325msgid "Finished"
     2326msgstr ""
     2327
     2328#: assets/js/app.js:1542
     2329msgid "Visual results view"
     2330msgstr ""
     2331
     2332#: assets/js/app.js:1542
     2333msgid "Review suggestions"
     2334msgstr ""
     2335
     2336#: assets/js/app.js:1542
     2337msgid "Skipped images"
     2338msgstr ""
     2339
     2340#. translators: 1: checked images, 2: skipped images, 3: suggestions
     2341#: assets/js/app.js:1552
     2342#, js-format
     2343msgid "%1$s images checked; %2$s skipped; %3$s suggestions saved."
     2344msgstr ""
     2345
     2346#: assets/js/app.js:1552
     2347msgid "Search finished within its criteria. Suggestions still need human review."
     2348msgstr ""
     2349
     2350#: assets/js/app.js:1552
     2351msgid "Coverage is partial: the search may be paused, cancelled, skipped images or reached a limit. Matching images may be missing."
     2352msgstr ""
     2353
     2354#: assets/js/app.js:1555
     2355msgid "This image could not be compared within the local permissions, format or resource limits."
     2356msgstr ""
     2357
     2358#. translators: %s: difference score out of 64
     2359#: assets/js/app.js:1557
     2360#, js-format
     2361msgid "Visual difference score: %s / 64. Lower scores suggest closer appearance, not identical files."
     2362msgstr ""
     2363
     2364#: assets/js/app.js:1559
     2365msgid "No results in this page. This does not establish that any media is unused."
     2366msgstr ""
     2367
     2368#: assets/js/app.js:1564
     2369msgid "Next visual results page"
     2370msgstr ""
     2371
     2372#: assets/js/app.js:1565
     2373msgid "Visually similar images — review only"
     2374msgstr ""
     2375
     2376#: assets/js/app.js:1565
     2377msgid "These are captured visual suggestions, not exact duplicates. Re-encoded or resized images can differ in quality and metadata. Media may change during or after the search. Review originals before acting; visual suggestions never authorize merging or deletion."
     2378msgstr ""
     2379
     2380#: assets/js/app.js:1570
     2381msgid "An audit is already running here. Wait, cancel it or close Tools to pause it."
     2382msgstr ""
     2383
     2384#. translators: 1: images checked, 2: signatures compared
     2385#: assets/js/app.js:1578
     2386#, js-format
     2387msgid "Local visual search: %1$s images checked; %2$s signatures compared. Closing pauses this task."
     2388msgstr ""
     2389
     2390#. translators: %s: processed file count
     2391#: assets/js/app.js:1578
     2392#, js-format
     2393msgid "Read-only discovery: %s files checked. Closing pauses this task."
     2394msgstr ""
     2395
     2396#: assets/js/app.js:1585
     2397msgid "Visual search saved. Review suggestions and coverage below."
     2398msgstr ""
     2399
     2400#. translators: 1: files, 2: skipped entries
     2401#: assets/js/app.js:1586
     2402#, js-format
     2403msgid "Audit saved: %1$s files; %2$s skipped entries. Results expire after 24 hours."
     2404msgstr ""
     2405
     2406#. translators: 1: processed files, 2: skipped entries
     2407#: assets/js/app.js:1589
     2408#, js-format
     2409msgid "Checked %1$s files; %2$s entries skipped. Results are for review only. Showing the first 100 rows."
     2410msgstr ""
     2411
     2412#: assets/js/app.js:1590
     2413msgid "Ownership review required"
     2414msgstr ""
     2415
     2416#. translators: %s: number of duplicate groups
     2417#: assets/js/app.js:1591
     2418#, js-format
     2419msgid "Exact duplicate groups found: %s. Shared attachment paths count as one file."
     2420msgstr ""
     2421
     2422#: assets/js/app.js:1594
     2423msgid "Find exact duplicates"
     2424msgstr ""
     2425
     2426#: assets/js/app.js:1595
     2427msgid "Find visually similar images"
     2428msgstr ""
     2429
     2430#: assets/js/app.js:1596
     2431msgid "Compare selected images"
     2432msgstr ""
     2433
     2434#: assets/js/app.js:1598
     2435msgid "Select up to ten images before opening Tools."
     2436msgstr ""
     2437
     2438#: assets/js/app.js:1600
     2439msgid "Visual signatures are suggestions only. They never authorize a merge."
     2440msgstr ""
     2441
     2442#: assets/js/app.js:1603
     2443msgid "Preview selected reference merge"
     2444msgstr ""
     2445
     2446#: assets/js/app.js:1605
     2447msgid "Select a canonical attachment and up to ten exact duplicates first."
     2448msgstr ""
     2449
     2450#: assets/js/app.js:1607
     2451msgid "Choose the attachment to keep"
     2452msgstr ""
     2453
     2454#: assets/js/app.js:1607
     2455msgid "This rewrites supported references only. Original attachments and files are retained. Unsupported sources block the operation; generated builder caches and retirement require separate review."
     2456msgstr ""
     2457
     2458#: assets/js/app.js:1607
     2459msgid "Build read-only preview"
     2460msgstr ""
     2461
     2462#. translators: 1: supported source writes, 2: unsupported references
     2463#: assets/js/app.js:1613
     2464#, js-format
     2465msgid "Preview: %1$s supported source writes, %2$s unsupported references. No files will be removed."
     2466msgstr ""
     2467
     2468#: assets/js/app.js:1614
     2469msgid "Before"
     2470msgstr ""
     2471
     2472#: assets/js/app.js:1614
     2473msgid "After"
     2474msgstr ""
     2475
     2476#: assets/js/app.js:1615
     2477msgid "The operation is blocked. Unsupported or missing writers must be resolved before any changes."
     2478msgstr ""
     2479
     2480#: assets/js/app.js:1616
     2481msgid "Apply these reference changes?"
     2482msgstr ""
     2483
     2484#: assets/js/app.js:1616
     2485msgid "A recovery journal retains the original source values. Later editor changes are preserved as conflicts during rollback. The original files stay in place."
     2486msgstr ""
     2487
     2488#: assets/js/app.js:1616
     2489msgid "I reviewed the canonical attachment and these source changes."
     2490msgstr ""
     2491
     2492#: assets/js/app.js:1616
     2493msgid "Apply reference changes"
     2494msgstr ""
     2495
     2496#. translators: 1: completed source writes, 2: total source writes
     2497#: assets/js/app.js:1620
     2498#, js-format
     2499msgid "Reference changes: %1$s of %2$s sources."
     2500msgstr ""
     2501
     2502#: assets/js/app.js:1621
     2503msgid "Reference job saved. Original files are retained. Roll back from Tools if needed; complete a fresh scan and cache review before considering retirement."
     2504msgstr ""
     2505
     2506#: assets/js/app.js:1623
     2507msgid "Roll back last reference merge"
     2508msgstr ""
     2509
     2510#: assets/js/app.js:1625
     2511msgid "There is no reference job to roll back."
     2512msgstr ""
     2513
     2514#: assets/js/app.js:1627
     2515msgid "Roll back reference changes?"
     2516msgstr ""
     2517
     2518#: assets/js/app.js:1627
     2519msgid "Only sources that still match the saved written values can be restored. Later editor changes will be preserved and reported as conflicts."
     2520msgstr ""
     2521
     2522#: assets/js/app.js:1627
     2523msgid "Roll back"
     2524msgstr ""
     2525
     2526#: assets/js/app.js:1630
     2527msgid "Reference rollback saved. Quarantined duplicates were restored first; later editor changes remain protected."
     2528msgstr ""
     2529
     2530#: assets/js/app.js:1635
     2531msgid "Regenerate merge caches"
     2532msgstr ""
     2533
     2534#: assets/js/app.js:1638
     2535#: assets/js/app.js:1651
     2536msgid "Select a completed reference job first."
     2537msgstr ""
     2538
     2539#. translators: 1: attempted posts, 2: affected posts
     2540#: assets/js/app.js:1644
     2541#, js-format
     2542msgid "Cache generation: %1$s of %2$s posts."
     2543msgstr ""
     2544
     2545#: assets/js/app.js:1646
     2546msgid "This reference job has no builder caches to regenerate. Original files remain protected."
     2547msgstr ""
     2548
     2549#: assets/js/app.js:1646
     2550msgid "Supported cache assets regenerated. Review the public pages and run a fresh scan. Original files remain protected. Duplicate quarantine requires a separate saved-backup confirmation."
     2551msgstr ""
     2552
     2553#: assets/js/app.js:1646
     2554msgid "Some caches need manual review. You can retry after resolving the builder or source issue. Reference changes and recovery journals are retained."
     2555msgstr ""
     2556
     2557#: assets/js/app.js:1654
     2558msgid "Prepare duplicate quarantine and rescan"
     2559msgstr ""
     2560
     2561#: assets/js/app.js:1657
     2562msgid "Preparing a fresh usage scan. No files are being moved."
     2563msgstr ""
     2564
     2565#. translators: %s: scan percentage
     2566#: assets/js/app.js:1663
     2567#, js-format
     2568msgid "Checking duplicate usage: %s%%."
     2569msgstr ""
     2570
     2571#: assets/js/app.js:1667
     2572msgid "Complete a fresh scan before backing up duplicates."
     2573msgstr ""
     2574
     2575#: assets/js/app.js:1669
     2576msgid "Fresh scan complete. Next use “Back up merged duplicates”, download the ZIP and review the published pages and relevant caches before confirming quarantine."
     2577msgstr ""
     2578
     2579#: assets/js/app.js:1671
     2580msgid "Back up merged duplicates"
     2581msgstr ""
     2582
     2583#. translators: 1: completed files, 2: total files
     2584#: assets/js/app.js:1676
     2585#, js-format
     2586msgid "Building duplicate backup: %1$s of %2$s files."
     2587msgstr ""
     2588
     2589#: assets/js/app.js:1686
     2590msgid "Quarantine merged duplicates?"
     2591msgstr ""
     2592
     2593#: assets/js/app.js:1686
     2594msgid "Only this job’s duplicate files will move to protected quarantine. The canonical media stays live. Rollback restores these files before restoring references. Permanent deletion remains blocked by the recovery journal."
     2595msgstr ""
     2596
     2597#: assets/js/app.js:1686
     2598msgid "Move duplicates to quarantine"
     2599msgstr ""
     2600
     2601#: assets/js/app.js:1689
     2602msgid "Duplicates moved to quarantine. Use reference rollback to restore files before restoring their references. No media was permanently deleted."
     2603msgstr ""
     2604
     2605#: assets/js/app.js:1689
     2606msgid "Quarantine needs recovery review. Files were restored where possible and the journal was retained. Use reference rollback to resolve the operation."
     2607msgstr ""
     2608
     2609#: assets/js/app.js:1695
     2610msgid "Confirm backup and quarantine duplicates"
     2611msgstr ""
     2612
     2613#: assets/js/app.js:1698
     2614msgid "Backup verified. Download and save it before confirming; an archive left on this server expires after 24 hours."
     2615msgstr ""
     2616
     2617#: assets/js/app.js:1699
     2618msgid "Download duplicate recovery ZIP"
     2619msgstr ""
     2620
     2621#: assets/js/app.js:1699
     2622#: assets/js/app.js:1739
     2623msgid "I downloaded and saved this recovery backup."
     2624msgstr ""
     2625
     2626#: assets/js/app.js:1699
     2627msgid "I reviewed the published pages and cleared relevant page and CDN caches."
     2628msgstr ""
     2629
     2630#: assets/js/app.js:1702
     2631msgid "Start a new uploads audit"
     2632msgstr ""
     2633
     2634#: assets/js/app.js:1703
     2635msgid "Resume or browse audit"
     2636msgstr ""
     2637
     2638#: assets/js/app.js:1704
     2639msgid "Audit stopped. Saved results remain available until expiry. No media files changed."
     2640msgstr ""
     2641
     2642#: assets/js/app.js:1704
     2643msgid "Cancel selected audit"
     2644msgstr ""
     2645
     2646#: assets/js/app.js:1705
     2647msgid "Resume or browse visual search"
     2648msgstr ""
     2649
     2650#: assets/js/app.js:1706
     2651msgid "Visual search stopped. Saved suggestions remain available until expiry. No media was changed."
     2652msgstr ""
     2653
     2654#: assets/js/app.js:1706
     2655msgid "Cancel selected visual search"
     2656msgstr ""
     2657
     2658#: assets/js/app.js:1709
     2659msgid "Only recent jobs are listed. Saved task tokens still work in WP-CLI until expiry."
     2660msgstr ""
     2661
     2662#: assets/js/app.js:1710
     2663msgid "Test request routing"
     2664msgstr ""
     2665
     2666#: assets/js/app.js:1711
     2667msgid "Testing one missing-upload route…"
     2668msgstr ""
     2669
     2670#: assets/js/app.js:1714
     2671msgid "Routing check succeeded. The verification period is separate from quarantine age."
     2672msgstr ""
     2673
     2674#: assets/js/app.js:1714
     2675msgid "Routing was not verified. Review the status and hosting examples."
     2676msgstr ""
     2677
     2678#: assets/js/app.js:1716
     2679msgid "Export selected quarantine"
     2680msgstr ""
     2681
     2682#: assets/js/app.js:1718
     2683msgid "Select between 1 and 100 quarantined media items, including their shared copies, before opening Tools."
     2684msgstr ""
     2685
     2686#. translators: 1: export phase, 2: completed files, 3: total files
     2687#: assets/js/app.js:1723
     2688#, js-format
     2689msgid "Recovery export: %1$s, %2$s of %3$s files. Closing pauses this task."
     2690msgstr ""
     2691
     2692#: assets/js/app.js:1728
     2693msgid "Archive checksums verified. Download it and confirm you have saved the backup. The private download expires in 24 hours."
     2694msgstr ""
     2695
     2696#: assets/js/app.js:1729
     2697msgid "Download recovery ZIP"
     2698msgstr ""
     2699
     2700#: assets/js/app.js:1734
     2701msgid "Saved backup confirmed. The minimum waiting period and all usage checks still apply."
     2702msgstr ""
     2703
     2704#: assets/js/app.js:1737
     2705msgid "Confirm saved backup"
     2706msgstr ""
     2707
     2708#: assets/js/app.js:1741
     2709msgid "Saved backup recovery"
     2710msgstr ""
     2711
     2712#: assets/js/app.js:1742
     2713msgid "Recovery ZIP"
     2714msgstr ""
     2715
     2716#: assets/js/app.js:1746
     2717msgid "Verifying files"
     2718msgstr ""
     2719
     2720#: assets/js/app.js:1747
     2721msgid "Recovering attachment records"
     2722msgstr ""
     2723
     2724#: assets/js/app.js:1748
     2725msgid "Saving recovery records"
     2726msgstr ""
     2727
     2728#: assets/js/app.js:1749
     2729msgid "Preparing verified files"
     2730msgstr ""
     2731
     2732#: assets/js/app.js:1750
     2733msgid "Restoring media"
     2734msgstr ""
     2735
     2736#: assets/js/app.js:1756
     2737msgid "Verification paused"
     2738msgstr ""
     2739
     2740#: assets/js/app.js:1756
     2741msgid "Ready to preview"
     2742msgstr ""
     2743
     2744#: assets/js/app.js:1756
     2745msgid "Recovery paused"
     2746msgstr ""
     2747
     2748#: assets/js/app.js:1756
     2749msgid "Recovery complete"
     2750msgstr ""
     2751
     2752#: assets/js/app.js:1756
     2753msgid "Manual review needed"
     2754msgstr ""
     2755
     2756#: assets/js/app.js:1756
     2757msgid "Unsupported backup"
     2758msgstr ""
     2759
     2760#: assets/js/app.js:1756
     2761msgid "Upload incomplete"
     2762msgstr ""
     2763
     2764#. translators: 1: saved recovery number, 2: status, 3: number of media items
     2765#: assets/js/app.js:1757
     2766#, js-format
     2767msgid "Backup %1$s · %2$s · %3$s items"
     2768msgstr ""
     2769
     2770#: assets/js/app.js:1757
     2771msgid "Review needed"
     2772msgstr ""
     2773
     2774#. translators: 1: recovery phase, 2: completed entries, 3: total entries
     2775#: assets/js/app.js:1763
     2776#, js-format
     2777msgid "%1$s: %2$s of %3$s. Closing pauses this task; resume here after reloading."
     2778msgstr ""
     2779
     2780#: assets/js/app.js:1769
     2781msgid "Recovery complete. Original IDs, file bytes and supported core fields were verified. Existing associations and alt text were preserved; recreated records use verified original contexts. Plugin-specific and taxonomy metadata are not restored. Run a fresh scan."
     2782msgstr ""
     2783
     2784#: assets/js/app.js:1773
     2785msgid "Recovery preparation needs manual review after an interruption. Your backup and existing media are preserved. Ask your site administrator to review this recovery before continuing."
     2786msgstr ""
     2787
     2788#. translators: %s: unexpected attachment ID
     2789#: assets/js/app.js:1774
     2790#, js-format
     2791msgid "An attachment ID was taken during recovery. Review attachment #%s with your site administrator. Files and recovery records were retained."
     2792msgstr ""
     2793
     2794#: assets/js/app.js:1777
     2795msgid "This upload cannot be restored. Upload a complete supported backup."
     2796msgstr ""
     2797
     2798#: assets/js/app.js:1779
     2799msgid "Will restore"
     2800msgstr ""
     2801
     2802#: assets/js/app.js:1779
     2803msgid "Identical file already present"
     2804msgstr ""
     2805
     2806#: assets/js/app.js:1779
     2807msgid "Conflict: current file will be kept"
     2808msgstr ""
     2809
     2810#: assets/js/app.js:1780
     2811msgid "Recreate the original attachment ID"
     2812msgstr ""
     2813
     2814#: assets/js/app.js:1780
     2815msgid "Repair matching existing attachment"
     2816msgstr ""
     2817
     2818#. translators: 1: image width, 2: image height, 3: number of image sizes
     2819#: assets/js/app.js:1780
     2820#, js-format
     2821msgid "Metadata: %1$s × %2$s; %3$s sizes."
     2822msgstr ""
     2823
     2824#. translators: %s: number of saved edit backups
     2825#: assets/js/app.js:1780
     2826#, js-format
     2827msgid "Saved edit backups: %s."
     2828msgstr ""
     2829
     2830#. translators: %s: shared file owner attachment ID
     2831#: assets/js/app.js:1780
     2832#, js-format
     2833msgid "Shared files with attachment #%s."
     2834msgstr ""
     2835
     2836#: assets/js/app.js:1782
     2837msgid "Read-only recovery preview"
     2838msgstr ""
     2839
     2840#: assets/js/app.js:1782
     2841msgid "Recovery covers file bytes, core file metadata and supported attachment fields. New backups also preserve original parent, author and alt text for recreated records. Existing records keep their current associations and alt text. Plugin-specific metadata and taxonomies are unsupported. This is not a full site backup."
     2842msgstr ""
     2843
     2844#: assets/js/app.js:1782
     2845msgid "Files and current destinations"
     2846msgstr ""
     2847
     2848#: assets/js/app.js:1783
     2849msgid "Resolve these conflicts, then refresh the preview. Current files and records are preserved."
     2850msgstr ""
     2851
     2852#: assets/js/app.js:1783
     2853msgid "Preview verified. Nothing has been restored yet. Review the files and attachment IDs before confirming."
     2854msgstr ""
     2855
     2856#: assets/js/app.js:1789
     2857msgid "Restore this trusted backup?"
     2858msgstr ""
     2859
     2860#: assets/js/app.js:1789
     2861msgid "Only restore a backup you created and trust. Checksums verify file consistency, not its creator. Existing files are never replaced. Recovery keeps the original attachment IDs and does not delete media."
     2862msgstr ""
     2863
     2864#: assets/js/app.js:1789
     2865msgid "This is a reinstall of the same site. Adopt the backup identity for this matching site address."
     2866msgstr ""
     2867
     2868#: assets/js/app.js:1789
     2869msgid "Files are prepared in protected Quarantine storage. Nginx needs the documented access rules from your host; the ZIP itself remains outside public web storage."
     2870msgstr ""
     2871
     2872#: assets/js/app.js:1789
     2873msgid "I reviewed this preview and confirm this is my trusted recovery backup."
     2874msgstr ""
     2875
     2876#: assets/js/app.js:1789
     2877msgid "Confirm and restore"
     2878msgstr ""
     2879
     2880#: assets/js/app.js:1791
     2881msgid "Confirm same-site backup identity adoption before restoring."
     2882msgstr ""
     2883
     2884#: assets/js/app.js:1797
     2885msgid "Review and confirm recovery"
     2886msgstr ""
     2887
     2888#: assets/js/app.js:1802
     2889msgid "Recovery paused. Resolve the problem and resume this saved backup."
     2890msgstr ""
     2891
     2892#: assets/js/app.js:1805
     2893msgid "Upload and verify ZIP"
     2894msgstr ""
     2895
     2896#: assets/js/app.js:1806
     2897msgid "Choose one recovery ZIP first."
     2898msgstr ""
     2899
     2900#: assets/js/app.js:1808
     2901msgid "Uploading to private recovery storage…"
     2902msgstr ""
     2903
     2904#: assets/js/app.js:1813
     2905msgid "Resume or refresh preview"
     2906msgstr ""
     2907
     2908#: assets/js/app.js:1815
     2909msgid "Upload a backup or choose a saved recovery first."
     2910msgstr ""
     2911
     2912#: assets/js/app.js:1818
     2913msgid "Recover from a backup ZIP"
     2914msgstr ""
     2915
     2916#: assets/js/app.js:1818
     2917msgid "Upload → verify → preview → confirm → restore. Idle previews expire after 24 hours. Confirmed recovery remains available after closing or reloading."
     2918msgstr ""
     2919
     2920#: assets/js/app.js:1821
     2921msgid "Media tools"
     2922msgstr ""
     2923
     2924#: assets/js/app.js:1821
     2925msgid "Discovery results never delete or merge files. Request routing verification covers one path; CDN and browser caches remain outside observation."
     2926msgstr ""
     2927
     2928#: assets/js/app.js:1821
     2929#: assets/js/app.js:2827
     2930msgid "Close"
     2931msgstr ""
     2932
     2933#: assets/js/app.js:1824
     2934msgid "Local storage available. Advanced mutation features remain subject to recovery checks."
     2935msgstr ""
     2936
     2937#: assets/js/app.js:1827
     2938msgid "Download operation CSV"
     2939msgstr ""
     2940
     2941#: assets/js/app.js:1830
     2942msgid "Server setup examples (for your hosting administrator)"
     2943msgstr ""
     2944
     2945#: assets/js/app.js:1833
     2946msgid "Download inventory CSV"
     2947msgstr ""
     2948
     2949#: assets/js/app.js:1873
     2950msgid "Audit-only mode: cleanup is disabled"
     2951msgstr ""
     2952
     2953#: assets/js/app.js:1874
     2954msgid "Show affected sources"
     2955msgstr ""
     2956
     2957#: assets/js/app.js:1875
     2958msgid "Post / page"
     2959msgstr ""
     2960
     2961#: assets/js/app.js:1875
     2962msgid "Term"
     2963msgstr ""
     2964
     2965#: assets/js/app.js:1875
     2966msgid "User"
     2967msgstr ""
     2968
     2969#: assets/js/app.js:1875
     2970msgid "Setting"
     2971msgstr ""
     2972
    9402973#. translators: %s: number of files
    941 #: assets/js/app.js:1233
     2974#: assets/js/app.js:1886
    9422975#, js-format
    9432976msgid "Deleting %s file was interrupted"
    … …  
    9462979msgstr[1] ""
    9472980
    948 #: assets/js/app.js:1234
    949 msgid "A permanent delete stopped before it finished. Retry to complete it; nothing else is affected."
    950 msgstr ""
    951 
    952 #: assets/js/app.js:1239
     2981#: assets/js/app.js:1887
     2982msgid "A previously authorized permanent deletion stopped before it finished. Routing verification may be incomplete or browser-only. Retry continues that authorization; it does not complete a verified window."
     2983msgstr ""
     2984
     2985#: assets/js/app.js:1892
    9532986msgid "Interrupted cleanup completed."
    9542987msgstr ""
    9552988
    956 #: assets/js/app.js:1243
     2989#: assets/js/app.js:1896
    9572990msgid "Retry"
    9582991msgstr ""
    9592992
    9602993#. translators: %s: number of records
    961 #: assets/js/app.js:1252
     2994#: assets/js/app.js:1905
    9622995#, js-format
    9632996msgid "%s quarantine record needs review"
    … …  
    9662999msgstr[1] ""
    9673000
    968 #: assets/js/app.js:1253
     3001#: assets/js/app.js:1906
    9693002msgid "These records no longer match a media item, and their files could not be verified. Nothing was deleted. Check your backups before acting on them."
    9703003msgstr ""
    9713004
    972 #: assets/js/app.js:1254
     3005#: assets/js/app.js:1907
    9733006msgid "Show record IDs"
    9743007msgstr ""
    9753008
    976 #: assets/js/app.js:1265
     3009#: assets/js/app.js:1918
    9773010msgid "Public page check was partial"
    9783011msgstr ""
    9793012
    980 #: assets/js/app.js:1265
     3013#: assets/js/app.js:1918
    9813014msgid "Public pages checked"
    9823015msgstr ""
    9833016
    984 #: assets/js/app.js:1266
     3017#: assets/js/app.js:1919
    9853018msgid "Pages that were not loaded were still covered by the database scan."
    9863019msgstr ""
    9873020
    988 #: assets/js/app.js:1267
     3021#: assets/js/app.js:1920
    9893022msgid "Adjust page limit"
    9903023msgstr ""
    9913024
    992 #: assets/js/app.js:1290
     3025#: assets/js/app.js:1943
    9933026msgid "Find unused media, with proof."
    9943027msgstr ""
    9953028
    996 #: assets/js/app.js:1294
     3029#: assets/js/app.js:1947
    9973030msgid "Rapid Media Reclaim checks everywhere WordPress can use a file and shows you the evidence before anything moves."
    9983031msgstr ""
    9993032
    1000 #: assets/js/app.js:1299
     3033#: assets/js/app.js:1952
    10013034msgid "Scan"
    10023035msgstr ""
    10033036
    1004 #: assets/js/app.js:1299
     3037#: assets/js/app.js:1952
    10053038msgid "Posts, page builders, custom fields, settings and theme files."
    10063039msgstr ""
    10073040
    1008 #: assets/js/app.js:1300
     3041#: assets/js/app.js:1953
    10093042msgid "Review evidence"
    10103043msgstr ""
    10113044
    1012 #: assets/js/app.js:1300
     3045#: assets/js/app.js:1953
    10133046msgid "See where each file is used, or why it looks unused."
    10143047msgstr ""
    10153048
    1016 #: assets/js/app.js:1301
     3049#: assets/js/app.js:1954
    10173050msgid "Unused files move to a safe folder. Nothing is deleted."
    10183051msgstr ""
    10193052
    1020 #: assets/js/app.js:1307
     3053#: assets/js/app.js:1960
    10213054msgid "Scan media library"
    10223055msgstr ""
    10233056
    10243057#. translators: %s: number of files
    1025 #: assets/js/app.js:1313
     3058#: assets/js/app.js:1966
    10263059#, js-format
    10273060msgid "Your library has %s file. Scanning is read-only."
    … …  
    10303063msgstr[1] ""
    10313064
    1032 #: assets/js/app.js:1339
     3065#: assets/js/app.js:1992
    10333066msgid "The scan stopped"
    10343067msgstr ""
    10353068
    1036 #: assets/js/app.js:1341
     3069#: assets/js/app.js:1994
    10373070msgid "Reload page"
    10383071msgstr ""
    10393072
    1040 #: assets/js/app.js:1344
     3073#: assets/js/app.js:1997
    10413074msgid "Something went wrong while scanning."
    10423075msgstr ""
    10433076
    1044 #: assets/js/app.js:1345
     3077#: assets/js/app.js:1998
    10453078msgid "Your previous results are unchanged."
    10463079msgstr ""
    10473080
    10483081#. translators: 1: step number, 2: number of steps, 3: what is being checked
    1049 #: assets/js/app.js:1361
     3082#: assets/js/app.js:2014
    10503083#, js-format
    10513084msgid "Step %1$s of %2$s · %3$s"
    10523085msgstr ""
    10533086
    1054 #: assets/js/app.js:1366
     3087#: assets/js/app.js:2019
    10553088msgid "Preparing…"
    10563089msgstr ""
    10573090
    1058 #: assets/js/app.js:1381
     3091#: assets/js/app.js:2034
    10593092msgid "Scanning your media library"
    10603093msgstr ""
    10613094
    1062 #: assets/js/app.js:1385
     3095#: assets/js/app.js:2038
    10633096msgid "Elapsed time"
    10643097msgstr ""
    10653098
    1066 #: assets/js/app.js:1389
     3099#: assets/js/app.js:2042
    10673100msgid "Cancelling…"
    10683101msgstr ""
    10693102
    1070 #: assets/js/app.js:1389
     3103#: assets/js/app.js:2042
    10713104#: assets/js/ui.js:201
    10723105msgid "Cancel"
    10733106msgstr ""
    10743107
    1075 #: assets/js/app.js:1399
     3108#: assets/js/app.js:2052
    10763109msgid "Scan progress"
    10773110msgstr ""
    10783111
    10793112#. translators: 1: items checked, 2: total items, 3: percent
    1080 #: assets/js/app.js:1412
     3113#: assets/js/app.js:2065
    10813114#, js-format
    10823115msgid "%1$s of %2$s items checked · %3$s%%"
    10833116msgstr ""
    10843117
    1085 #: assets/js/app.js:1420
     3118#: assets/js/app.js:2073
    10863119msgid "Your current results stay available while the scan runs."
    10873120msgstr ""
    10883121
    1089 #: assets/js/app.js:1420
     3122#: assets/js/app.js:2073
    10903123msgid "Scanning only reads your site. You can leave this page; the scan continues in the background."
    10913124msgstr ""
    10923125
    10933126#. translators: %s: size
    1094 #: assets/js/app.js:1455
     3127#: assets/js/app.js:2108
    10953128#, js-format
    10963129msgid "%s reclaimable"
    10973130msgstr ""
    10983131
    1099 #: assets/js/app.js:1455
     3132#: assets/js/app.js:2108
    11003133msgid "Nothing to clean"
    11013134msgstr ""
    11023135
    1103 #: assets/js/app.js:1458
     3136#: assets/js/app.js:2111
    11043137msgid "With proof of use"
    11053138msgstr ""
    11063139
    1107 #: assets/js/app.js:1461
    1108 msgid "Quarantined"
    1109 msgstr ""
    1110 
    11113140#. translators: %s: size
    1112 #: assets/js/app.js:1463
     3141#: assets/js/app.js:2116
    11133142#, js-format
    11143143msgid "%s · restore anytime"
    11153144msgstr ""
    11163145
    1117 #: assets/js/app.js:1463
     3146#: assets/js/app.js:2116
    11183147msgid "Restore anytime"
    11193148msgstr ""
    11203149
    1121 #: assets/js/app.js:1465
     3150#: assets/js/app.js:2118
    11223151msgid "Protected from cleanup"
    11233152msgstr ""
    11243153
    1125 #: assets/js/app.js:1562
     3154#: assets/js/app.js:2215
    11263155msgid "Search by file name or title"
    11273156msgstr ""
    11283157
    1129 #: assets/js/app.js:1582
     3158#: assets/js/app.js:2235
    11303159msgid "File type"
    11313160msgstr ""
    11323161
    1133 #: assets/js/app.js:1587
     3162#: assets/js/app.js:2240
    11343163msgid "Confidence"
    11353164msgstr ""
    11363165
    1137 #: assets/js/app.js:1588
     3166#: assets/js/app.js:2241
    11383167msgid "Any confidence"
    11393168msgstr ""
    11403169
    1141 #: assets/js/app.js:1599
     3170#: assets/js/app.js:2252
    11423171msgid "What does confidence mean?"
    11433172msgstr ""
    11443173
    1145 #: assets/js/app.js:1600
     3174#: assets/js/app.js:2253
    11463175msgid "How sure we are that a file is unused. High: no trace found anywhere. Medium: only its file name was mentioned, or it was uploaded in the last day. Low: something still points to it by ID or URL in a place that doesn’t count as use, like a trashed post."
    11473176msgstr ""
    11483177
    1149 #: assets/js/app.js:1603
     3178#: assets/js/app.js:2256
    11503179msgid "Sort by"
    11513180msgstr ""
    11523181
    1153 #: assets/js/app.js:1612
     3182#: assets/js/app.js:2265
    11543183msgid "Layout"
    11553184msgstr ""
    11563185
    1157 #: assets/js/app.js:1613
     3186#: assets/js/app.js:2266
    11583187msgid "Grid view"
    11593188msgstr ""
    11603189
    1161 #: assets/js/app.js:1614
     3190#: assets/js/app.js:2267
    11623191msgid "List view"
    11633192msgstr ""
    11643193
    1165 #: assets/js/app.js:1633
     3194#: assets/js/app.js:2286
    11663195msgid "Search media"
    11673196msgstr ""
    11683197
    1169 #: assets/js/app.js:1704
    1170 msgid "Ready to delete"
     3198#: assets/js/app.js:2357
     3199msgid "Waiting period met"
    11713200msgstr ""
    11723201
    11733202#. translators: 1: current day, 2: total days, e.g. "Day 3 of 14"
    1174 #: assets/js/app.js:1707
     3203#: assets/js/app.js:2360
    11753204#, js-format
    11763205msgid "Day %1$s of %2$s"
    … …  
    11783207
    11793208#. translators: %s: number of places
    1180 #: assets/js/app.js:1712
     3209#: assets/js/app.js:2365
    11813210#, js-format
    11823211msgid "Used in %s place"
    … …  
    11863215
    11873216#. translators: %s: number of translated copies sharing the file
    1188 #: assets/js/app.js:1742
     3217#: assets/js/app.js:2395
    11893218#, js-format
    11903219msgid "Shared by %s translation"
    … …  
    11943223
    11953224#. translators: 1: pages loaded, 2: pages in the crawl
    1196 #: assets/js/app.js:1758
     3225#: assets/js/app.js:2411
    11973226#, js-format
    11983227msgid "%1$s of %2$s loaded"
    … …  
    12003229
    12013230#. translators: %s: number of pages
    1202 #: assets/js/app.js:1761
     3231#: assets/js/app.js:2414
    12033232#, js-format
    12043233msgid "%s couldn’t be loaded"
    … …  
    12083237
    12093238#. translators: %s: number of pages
    1210 #: assets/js/app.js:1765
     3239#: assets/js/app.js:2418
    12113240#, js-format
    12123241msgid "%s skipped (private or protected)"
    … …  
    12163245
    12173246#. translators: %s: number of pages
    1218 #: assets/js/app.js:1769
     3247#: assets/js/app.js:2422
    12193248#, js-format
    12203249msgid "%s not reached"
    … …  
    12243253
    12253254#. translators: %s: page limit
    1226 #: assets/js/app.js:1773
     3255#: assets/js/app.js:2426
    12273256#, js-format
    12283257msgid "site has more than the %s-page limit"
    … …  
    12303259
    12313260#. translators: %s: file name
    1232 #: assets/js/app.js:1788
    1233 #: assets/js/app.js:1809
     3261#: assets/js/app.js:2441
     3262#: assets/js/app.js:2462
    12343263#, js-format
    12353264msgid "Select %s"
    … …  
    12373266
    12383267#. translators: %s: file name
    1239 #: assets/js/app.js:1790
     3268#: assets/js/app.js:2443
    12403269#, js-format
    12413270msgid "View details for %s"
    12423271msgstr ""
    12433272
    1244 #: assets/js/app.js:1852
     3273#: assets/js/app.js:2505
    12453274msgid "Select"
    12463275msgstr ""
    12473276
    1248 #: assets/js/app.js:1853
     3277#: assets/js/app.js:2506
    12493278msgid "File"
    12503279msgstr ""
    12513280
    1252 #: assets/js/app.js:1854
    1253 #: assets/js/app.js:2620
     3281#: assets/js/app.js:2507
     3282#: assets/js/app.js:3294
    12543283msgid "Type"
    12553284msgstr ""
    12563285
    1257 #: assets/js/app.js:1855
     3286#: assets/js/app.js:2508
    12583287msgid "Size"
    12593288msgstr ""
    12603289
    1261 #: assets/js/app.js:1856
     3290#: assets/js/app.js:2509
    12623291msgid "Status"
    12633292msgstr ""
    12643293
    1265 #: assets/js/app.js:1857
    1266 #: assets/js/app.js:2621
     3294#: assets/js/app.js:2510
     3295#: assets/js/app.js:3295
    12673296msgid "Uploaded"
    12683297msgstr ""
    12693298
    1270 #: assets/js/app.js:1914
     3299#: assets/js/app.js:2567
    12713300msgid "No files match your filters"
    12723301msgstr ""
    12733302
    1274 #: assets/js/app.js:1915
     3303#: assets/js/app.js:2568
    12753304msgid "Try a different search or file type."
    12763305msgstr ""
    12773306
    1278 #: assets/js/app.js:1916
     3307#: assets/js/app.js:2569
    12793308msgid "Clear filters"
    12803309msgstr ""
    12813310
    1282 #: assets/js/app.js:1920
     3311#: assets/js/app.js:2573
    12833312msgid "No unused media found"
    12843313msgstr ""
    12853314
    1286 #: assets/js/app.js:1920
    1287 msgid "Your library is clean. Every file is used somewhere or marked Keep."
    1288 msgstr ""
    1289 
    1290 #: assets/js/app.js:1921
     3315#: assets/js/app.js:2573
     3316msgid "Other files may be in use, marked Keep, or in quarantine."
     3317msgstr ""
     3318
     3319#: assets/js/app.js:2574
    12913320msgid "Quarantine is empty"
    12923321msgstr ""
    12933322
    1294 #: assets/js/app.js:1921
     3323#: assets/js/app.js:2574
    12953324msgid "Files you move to quarantine wait here, ready to restore with one click."
    12963325msgstr ""
    12973326
    1298 #: assets/js/app.js:1922
     3327#: assets/js/app.js:2575
    12993328msgid "No files in use yet"
    13003329msgstr ""
    13013330
    1302 #: assets/js/app.js:1922
     3331#: assets/js/app.js:2575
    13033332msgid "Files that are used on your site appear here with proof of where."
    13043333msgstr ""
    13053334
    1306 #: assets/js/app.js:1923
     3335#: assets/js/app.js:2576
    13073336msgid "Nothing kept"
    13083337msgstr ""
    13093338
    1310 #: assets/js/app.js:1923
     3339#: assets/js/app.js:2576
    13113340msgid "Mark files as Keep to protect them from cleanup, for example images used in newsletters or apps."
    13123341msgstr ""
    13133342
    1314 #: assets/js/app.js:1924
     3343#: assets/js/app.js:2577
    13153344msgid "Your Media Library is empty"
    13163345msgstr ""
    13173346
    1318 #: assets/js/app.js:1924
     3347#: assets/js/app.js:2577
    13193348msgid "Upload files in Media → Add New and scan again."
    13203349msgstr ""
    13213350
    1322 #: assets/js/app.js:1950
     3351#: assets/js/app.js:2603
    13233352msgid "Couldn’t load files"
    13243353msgstr ""
    13253354
    1326 #: assets/js/app.js:1982
     3355#: assets/js/app.js:2635
    13273356msgid "Select all loaded files"
    13283357msgstr ""
    13293358
    13303359#. translators: %s: number of files
    1331 #: assets/js/app.js:1993
     3360#: assets/js/app.js:2646
    13323361#, js-format
    13333362msgid "%s matching file selected."
    … …  
    13363365msgstr[1] ""
    13373366
    1338 #: assets/js/app.js:1997
     3367#: assets/js/app.js:2650
    13393368msgid "Clear selection"
    13403369msgstr ""
    13413370
    1342 #: assets/js/app.js:2004
     3371#: assets/js/app.js:2657
    13433372msgid "Selecting…"
    13443373msgstr ""
    13453374
    13463375#. translators: %s: number of files
    1347 #: assets/js/app.js:2005
     3376#: assets/js/app.js:2658
    13483377#, js-format
    13493378msgid "Select all %s matching files"
    13503379msgstr ""
    13513380
    1352 #: assets/js/app.js:2011
     3381#: assets/js/app.js:2664
    13533382msgid "Select all"
    13543383msgstr ""
    13553384
    13563385#. translators: 1: shown, 2: total
    1357 #: assets/js/app.js:2016
     3386#: assets/js/app.js:2669
    13583387#, js-format
    13593388msgid "Showing %1$s of %2$s"
    13603389msgstr ""
    13613390
    1362 #: assets/js/app.js:2034
    1363 #: assets/js/app.js:2294
     3391#: assets/js/app.js:2687
     3392#: assets/js/app.js:2951
    13643393msgid "Loading…"
    13653394msgstr ""
    13663395
    1367 #: assets/js/app.js:2034
     3396#: assets/js/app.js:2687
    13683397msgid "Load more"
    13693398msgstr ""
    13703399
    13713400#. translators: 1: action, 2: count
    1372 #: assets/js/app.js:2084
     3401#: assets/js/app.js:2737
    13733402#, js-format
    13743403msgid "%1$s (%2$s)"
    … …  
    13763405
    13773406#. translators: %s: number of files
    1378 #: assets/js/app.js:2100
     3407#: assets/js/app.js:2753
    13793408#, js-format
    13803409msgid "%s selected"
    … …  
    13833412msgstr[1] ""
    13843413
    1385 #: assets/js/app.js:2103
     3414#: assets/js/app.js:2756
    13863415msgid "Clear"
    13873416msgstr ""
    13883417
    1389 #: assets/js/app.js:2103
     3418#: assets/js/app.js:2756
    13903419msgid "selection"
    13913420msgstr ""
    13923421
    1393 #: assets/js/app.js:2172
     3422#: assets/js/app.js:2825
    13943423msgid "Previous file"
    13953424msgstr ""
    13963425
    1397 #: assets/js/app.js:2173
     3426#: assets/js/app.js:2826
    13983427msgid "Next file"
    13993428msgstr ""
    14003429
    1401 #: assets/js/app.js:2174
    1402 msgid "Close"
    1403 msgstr ""
    1404 
    1405 #: assets/js/app.js:2174
     3430#: assets/js/app.js:2827
    14063431msgid "Close (Esc)"
    14073432msgstr ""
    14083433
    1409 #: assets/js/app.js:2294
     3434#: assets/js/app.js:2951
    14103435msgid "File not found"
    14113436msgstr ""
    14123437
    14133438#. translators: %s: date
    1414 #: assets/js/app.js:2411
     3439#: assets/js/app.js:3077
    14153440#, js-format
    14163441msgid "In quarantine since %s."
    14173442msgstr ""
    14183443
    1419 #: assets/js/app.js:2413
    1420 msgid "It can be deleted permanently whenever you’re ready."
     3444#: assets/js/app.js:3079
     3445msgid "The waiting period has passed. A saved recovery backup, usage checks and explicit confirmation are still required."
    14213446msgstr ""
    14223447
    14233448#. translators: 1: "Day 3 of 14", 2: date
    1424 #: assets/js/app.js:2414
    1425 #, js-format
    1426 msgid "%1$s. It can be deleted permanently from %2$s."
     3449#: assets/js/app.js:3080
     3450#, js-format
     3451msgid "%1$s. The waiting period ends on %2$s; all other safety checks still apply."
     3452msgstr ""
     3453
     3454#: assets/js/app.js:3083
     3455msgid "At the last check, the verified window was complete with no known interruption in routing verification. This does not prove disuse or grant deletion permission."
     3456msgstr ""
     3457
     3458#. translators: 1: elapsed routing-check days, 2: required days
     3459#: assets/js/app.js:3083
     3460#, js-format
     3461msgid "Verified routing period: %1$s of %2$s days. Incomplete, unknown or paused verification is separate from waiting age. Manual deletion still requires every existing check."
    14273462msgstr ""
    14283463
    14293464#. translators: %s: number of places
    1430 #: assets/js/app.js:2427
     3465#: assets/js/app.js:3094
    14313466#, js-format
    14323467msgid "The latest scan found this file in %s place. It shows as missing there until you restore it."
    … …  
    14353470msgstr[1] ""
    14363471
    1437 #: assets/js/app.js:2441
     3472#: assets/js/app.js:3108
    14383473msgid "You marked this file Keep. It is never listed as unused or moved by bulk actions."
    14393474msgstr ""
    14403475
    1441 #: assets/js/app.js:2451
     3476#: assets/js/app.js:3118
    14423477msgid "Why we think it’s unused"
    14433478msgstr ""
    14443479
    1445 #: assets/js/app.js:2453
     3480#: assets/js/app.js:3120
    14463481msgid "Evidence"
    14473482msgstr ""
    14483483
    14493484#. translators: %s: number of signals
    1450 #: assets/js/app.js:2475
     3485#: assets/js/app.js:3142
    14513486#, js-format
    14523487msgid "%s weak signal"
    … …  
    14553490msgstr[1] ""
    14563491
    1457 #: assets/js/app.js:2476
     3492#: assets/js/app.js:3143
    14583493msgid "These don’t count as use, but they lower our confidence. Check them before removing the file."
    14593494msgstr ""
    14603495
    1461 #: assets/js/app.js:2487
     3496#: assets/js/app.js:3154
    14623497msgid "The latest scan found no use of this file."
    14633498msgstr ""
    14643499
    1465 #: assets/js/app.js:2492
     3500#: assets/js/app.js:3160
     3501msgid "Some usage updates could not be saved. Run a complete scan before relying on this result or cleaning up."
     3502msgstr ""
     3503
     3504#: assets/js/app.js:3162
     3505msgid "Usage updates are waiting for background indexing. This result may be stale; cleanup is paused until indexing finishes."
     3506msgstr ""
     3507
     3508#: assets/js/app.js:3164
     3509msgid "Some stored content could not be checked within scan limits. This file may still be in use. Resolve the affected sources and rescan before cleaning up."
     3510msgstr ""
     3511
     3512#: assets/js/app.js:3166
    14663513msgid "No trace of this file was found anywhere we checked."
    14673514msgstr ""
    14683515
    1469 #: assets/js/app.js:2494
     3516#: assets/js/app.js:3168
    14703517msgid "Something still points to this file by ID or URL in a place that doesn’t count as use, such as a trashed post. Review the weak signals below."
    14713518msgstr ""
    14723519
    1473 #: assets/js/app.js:2496
     3520#: assets/js/app.js:3170
    14743521msgid "It was uploaded less than a day ago and may be about to be used."
    14753522msgstr ""
    14763523
    1477 #: assets/js/app.js:2498
     3524#: assets/js/app.js:3172
    14783525msgid "Only its file name was mentioned somewhere, which is not proof of use. Review the weak signals below."
    14793526msgstr ""
    14803527
    1481 #: assets/js/app.js:2512
     3528#: assets/js/app.js:3186
    14823529msgid "Details about what was checked appear after the next scan."
    14833530msgstr ""
    14843531
    1485 #: assets/js/app.js:2526
     3532#: assets/js/app.js:3200
     3533msgid "Incomplete · stored values exceeded scan limits"
     3534msgstr ""
     3535
     3536#: assets/js/app.js:3200
    14863537msgid "Checked · some values read as plain data"
    14873538msgstr ""
    14883539
    1489 #: assets/js/app.js:2526
     3540#: assets/js/app.js:3200
    14903541msgid "Checked"
    14913542msgstr ""
    14923543
    14933544#. translators: %s: number of items
    1494 #: assets/js/app.js:2527
     3545#: assets/js/app.js:3201
    14953546#, js-format
    14963547msgid "Not found in %s checked"
    … …  
    14993550msgstr[1] ""
    15003551
    1501 #: assets/js/app.js:2528
     3552#: assets/js/app.js:3202
    15023553msgid "Not found"
    15033554msgstr ""
    15043555
    15053556#. translators: %s: number
    1506 #: assets/js/app.js:2562
     3557#: assets/js/app.js:3236
    15073558#, js-format
    15083559msgid "Show %s more"
    15093560msgstr ""
    15103561
    1511 #: assets/js/app.js:2583
     3562#: assets/js/app.js:3257
    15123563msgid "Edit"
    15133564msgstr ""
    15143565
    1515 #: assets/js/app.js:2586
     3566#: assets/js/app.js:3260
    15163567msgid "View"
    15173568msgstr ""
    15183569
    1519 #: assets/js/app.js:2606
     3570#: assets/js/app.js:3280
    15203571msgid "Edit in Media Library"
    15213572msgstr ""
    15223573
    1523 #: assets/js/app.js:2609
     3574#: assets/js/app.js:3283
    15243575msgid "Open file"
    15253576msgstr ""
    15263577
    1527 #: assets/js/app.js:2614
     3578#: assets/js/app.js:3288
    15283579msgid "Details"
    15293580msgstr ""
    15303581
    1531 #: assets/js/app.js:2618
     3582#: assets/js/app.js:3292
    15323583msgid "File name"
    15333584msgstr ""
    15343585
    1535 #: assets/js/app.js:2619
     3586#: assets/js/app.js:3293
    15363587msgid "Title"
    15373588msgstr ""
    15383589
    1539 #: assets/js/app.js:2622
     3590#: assets/js/app.js:3296
    15403591msgid "Total size"
    15413592msgstr ""
    15423593
    1543 #: assets/js/app.js:2623
     3594#: assets/js/app.js:3297
    15443595msgid "ID"
    15453596msgstr ""
    15463597
    1547 #: assets/js/app.js:2624
     3598#: assets/js/app.js:3298
    15483599msgid "Translations"
    15493600msgstr ""
    15503601
    1551 #: assets/js/app.js:2624
     3602#: assets/js/app.js:3298
    15523603msgid "Actions apply to all of them."
    15533604msgstr ""
    15543605
    1555 #: assets/js/app.js:2647
     3606#: assets/js/app.js:3321
    15563607msgid "Original"
    15573608msgstr ""
    15583609
    1559 #: assets/js/app.js:2650
     3610#: assets/js/app.js:3324
    15603611msgid "Original (before scaling)"
    15613612msgstr ""
    15623613
    1563 #: assets/js/app.js:2653
     3614#: assets/js/app.js:3327
    15643615msgid "Edit backup"
    15653616msgstr ""
    15663617
    15673618#. translators: %s: number of files
    1568 #: assets/js/app.js:2660
     3619#: assets/js/app.js:3334
    15693620#, js-format
    15703621msgid "%s file on disk"
    … …  
    15743625
    15753626#. translators: %s: number of bytes
    1576 #: assets/js/app.js:2674
     3627#: assets/js/app.js:3348
    15773628#, js-format
    15783629msgid "%s byte"
    … …  
    15813632msgstr[1] ""
    15823633
    1583 #: assets/js/app.js:2703
     3634#: assets/js/app.js:3377
    15843635msgid "Count drafts as use"
    15853636msgstr ""
    15863637
    1587 #: assets/js/app.js:2703
     3638#: assets/js/app.js:3377
    15883639msgid "Files used only in drafts, private or scheduled posts are treated as in use."
    15893640msgstr ""
    15903641
    1591 #: assets/js/app.js:2704
     3642#: assets/js/app.js:3379
    15923643msgid "Count trashed posts as weak evidence"
    15933644msgstr ""
    15943645
    1595 #: assets/js/app.js:2704
     3646#: assets/js/app.js:3379
    15963647msgid "Files used only in trashed posts get lower confidence instead of high."
    15973648msgstr ""
    15983649
    1599 #: assets/js/app.js:2706
     3650#: assets/js/app.js:3381
    16003651msgid "Watch public browser media errors"
    16013652msgstr ""
    16023653
    1603 #: assets/js/app.js:2706
     3654#: assets/js/app.js:3381
    16043655msgid "Opt in to bounded anonymous same-origin error reports. No IP addresses or browsing history are stored. Static server/CDN requests are not intercepted; coverage is incomplete."
    16053656msgstr ""
    16063657
    1607 #: assets/js/app.js:2707
     3658#: assets/js/app.js:3382
    16083659msgid "Automatically restore reported files"
    16093660msgstr ""
    16103661
    1611 #: assets/js/app.js:2707
     3662#: assets/js/app.js:3382
    16123663msgid "Requires watching. Any visitor who requests a quarantined file’s address can bring it back, so quarantine stops being permanent for public files. Unattached media and media attached to published, non-password-protected content can be restored."
    16133664msgstr ""
    16143665
    1615 #: assets/js/app.js:2708
     3666#: assets/js/app.js:3383
    16163667msgid "Crawl public page HTML during scans"
    16173668msgstr ""
    16183669
    1619 #: assets/js/app.js:2708
     3670#: assets/js/app.js:3383
    16203671msgid "Anonymous same-origin public posts/pages only. No login, redirects or JavaScript. Failed and skipped pages remain coverage gaps."
    16213672msgstr ""
    16223673
    1623 #: assets/js/app.js:2716
     3674#: assets/js/app.js:3391
    16243675msgid "Quarantine period"
    16253676msgstr ""
    16263677
    1627 #: assets/js/app.js:2717
     3678#: assets/js/app.js:3392
    16283679msgid "days"
    16293680msgstr ""
    16303681
    1631 #: assets/js/app.js:2718
    1632 msgid "How long files wait in quarantine before they can be deleted permanently without an extra warning."
    1633 msgstr ""
    1634 
    1635 #: assets/js/app.js:2722
     3682#: assets/js/app.js:3393
     3683msgid "How long files wait in quarantine before they can be deleted permanently. A verified, saved recovery backup is also required."
     3684msgstr ""
     3685
     3686#: assets/js/app.js:3395
     3687msgid "Old or CDN uploads roots (one URL per line, up to 10)"
     3688msgstr ""
     3689
     3690#: assets/js/app.js:3398
    16363691msgid "Maximum public pages per scan (1–500)"
    16373692msgstr ""
    16383693
    1639 #: assets/js/app.js:2728
     3694#: assets/js/app.js:3404
    16403695msgid "Save settings"
    16413696msgstr ""
    16423697
    1643 #: assets/js/app.js:2734
    1644 msgid "Enter a number of days between 0 and 365."
    1645 msgstr ""
    1646 
    1647 #: assets/js/app.js:2737
     3698#: assets/js/app.js:3410
     3699msgid "Enter a number of days between 14 and 365."
     3700msgstr ""
     3701
     3702#: assets/js/app.js:3413
    16483703msgid "Enter a page limit between 1 and 500."
    16493704msgstr ""
    16503705
    1651 #: assets/js/app.js:2752
     3706#: assets/js/app.js:3428
    16523707msgid "Settings saved. Rescan to apply them to your results."
    16533708msgstr ""
    16543709
    1655 #: assets/js/app.js:2753
     3710#: assets/js/app.js:3429
    16563711msgid "Rescan now"
    16573712msgstr ""
    16583713
    1659 #: assets/js/app.js:2756
     3714#: assets/js/app.js:3432
    16603715msgid "Settings saved."
    16613716msgstr ""
    16623717
    1663 #: assets/js/app.js:2773
     3718#: assets/js/app.js:3449
    16643719msgid "Selection cleared."
    16653720msgstr ""
    … …  
    16893744msgstr ""
    16903745
    1691 #: assets/js/ui.js:271
     3746#: assets/js/ui.js:273
    16923747#: assets/js/util.js:302
    16933748msgid "Something went wrong. Please try again."
  • rapid-media-reclaim/tags/1.1.0/rapid-media-reclaim.php

    r3794616 r3814937  
    33 * Plugin Name:       Rapid Media Reclaim
    44 * Description:       Review potentially unused media with usage evidence, reversible quarantine and one-click restore before reclaiming storage.
    5  * Version:           1.0.0
     5 * Version:           1.1.0
    66 * Author:            Nazim Husain
    77 * Author URI:        https://nazimansari.com
    … …  
    3030}
    3131
    32 define( 'SAFE_MEDIA_CLEANER_VERSION', '1.0.0' );
     32define( 'SAFE_MEDIA_CLEANER_VERSION', '1.1.0' );
    3333define( 'SAFE_MEDIA_CLEANER_FILE', __FILE__ );
    3434define( 'SAFE_MEDIA_CLEANER_PATH', plugin_dir_path( __FILE__ ) );
  • rapid-media-reclaim/tags/1.1.0/readme.txt

    r3794616 r3814937  
    55Requires at least: 6.0
    66Tested up to: 7.1
    7 Stable tag: 1.0.0
     7Stable tag: 1.1.0
    88Requires PHP: 7.4
    99License: GPLv2 or later
    … …  
    25252. **Review the evidence.** Open any file to see where it is used, or why it looks unused.
    26263. **Quarantine.** Move unused files out of the public uploads folder. Pages keep working if the scan was right; if a file was still needed, restore it with one click.
    27 4. **Delete when you are sure.** After the quarantine period (14 days by default), delete quarantined files permanently.
     274. **Delete when you are sure.** After at least 14 days in quarantine, export and save a verified recovery backup before confirming permanent deletion. Requests or current usage block deletion.
    2828
    2929= Where it looks =
    … …  
    3131* Gutenberg blocks (image, gallery, cover, media & text, file, video, audio and more), reusable blocks, templates and template parts.
    3232* Classic editor content, `wp-image-` classes and gallery, video, audio and playlist shortcodes.
    33 * Page builders: Elementor, Bricks, Beaver Builder, Divi, WPBakery and Oxygen.
    34 * Advanced Custom Fields image, file and gallery fields, including repeaters, even when ACF is inactive.
     33* Page builders: Elementor, Bricks, Beaver Builder, Divi, WPBakery and Oxygen, including media in Divi and WPBakery shortcodes.
     34* Advanced Custom Fields image, file and gallery fields, including repeaters, groups and flexible content, even when ACF is inactive.
    3535* WooCommerce product galleries, variation images, category thumbnails and the placeholder image.
    3636* Site icon, custom logo, header and background images, widgets and other settings.
    3737* Term and user meta, and files referenced directly in your theme's code.
    38 * Every image size, scaled and rotated originals, edited copies, and WebP/AVIF versions. Files served from a CDN or staging domain are recognised too.
     38* Every image size, scaled and rotated originals, edited copies, and WebP/AVIF versions. Files served from a CDN or staging domain are recognised too, and you can list old or CDN uploads addresses in Settings.
    3939* Translations: media items that share one file (WPML, Polylang) count as used when any of them is.
    4040
    … …  
    5656* A warning when you delete a media item that is still in use.
    5757* "Keep" marks for files you never want listed as unused.
    58 * Scans run in small batches, continue in the background if you close the page, and keep your previous results visible until a rescan finishes.
     58* Scans run in small batches, continue in the background if you close the page, and keep your previous results visible until a rescan finishes. Content changes made outside the admin are re-indexed in a guarded background queue.
     59* Recovery ZIPs: export quarantined media as a private, checksummed ZIP and restore it later with its original attachment IDs. Existing files are never overwritten.
     60* A space saved report and operation history, with CSV exports of the media inventory, operations and audits.
     61* WP-CLI commands for administrators (`wp rapid-media-reclaim scan`, `status`, `quarantine`, `restore`, `export`, `report` and more), with `--dry-run`.
     62* Multisite: network activation and deactivation, and setup of new sites.
     63
     64= Tools (new in 1.1) =
     65Open Tools from the plugin screen. Each task runs in bounded steps, can be paused or cancelled, and saves its progress.
     66
     67* **Exact duplicates.** Find byte-identical copies, preview the reference changes, and point supported content (core blocks and classic content, Elementor, Beaver Builder, Bricks, ACF fields, Divi and WPBakery shortcodes) at the copy you keep. Every merge can be rolled back. Supported Elementor and Beaver Builder caches can be regenerated for the affected posts. Merged duplicates move to quarantine only after a fresh scan and a saved recovery backup. Unsupported sources block the merge.
     68* **Visually similar images.** A local, review-only search for images that look alike (requires the PHP GD extension). Suggestions never merge or delete anything.
     69* **Uploads audit.** A saved, review-only walk of the uploads folder that sorts files by ownership, with filters and CSV export. Supported images and PDFs that are not in the Media Library can be backed up, checked again, quarantined and restored; permanent deletion needs a saved backup, a completed routing-check period of at least 14 days and a separate confirmation.
     70* **Request routing check.** Test whether a missing-upload request reaches WordPress, and track a verified routing-check period for optional server request watching.
    5971
    6072= Watching, crawling and privacy =
    6173Both features are disabled by default. Enable them in Media > Rapid Media Reclaim > Settings.
    6274
    63 **Browser watching** reports up to 10 failed same-origin uploads per report, up to 60 reports per site and 10 per visitor per minute. Reports only count for media on published, non-password-protected content. For each reported attachment, only the time it was last reported is stored. No visitor IP, referrer, user agent, page URL or response body is stored; to apply the per-visitor limit, a salted hash of the visitor's IP is kept for one minute. Public tokens stay valid for up to two days, so cached pages keep working. Tokens are public and replayable, so reports are hints, not proof of human use. Reports never return media IDs, paths, quarantine contents or restore outcomes.
     75**Browser watching** reports up to 10 failed same-origin uploads per report, up to 60 reports per site and 10 per visitor per minute. Reports count for unattached media and media attached to published, non-password-protected content. For each reported attachment, only the time it was last reported is stored. No visitor IP, referrer, user agent, page URL or response body is stored; to apply the per-visitor limit, a salted hash of the visitor's IP is kept for one minute. Public tokens stay valid for up to two days, so cached pages keep working. Tokens are public and replayable, so reports are hints, not proof of human use. Reports never return media IDs, paths, quarantine contents or restore outcomes.
    6476
    6577**Automatic restore** is separately opt-in. When it is on, any visitor who requests the address of a quarantined public file can bring that file back, so quarantine is no longer permanent for public files. Unattached media is eligible, as is media attached to published content without a password. Media attached to private, draft or password-protected content is excluded.
    … …  
    6779Static requests handled by a web server or CDN never reach PHP. The observer covers only opted-in anonymous public HTML visits with JavaScript, common image, video and source errors, and retries once. It cannot cover CSS backgrounds, offline clients, cached pages without the script, all embeds, logged-in or private content, external CDNs or requests outside the browser. No server configuration is changed.
    6880
    69 **The optional crawler** fetches at most 100 public posts and pages by default (configurable from 1 to 500), without credentials or JavaScript. Requests use same-origin, published, non-password-protected permalinks, with no query strings, no redirects, five second timeouts and a 1 MiB response limit. It does not follow arbitrary links, submit forms, crawl archives or custom post types, or fetch external URLs. Failed, skipped, capped and pending pages are shown as coverage gaps. Loopback restrictions, plain permalinks and redirects may prevent coverage. Review evidence and back up before cleanup.
     81**Server request watching** can observe exact quarantined upload paths only when the missing request reaches WordPress. Tools includes a signed routing canary; it verifies one route for 24 hours, not all file types or your CDN. Recognized requests are counted and protect the media before any opt-in restore. Flag-only is the default. The plugin never changes server configuration. Static handlers, CDN/browser caches, encoded paths, rate limits and capped manifest lookups can bypass observation. A lack of observed requests is never proof of disuse.
     82
     83**The optional crawler** discovers conventional same-origin sitemaps and falls back to published public post types. It checks at most 100 public pages by default (configurable 1–500) and up to 20 linked same-origin stylesheets. Requests omit credentials and JavaScript, with no redirects, five-second timeouts and a 1 MiB response limit. Sitemap XML entities/DTDs are rejected. Failed, skipped, capped and pending work is shown as coverage gaps. JavaScript-only images, CSS imports and external stylesheets remain outside coverage.
    7084
    7185**Recovery records** remain until all files are restored or payload cleanup completes. Interrupted moves and restores can be retried using the recorded SHA-256 identity. Unsupported hard links fail closed. Uninstall retains recovery data and access guards if any restore is unresolved; resolve it before uninstalling.
    … …  
    8195
    8296= Will this delete my images? =
    83 Not without you asking twice. Scanning changes nothing. Quarantining moves files to a protected folder and can be undone. Only the "Delete permanently" action in the quarantine removes files.
     97Not without you asking twice. Scanning changes nothing. Quarantining moves files to a protected folder and can be undone. Only explicitly confirmed permanent-deletion actions remove files. Standalone file cleanup in Tools follows its own backup and fresh-review steps.
    8498
    8599= What happens to a page that still uses a quarantined file? =
    … …  
    87101
    88102= Do I still need a backup? =
    89 Keep a recent backup before cleanup. Quarantine and supplemental coverage reduce risk but do not replace backups or review.
     103Keep a recent database and uploads backup. Recovery exports are private, owner-bound ZIPs with checksums and expire after one day on the server. Save them before confirming backup retention. Exports currently support 64 MiB per file and 512 MiB per archive; larger files require manual recovery. Quarantine and supplemental coverage do not replace independent backups or review.
    90104
    91105= Does it work with my page builder? =
    92 Elementor, Bricks, Beaver Builder, Divi, WPBakery and Oxygen are supported, and any data that stores media as links or IDs in post meta or settings is checked as well. Unrecognized builder formats or inaccessible sources may be missed entirely; review evidence and keep uncertain files.
     106Readers cover bounded recognized Elementor, Bricks, Beaver Builder, Divi and WPBakery structures, with generic fallback for other stored links and IDs, including Oxygen. Typed duplicate writers cover a narrower set of controls. Rendering of licensed premium builders has not been qualified. Unrecognized builder formats or inaccessible sources may be missed entirely; review evidence and keep uncertain files.
    93107
    94108= Is it slow on large sites? =
    … …  
    110124No. Every feature is free.
    111125
     126== Screenshots ==
     127
     1281. Review potentially unused media with usage categories and confidence. Synthetic demo media shown.
     1292. Configure the quarantine period, old or CDN uploads addresses, draft handling and opt-in browser error watching, with coverage limits explained.
     1303. Review quarantined media before restoring it or considering permanent deletion. Synthetic demo media shown.
     131
    112132== Changelog ==
     133
     134= 1.1.0 =
     135* New: Tools panel with resumable, cancellable background tasks.
     136* New: Exact-duplicate finder. Preview, apply and roll back reference changes in core blocks and content, Elementor, Beaver Builder, Bricks, ACF and Divi/WPBakery shortcodes, regenerate supported Elementor and Beaver Builder caches, and quarantine merged duplicates after a fresh scan and saved backup.
     137* New: Review-only search for visually similar images (requires PHP GD).
     138* New: Saved uploads audits with ownership categories, filters and CSV export. Supported standalone images and PDFs outside the Media Library can be backed up, quarantined, restored and, after a verified waiting period, permanently deleted.
     139* New: Private, checksummed recovery ZIPs for quarantined media, with verified, trust-confirmed restore that keeps original attachment IDs and never overwrites files.
     140* New: Optional server request watching (flag-only by default) and a request routing check with a tracked verification period.
     141* New: Space saved report, operation history and CSV exports.
     142* New: WP-CLI commands for administrators, with `--dry-run`.
     143* New: Setting for old or CDN uploads addresses (up to 10).
     144* New: Multisite network activation, deactivation and new-site setup.
     145* Improved: Bounded background indexing; content changes made outside the admin are re-indexed in a guarded queue.
     146* Improved: Deeper evidence for Bricks, Beaver Builder, Divi/WPBakery shortcodes and ACF field structures, with clearer incomplete-scan warnings.
     147* Improved: The crawler reads same-origin sitemaps, falls back to all public post types and checks up to 20 linked same-origin stylesheets.
     148* Improved: Browser watching also counts reports for unattached media.
     149* Changed: Permanent deletion now requires at least 14 days in quarantine and a downloaded, confirmed recovery backup. Recorded requests or current usage block deletion.
     150* Fixed: Stronger recovery and concurrency safeguards. Interrupted moves and restores resume safely, replacement files are preserved, and uninstall keeps recovery data while anything is unresolved.
    113151
    114152= 1.0.0 =
    … …  
    121159* Optional public-page crawl and browser error watching, both off by default.
    122160* "Used in" column and delete warning in the Media Library.
     161
     162== Upgrade Notice ==
     163
     164= 1.1.0 =
     165Adds duplicate merging with rollback, visual similarity, uploads audits, recovery ZIPs and WP-CLI. Permanent deletion now needs 14+ days in quarantine and a saved recovery backup. Back up before upgrading.
  • rapid-media-reclaim/tags/1.1.0/uninstall.php

    r3794616 r3814937  
    3232        }
    3333        try {
     34                if ( ! SafeMediaCleaner\Recovery_Import::uninstall_ready() ) {
     35                        return __( 'Resume pending backup recovery in Tools before uninstalling. Its files, journals and protections were retained.', 'rapid-media-reclaim' );
     36                }
     37                if ( ! SafeMediaCleaner\File_Recovery::uninstall_ready() ) {
     38                        return __( 'Standalone file recovery is incomplete. Its manifests, payloads and guards were retained.', 'rapid-media-reclaim' );
     39                }
    3440                wp_clear_scheduled_hook( 'safe_media_cleaner_scan_continue' );
     41                wp_clear_scheduled_hook( SafeMediaCleaner\Maintenance::HOOK );
     42                wp_clear_scheduled_hook( SafeMediaCleaner\Routing_Window::HOOK );
     43                wp_clear_scheduled_hook( SafeMediaCleaner\Scan_Runner::CLEANUP_HOOK );
     44                wp_clear_scheduled_hook( SafeMediaCleaner\Status_Index::HOOK );
     45                wp_clear_scheduled_hook( SafeMediaCleaner\Deferred_Index::HOOK );
    3546                SafeMediaCleaner\Scan_Runner::cancel();
    3647                $table  = SafeMediaCleaner\Installer::table( 'quarantine' );
    … …  
    4152                if ( $exists === $table && ! SafeMediaCleaner\Installer::restore_for_uninstall() ) {
    4253                        return __( 'Some quarantined media could not be restored automatically.', 'rapid-media-reclaim' );
     54                }
     55                if ( ! SafeMediaCleaner\Merge::uninstall_ready() ) {
     56                        return __( 'Complete or roll back pending reference merges before uninstalling.', 'rapid-media-reclaim' );
    4357                }
    4458                if ( ! SafeMediaCleaner\Installer::quarantine_directory_clear() ) {
    … …  
    6781                if ( '' !== $error ) {
    6882                        return $error;
     83                }
     84                if ( ! SafeMediaCleaner\Recovery_Export::remove_for_uninstall() ) {
     85                        return __( 'Private recovery archives could not be removed. Retry cleanup before uninstalling.', 'rapid-media-reclaim' );
    6986                }
    7087                $dir = get_option( 'safe_media_cleaner_quarantine_dir' );
    … …  
    95112                delete_metadata( 'post', 0, '_safe_media_cleaner_quarantine_id', '', true );
    96113                delete_metadata( 'post', 0, '_safe_media_cleaner_watch_seen', '', true );
     114                delete_metadata( 'post', 0, '_safe_media_cleaner_backup', '', true );
     115                delete_metadata( 'post', 0, '_safe_media_cleaner_merge_guard', '', true );
    97116                wp_clear_scheduled_hook( 'safe_media_cleaner_scan_continue' );
     117                wp_clear_scheduled_hook( SafeMediaCleaner\Maintenance::HOOK );
     118                wp_clear_scheduled_hook( SafeMediaCleaner\Routing_Window::HOOK );
     119                wp_clear_scheduled_hook( SafeMediaCleaner\Scan_Runner::CLEANUP_HOOK );
     120                wp_clear_scheduled_hook( SafeMediaCleaner\Status_Index::HOOK );
     121                wp_clear_scheduled_hook( SafeMediaCleaner\Deferred_Index::HOOK );
    98122                return '';
    99123        } finally {
    … …  
    102126}
    103127
    104 $safe_media_cleaner_sites = is_multisite() ? get_sites(
    105         array(
    106                 'fields' => 'ids',
    107                 'number' => 0,
    108         )
    109 ) : array( get_current_blog_id() );
     128/**
     129 * Enumerate network sites in constant-memory, fresh keyset pages.
     130 *
     131 * @return \Generator Site IDs, including archived sites with recovery data.
     132 */
     133function safe_media_cleaner_uninstall_sites(): \Generator {
     134        if ( ! is_multisite() ) {
     135                yield get_current_blog_id();
     136                return;
     137        }
     138        global $wpdb;
     139        $after = 0;
     140        do {
     141                // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Fresh bounded network recovery enumeration, not a cached site inventory.
     142                $ids = $wpdb->get_col( $wpdb->prepare( "SELECT blog_id FROM {$wpdb->blogs} WHERE blog_id>%d ORDER BY blog_id LIMIT 100", $after ) );
     143                if ( $wpdb->last_error || ! is_array( $ids ) ) {
     144                        wp_die( esc_html__( 'Network recovery inventory could not be verified. All remaining recovery data was retained.', 'rapid-media-reclaim' ) );
     145                }
     146                foreach ( $ids as $id ) {
     147                        $after = (int) $id;
     148                        yield $after;
     149                }
     150                $count = count( $ids );
     151        } while ( 100 === $count );
     152}
    110153
    111154// 1. Restore and verify every site before removing anything anywhere.
    112155$safe_media_cleaner_problems = array();
    113 foreach ( $safe_media_cleaner_sites as $safe_media_cleaner_site ) {
     156foreach ( safe_media_cleaner_uninstall_sites() as $safe_media_cleaner_site ) {
    114157        if ( is_multisite() ) {
    115158                switch_to_blog( (int) $safe_media_cleaner_site );
    … …  
    137180
    138181// 2. Every site is clear: remove the plugin's data.
    139 foreach ( $safe_media_cleaner_sites as $safe_media_cleaner_site ) {
     182foreach ( safe_media_cleaner_uninstall_sites() as $safe_media_cleaner_site ) {
    140183        if ( is_multisite() ) {
    141184                switch_to_blog( (int) $safe_media_cleaner_site );
  • rapid-media-reclaim/trunk/assets/css/app.css

    r3794616 r3814937  
    25882588        }
    25892589}
     2590
     2591/* Tool actions stay readable inside the existing accessible modal. */
     2592.smc-tools__actions { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; margin: 16px 0; }
     2593.smc-tools__actions .smc-btn { white-space: normal; height: auto; min-height: 40px; text-align: center; }
     2594.smc-dialog__body pre { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 280px; overflow: auto; }
     2595@media (max-width: 540px) { .smc-tools__actions { grid-template-columns: minmax(0, 1fr); } }
     2596
     2597.smc-tools__output { min-width: 0; overflow-wrap: anywhere; }
     2598
     2599/* Backup recovery keeps its confirmation and conflicts separate from discovery. */
     2600.smc-recovery { margin-top: 24px; padding-top: 20px; border-top: 1px solid var(--smc-border, #dcdcde); }
     2601.smc-recovery input[type="file"] { display: block; max-width: 100%; margin-bottom: 12px; }
     2602.smc-recovery__preview { max-height: 50vh; overflow: auto; overflow-wrap: anywhere; }
     2603.smc-recovery__preview li { margin-bottom: 12px; }
     2604.smc-recovery__preview li p { margin: 4px 0; }
     2605.smc-recovery__conflicts { color: #8a2424; }
     2606
     2607.smc-savings__metrics { display: grid; grid-template-columns: repeat(auto-fit,minmax(150px,1fr)); gap: 16px; margin: 16px 0; }
     2608.smc-savings__metrics dt { color: var(--smc-muted); font-size: 12px; }
     2609.smc-savings__metrics dd { font-size: 22px; font-weight: 600; margin: 8px 0 0; overflow-wrap: anywhere; }
     2610.smc-savings__history { max-height: 260px; overflow: auto; font-size: 12px; }
     2611
     2612/* Keep live audit checks separate from their saved ownership hints. */
     2613.smc-dialog__body .smc-audit-result { padding-block: 12px; border-bottom: 1px solid var(--smc-border-soft, #e8e8ea); overflow-wrap: anywhere; }
     2614.smc-dialog__body .smc-audit-result > .smc-btn { display: block; margin-block: 8px; max-width: 100%; white-space: normal; height: auto; min-height: 32px; }
     2615.smc-dialog__body .smc-audit-result p { margin-block: 6px; }
  • rapid-media-reclaim/trunk/assets/js/app.js

    r3794616 r3814937  
    2020        const PER_PAGE = 60;
    2121        const MAX_IDS = boot.maxIds || 500;
     22        const MAX_FILE_IDS = boot.maxFileIds || 10;
    2223
    2324        const VIEWS = [
    … …  
    545546
    546547        function eligibleIds( action, entries ) {
     548                if ( [ 'quarantine', 'purge' ].includes( action ) && state.summary && state.summary.storage && state.summary.storage.audit_only ) { return []; }
    547549                const out = [];
    548550                entries.forEach( ( s, id ) => {
    … …  
    631633                const body = [
    632634                        h( 'p', null, __( 'The files are deleted from the server and their Media Library entries are removed. This can’t be undone.', 'rapid-media-reclaim' ) ),
     635                        h( 'p', { class: 'smc-callout smc-callout--warning' }, __( 'Routing verification may be incomplete, expired or browser-only. Quarantine age is separate from the verified window. No recognized requests does not prove that a file is unused. Saved-backup confirmation and all deletion checks still apply.', 'rapid-media-reclaim' ) ),
    633636                ];
    634637                const buttons = [];
    … …  
    656659                                )
    657660                        );
    658                         buttons.push( {
    659                                 label: rest.length ? sprintf( /* translators: %s: number of files */ __( 'Delete all %s anyway', 'rapid-media-reclaim' ), num( ids.length ) ) : __( 'Delete anyway', 'rapid-media-reclaim' ),
    660                                 value: 'force',
    661                                 variant: 'danger-outline',
    662                         } );
     661
    663662                }
    664663                if ( rest.length ) {
    … …  
    683682                        buttons,
    684683                } );
    685                 if ( value === 'force' ) {
    686                         return { ids, force: true };
    687                 }
    688684                if ( value === 'ready' ) {
    689685                        return { ids: rest, force: false };
    … …  
    692688        }
    693689
    694         /** Send ids in chunks of MAX_IDS; aggregates the results. */
     690        /** Send file operations in small serial chunks; Keep uses its larger metadata limit. */
    695691        async function runBulk( path, ids, payload, okKey, progressLabel ) {
    696                 const parts = SMC.chunk( ids, MAX_IDS );
     692                const parts = SMC.chunk( ids, path === '/keep' ? MAX_IDS : MAX_FILE_IDS );
    697693                const out = { ok: [], failed: [], bytes: 0, batches: [], error: null };
    698694                const handle = parts.length > 1 ? SMC.toast( { type: 'info', message: progressLabel( 0, ids.length ), timeout: 0 } ) : null;
    … …  
    826822                                                filesLabel( shown( res.ok ), res.bytes )
    827823                                        ),
    828                                         action: { label: __( 'Undo', 'rapid-media-reclaim' ), onClick: () => undo( () => Promise.all( batches.map( ( batch ) => api.post( '/restore', { batch } ) ) ), shown( res.ok ) ) },
     824                                        action: { label: __( 'Undo', 'rapid-media-reclaim' ), onClick: () => undo( () => restoreBatches( batches ), shown( res.ok ) ) },
    829825                                } );
    830826                        }
    … …  
    841837                                } );
    842838                                const other = res.failed.filter( ( f ) => f.code !== 'shared' );
    843                                 failureToast( other, _n( '%s file couldn’t be moved', '%s files couldn’t be moved', other.length, 'rapid-media-reclaim' ) );
     839                                failureToast( other, /* translators: %s: number of files */ _n( '%s file couldn’t be moved', '%s files couldn’t be moved', other.length, 'rapid-media-reclaim' ) );
    844840                        } else {
    845                                 failureToast( res.failed, _n( '%s file couldn’t be moved', '%s files couldn’t be moved', res.failed.length, 'rapid-media-reclaim' ) );
     841                                failureToast( res.failed, /* translators: %s: number of files */ _n( '%s file couldn’t be moved', '%s files couldn’t be moved', res.failed.length, 'rapid-media-reclaim' ) );
    846842                        }
    847843                } else if ( action === 'restore' ) {
    … …  
    856852                                } );
    857853                        }
    858                         failureToast( res.failed, _n( '%s file couldn’t be restored', '%s files couldn’t be restored', res.failed.length, 'rapid-media-reclaim' ) );
     854                        failureToast( res.failed, /* translators: %s: number of files */ _n( '%s file couldn’t be restored', '%s files couldn’t be restored', res.failed.length, 'rapid-media-reclaim' ) );
    859855                } else if ( action === 'purge' ) {
    860856                        res = await runBulk( '/purge', ids, { force }, 'purged', progress );
    … …  
    870866                                } );
    871867                        }
    872                         failureToast( other, _n( '%s file couldn’t be deleted', '%s files couldn’t be deleted', other.length, 'rapid-media-reclaim' ) );
     868                        failureToast( other, /* translators: %s: number of files */ _n( '%s file couldn’t be deleted', '%s files couldn’t be deleted', other.length, 'rapid-media-reclaim' ) );
    873869                        if ( tooRecent.length ) {
    874870                                putBack( res.failed.map( ( f ) => f.id ) );
    … …  
    889885                                } );
    890886                        }
    891                         failureToast( res.failed, _n( '%s file couldn’t be updated', '%s files couldn’t be updated', res.failed.length, 'rapid-media-reclaim' ) );
     887                        failureToast( res.failed, /* translators: %s: number of files */ _n( '%s file couldn’t be updated', '%s files couldn’t be updated', res.failed.length, 'rapid-media-reclaim' ) );
    892888                }
    893889
    … …  
    910906                } );
    911907                return Array.from( ids );
     908        }
     909
     910        /** Drain bounded restore windows in order, stopping on the first recoverable failure. */
     911        async function restoreBatches( batches ) {
     912                const results = [];
     913                for ( const batch of batches ) {
     914                        let res;
     915                        do {
     916                                res = await api.post( '/restore', { batch } );
     917                                applySummary( res.summary );
     918                                results.push( res );
     919                                if ( res.failed && res.failed.length ) {
     920                                        throw new Error( res.failed[0].message );
     921                                }
     922                        } while ( res.remaining > 0 );
     923                }
     924                return results;
    912925        }
    913926
    … …  
    923936                        } );
    924937                } catch ( err ) {
     938                        details.clear();
     939                        invalidate();
    925940                        SMC.toast( { type: 'error', message: err.message } );
    926941                }
    … …  
    11541169
    11551170        function renderHeader() {
     1171                const focused = els.header.contains( document.activeElement ) ? document.activeElement : null;
    11561172                const last = state.summary && state.summary.last_scan;
    11571173                let meta = null;
    … …  
    11671183
    11681184                const actions = h( 'div', { class: 'smc-header__actions' } );
     1185                actions.appendChild( h( 'button', { type: 'button', id: 'smc-tools-button', class: 'smc-btn smc-btn--secondary', onClick: openTools }, __( 'Tools', 'rapid-media-reclaim' ) ) );
    11691186
    11701187                if ( scanned() ) {
    … …  
    11921209                        actions
    11931210                );
     1211                if ( focused ) {
     1212                        const nextFocus = Array.from( els.header.querySelectorAll( 'button' ) ).find( ( node ) => ! node.disabled && node.textContent === focused.textContent && node.getAttribute( 'aria-label' ) === focused.getAttribute( 'aria-label' ) );
     1213                        if ( nextFocus ) { nextFocus.focus(); }
     1214                }
    11941215                renderNotices();
    11951216        }
    11961217
    11971218        // ------------------------------------------------------------------
     1219        const toolJobs = new Map();
     1220
     1221        /** Next-release tools share the core services; discovery never authorizes deletion. */
     1222        async function openTools() {
     1223                let active = true;
     1224                let exportJob = null;
     1225                let observationTimer = null;
     1226                const progress = h( 'p', { role: 'status', 'aria-live': 'polite' }, __( 'Loading storage and observation status…', 'rapid-media-reclaim' ) );
     1227                const output = h( 'div', { class: 'smc-tools__output' } );
     1228                const savings = h( 'section', { class: 'smc-recovery smc-savings', 'aria-label': __( 'Space saved report', 'rapid-media-reclaim' ) } );
     1229                const history = h( 'div', { class: 'smc-savings__history' } );
     1230                let historyAfter = 0;
     1231                const loadHistory = async () => {
     1232                        const page = await api.get( '/tools/report-history', { after: historyAfter, limit: 20 } );
     1233                        if ( ! active ) { return; }
     1234                        if ( page.status === 'unavailable' ) { throw new Error( __( 'Operation history unavailable. Check database access.', 'rapid-media-reclaim' ) ); }
     1235                        const labels = { quarantine: __( 'Quarantine', 'rapid-media-reclaim' ), restore: __( 'Restore', 'rapid-media-reclaim' ), remove: __( 'Permanent removal', 'rapid-media-reclaim' ), verified: __( 'Verified', 'rapid-media-reclaim' ), failed: __( 'Failed', 'rapid-media-reclaim' ), pending: __( 'Pending', 'rapid-media-reclaim' ), unknown: __( 'Unknown', 'rapid-media-reclaim' ), tracked: __( 'Tracked', 'rapid-media-reclaim' ), legacy: __( 'Legacy', 'rapid-media-reclaim' ), import: __( 'Imported backup', 'rapid-media-reclaim' ) };
     1236                        if ( historyAfter === 0 && ! page.items.length ) { history.appendChild( h( 'p', null, __( 'No tracked operations yet. Earlier activity is unknown.', 'rapid-media-reclaim' ) ) ); }
     1237                        page.items.forEach( ( row ) => history.appendChild( h( 'p', null, '#' + row.id + ' · ' + labels[ row.operation ] + ' · ' + labels[ row.result ] + ' · ' + bytes( row.bytes ) + ' · ' + labels[ row.coverage ] + ' · ' + row.updated_at + ' UTC' ) ) );
     1238                        historyAfter = page.next;
     1239                        historyMore.hidden = page.next === null;
     1240                };
     1241                const historyMore = h( 'button', { class: 'smc-btn smc-btn--secondary', type: 'button', onClick: async () => { historyMore.disabled = true; try { await loadHistory(); } catch ( error ) { progress.textContent = error.message; } finally { historyMore.disabled = false; } } }, __( 'Load operation history', 'rapid-media-reclaim' ) );
     1242                const showSavings = ( report ) => {
     1243                        const value = ( amount ) => amount === null ? __( 'Unknown', 'rapid-media-reclaim' ) : bytes( amount );
     1244                        const metrics = h( 'dl', { class: 'smc-savings__metrics' } );
     1245                        [ [ __( 'Estimated reclaimable', 'rapid-media-reclaim' ), report.estimated_reclaimable_bytes ], [ __( 'Media Library quarantine storage', 'rapid-media-reclaim' ), report.current_quarantine_bytes ], [ __( 'Media Library verified removed', 'rapid-media-reclaim' ), report.cumulative_verified_removed_bytes ] ].forEach( ( [ label, bytes ] ) => metrics.appendChild( h( 'div', null, h( 'dt', null, label ), h( 'dd', null, value( bytes ) ) ) ) );
     1246                        replace( savings, h( 'h3', null, __( 'Space saved report', 'rapid-media-reclaim' ) ), metrics,
     1247                                h( 'p', null, __( 'Logical bytes only. Physical disk allocation: not measured. Estimated reclaimable bytes do not authorize deletion.', 'rapid-media-reclaim' ) ),
     1248                                h( 'p', null, sprintf( /* translators: 1: tracking start UTC, 2: pending file operations, 3: unknown operations, 4: untracked active recovery records */ __( 'Tracking started: %1$s UTC. Pending: %2$s. Unknown operations: %3$s. Untracked active records: %4$s.', 'rapid-media-reclaim' ), report.tracking_started_at || __( 'Unknown', 'rapid-media-reclaim' ), report.pending_files === null ? __( 'Unknown', 'rapid-media-reclaim' ) : num( report.pending_files + report.pending_records ), report.unknown_operation_files === null ? __( 'Unknown', 'rapid-media-reclaim' ) : num( report.unknown_operation_files ), report.legacy_active_records === null ? __( 'Unknown', 'rapid-media-reclaim' ) : num( report.legacy_active_records ) ) ),
     1249                                h( 'p', null, sprintf( /* translators: 1: inventory estimate observation UTC, 2: oldest storage observation UTC */ __( 'Inventory estimate observed: %1$s UTC. Oldest storage observation: %2$s UTC.', 'rapid-media-reclaim' ), report.estimate_observed_at || __( 'Unknown', 'rapid-media-reclaim' ), report.oldest_storage_observation_at || __( 'Unknown', 'rapid-media-reclaim' ) ) ), h( 'p', null, report.coverage ), h( 'p', null, report.action_required ), history, historyMore );
     1250                };
     1251                const observation = h( 'section', { class: 'smc-recovery', 'aria-label': __( 'Routing verification', 'rapid-media-reclaim' ) } );
     1252                const showObservation = ( status ) => {
     1253                        const w = status.window || {};
     1254                        const modeLabels = { 'verified-PHP': __( 'PHP routing checked', 'rapid-media-reclaim' ), 'browser-only': __( 'Browser reports only', 'rapid-media-reclaim' ), unavailable: __( 'Unavailable', 'rapid-media-reclaim' ) };
     1255                        const current = status.mode === 'verified-PHP' && w.start && status.expires_at * 1000 > Date.now();
     1256                        const date = ( value ) => value ? new Date( value * 1000 ).toLocaleString() : __( 'Unknown', 'rapid-media-reclaim' );
     1257                        replace( observation, h( 'h3', null, __( 'Routing verification', 'rapid-media-reclaim' ) ),
     1258                                h( 'p', null, current ? __( 'No known interruption in routing verification', 'rapid-media-reclaim' ) : __( 'Routing verification incomplete, expired or paused', 'rapid-media-reclaim' ) ),
     1259                                h( 'p', null, sprintf( /* translators: 1: mode, 2: start date, 3: last success date, 4: expiry date, 5: interruptions */ __( 'Mode: %1$s. Window start: %2$s. Last successful check: %3$s. Expires: %4$s. Interruptions: %5$s.', 'rapid-media-reclaim' ), modeLabels[ current ? status.mode : ( status.fallback_mode || 'unavailable' ) ] || __( 'Unknown', 'rapid-media-reclaim' ), date( w.start ), date( status.verified_at ), date( status.expires_at ), num( w.interruptions || 0 ) ) ),
     1260                                h( 'p', null, sprintf( /* translators: 1: elapsed verification days, 2: required days */ __( 'Site routing period: %1$s of %2$s days. Each quarantined group also starts no earlier than its latest member.', 'rapid-media-reclaim' ), num( Math.floor( ( status.elapsed_seconds || 0 ) / 86400 ) ), num( status.required_days || 14 ) ) ),
     1261                                h( 'p', null, sprintf( /* translators: %s: most recent interruption date */ __( 'Latest known interruption: %s. Any interruption restarts the period after a new successful routing check.', 'rapid-media-reclaim' ), date( status.coverage_gap_at ) ) ),
     1262                                h( 'p', null, status.effective_scope ), h( 'p', null, status.coverage ) );
     1263                        clearTimeout( observationTimer );
     1264                        observationTimer = setTimeout( async () => {
     1265                                if ( ! active ) { return; }
     1266                                try { const fresh = await api.get( '/tools/status' ); if ( active ) { showObservation( fresh.observation ); } }
     1267                                catch ( error ) { if ( active ) { replace( observation, h( 'p', null, __( 'Routing status unavailable. Refresh Tools before relying on a previous check.', 'rapid-media-reclaim' ) ) ); } }
     1268                        }, current ? Math.max( 1000, Math.min( 60000, status.expires_at * 1000 - Date.now() ) ) : 60000 );
     1269                };
     1270                const actions = h( 'div', { class: 'smc-tools__actions' } );
     1271                const mergeSelect = h( 'select', { class: 'smc-select', 'aria-label': __( 'Reference job', 'rapid-media-reclaim' ), hidden: true } );
     1272                const rememberMerge = ( job ) => {
     1273                        toolJobs.set( 'merge', job );
     1274                        if ( ! Array.from( mergeSelect.options ).some( ( option ) => option.value === job.token ) ) { mergeSelect.appendChild( h( 'option', { value: job.token }, '#' + job.canonical + ' · ' + job.status ) ); }
     1275                        mergeSelect.value = job.token; mergeSelect.hidden = false;
     1276                };
     1277                const taskError = ( error ) => {
     1278                        const messages = {
     1279                                file_review_selection_stale: __( 'This audit selection is stale or unfinished. Run a fresh scan and uploads audit.', 'rapid-media-reclaim' ),
     1280                                file_review_selection_invalid: __( 'This saved row cannot be reviewed. Choose a supported image or PDF in a fresh audit.', 'rapid-media-reclaim' ),
     1281                                file_review_file_changed: __( 'The file changed, disappeared or exceeds the 16 MiB live-review limit. Start a fresh audit or review it manually.', 'rapid-media-reclaim' ),
     1282                                visual_gd_unavailable: __( 'Your server needs the PHP GD imaging extension for local visual search.', 'rapid-media-reclaim' ),
     1283                                visual_inventory_unavailable: __( 'The media inventory could not be read. Check database access and retry this step.', 'rapid-media-reclaim' ),
     1284                                visual_signature_invalid: __( 'Saved visual search data is unreadable. Start a new search; originals were not changed.', 'rapid-media-reclaim' ),
     1285                                visual_results_unavailable: __( 'Visual results could not be read. Retry after checking database access.', 'rapid-media-reclaim' ),
     1286                                visual_results_invalid: __( 'Saved visual results are invalid. Start a new search; originals were not changed.', 'rapid-media-reclaim' ),
     1287                                inventory_root_changed: __( 'Uploads storage changed or this is an older audit. Start a new uploads audit; no files were changed.', 'rapid-media-reclaim' ),
     1288                                inventory_filter_invalid: __( 'Choose a valid category, alphanumeric extension and minimum byte count.', 'rapid-media-reclaim' ),
     1289                                inventory_job_busy: __( 'The audit is finishing a step. Retry cancellation shortly.', 'rapid-media-reclaim' ),
     1290                                inventory_cancel_not_saved: __( 'Cancellation could not be saved. Retry after checking database access.', 'rapid-media-reclaim' ),
     1291                                retirement_fresh_scan_required: __( 'Prepare duplicate quarantine and complete its new scan before continuing.', 'rapid-media-reclaim' ),
     1292                                retirement_scan_busy: __( 'Wait for the current scan to finish, then prepare duplicate quarantine.', 'rapid-media-reclaim' ),
     1293                                retirement_usage_review_required: __( 'Usage evidence still references a duplicate. Review it and keep the file available.', 'rapid-media-reclaim' ),
     1294                                retirement_cache_review_required: __( 'Regenerate this reference job’s supported builder caches first. Unsupported builder caches keep quarantine blocked.', 'rapid-media-reclaim' ),
     1295                                retirement_cache_changed: __( 'Generated cache files changed. Regenerate them, prepare duplicate quarantine again and complete a new scan.', 'rapid-media-reclaim' ),
     1296                                retirement_saved_backup_required: __( 'Download and confirm a current duplicate backup before quarantine.', 'rapid-media-reclaim' ),
     1297                                retirement_unverified_variants: __( 'Image variants or edit backups could not be matched safely. Originals remain available for review.', 'rapid-media-reclaim' ),
     1298                                retirement_state_not_saved: __( 'Completion could not be saved. Refresh Quarantine and use reference rollback; recovery data was retained.', 'rapid-media-reclaim' ),
     1299                                retirement_recovery_batch_changed: __( 'Recovery ownership changed. Review the quarantine records before restoring this reference job.', 'rapid-media-reclaim' ),
     1300                                retirement_backup_budget: __( 'This duplicate group exceeds the current limit of 100 files or 64 MiB. Originals remain available.', 'rapid-media-reclaim' ),
     1301                                retirement_other_recovery_job: __( 'Another reference recovery journal protects this media. Resolve that operation first.', 'rapid-media-reclaim' ),
     1302                                retirement_attachment_unavailable: __( 'A duplicate is kept, shared, already quarantined or unavailable. Review its recovery state first.', 'rapid-media-reclaim' ),
     1303                                retirement_storage_or_index_incomplete: __( 'Storage or usage indexing needs review. Complete pending work before quarantine.', 'rapid-media-reclaim' ),
     1304                                cache_source_changed: __( 'A source changed after this merge. Resolve its reference recovery job before quarantine.', 'rapid-media-reclaim' )
     1305                        };
     1306                        return messages[ error.message ] || error.message || __( 'The task could not finish. No media was deleted.', 'rapid-media-reclaim' );
     1307                };
     1308                const run = ( label, action ) => {
     1309                        const button = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: async () => {
     1310                                button.disabled = true;
     1311                                try { await action(); } catch ( error ) { progress.textContent = taskError( error ); }
     1312                                finally {
     1313                                        button.disabled = false;
     1314                                        if ( active && button.isConnected && document.activeElement === document.body ) { button.focus(); }
     1315                                }
     1316                        } }, label );
     1317                        actions.appendChild( button );
     1318                        return button;
     1319                };
     1320                const uploadSelect = h( 'select', { class: 'smc-select', 'aria-label': __( 'Saved uploads audits', 'rapid-media-reclaim' ) }, h( 'option', { value: '' }, __( 'Choose a saved uploads audit', 'rapid-media-reclaim' ) ) );
     1321                const uploadStatus = h( 'p', { role: 'status', 'aria-live': 'polite' } );
     1322                const rememberUpload = ( job ) => {
     1323                        if ( job.kind !== 'uploads' ) { return; }
     1324                        toolJobs.set( 'uploads:' + job.token, job );
     1325                        let option = Array.from( uploadSelect.options ).find( ( item ) => item.value === job.token );
     1326                        if ( ! option ) { option = h( 'option', { value: job.token } ); uploadSelect.appendChild( option ); }
     1327                        const status = { running: __( 'Paused or running', 'rapid-media-reclaim' ), done: __( 'Walk finished', 'rapid-media-reclaim' ), cancelled: __( 'Cancelled', 'rapid-media-reclaim' ) };
     1328                        option.textContent = ( job.created ? new Date( job.created * 1000 ).toLocaleString() : job.token.slice( 0, 8 ) ) + ' · ' + ( status[ job.status ] || job.status ) + ' · ' + num( job.processed );
     1329                        uploadSelect.value = job.token;
     1330                };
     1331
     1332                const fileSelect = h( 'select', { class: 'smc-select', 'aria-label': __( 'Standalone recovery job', 'rapid-media-reclaim' ) }, h( 'option', { value: '' }, __( 'Choose standalone recovery', 'rapid-media-reclaim' ) ) );
     1333                const fileOutput = h( 'div', { class: 'smc-recovery__preview', role: 'status', 'aria-live': 'polite' } );
     1334                let fileBusy = false;
     1335                const filePhases = { prepared: __( 'Backup preparation', 'rapid-media-reclaim' ), staged: __( 'Backed up — originals still live', 'rapid-media-reclaim' ), quarantining: __( 'Interrupted quarantine — review or restore', 'rapid-media-reclaim' ), quarantined: __( 'Quarantined', 'rapid-media-reclaim' ), restoring: __( 'Recovery needs retry', 'rapid-media-reclaim' ), restored: __( 'Restored', 'rapid-media-reclaim' ), purging: __( 'Authorized deletion needs retry', 'rapid-media-reclaim' ), purged: __( 'Permanently deleted — ZIP required for recovery', 'rapid-media-reclaim' ), discarding: __( 'Discard needs retry', 'rapid-media-reclaim' ) };
     1336                const filePhase = ( job ) => job.imported && job.state === 'staged' ? __( 'Verified private recovery preview', 'rapid-media-reclaim' ) : filePhases[ job.state ] || job.state;
     1337                const rememberFile = ( job ) => {
     1338                        toolJobs.set( 'file:' + job.token, job );
     1339                        let option = Array.from( fileSelect.options ).find( ( o ) => o.value === job.token );
     1340                        if ( ! option ) { option = h( 'option', { value: job.token } ); fileSelect.appendChild( option ); }
     1341                        option.textContent = filePhase( job ) + ' · ' + ( job.files[0] || {} ).path;
     1342                        fileSelect.value = job.token;
     1343                };
     1344                const fileError = ( error ) => {
     1345                        const messages = {
     1346                                file_approval_stale_or_backup_missing: __( 'The review expired, content changed or a saved backup is missing. Download/confirm the backup and run fresh checks.', 'rapid-media-reclaim' ),
     1347                                file_quarantine_watch_required: __( 'Enable request watching and automatic restore in Settings, then verify request routing before quarantine.', 'rapid-media-reclaim' ),
     1348                                file_quarantine_review_blocked: __( 'A current reference, possible owner, recorded request or storage restriction blocks quarantine. Keep this file.', 'rapid-media-reclaim' ),
     1349                                file_backup_download_required: __( 'Download and save this backup before confirming it.', 'rapid-media-reclaim' ),
     1350                                file_recovery_restore_conflict: __( 'A different file occupies the original path, or recovery bytes are missing. Nothing was overwritten. Keep both files and resolve the conflict before retrying.', 'rapid-media-reclaim' ),
     1351                                file_quarantine_source_raced: __( 'The original changed during capture. The replacement and backup were retained. Restore or ask your administrator to resolve the conflict.', 'rapid-media-reclaim' ),
     1352                                file_import_confirmation_required: __( 'Verify this backup and explicitly trust its origin before restoring. Cross-site backups also need adoption confirmation.', 'rapid-media-reclaim' ),
     1353                                file_approval_payload_changed: __( 'The file or its attributes changed. Restore this preparation and create a fresh audit/backup.', 'rapid-media-reclaim' )
     1354                        };
     1355                        return messages[ error.message ] || taskError( error ) + ' ' + __( 'Recovery records are retained. Refresh the list; restore or retry after resolving the problem.', 'rapid-media-reclaim' );
     1356                };
     1357                const fileWork = async ( work ) => {
     1358                        if ( fileBusy ) { fileOutput.textContent = __( 'Wait for the current standalone recovery operation.', 'rapid-media-reclaim' ); return; }
     1359                        fileBusy = true;
     1360                        try { await work(); } catch ( error ) { fileOutput.textContent = fileError( error ); }
     1361                        finally { fileBusy = false; }
     1362                };
     1363                const showFile = ( job ) => {
     1364                        rememberFile( job );
     1365                        const buttons = h( 'div', { class: 'smc-tools__actions' } );
     1366                        const add = ( label, fn, disabled = false ) => {
     1367                                const b = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', disabled, onClick: () => fileWork( async () => { b.disabled = true; try { await fn(); } finally { b.disabled = false; } } ) }, label ); buttons.appendChild( b ); return b;
     1368                        };
     1369                        const notes = h( 'div' );
     1370                        if ( job.state === 'prepared' ) {
     1371                                add( __( 'Resume backup preparation', 'rapid-media-reclaim' ), async () => {
     1372                                        while ( active && job.state === 'prepared' ) { job = await api.post( '/tools/files/step', { token: job.token } ); rememberFile( job ); }
     1373                                        if ( active ) { showFile( job ); }
     1374                                } );
     1375                        }
     1376                        if ( job.state !== 'prepared' && job.state !== 'discarding' && job.state !== 'purged' && job.state !== 'purging' ) {
     1377                                buttons.appendChild( h( 'a', { class: 'smc-btn smc-btn--secondary', href: safeHref( job.download_url ), target: '_blank', rel: 'noopener noreferrer' }, __( 'Download standalone recovery ZIP', 'rapid-media-reclaim' ) ) );
     1378                        }
     1379                        if ( job.imported && ! job.trusted ) {
     1380                                const trust = h( 'input', { type: 'checkbox' } ); const adopt = h( 'input', { type: 'checkbox' } );
     1381                                notes.appendChild( h( 'p', null, h( 'label', null, trust, ' ', __( 'I trust the source of this ZIP and reviewed every destination below.', 'rapid-media-reclaim' ) ) ) );
     1382                                if ( job.cross_site ) { notes.appendChild( h( 'p', null, h( 'label', null, adopt, ' ', __( 'I explicitly approve importing these paths from a different site.', 'rapid-media-reclaim' ) ) ) ); }
     1383                                add( __( 'Trust this backup', 'rapid-media-reclaim' ), async () => {
     1384                                        if ( ! trust.checked || ( job.cross_site && ! adopt.checked ) ) { throw new Error( __( 'Confirm backup trust and any cross-site adoption first.', 'rapid-media-reclaim' ) ); }
     1385                                        showFile( await api.post( '/tools/files/trust', { token: job.token, trusted_backup: true, adopt_site: adopt.checked } ) );
     1386                                }, job.state !== 'staged' );
     1387                                add( __( 'Discard untrusted upload', 'rapid-media-reclaim' ), async () => {
     1388                                        const yes = await SMC.dialog( { title: __( 'Discard this recovery upload?', 'rapid-media-reclaim' ), body: h( 'p', null, __( 'Only this untrusted upload and its private verified copies will be removed. Public files are untouched. Keep your original ZIP.', 'rapid-media-reclaim' ) ), buttons: [ { label: __( 'Discard upload', 'rapid-media-reclaim' ), value: true } ] } );
     1389                                        if ( yes ) { await api.post( '/tools/files/discard', { token: job.token } ); const option = Array.from( fileSelect.options ).find( ( o ) => o.value === job.token ); if ( option ) { option.remove(); } toolJobs.delete( 'file:' + job.token ); fileOutput.textContent = __( 'Untrusted upload discarded. Public files were not changed.', 'rapid-media-reclaim' ); }
     1390                                } );
     1391                        }
     1392                        if ( ! job.imported && job.state === 'staged' ) {
     1393                                const saved = h( 'input', { type: 'checkbox', checked: job.backup_saved } );
     1394                                notes.appendChild( h( 'p', null, h( 'label', null, saved, ' ', __( 'I downloaded and saved this recovery ZIP outside this server.', 'rapid-media-reclaim' ) ) ) );
     1395                                add( __( 'Confirm saved standalone backup', 'rapid-media-reclaim' ), async () => {
     1396                                        if ( ! saved.checked ) { throw new Error( __( 'Save your backup and confirm it first.', 'rapid-media-reclaim' ) ); }
     1397                                        showFile( await api.post( '/tools/files/backup-confirm', { token: job.token, confirmed: true } ) );
     1398                                } );
     1399                                add( job.approval && job.approval.status === 'checking' ? __( 'Resume standalone checks', 'rapid-media-reclaim' ) : __( 'Check before standalone quarantine', 'rapid-media-reclaim' ), async () => {
     1400                                        if ( ! job.approval || job.approval.status !== 'checking' ) { job = await api.post( '/tools/files/approval-start', { token: job.token } ); }
     1401                                        while ( active && job.approval.status === 'checking' ) {
     1402                                                job = await api.post( '/tools/files/approval-step', { token: job.token } ); rememberFile( job );
     1403                                                fileOutput.textContent = sprintf( /* translators: %s: checked stored rows */ __( '%s stored rows checked. Closing pauses; resume this saved recovery job later.', 'rapid-media-reclaim' ), num( job.approval.rows ) );
     1404                                        }
     1405                                        if ( active ) { showFile( job ); }
     1406                                }, ! job.backup_saved );
     1407                                if ( job.approval && job.approval.status === 'ready' ) {
     1408                                        const reviewed = h( 'input', { type: 'checkbox' } );
     1409                                        notes.appendChild( h( 'p', null, h( 'label', null, reviewed, ' ', __( 'I reviewed the public pages, relevant theme/plugin behavior and caches. These checks cannot prove the file is unused.', 'rapid-media-reclaim' ) ) ) );
     1410                                        add( __( 'Quarantine this standalone file', 'rapid-media-reclaim' ), async () => {
     1411                                                if ( ! reviewed.checked ) { throw new Error( __( 'Review the public pages and caches first.', 'rapid-media-reclaim' ) ); }
     1412                                                const yes = await SMC.dialog( { title: __( 'Quarantine this standalone file?', 'rapid-media-reclaim' ), body: h( 'p', null, __( 'Its public URL will become unavailable until restored. A saved ZIP, fresh checks, request watching and verified routing are required. Static/CDN/cache paths may bypass observation. No permanent deletion occurs.', 'rapid-media-reclaim' ) ), buttons: [ { label: __( 'Move file to quarantine', 'rapid-media-reclaim' ), value: true, variant: 'primary' } ] } );
     1413                                                if ( yes ) { showFile( await api.post( '/tools/files/quarantine', { token: job.token, confirmed: true } ) ); }
     1414                                        } );
     1415                                }
     1416                        }
     1417                        if ( ! [ 'restored', 'purged', 'purging' ].includes( job.state ) && ( ! job.imported || job.trusted ) ) {
     1418                                add( __( 'Restore standalone files', 'rapid-media-reclaim' ), async () => { showFile( await api.post( '/tools/files/restore', { token: job.token } ) ); } );
     1419                        }
     1420                        if ( [ 'quarantined', 'purging' ].includes( job.state ) ) {
     1421                                notes.appendChild( h( 'p', null, job.window && job.window.verified_window_complete ? __( 'The routing-check window is complete. This does not prove continuous request capture or non-usage.', 'rapid-media-reclaim' ) : __( 'Permanent deletion is blocked until the routing-check window is complete, with at least 14 days and no recorded requests.', 'rapid-media-reclaim' ) ) );
     1422                                add( __( 'Run fresh checks before permanent deletion', 'rapid-media-reclaim' ), async () => {
     1423                                        job = await api.post( '/tools/files/approval-start', { token: job.token } );
     1424                                        while ( active && job.approval.status === 'checking' ) {
     1425                                                job = await api.post( '/tools/files/approval-step', { token: job.token } ); rememberFile( job );
     1426                                                fileOutput.textContent = sprintf( __( '%s stored rows checked. Closing pauses; resume this saved recovery job later.', 'rapid-media-reclaim' ), num( job.approval.rows ) );
     1427                                        }
     1428                                        if ( active ) { showFile( job ); }
     1429                                }, ! job.window || ! job.window.verified_window_complete );
     1430                                add( __( 'Permanently delete standalone quarantine copies', 'rapid-media-reclaim' ), async () => {
     1431                                        const yes = await SMC.dialog( { title: __( 'Permanently delete this standalone file?', 'rapid-media-reclaim' ), body: h( 'p', null, __( 'Both server recovery copies will be deleted. Recovery will require your downloaded ZIP. Review public pages, dynamic uses and caches first; routing checks cannot prove non-usage. Any replacement at the original public path is kept.', 'rapid-media-reclaim' ) ), buttons: [ { label: __( 'Permanently delete copies', 'rapid-media-reclaim' ), value: true } ] } );
     1432                                        if ( yes ) { showFile( await api.post( '/tools/files/purge', { token: job.token, confirmed: true } ) ); }
     1433                                }, ! job.window || ! job.window.verified_window_complete || ! job.approval || job.approval.status !== 'ready' );
     1434                        }
     1435
     1436                        const reasons = { sources_changed: __( 'Content changed during review. Restart checks.', 'rapid-media-reclaim' ), stored_match: __( 'A possible stored reference or owner blocks quarantine. Keep the file.', 'rapid-media-reclaim' ), source_limit: __( 'Some content could not be fully checked. Resolve the source limit before quarantine.', 'rapid-media-reclaim' ) };
     1437                        replace( fileOutput, h( 'h4', null, filePhase( job ) ), h( 'ul', null, ...job.files.map( ( f ) => h( 'li', null, f.path + ' · ' + bytes( f.bytes ) + ( f.mode !== undefined ? ' · ' + __( 'Permissions:', 'rapid-media-reclaim' ) + ' ' + f.mode.toString( 8 ) : '' ) ) ) ),
     1438                                job.approval ? h( 'p', null, job.approval.status === 'ready' ? __( 'Stored-source checks are current for five minutes. They establish eligibility for manual quarantine, not non-usage or purge permission.', 'rapid-media-reclaim' ) : reasons[ job.approval.reason ] || __( 'Stored-source checks are pending.', 'rapid-media-reclaim' ) ) : null,
     1439                                job.hits ? h( 'p', null, __( 'A request was recorded. This path is protected from re-quarantine.', 'rapid-media-reclaim' ) ) : null,
     1440                                job.state === 'purged' ? h( 'p', null, job.verified_removed_bytes === null ? __( 'Deletion completed. Removed bytes are unknown because a verified receipt was interrupted.', 'rapid-media-reclaim' ) : sprintf( /* translators: %s: logical original bytes removed */ __( 'Verified removal: %s logical original bytes, counted once. Recovery ZIPs and physical allocation are excluded.', 'rapid-media-reclaim' ), bytes( job.verified_removed_bytes ) ) ) : null,
     1441                                notes, buttons );
     1442                };
     1443                const fileUpload = h( 'input', { type: 'file', accept: '.zip,application/zip', 'aria-label': __( 'Standalone recovery ZIP', 'rapid-media-reclaim' ) } );
     1444                const fileSection = h( 'section', { class: 'smc-recovery' }, h( 'h3', null, __( 'Standalone file recovery', 'rapid-media-reclaim' ) ),
     1445                        h( 'p', null, __( 'Standalone files are separate from Media Library counts. Prepare a backup from an uploads-audit row, then select its recovery job here. Archives preserve ordinary file permissions and modification times; ownership, ACLs and directory attributes are not reconstructed. Permanent deletion needs a saved backup, fresh review, a completed routing-check window of at least 14 days and a separate confirmation. Quarantine retains recovery copies and does not free disk space.', 'rapid-media-reclaim' ) ), fileSelect,
     1446                        h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: () => { const job = toolJobs.get( 'file:' + fileSelect.value ); if ( job ) { showFile( job ); } } }, __( 'Open standalone recovery', 'rapid-media-reclaim' ) ), fileUpload,
     1447                        h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: () => fileWork( async () => {
     1448                                const file = fileUpload.files[0]; if ( ! file ) { throw new Error( __( 'Choose a standalone recovery ZIP first.', 'rapid-media-reclaim' ) ); }
     1449                                const data = new FormData(); data.append( 'archive', file );
     1450                                let job = await wp.apiFetch( { path: ( boot.restPath || '/rapid-media-reclaim/v1' ) + '/tools/files/upload', method: 'POST', body: data } ); rememberFile( job );
     1451                                while ( active && job.state === 'prepared' ) { job = await api.post( '/tools/files/step', { token: job.token } ); rememberFile( job ); }
     1452                                if ( active ) { showFile( job ); }
     1453                        } ) }, __( 'Upload standalone recovery ZIP', 'rapid-media-reclaim' ) ), fileOutput );
     1454                let fileBefore = 0;
     1455                const olderFiles = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', hidden: true, onClick: () => fileWork( loadFiles ) }, __( 'Load older standalone recovery records', 'rapid-media-reclaim' ) );
     1456                fileSection.appendChild( olderFiles );
     1457                async function loadFiles() {
     1458                        const result = await api.get( '/tools/files/jobs' + ( fileBefore ? '?before=' + fileBefore : '' ) );
     1459                        if ( ! active ) { return; }
     1460                        result.jobs.slice().reverse().forEach( rememberFile ); fileBefore = result.next; olderFiles.hidden = ! result.limited;
     1461                        if ( result.unreadable ) { fileOutput.textContent = __( 'Some recovery records could not be read. Keep all backups and ask your administrator to review storage; uninstall remains blocked for unresolved data.', 'rapid-media-reclaim' ); }
     1462                }
     1463                loadFiles().catch( ( error ) => { if ( active ) { fileOutput.textContent = fileError( error ); } } );
     1464
     1465                let fileReviewBusy = false;
     1466                const uploadReviewRow = ( job, saved, labels ) => {
     1467                        const row = saved.item;
     1468                        const detail = h( 'div', { role: 'status', 'aria-live': 'polite' } );
     1469                        const check = h( 'button', {
     1470                                type: 'button', class: 'smc-btn smc-btn--secondary smc-btn--sm',
     1471                                disabled: ! /\.(?:jpe?g|png|gif|webp|avif|pdf)$/i.test( row.path ),
     1472                                onClick: async () => {
     1473                                        if ( fileReviewBusy ) { detail.textContent = __( 'Wait for the current live check to finish.', 'rapid-media-reclaim' ); return; }
     1474                                        fileReviewBusy = true; check.disabled = true;
     1475                                        try {
     1476                                                const review = await api.post( '/tools/file-review', { token: job.token, row_id: saved.result_id } );
     1477                                                if ( ! active || ! detail.isConnected ) { return; }
     1478                                                const messages = {
     1479                                                        ownership_match: __( 'Possible current metadata owner found. Keep this file.', 'rapid-media-reclaim' ),
     1480                                                        reference_match: __( 'Possible stored reference found. Keep this file.', 'rapid-media-reclaim' ),
     1481                                                        incomplete: __( 'The live check is incomplete. No cleanup approval was issued.', 'rapid-media-reclaim' ),
     1482                                                        no_match_in_checked_sources: __( 'No match in the checked stored sources. This does not establish that the file is unused.', 'rapid-media-reclaim' )
     1483                                                };
     1484                                                replace( detail,
     1485                                                        h( 'p', null, messages[ review.status ] ),
     1486                                                        h( 'p', null, sprintf( /* translators: %s: inspected database rows */ __( '%s stored rows checked. Checks are bounded and are not an atomic snapshot. Theme/PHP code, custom tables, network options, caches and external usage may remain unchecked. No files were moved.', 'rapid-media-reclaim' ), num( review.coverage.rows ) ) ),
     1487                                                        ...review.coverage.hits.map( ( hit ) => h( 'p', null, hit.source_type + ' #' + hit.source_id + ' · ' + hit.field + ' · ' + hit.match ) ),
     1488                                                        review.coverage.hits_limit ? h( 'p', null, __( 'Additional matches were found; only the first 20 are shown.', 'rapid-media-reclaim' ) ) : null,
     1489                                                        review.coverage.gaps.length ? h( 'p', null, __( 'Coverage limits:', 'rapid-media-reclaim' ) + ' ' + review.coverage.gaps.join( ', ' ) ) : null,
     1490                                                        review.storage.audit_only ? h( 'p', null, __( 'Storage or indexing restrictions also block cleanup.', 'rapid-media-reclaim' ) ) : null
     1491                                                );
     1492                                        } catch ( error ) { detail.textContent = taskError( error ); }
     1493                                        finally { fileReviewBusy = false; check.disabled = false; }
     1494                                }
     1495                        }, __( 'Check current ownership and references', 'rapid-media-reclaim' ) );
     1496                        const prepare = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary smc-btn--sm', disabled: check.disabled, onClick: () => fileWork( async () => { showFile( await api.post( '/tools/files/prepare', { audit: job.token, row: saved.result_id } ) ); fileSection.scrollIntoView( { block: 'start', behavior: 'smooth' } ); } ) }, __( 'Prepare standalone recovery backup', 'rapid-media-reclaim' ) );
     1497                        return h( 'li', { class: 'smc-audit-result' },
     1498                                row.path + ' · ' + bytes( row.bytes ) + ' · ' + ( labels[ row.status ] || __( 'Review required', 'rapid-media-reclaim' ) ) + ( row.owners && row.owners.length ? ' · #' + row.owners.join( ', #' ) : '' ),
     1499                                row.unregistered_size ? h( 'p', null, __( 'An unregistered size is still owned. Do not delete it based on its size name.', 'rapid-media-reclaim' ) ) : null,
     1500                                check, prepare, detail
     1501                        );
     1502                };
     1503                const showUploadResults = async ( job ) => {
     1504                        const labels = { all: __( 'All categories', 'rapid-media-reclaim' ), indexed_original: __( 'Indexed original', 'rapid-media-reclaim' ), indexed_derivative: __( 'Indexed derivative', 'rapid-media-reclaim' ), indexed_shared: __( 'Indexed shared path', 'rapid-media-reclaim' ), possible_derivative_review: __( 'Possible old derivative — review', 'rapid-media-reclaim' ), unindexed_review: __( 'No indexed owner — review', 'rapid-media-reclaim' ), ownership_unavailable: __( 'Ownership unavailable', 'rapid-media-reclaim' ) };
     1505                        const category = h( 'select', { class: 'smc-select', 'aria-label': __( 'Ownership category', 'rapid-media-reclaim' ) }, ...Object.entries( labels ).map( ( [ value, label ] ) => h( 'option', { value }, label ) ) );
     1506                        const extension = h( 'input', { type: 'text', class: 'smc-input', maxLength: 12, placeholder: __( 'Extension, e.g. jpg', 'rapid-media-reclaim' ), 'aria-label': __( 'File extension', 'rapid-media-reclaim' ) } );
     1507                        const minimum = h( 'input', { type: 'number', class: 'smc-input', min: 0, max: 2147483647, value: 0, 'aria-label': __( 'Minimum file bytes', 'rapid-media-reclaim' ) } );
     1508                        const list = h( 'ul' ); const note = h( 'p', { role: 'status', 'aria-live': 'polite' } );
     1509                        const csv = h( 'a', { class: 'smc-btn smc-btn--secondary' }, __( 'Download filtered audit CSV', 'rapid-media-reclaim' ) );
     1510                        let after = 0; let busy = false;
     1511                        const page = async ( reset = false ) => {
     1512                                if ( busy || ! active || ! list.isConnected ) { return; }
     1513                                busy = true; apply.disabled = true; next.disabled = true;
     1514                                try {
     1515                                        const result = await api.get( '/tools/discover-results', { token: job.token, after: reset ? 0 : after, status: category.value, extension: extension.value.trim().toLowerCase(), min_bytes: minimum.value } );
     1516                                        if ( ! active || ! list.isConnected ) { return; }
     1517                                        after = result.next; next.hidden = ! result.has_more;
     1518                                        csv.href = safeHref( result.csv_url );
     1519                                        note.textContent = result.snapshot_current ? __( 'Ownership comes from the saved index generation, not a live usage check. No indexed owner does not mean unused. Each page examines at most 100 saved rows; filtered pages can be empty.', 'rapid-media-reclaim' ) : __( 'The index changed or was unavailable. These ownership hints are stale; start a new scan and audit before reviewing them.', 'rapid-media-reclaim' );
     1520                                        replace( list, ...result.rows.map( ( saved ) => uploadReviewRow( job, saved, labels ) ) );
     1521                                        if ( ! result.rows.length ) { list.appendChild( h( 'li', null, __( 'No matching files in this page. Continue if more rows are available.', 'rapid-media-reclaim' ) ) ); }
     1522                                } catch ( error ) { note.textContent = taskError( error ); }
     1523                                finally { busy = false; apply.disabled = false; next.disabled = false; }
     1524                        };
     1525                        const apply = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: () => page( true ) }, __( 'Apply audit filters', 'rapid-media-reclaim' ) );
     1526                        const next = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: () => page() }, __( 'Next audit page', 'rapid-media-reclaim' ) );
     1527                        replace( output, h( 'h3', null, __( 'Uploads audit — review only', 'rapid-media-reclaim' ) ), h( 'p', null, __( 'This best-effort walk excludes known caches, backups, protected plugin downloads and symlinks. Files may change during the walk. Audit categories never authorize removal. Supported files can begin a separate backup and fresh-review workflow.', 'rapid-media-reclaim' ) ), h( 'div', { class: 'smc-tools__actions' }, category, extension, h( 'label', null, __( 'Minimum bytes', 'rapid-media-reclaim' ), minimum ), apply, csv ), note, list, next );
     1528                        await page( true );
     1529                };
     1530                const visualSelect = h( 'select', { class: 'smc-select', 'aria-label': __( 'Saved visual searches', 'rapid-media-reclaim' ) }, h( 'option', { value: '' }, __( 'Choose a visual search', 'rapid-media-reclaim' ) ) );
     1531                const visualStatus = h( 'p', { role: 'status', 'aria-live': 'polite' } );
     1532                const rememberVisual = ( job ) => {
     1533                        if ( job.kind !== 'similarity' ) { return; }
     1534                        toolJobs.set( 'similarity:' + job.token, job );
     1535                        let option = Array.from( visualSelect.options ).find( ( item ) => item.value === job.token );
     1536                        if ( ! option ) { option = h( 'option', { value: job.token } ); visualSelect.appendChild( option ); }
     1537                        const status = job.status === 'cancelled' ? __( 'Cancelled', 'rapid-media-reclaim' ) : job.status === 'done' ? __( 'Finished', 'rapid-media-reclaim' ) : __( 'Paused or running', 'rapid-media-reclaim' );
     1538                        option.textContent = new Date( job.created * 1000 ).toLocaleString() + ' · ' + status + ' · ' + num( job.processed ); visualSelect.value = job.token;
     1539                };
     1540                const showVisualResults = async ( job ) => {
     1541                        const list = h( 'div' ); const note = h( 'p', { role: 'status', 'aria-live': 'polite' } );
     1542                        const view = h( 'select', { class: 'smc-select', 'aria-label': __( 'Visual results view', 'rapid-media-reclaim' ) }, h( 'option', { value: 'pairs' }, __( 'Review suggestions', 'rapid-media-reclaim' ) ), h( 'option', { value: 'skipped' }, __( 'Skipped images', 'rapid-media-reclaim' ) ) );
     1543                        let after = 0; let busy = false;
     1544                        const page = async ( reset = false ) => {
     1545                                if ( busy || ! active || ! list.isConnected ) { return; }
     1546                                busy = true; next.disabled = true; view.disabled = true;
     1547                                try {
     1548                                        const result = await api.get( '/tools/discover-results', { token: job.token, after: reset ? 0 : after, view: view.value } );
     1549                                        if ( ! active || ! list.isConnected ) { return; }
     1550                                        after = result.next; next.hidden = ! result.has_more;
     1551                                        const coverage = result.job.visual || {};
     1552                                        note.textContent = sprintf( /* translators: 1: checked images, 2: skipped images, 3: suggestions */ __( '%1$s images checked; %2$s skipped; %3$s suggestions saved.', 'rapid-media-reclaim' ), num( result.job.processed ), num( result.job.skipped ), num( coverage.pairs || 0 ) ) + ' ' + ( coverage.complete ? __( 'Search finished within its criteria. Suggestions still need human review.', 'rapid-media-reclaim' ) : __( 'Coverage is partial: the search may be paused, cancelled, skipped images or reached a limit. Matching images may be missing.', 'rapid-media-reclaim' ) );
     1553                                        replace( list, ...result.rows.map( ( saved ) => {
     1554                                                const row = saved.item;
     1555                                                if ( row.type !== 'visual_pair' ) { return h( 'p', null, '#' + row.attachment_id + ' · ' + __( 'This image could not be compared within the local permissions, format or resource limits.', 'rapid-media-reclaim' ), h( 'small', null, ' (' + row.reason + ')' ) ); }
     1556                                                const member = ( item ) => h( 'div', null, item.preview_url ? h( 'img', { src: safeHref( item.preview_url ), alt: item.path, loading: 'lazy', width: 120, height: 90, style: 'object-fit:contain;max-width:100%;' } ) : null, h( 'p', null, h( 'a', { href: safeHref( item.edit_url ), target: '_blank', rel: 'noopener noreferrer' }, '#' + item.id + ' · ' + item.path ) ) );
     1557                                                return h( 'section', { class: 'smc-recovery' }, h( 'div', { class: 'smc-tools__actions' }, member( row.first ), member( row.second ) ), h( 'p', null, sprintf( /* translators: %s: difference score out of 64 */ __( 'Visual difference score: %s / 64. Lower scores suggest closer appearance, not identical files.', 'rapid-media-reclaim' ), num( row.distance.hamming ) ) ) );
     1558                                        } ) );
     1559                                        if ( ! result.rows.length ) { list.appendChild( h( 'p', null, __( 'No results in this page. This does not establish that any media is unused.', 'rapid-media-reclaim' ) ) ); }
     1560                                } catch ( error ) { note.textContent = taskError( error ); }
     1561                                finally { busy = false; next.disabled = false; view.disabled = false; }
     1562                        };
     1563                        view.addEventListener( 'change', () => page( true ) );
     1564                        const next = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: () => page() }, __( 'Next visual results page', 'rapid-media-reclaim' ) );
     1565                        replace( output, h( 'h3', null, __( 'Visually similar images — review only', 'rapid-media-reclaim' ) ), h( 'p', null, __( 'These are captured visual suggestions, not exact duplicates. Re-encoded or resized images can differ in quality and metadata. Media may change during or after the search. Review originals before acting; visual suggestions never authorize merging or deletion.', 'rapid-media-reclaim' ) ), view, note, list, next );
     1566                        await page( true );
     1567                };
     1568                let discoveryBusy = false;
     1569                const discover = async ( kind, fresh = false ) => {
     1570                        if ( discoveryBusy ) { throw new Error( __( 'An audit is already running here. Wait, cancel it or close Tools to pause it.', 'rapid-media-reclaim' ) ); }
     1571                        discoveryBusy = true;
     1572                        try {
     1573                        let job = ( ! fresh && ( kind === 'uploads' ? toolJobs.get( 'uploads:' + uploadSelect.value ) : kind === 'similarity' ? toolJobs.get( 'similarity:' + visualSelect.value ) : toolJobs.get( kind ) ) ) || await api.post( '/tools/discover', { kind } );
     1574                        if ( kind === 'uploads' ) { rememberUpload( job ); }
     1575                        if ( kind === 'similarity' ) { rememberVisual( job ); }
     1576                        toolJobs.set( kind, job );
     1577                        while ( active && job.status === 'running' ) {
     1578                                if ( kind === 'similarity' ) { progress.textContent = sprintf( /* translators: 1: images checked, 2: signatures compared */ __( 'Local visual search: %1$s images checked; %2$s signatures compared. Closing pauses this task.', 'rapid-media-reclaim' ), num( job.processed ), num( ( job.visual || {} ).compared || 0 ) ); } else { progress.textContent = sprintf( /* translators: %s: processed file count */ __( 'Read-only discovery: %s files checked. Closing pauses this task.', 'rapid-media-reclaim' ), num( job.processed ) ); }
     1579                                job = await api.post( '/tools/discover-step', { token: job.token } );
     1580                                toolJobs.set( kind, job );
     1581                                if ( kind === 'uploads' ) { rememberUpload( job ); }
     1582                        if ( kind === 'similarity' ) { rememberVisual( job ); }
     1583                        }
     1584                        if ( ! active ) { return; }
     1585                        if ( kind === 'similarity' ) { visualStatus.textContent = __( 'Visual search saved. Review suggestions and coverage below.', 'rapid-media-reclaim' ); progress.textContent = visualStatus.textContent; await showVisualResults( job ); return; }
     1586                        if ( kind === 'uploads' ) { uploadStatus.textContent = sprintf( /* translators: 1: files, 2: skipped entries */ __( 'Audit saved: %1$s files; %2$s skipped entries. Results expire after 24 hours.', 'rapid-media-reclaim' ), num( job.processed ), num( job.skipped || 0 ) ); progress.textContent = uploadStatus.textContent; await showUploadResults( job ); return; }
     1587                        const result = await api.get( '/tools/discover-results', { token: job.token } );
     1588                        const rows = result.rows || [];
     1589                        progress.textContent = sprintf( /* translators: 1: processed files, 2: skipped entries */ __( 'Checked %1$s files; %2$s entries skipped. Results are for review only. Showing the first 100 rows.', 'rapid-media-reclaim' ), num( job.processed ), num( job.skipped || 0 ) );
     1590                        const lines = rows.map( ( row ) => h( 'li', null, ( row.item.path || '#' + row.item.attachment_id ) + ' — ' + ( row.item.reason || row.item.sha256 || __( 'Ownership review required', 'rapid-media-reclaim' ) ) ) );
     1591                        replace( output, h( 'p', null, sprintf( /* translators: %s: number of duplicate groups */ __( 'Exact duplicate groups found: %s. Shared attachment paths count as one file.', 'rapid-media-reclaim' ), num( ( result.duplicate_groups || [] ).length ) ) ), h( 'ul', null, ...lines ) );
     1592                        } finally { discoveryBusy = false; }
     1593                };
     1594                run( __( 'Find exact duplicates', 'rapid-media-reclaim' ), () => discover( 'duplicates' ) );
     1595                run( __( 'Find visually similar images', 'rapid-media-reclaim' ), () => discover( 'similarity', true ) );
     1596                run( __( 'Compare selected images', 'rapid-media-reclaim' ), async () => {
     1597                        const ids = Array.from( state.selection.keys() );
     1598                        if ( ! ids.length || ids.length > 10 ) { throw new Error( __( 'Select up to ten images before opening Tools.', 'rapid-media-reclaim' ) ); }
     1599                        const result = await api.post( '/tools/visual', { ids } );
     1600                        progress.textContent = __( 'Visual signatures are suggestions only. They never authorize a merge.', 'rapid-media-reclaim' );
     1601                        replace( output, h( 'pre', null, JSON.stringify( result.rows, null, 2 ) ) );
     1602                } );
     1603                run( __( 'Preview selected reference merge', 'rapid-media-reclaim' ), async () => {
     1604                        const ids = Array.from( state.selection.keys() );
     1605                        if ( ids.length < 2 || ids.length > 11 ) { throw new Error( __( 'Select a canonical attachment and up to ten exact duplicates first.', 'rapid-media-reclaim' ) ); }
     1606                        const canonicalInput = h( 'select', { class: 'smc-select' }, ...ids.map( ( id ) => { const item = state.list && state.list.items && state.list.items.find( ( item ) => item.id === id ); return h( 'option', { value: String( id ) }, '#' + id + ( item ? ' · ' + displayName( item ) : '' ) ); } ) );
     1607                        const chosen = await SMC.dialog( { title: __( 'Choose the attachment to keep', 'rapid-media-reclaim' ), body: h( 'div', null, h( 'p', null, __( 'This rewrites supported references only. Original attachments and files are retained. Unsupported sources block the operation; generated builder caches and retirement require separate review.', 'rapid-media-reclaim' ) ), canonicalInput ), buttons: [ { label: __( 'Build read-only preview', 'rapid-media-reclaim' ), value: 'preview', variant: 'primary' } ] } );
     1608                        if ( ! chosen ) { return; }
     1609                        const canonical = Number( canonicalInput.value );
     1610                        const retired = ids.filter( ( id ) => id !== canonical );
     1611                        const preview = await api.post( '/tools/merge-preview', { canonical, retired } );
     1612                        const blocked = preview.blocked || [];
     1613                        progress.textContent = sprintf( /* translators: 1: supported source writes, 2: unsupported references */ __( 'Preview: %1$s supported source writes, %2$s unsupported references. No files will be removed.', 'rapid-media-reclaim' ), num( preview.writes.length ), num( blocked.length ) );
     1614                        const lines = preview.writes.map( ( write ) => h( 'li', null, h( 'details', null, h( 'summary', null, '#' + write.id + ' · ' + write.kind + ( write.key ? ' · ' + write.key : '' ) ), h( 'p', null, __( 'Before', 'rapid-media-reclaim' ) ), h( 'pre', null, typeof write.before === 'string' ? write.before : JSON.stringify( write.before, null, 2 ) ), h( 'p', null, __( 'After', 'rapid-media-reclaim' ) ), h( 'pre', null, typeof write.after === 'string' ? write.after : JSON.stringify( write.after, null, 2 ) ) ) ) );
     1615                        if ( blocked.length || ! lines.length ) { replace( output, h( 'ul', null, ...lines ), h( 'p', null, __( 'The operation is blocked. Unsupported or missing writers must be resolved before any changes.', 'rapid-media-reclaim' ) ) ); return; }
     1616                        const confirmed = await SMC.dialog( { title: __( 'Apply these reference changes?', 'rapid-media-reclaim' ), body: h( 'div', null, h( 'ul', null, ...lines ), h( 'p', null, __( 'A recovery journal retains the original source values. Later editor changes are preserved as conflicts during rollback. The original files stay in place.', 'rapid-media-reclaim' ) ) ), confirmCheck: __( 'I reviewed the canonical attachment and these source changes.', 'rapid-media-reclaim' ), buttons: [ { label: __( 'Apply reference changes', 'rapid-media-reclaim' ), value: 'apply', variant: 'primary' } ] } );
     1617                        if ( ! confirmed ) { return; }
     1618                        let job = await api.post( '/tools/merge-start', { canonical, retired, digest: preview.digest } );
     1619                        rememberMerge( job );
     1620                        while ( active && job.status === 'applying' ) { job = await api.post( '/tools/merge-step', { token: job.token } ); rememberMerge( job ); progress.textContent = sprintf( /* translators: 1: completed source writes, 2: total source writes */ __( 'Reference changes: %1$s of %2$s sources.', 'rapid-media-reclaim' ), num( job.cursor ), num( job.sources ) ); }
     1621                        replace( output, h( 'p', null, __( 'Reference job saved. Original files are retained. Roll back from Tools if needed; complete a fresh scan and cache review before considering retirement.', 'rapid-media-reclaim' ) ) );
     1622                } );
     1623                run( __( 'Roll back last reference merge', 'rapid-media-reclaim' ), async () => {
     1624                        let job = toolJobs.get( 'merge' );
     1625                        if ( ! job && ! mergeSelect.value ) { throw new Error( __( 'There is no reference job to roll back.', 'rapid-media-reclaim' ) ); }
     1626                        if ( mergeSelect.value ) { job = { token: mergeSelect.value }; }
     1627                        const confirmed = await SMC.dialog( { title: __( 'Roll back reference changes?', 'rapid-media-reclaim' ), body: h( 'p', null, __( 'Only sources that still match the saved written values can be restored. Later editor changes will be preserved and reported as conflicts.', 'rapid-media-reclaim' ) ), buttons: [ { label: __( 'Roll back', 'rapid-media-reclaim' ), value: 'rollback', variant: 'primary' } ] } );
     1628                        if ( ! confirmed ) { return; }
     1629                        do { job = await api.post( '/tools/merge-rollback', { token: job.token } ); rememberMerge( job ); } while ( active && job.status === 'rolling_back' );
     1630                        progress.textContent = __( 'Reference rollback saved. Quarantined duplicates were restored first; later editor changes remain protected.', 'rapid-media-reclaim' );
     1631                        await api.get( '/summary' ).then( ( data ) => applySummary( data.summary ) ).catch( () => {} );
     1632                        invalidate();
     1633                } );
     1634
     1635                run( __( 'Regenerate merge caches', 'rapid-media-reclaim' ), async () => {
     1636                        let job = toolJobs.get( 'merge' );
     1637                        if ( mergeSelect.value ) { job = { token: mergeSelect.value }; }
     1638                        if ( ! job ) { throw new Error( __( 'Select a completed reference job first.', 'rapid-media-reclaim' ) ); }
     1639                        job = await api.post( '/tools/merge-cache-start', { token: job.token } );
     1640                        rememberMerge( job );
     1641                        while ( active && job.cache.status === 'running' ) {
     1642                                job = await api.post( '/tools/merge-cache-step', { token: job.token } );
     1643                                rememberMerge( job );
     1644                                progress.textContent = sprintf( /* translators: 1: attempted posts, 2: affected posts */ __( 'Cache generation: %1$s of %2$s posts.', 'rapid-media-reclaim' ), num( job.cache.cursor ), num( job.cache.tasks.length ) );
     1645                        }
     1646                        replace( output, h( 'p', null, job.cache.status === 'not_required' ? __( 'This reference job has no builder caches to regenerate. Original files remain protected.', 'rapid-media-reclaim' ) : job.cache.status === 'regenerated' ? __( 'Supported cache assets regenerated. Review the public pages and run a fresh scan. Original files remain protected. Duplicate quarantine requires a separate saved-backup confirmation.', 'rapid-media-reclaim' ) : __( 'Some caches need manual review. You can retry after resolving the builder or source issue. Reference changes and recovery journals are retained.', 'rapid-media-reclaim' ) ) );
     1647                } );
     1648
     1649                const retirementJob = () => {
     1650                        const job = mergeSelect.value ? { token: mergeSelect.value } : toolJobs.get( 'merge' );
     1651                        if ( ! job ) { throw new Error( __( 'Select a completed reference job first.', 'rapid-media-reclaim' ) ); }
     1652                        return job;
     1653                };
     1654                run( __( 'Prepare duplicate quarantine and rescan', 'rapid-media-reclaim' ), async () => {
     1655                        const job = retirementJob();
     1656                        await api.post( '/tools/merge-retire-prepare', { token: job.token } );
     1657                        progress.textContent = __( 'Preparing a fresh usage scan. No files are being moved.', 'rapid-media-reclaim' );
     1658                        await SMC.sleep( 1100 );
     1659                        if ( ! active ) { return; }
     1660                        let res = await api.post( '/scan' );
     1661                        while ( active && res.scan.status === 'running' ) {
     1662                                res = await api.post( '/scan/step' );
     1663                                progress.textContent = sprintf( /* translators: %s: scan percentage */ __( 'Checking duplicate usage: %s%%.', 'rapid-media-reclaim' ), num( res.scan.percent ) );
     1664                        }
     1665                        state.scan = res.scan;
     1666                        if ( ! active ) { return; }
     1667                        if ( res.scan.status !== 'done' ) { throw new Error( __( 'Complete a fresh scan before backing up duplicates.', 'rapid-media-reclaim' ) ); }
     1668                        invalidate();
     1669                        replace( output, h( 'p', null, __( 'Fresh scan complete. Next use “Back up merged duplicates”, download the ZIP and review the published pages and relevant caches before confirming quarantine.', 'rapid-media-reclaim' ) ) );
     1670                } );
     1671                run( __( 'Back up merged duplicates', 'rapid-media-reclaim' ), async () => {
     1672                        const job = retirementJob();
     1673                        const prepared = await api.post( '/tools/merge-retire-backup', { token: job.token } );
     1674                        let backup = prepared.export;
     1675                        while ( active && backup.status !== 'ready' ) {
     1676                                progress.textContent = sprintf( /* translators: 1: completed files, 2: total files */ __( 'Building duplicate backup: %1$s of %2$s files.', 'rapid-media-reclaim' ), num( backup.completed ), num( backup.total ) );
     1677                                backup = await api.post( '/tools/export-step', { token: backup.token } );
     1678                        }
     1679                        if ( ! active ) { return; }
     1680                        const saved = h( 'input', { type: 'checkbox' } );
     1681                        const reviewed = h( 'input', { type: 'checkbox' } );
     1682                        const move = h( 'button', { type: 'button', class: 'smc-btn smc-btn--primary', disabled: true, onClick: async () => {
     1683                                move.disabled = true;
     1684                                try {
     1685                                        await api.post( '/tools/export-confirm', { token: backup.token, saved_backup: true } );
     1686                                        const confirmed = await SMC.dialog( { title: __( 'Quarantine merged duplicates?', 'rapid-media-reclaim' ), body: h( 'p', null, __( 'Only this job’s duplicate files will move to protected quarantine. The canonical media stays live. Rollback restores these files before restoring references. Permanent deletion remains blocked by the recovery journal.', 'rapid-media-reclaim' ) ), buttons: [ { label: __( 'Move duplicates to quarantine', 'rapid-media-reclaim' ), value: 'quarantine', variant: 'primary' } ] } );
     1687                                        if ( ! confirmed ) { return; }
     1688                                        const result = await api.post( '/tools/merge-retire', { token: job.token, confirmed: true } );
     1689                                        progress.textContent = result.status === 'quarantined' ? __( 'Duplicates moved to quarantine. Use reference rollback to restore files before restoring their references. No media was permanently deleted.', 'rapid-media-reclaim' ) : __( 'Quarantine needs recovery review. Files were restored where possible and the journal was retained. Use reference rollback to resolve the operation.', 'rapid-media-reclaim' );
     1690                                        await api.get( '/summary' ).then( ( data ) => applySummary( data.summary ) ).catch( () => {} );
     1691                                        invalidate();
     1692                                        replace( output, h( 'p', null, progress.textContent ) );
     1693                                } catch ( error ) { progress.textContent = taskError( error ); }
     1694                                finally { move.disabled = ! saved.checked || ! reviewed.checked; }
     1695                        } }, __( 'Confirm backup and quarantine duplicates', 'rapid-media-reclaim' ) );
     1696                        const enable = () => { move.disabled = ! saved.checked || ! reviewed.checked; };
     1697                        saved.addEventListener( 'change', enable ); reviewed.addEventListener( 'change', enable );
     1698                        progress.textContent = __( 'Backup verified. Download and save it before confirming; an archive left on this server expires after 24 hours.', 'rapid-media-reclaim' );
     1699                        replace( output, h( 'a', { class: 'smc-btn smc-btn--secondary', href: safeHref( backup.download_url ), target: '_blank', rel: 'noopener noreferrer' }, __( 'Download duplicate recovery ZIP', 'rapid-media-reclaim' ) ), h( 'p', null, h( 'label', null, saved, ' ', __( 'I downloaded and saved this recovery backup.', 'rapid-media-reclaim' ) ) ), h( 'p', null, h( 'label', null, reviewed, ' ', __( 'I reviewed the published pages and cleared relevant page and CDN caches.', 'rapid-media-reclaim' ) ) ), move );
     1700                } );
     1701
     1702                run( __( 'Start a new uploads audit', 'rapid-media-reclaim' ), () => discover( 'uploads', true ) );
     1703                const resumeUpload = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: async () => { if ( ! uploadSelect.value ) { return; } resumeUpload.disabled = true; try { await discover( 'uploads' ); } catch ( error ) { uploadStatus.textContent = taskError( error ); } finally { resumeUpload.disabled = false; } } }, __( 'Resume or browse audit', 'rapid-media-reclaim' ) );
     1704                const cancelUpload = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: async () => { if ( ! uploadSelect.value ) { return; } cancelUpload.disabled = true; try { const job = await api.post( '/tools/discover-cancel', { token: uploadSelect.value } ); rememberUpload( job ); toolJobs.set( 'uploads', job ); uploadStatus.textContent = __( 'Audit stopped. Saved results remain available until expiry. No media files changed.', 'rapid-media-reclaim' ); } catch ( error ) { uploadStatus.textContent = taskError( error ); } finally { cancelUpload.disabled = false; } } }, __( 'Cancel selected audit', 'rapid-media-reclaim' ) );
     1705                const resumeVisual = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: async () => { if ( ! visualSelect.value ) { return; } resumeVisual.disabled = true; try { await discover( 'similarity' ); } catch ( error ) { visualStatus.textContent = taskError( error ); } finally { resumeVisual.disabled = false; } } }, __( 'Resume or browse visual search', 'rapid-media-reclaim' ) );
     1706                const cancelVisual = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: async () => { if ( ! visualSelect.value ) { return; } cancelVisual.disabled = true; try { rememberVisual( await api.post( '/tools/discover-cancel', { token: visualSelect.value } ) ); visualStatus.textContent = __( 'Visual search stopped. Saved suggestions remain available until expiry. No media was changed.', 'rapid-media-reclaim' ); } catch ( error ) { visualStatus.textContent = taskError( error ); } finally { cancelVisual.disabled = false; } } }, __( 'Cancel selected visual search', 'rapid-media-reclaim' ) );
     1707                const visualJobs = h( 'section', { class: 'smc-recovery' }, h( 'h3', null, __( 'Saved visual searches', 'rapid-media-reclaim' ) ), h( 'div', { class: 'smc-tools__actions' }, visualSelect, resumeVisual, cancelVisual ), visualStatus );
     1708                const uploads = h( 'section', { class: 'smc-recovery' }, h( 'h3', null, __( 'Saved uploads audits', 'rapid-media-reclaim' ) ), h( 'div', { class: 'smc-tools__actions' }, uploadSelect, resumeUpload, cancelUpload ), uploadStatus );
     1709                api.get( '/tools/discover-jobs' ).then( ( result ) => { if ( ! active ) { return; } result.jobs.slice().reverse().forEach( ( job ) => { rememberUpload( job ); rememberVisual( job ); } ); if ( result.limited ) { uploadStatus.textContent = visualStatus.textContent = __( 'Only recent jobs are listed. Saved task tokens still work in WP-CLI until expiry.', 'rapid-media-reclaim' ); } } ).catch( ( error ) => { uploadStatus.textContent = taskError( error ); } );
     1710                run( __( 'Test request routing', 'rapid-media-reclaim' ), async () => {
     1711                        progress.textContent = __( 'Testing one missing-upload route…', 'rapid-media-reclaim' );
     1712                        const result = await api.post( '/tools/probe', {} );
     1713                        showObservation( result );
     1714                        progress.textContent = result.mode === 'verified-PHP' ? __( 'Routing check succeeded. The verification period is separate from quarantine age.', 'rapid-media-reclaim' ) : __( 'Routing was not verified. Review the status and hosting examples.', 'rapid-media-reclaim' );
     1715                } );
     1716                run( __( 'Export selected quarantine', 'rapid-media-reclaim' ), async () => {
     1717                        const ids = Array.from( state.selection ).filter( ( entry ) => entry[1].status === 'quarantined' ).map( ( entry ) => entry[0] );
     1718                        if ( ! ids.length || ids.length > 100 ) { throw new Error( __( 'Select between 1 and 100 quarantined media items, including their shared copies, before opening Tools.', 'rapid-media-reclaim' ) ); }
     1719                        const selectionKey = 'export:' + ids.slice().sort( ( a, b ) => a - b ).join( ',' );
     1720                        exportJob = toolJobs.get( selectionKey ) || await api.post( '/tools/export', { ids } );
     1721                        toolJobs.set( selectionKey, exportJob );
     1722                        while ( active && exportJob.status !== 'ready' ) {
     1723                                progress.textContent = sprintf( /* translators: 1: export phase, 2: completed files, 3: total files */ __( 'Recovery export: %1$s, %2$s of %3$s files. Closing pauses this task.', 'rapid-media-reclaim' ), exportJob.status, num( exportJob.completed ), num( exportJob.total ) );
     1724                                exportJob = await api.post( '/tools/export-step', { token: exportJob.token } );
     1725                                toolJobs.set( selectionKey, exportJob );
     1726                        }
     1727                        if ( ! active ) { return; }
     1728                        progress.textContent = __( 'Archive checksums verified. Download it and confirm you have saved the backup. The private download expires in 24 hours.', 'rapid-media-reclaim' );
     1729                        const link = h( 'a', { class: 'smc-btn smc-btn--primary', href: safeHref( exportJob.download_url ), target: '_blank', rel: 'noopener noreferrer' }, __( 'Download recovery ZIP', 'rapid-media-reclaim' ) );
     1730                        const saved = h( 'input', { type: 'checkbox' } );
     1731                        const confirm = h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', disabled: true, onClick: async () => {
     1732                                try {
     1733                                        await api.post( '/tools/export-confirm', { token: exportJob.token, saved_backup: true } );
     1734                                        progress.textContent = __( 'Saved backup confirmed. The minimum waiting period and all usage checks still apply.', 'rapid-media-reclaim' );
     1735                                        confirm.disabled = true;
     1736                                } catch ( error ) { progress.textContent = error.message; }
     1737                        } }, __( 'Confirm saved backup', 'rapid-media-reclaim' ) );
     1738                        saved.addEventListener( 'change', () => { confirm.disabled = ! saved.checked; } );
     1739                        replace( output, link, h( 'p', null, h( 'label', null, saved, ' ', __( 'I downloaded and saved this recovery backup.', 'rapid-media-reclaim' ) ) ), confirm );
     1740                } );
     1741                const importSelect = h( 'select', { class: 'smc-select', 'aria-label': __( 'Saved backup recovery', 'rapid-media-reclaim' ) } );
     1742                const archiveInput = h( 'input', { type: 'file', accept: '.zip,application/zip', 'aria-label': __( 'Recovery ZIP', 'rapid-media-reclaim' ) } );
     1743                const recoveryOutput = h( 'div', { class: 'smc-recovery__preview' } );
     1744                const recoveryProgress = h( 'p', { role: 'status', 'aria-live': 'polite' } );
     1745                const phases = {
     1746                        verifying: __( 'Verifying files', 'rapid-media-reclaim' ),
     1747                        attachments: __( 'Recovering attachment records', 'rapid-media-reclaim' ),
     1748                        registering: __( 'Saving recovery records', 'rapid-media-reclaim' ),
     1749                        copying: __( 'Preparing verified files', 'rapid-media-reclaim' ),
     1750                        restoring: __( 'Restoring media', 'rapid-media-reclaim' ),
     1751                };
     1752                const rememberImport = ( job ) => {
     1753                        toolJobs.set( 'import:' + job.token, job );
     1754                        let option = Array.from( importSelect.options ).find( ( entry ) => entry.value === job.token );
     1755                        if ( ! option ) { option = h( 'option', { value: job.token } ); importSelect.appendChild( option ); }
     1756                        const labels = { verifying: __( 'Verification paused', 'rapid-media-reclaim' ), preview: __( 'Ready to preview', 'rapid-media-reclaim' ), restoring: __( 'Recovery paused', 'rapid-media-reclaim' ), done: __( 'Recovery complete', 'rapid-media-reclaim' ), review: __( 'Manual review needed', 'rapid-media-reclaim' ), rejected: __( 'Unsupported backup', 'rapid-media-reclaim' ), receiving: __( 'Upload incomplete', 'rapid-media-reclaim' ) };
     1757                        option.textContent = sprintf( /* translators: 1: saved recovery number, 2: status, 3: number of media items */ __( 'Backup %1$s · %2$s · %3$s items', 'rapid-media-reclaim' ), num( Array.from( importSelect.options ).indexOf( option ) + 1 ), labels[ job.status ] || __( 'Review needed', 'rapid-media-reclaim' ), num( job.items ) );
     1758                        importSelect.value = job.token;
     1759                };
     1760                const advanceImport = async ( job ) => {
     1761                        rememberImport( job );
     1762                        while ( active && ( job.status === 'verifying' || job.status === 'restoring' ) ) {
     1763                                recoveryProgress.textContent = sprintf( /* translators: 1: recovery phase, 2: completed entries, 3: total entries */ __( '%1$s: %2$s of %3$s. Closing pauses this task; resume here after reloading.', 'rapid-media-reclaim' ), phases[ job.phase ] || phases.verifying, num( job.completed ), num( job.total ) );
     1764                                job = await api.post( '/tools/import-step', { token: job.token } );
     1765                                rememberImport( job );
     1766                        }
     1767                        if ( ! active ) { return; }
     1768                        if ( job.status === 'done' ) {
     1769                                recoveryProgress.textContent = __( 'Recovery complete. Original IDs, file bytes and supported core fields were verified. Existing associations and alt text were preserved; recreated records use verified original contexts. Plugin-specific and taxonomy metadata are not restored. Run a fresh scan.', 'rapid-media-reclaim' );
     1770                                return;
     1771                        }
     1772                        if ( job.status === 'review' ) {
     1773                                if ( job.review_reason === 'preparation' ) { recoveryProgress.textContent = __( 'Recovery preparation needs manual review after an interruption. Your backup and existing media are preserved. Ask your site administrator to review this recovery before continuing.', 'rapid-media-reclaim' ); return; }
     1774                                recoveryProgress.textContent = sprintf( /* translators: %s: unexpected attachment ID */ __( 'An attachment ID was taken during recovery. Review attachment #%s with your site administrator. Files and recovery records were retained.', 'rapid-media-reclaim' ), num( job.review_id ) );
     1775                                return;
     1776                        }
     1777                        if ( job.status !== 'preview' ) { throw new Error( __( 'This upload cannot be restored. Upload a complete supported backup.', 'rapid-media-reclaim' ) ); }
     1778                        const preview = await api.post( '/tools/import-preview', { token: job.token } );
     1779                        const stateLabels = { missing: __( 'Will restore', 'rapid-media-reclaim' ), identical: __( 'Identical file already present', 'rapid-media-reclaim' ), conflict: __( 'Conflict: current file will be kept', 'rapid-media-reclaim' ) };
     1780                        const items = preview.items.map( ( item ) => h( 'li', null, h( 'strong', null, item.title || '#' + item.id ), h( 'p', null, '#' + item.id + ' · ' + item.file + ' · ' + item.mime ), h( 'p', null, item.conflict || ( item.missing ? __( 'Recreate the original attachment ID', 'rapid-media-reclaim' ) : __( 'Repair matching existing attachment', 'rapid-media-reclaim' ) ) ), h( 'p', null, sprintf( /* translators: 1: image width, 2: image height, 3: number of image sizes */ __( 'Metadata: %1$s × %2$s; %3$s sizes.', 'rapid-media-reclaim' ), num( item.width ), num( item.height ), num( item.sizes ) ) ), h( 'p', null, sprintf( /* translators: %s: number of saved edit backups */ __( 'Saved edit backups: %s.', 'rapid-media-reclaim' ), num( item.backups ) ) ), item.owner_id ? h( 'p', null, sprintf( /* translators: %s: shared file owner attachment ID */ __( 'Shared files with attachment #%s.', 'rapid-media-reclaim' ), num( item.owner_id ) ) ) : null ) );
     1781                        const files = preview.files.map( ( file ) => h( 'li', null, file.name + ' · ' + bytes( file.bytes ) + ' · ' + stateLabels[ file.state ] ) );
     1782                        replace( recoveryOutput, h( 'h4', null, __( 'Read-only recovery preview', 'rapid-media-reclaim' ) ), h( 'p', null, __( 'Recovery covers file bytes, core file metadata and supported attachment fields. New backups also preserve original parent, author and alt text for recreated records. Existing records keep their current associations and alt text. Plugin-specific metadata and taxonomies are unsupported. This is not a full site backup.', 'rapid-media-reclaim' ) ), h( 'ul', null, ...items ), h( 'details', null, h( 'summary', null, __( 'Files and current destinations', 'rapid-media-reclaim' ) ), h( 'ul', null, ...files ) ), h( 'ul', { class: 'smc-recovery__conflicts' }, ...preview.conflicts.map( ( conflict ) => h( 'li', null, conflict ) ) ) );
     1783                        recoveryProgress.textContent = preview.conflicts.length ? __( 'Resolve these conflicts, then refresh the preview. Current files and records are preserved.', 'rapid-media-reclaim' ) : __( 'Preview verified. Nothing has been restored yet. Review the files and attachment IDs before confirming.', 'rapid-media-reclaim' );
     1784                        if ( preview.conflicts.length ) { return; }
     1785                        const confirm = h( 'button', { type: 'button', class: 'smc-btn smc-btn--primary', onClick: async () => {
     1786                                confirm.disabled = true;
     1787                                try {
     1788                                        const adoption = h( 'input', { type: 'checkbox' } );
     1789                                        const confirmed = await SMC.dialog( { title: __( 'Restore this trusted backup?', 'rapid-media-reclaim' ), body: h( 'div', null, h( 'p', null, __( 'Only restore a backup you created and trust. Checksums verify file consistency, not its creator. Existing files are never replaced. Recovery keeps the original attachment IDs and does not delete media.', 'rapid-media-reclaim' ) ), preview.adoption_required ? h( 'p', null, h( 'label', null, adoption, ' ', __( 'This is a reinstall of the same site. Adopt the backup identity for this matching site address.', 'rapid-media-reclaim' ) ) ) : null, h( 'p', null, __( 'Files are prepared in protected Quarantine storage. Nginx needs the documented access rules from your host; the ZIP itself remains outside public web storage.', 'rapid-media-reclaim' ) ) ), confirmCheck: __( 'I reviewed this preview and confirm this is my trusted recovery backup.', 'rapid-media-reclaim' ), buttons: [ { label: __( 'Confirm and restore', 'rapid-media-reclaim' ), value: 'restore', variant: 'primary' } ] } );
     1790                                        if ( ! confirmed ) { return; }
     1791                                        if ( preview.adoption_required && ! adoption.checked ) { throw new Error( __( 'Confirm same-site backup identity adoption before restoring.', 'rapid-media-reclaim' ) ); }
     1792                                        const started = await api.post( '/tools/import-confirm', { token: job.token, digest: preview.digest, trusted_backup: true, adopt_site: adoption.checked } );
     1793                                        clear( recoveryOutput );
     1794                                        await advanceImport( started );
     1795                                } catch ( error ) { recoveryProgress.textContent = error.message; }
     1796                                finally { confirm.disabled = false; }
     1797                        } }, __( 'Review and confirm recovery', 'rapid-media-reclaim' ) );
     1798                        recoveryOutput.appendChild( confirm );
     1799                };
     1800                const importAction = ( label, action ) => h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary', onClick: async ( event ) => {
     1801                        const button = event.currentTarget; button.disabled = true;
     1802                        try { await action(); } catch ( error ) { recoveryProgress.textContent = error.message || __( 'Recovery paused. Resolve the problem and resume this saved backup.', 'rapid-media-reclaim' ); }
     1803                        finally { button.disabled = false; }
     1804                } }, label );
     1805                const uploadButton = importAction( __( 'Upload and verify ZIP', 'rapid-media-reclaim' ), async () => {
     1806                        if ( ! archiveInput.files || archiveInput.files.length !== 1 ) { throw new Error( __( 'Choose one recovery ZIP first.', 'rapid-media-reclaim' ) ); }
     1807                        const data = new FormData(); data.append( 'archive', archiveInput.files[ 0 ] );
     1808                        recoveryProgress.textContent = __( 'Uploading to private recovery storage…', 'rapid-media-reclaim' );
     1809                        const job = await wp.apiFetch( { path: ( boot.restPath || '/rapid-media-reclaim/v1' ) + '/tools/import-upload', method: 'POST', body: data } );
     1810                        archiveInput.value = '';
     1811                        await advanceImport( job );
     1812                } );
     1813                const resumeButton = importAction( __( 'Resume or refresh preview', 'rapid-media-reclaim' ), async () => {
     1814                        const job = toolJobs.get( 'import:' + importSelect.value );
     1815                        if ( ! job ) { throw new Error( __( 'Upload a backup or choose a saved recovery first.', 'rapid-media-reclaim' ) ); }
     1816                        await advanceImport( job );
     1817                } );
     1818                const recovery = h( 'section', { class: 'smc-recovery', 'aria-label': __( 'Recover from a backup ZIP', 'rapid-media-reclaim' ) }, h( 'h3', null, __( 'Recover from a backup ZIP', 'rapid-media-reclaim' ) ), h( 'p', null, __( 'Upload → verify → preview → confirm → restore. Idle previews expire after 24 hours. Confirmed recovery remains available after closing or reloading.', 'rapid-media-reclaim' ) ), archiveInput, h( 'div', { class: 'smc-tools__actions' }, uploadButton, importSelect, resumeButton ), recoveryProgress, recoveryOutput );
     1819                api.get( '/tools/import-jobs' ).then( ( jobs ) => { if ( active ) { jobs.slice().reverse().forEach( rememberImport ); } } ).catch( ( error ) => { recoveryProgress.textContent = error.message; } );
     1820
     1821                const modal = SMC.dialog( { returnFocus: '#smc-tools-button', title: __( 'Media tools', 'rapid-media-reclaim' ), body: h( 'div', null, h( 'p', null, __( 'Discovery results never delete or merge files. Request routing verification covers one path; CDN and browser caches remain outside observation.', 'rapid-media-reclaim' ) ), actions, uploads, visualJobs, fileSection, savings, observation, mergeSelect, progress, output, recovery ), cancelLabel: __( 'Close', 'rapid-media-reclaim' ), buttons: [] } );
     1822                api.get( '/tools/status' ).then( ( status ) => {
     1823                        if ( ! active ) { return; }
     1824                        progress.textContent = status.storage.audit_only ? status.storage.reasons.join( ' ' ) : __( 'Local storage available. Advanced mutation features remain subject to recovery checks.', 'rapid-media-reclaim' );
     1825                        showObservation( status.observation );
     1826                        showSavings( status.ledger );
     1827                        if ( status.operations_csv_url ) { savings.appendChild( h( 'a', { class: 'smc-btn smc-btn--secondary', href: safeHref( status.operations_csv_url ) }, __( 'Download operation CSV', 'rapid-media-reclaim' ) ) ); }
     1828                        if ( status.configuration ) {
     1829                                const config = status.configuration;
     1830                                actions.after( h( 'details', null, h( 'summary', null, __( 'Server setup examples (for your hosting administrator)', 'rapid-media-reclaim' ) ), h( 'p', null, config.guidance ), config.nginx ? h( 'pre', null, config.nginx ) : null, config.apache ? h( 'pre', null, config.apache ) : null ) );
     1831                        }
     1832                        ( status.merge_jobs || [] ).slice().reverse().forEach( rememberMerge );
     1833                        if ( status.csv_url ) { actions.appendChild( h( 'a', { class: 'smc-btn smc-btn--secondary', href: safeHref( status.csv_url ) }, __( 'Download inventory CSV', 'rapid-media-reclaim' ) ) ); }
     1834                } ).catch( ( error ) => { progress.textContent = error.message; } );
     1835                await modal;
     1836                active = false;
     1837                clearTimeout( observationTimer );
     1838        }
     1839
    11981840        // Notices (between the header and the summary tiles).
    11991841        // ------------------------------------------------------------------
    … …  
    12251867                const summary = state.summary || {};
    12261868                const last = summary.last_scan;
     1869                if ( summary.storage && summary.storage.audit_only ) {
     1870                        const database = ( summary.last_scan && summary.last_scan.coverage || [] ).find( ( entry ) => entry.id === 'database_adapter' );
     1871                        const examples = database && database.detail && database.detail.examples || [];
     1872                        items.push( notice( {
     1873                                tone: 'warning', title: __( 'Audit-only mode: cleanup is disabled', 'rapid-media-reclaim' ), text: summary.storage.reasons.join( ' ' ),
     1874                                extra: examples.length ? h( 'details', null, h( 'summary', null, __( 'Show affected sources', 'rapid-media-reclaim' ) ), h( 'ul', null, ...examples.map( ( source ) => {
     1875                                        const label = { posts: __( 'Post / page', 'rapid-media-reclaim' ), terms: __( 'Term', 'rapid-media-reclaim' ), users: __( 'User', 'rapid-media-reclaim' ), options: __( 'Setting', 'rapid-media-reclaim' ) }[ source.phase ] || source.phase;
     1876                                        return h( 'li', null, label + ( source.id ? ' #' + source.id : '' ) + ( source.key ? ' · ' + source.key : '' ) );
     1877                                } ) ) ) : null,
     1878                        } ) );
     1879                }
    12271880
    12281881                // Interrupted permanent deletion that can be finished safely.
    … …  
    12321885                                tone: 'error',
    12331886                                title: sprintf( /* translators: %s: number of files */ _n( 'Deleting %s file was interrupted', 'Deleting %s files was interrupted', recoveryIds.length, 'rapid-media-reclaim' ), num( recoveryIds.length ) ),
    1234                                 text: __( 'A permanent delete stopped before it finished. Retry to complete it; nothing else is affected.', 'rapid-media-reclaim' ),
     1887                                text: __( 'A previously authorized permanent deletion stopped before it finished. Routing verification may be incomplete or browser-only. Retry continues that authorization; it does not complete a verified window.', 'rapid-media-reclaim' ),
    12351888                                actions: [ h( 'button', { type: 'button', class: 'smc-btn smc-btn--secondary smc-btn--sm', onClick: async () => {
    12361889                                        try {
    1237                                                 const res = await api.post( '/purge', { ids: recoveryIds, force: true, retry_only: true } );
    1238                                                 applySummary( res.summary );
     1890                                                const res = await runBulk( '/purge', recoveryIds, { force: true, retry_only: true }, 'purged', ( done, total ) => done + ' / ' + total );
     1891                                                if ( res.error ) { throw res.error; }
    12391892                                                SMC.toast( { type: res.failed.length ? 'error' : 'success', message: res.failed.length ? res.failed[0].message : __( 'Interrupted cleanup completed.', 'rapid-media-reclaim' ) } );
    12401893                                        } catch ( error ) {
    … …  
    17022355                }
    17032356                if ( q.purge_ready || ! days ) {
    1704                         return __( 'Ready to delete', 'rapid-media-reclaim' );
     2357                        return __( 'Waiting period met', 'rapid-media-reclaim' );
    17052358                }
    17062359                /* translators: 1: current day, 2: total days, e.g. "Day 3 of 14" */
    … …  
    19182571                }
    19192572                const copy = {
    1920                         unused: [ 'sparkle', __( 'No unused media found', 'rapid-media-reclaim' ), __( 'Your library is clean. Every file is used somewhere or marked Keep.', 'rapid-media-reclaim' ) ],
     2573                        unused: [ 'sparkle', __( 'No unused media found', 'rapid-media-reclaim' ), __( 'Other files may be in use, marked Keep, or in quarantine.', 'rapid-media-reclaim' ) ],
    19212574                        quarantined: [ 'box', __( 'Quarantine is empty', 'rapid-media-reclaim' ), __( 'Files you move to quarantine wait here, ready to restore with one click.', 'rapid-media-reclaim' ) ],
    19222575                        used: [ 'shield', __( 'No files in use yet', 'rapid-media-reclaim' ), __( 'Files that are used on your site appear here with proof of where.', 'rapid-media-reclaim' ) ],
    … …  
    22222875                }
    22232876                writeHash();
     2877                const cached = details.get( id ) || listItem( id );
     2878                if ( cached && cached.status === 'quarantined' ) { details.delete( id ); }
    22242879                renderDrawer();
    22252880                if ( ! wasOpen || ! ( opts && opts.keepFocus ) ) {
    … …  
    22342889                }
    22352890                const id = drawer.id;
     2891                clearTimeout( drawer.observationTimer );
    22362892                drawer.id = null;
    22372893                drawer.token++;
    … …  
    22802936
    22812937        function renderDrawer() {
     2938                clearTimeout( drawer.observationTimer );
    22822939                const id = drawer.id;
    22832940                if ( id === null ) {
    … …  
    23082965
    23092966                const full = detail && ! detail.error ? detail : null;
     2967                if ( full && item.status === 'quarantined' ) {
     2968                        const expires = item.quarantine && item.quarantine.observation && item.quarantine.observation.expires_at || 0;
     2969                        drawer.observationTimer = setTimeout( () => {
     2970                                if ( drawer.id !== id ) { return; }
     2971                                details.delete( id );
     2972                                loadDetail( id );
     2973                        }, expires * 1000 > Date.now() ? Math.max( 1000, Math.min( 60000, expires * 1000 - Date.now() ) ) : 60000 );
     2974                }
     2975
    23102976                replace(
    23112977                        drawer.body,
    … …  
    23252991                replace(
    23262992                        drawer.foot,
    2327                         ACTION_ORDER.filter( ( name ) => ACTIONS[ name ].eligible( selInfo( item ) ) ).map( ( name ) =>
     2993                        ACTION_ORDER.filter( ( name ) => eligibleIds( name, statusEntry ).length ).map( ( name ) =>
    23282994                                h(
    23292995                                        'button',
    … …  
    24113077                                                since ? sprintf( /* translators: %s: date */ __( 'In quarantine since %s.', 'rapid-media-reclaim' ), since ) + ' ' : '',
    24123078                                                q.purge_ready || ! days
    2413                                                         ? __( 'It can be deleted permanently whenever you’re ready.', 'rapid-media-reclaim' )
    2414                                                         : sprintf( /* translators: 1: "Day 3 of 14", 2: date */ __( '%1$s. It can be deleted permanently from %2$s.', 'rapid-media-reclaim' ), quarantineLabel( item ), readyAt )
     3079                                                        ? __( 'The waiting period has passed. A saved recovery backup, usage checks and explicit confirmation are still required.', 'rapid-media-reclaim' )
     3080                                                        : sprintf( /* translators: 1: "Day 3 of 14", 2: date */ __( '%1$s. The waiting period ends on %2$s; all other safety checks still apply.', 'rapid-media-reclaim' ), quarantineLabel( item ), readyAt )
    24153081                                        )
    24163082                                ),
     3083                                h( 'p', { class: 'smc-callout smc-callout--info' }, full && q.observation && q.observation.verified_window_complete && q.observation.expires_at * 1000 > Date.now() ? __( 'At the last check, the verified window was complete with no known interruption in routing verification. This does not prove disuse or grant deletion permission.', 'rapid-media-reclaim' ) : sprintf( /* translators: 1: elapsed routing-check days, 2: required days */ __( 'Verified routing period: %1$s of %2$s days. Incomplete, unknown or paused verification is separate from waiting age. Manual deletion still requires every existing check.', 'rapid-media-reclaim' ), num( Math.floor( ( full && q.observation && q.observation.elapsed_seconds || 0 ) / 86400 ) ), num( days ) ) ),
    24173084                                used
    24183085                                        ? h(
    … …  
    24893156                const recent = Date.now() - Date.parse( full.date ) < 86400000;
    24903157                let text;
    2491                 if ( confidence === 'high' ) {
     3158                const unread = ( full.checked || [] ).some( ( source ) => source.id === 'database_adapter' && source.detail && source.detail.partial );
     3159                if ( full.index_fault || ( state.summary && state.summary.index_fault ) ) {
     3160                        text = __( 'Some usage updates could not be saved. Run a complete scan before relying on this result or cleaning up.', 'rapid-media-reclaim' );
     3161                } else if ( full.index_pending || ( state.summary && state.summary.index_pending ) ) {
     3162                        text = __( 'Usage updates are waiting for background indexing. This result may be stale; cleanup is paused until indexing finishes.', 'rapid-media-reclaim' );
     3163                } else if ( unread ) {
     3164                        text = __( 'Some stored content could not be checked within scan limits. This file may still be in use. Resolve the affected sources and rescan before cleaning up.', 'rapid-media-reclaim' );
     3165                } else if ( confidence === 'high' ) {
    24923166                        text = __( 'No trace of this file was found anywhere we checked.', 'rapid-media-reclaim' );
    24933167                } else if ( confidence === 'low' ) {
    … …  
    25243198                                                'span',
    25253199                                                { class: 'smc-checklist__count' },
    2526                                                 c.detail && Object.prototype.hasOwnProperty.call( c.detail, 'partial' ) ? ( c.detail.partial ? __( 'Checked · some values read as plain data', 'rapid-media-reclaim' ) : __( 'Checked', 'rapid-media-reclaim' ) ) : c.id === 'frontend' && c.detail ? crawlSummary( c.detail ) : c.count
     3200                                                c.id === 'database_adapter' ? __( 'Incomplete · stored values exceeded scan limits', 'rapid-media-reclaim' ) : c.detail && Object.prototype.hasOwnProperty.call( c.detail, 'partial' ) ? ( c.detail.partial ? __( 'Checked · some values read as plain data', 'rapid-media-reclaim' ) : __( 'Checked', 'rapid-media-reclaim' ) ) : c.id === 'frontend' && c.detail ? crawlSummary( c.detail ) : c.count
    25273201                                                        ? sprintf( /* translators: %s: number of items */ _n( 'Not found in %s checked', 'Not found in %s checked', c.count, 'rapid-media-reclaim' ), num( c.count ) )
    25283202                                                        : __( 'Not found', 'rapid-media-reclaim' )
    … …  
    26883362        function openSettings() {
    26893363                const s = state.settings;
    2690                 const days = h( 'input', { type: 'number', class: 'smc-input', id: 'smc-set-days', min: '0', max: '365', step: '1', value: String( s.quarantine_days ), 'aria-describedby': 'smc-set-days-help' } );
     3364                const days = h( 'input', { type: 'number', class: 'smc-input', id: 'smc-set-days', min: '14', max: '365', step: '1', value: String( s.quarantine_days ), 'aria-describedby': 'smc-set-days-help' } );
    26913365                const toggle = ( id, label, help, checked ) => {
    26923366                        const input = h( 'input', { type: 'checkbox', class: 'smc-switch__input', id, checked, 'aria-describedby': id + '-help', role: 'switch' } );
    … …  
    27023376                };
    27033377                const drafts = toggle( 'smc-set-drafts', __( 'Count drafts as use', 'rapid-media-reclaim' ), __( 'Files used only in drafts, private or scheduled posts are treated as in use.', 'rapid-media-reclaim' ), !! s.include_drafts );
     3378                const aliases = h( 'textarea', { class: 'smc-input', rows: '3', maxlength: '20480', id: 'smc-upload-aliases' }, ( s.upload_aliases || [] ).join( '\n' ) );
    27043379                const trash = toggle( 'smc-set-trash', __( 'Count trashed posts as weak evidence', 'rapid-media-reclaim' ), __( 'Files used only in trashed posts get lower confidence instead of high.', 'rapid-media-reclaim' ), !! s.include_trash );
    27053380
    … …  
    27163391                                h( 'label', { class: 'smc-field__label', for: 'smc-set-days' }, __( 'Quarantine period', 'rapid-media-reclaim' ) ),
    27173392                                h( 'div', { class: 'smc-input-group' }, days, h( 'span', null, __( 'days', 'rapid-media-reclaim' ) ) ),
    2718                                 h( 'p', { class: 'smc-field__help', id: 'smc-set-days-help' }, __( 'How long files wait in quarantine before they can be deleted permanently without an extra warning.', 'rapid-media-reclaim' ) )
     3393                                h( 'p', { class: 'smc-field__help', id: 'smc-set-days-help' }, __( 'How long files wait in quarantine before they can be deleted permanently. A verified, saved recovery backup is also required.', 'rapid-media-reclaim' ) )
    27193394                        ),
     3395                        h( 'label', { for: 'smc-upload-aliases' }, __( 'Old or CDN uploads roots (one URL per line, up to 10)', 'rapid-media-reclaim' ) ), aliases,
    27203396                        drafts.el,
    27213397                        trash.el, watch.el, restore.el, crawl.el,
    … …  
    27303406                        onSubmit: async () => {
    27313407                                const value = parseInt( days.value, 10 );
    2732                                 if ( isNaN( value ) || value < 0 || value > 365 ) {
     3408                                if ( isNaN( value ) || value < 14 || value > 365 ) {
    27333409                                        days.focus();
    2734                                         throw { message: __( 'Enter a number of days between 0 and 365.', 'rapid-media-reclaim' ) };
     3410                                        throw { message: __( 'Enter a number of days between 14 and 365.', 'rapid-media-reclaim' ) };
    27353411                                }
    27363412                                const limit = Number( crawlLimit.value );
    27373413                                if ( ! Number.isInteger( limit ) || limit < 1 || limit > 500 ) { crawlLimit.focus(); throw { message: __( 'Enter a page limit between 1 and 500.', 'rapid-media-reclaim' ) }; }
    2738                                 const res = await api.post( '/settings', { quarantine_days: value, include_drafts: drafts.input.checked, include_trash: trash.input.checked, request_watch: watch.input.checked, auto_restore: restore.input.checked, frontend_crawl: crawl.input.checked, crawl_limit: limit } );
     3414                                const res = await api.post( '/settings', { quarantine_days: value, upload_aliases: aliases.value.split( /\r?\n/ ).map( ( value ) => value.trim() ).filter( Boolean ), include_drafts: drafts.input.checked, include_trash: trash.input.checked, request_watch: watch.input.checked, auto_restore: restore.input.checked, frontend_crawl: crawl.input.checked, crawl_limit: limit } );
    27393415                                const daysChanged = res.settings.quarantine_days !== state.settings.quarantine_days;
    27403416                                state.settings = res.settings;
  • rapid-media-reclaim/trunk/assets/js/ui.js

    r3794616 r3814937  
    230230                                el.close();
    231231                                el.remove();
    232                                 if ( previous && previous.isConnected && typeof previous.focus === 'function' ) {
    233                                         previous.focus();
     232                                // Header refreshes may replace the opener while a long tool runs.
     233                                const returnTo = ( opts.returnFocus && document.querySelector( opts.returnFocus ) ) || ( previous && previous.isConnected ? previous : previous && Array.from( document.querySelectorAll( 'button, a, input, select' ) ).find( ( node ) => node.tagName === previous.tagName && node.textContent === previous.textContent && node.getAttribute( 'aria-label' ) === previous.getAttribute( 'aria-label' ) && node.getClientRects().length && ! node.disabled ) );
     234                                if ( returnTo && typeof returnTo.focus === 'function' ) {
     235                                        returnTo.focus();
    234236                                }
    235237                                resolve( value );
  • rapid-media-reclaim/trunk/includes/admin/class-admin.php

    r3794616 r3814937  
    123123
    124124                return array(
    125                         'version'   => SAFE_MEDIA_CLEANER_VERSION,
    126                         'restPath'  => '/' . Controller::NS,
    127                         'locale'    => str_replace( '_', '-', get_user_locale() ),
    128                         'pageUrl'   => self::page_url(),
    129                         'reviewUrl' => 'https://wordpress.org/support/plugin/rapid-media-reclaim/reviews/#new-post',
    130                         'sourceUrl' => 'https://wordpress.org/plugins/rapid-media-reclaim/',
    131                         'maxIds'    => Controller::MAX_IDS,
    132                         'maxSelect' => Controller::MAX_SELECT,
    133                         'summary'   => $payload['summary'],
    134                         'scan'      => $payload['scan'],
    135                         'settings'  => $payload['settings'],
    136                         'initial'   => $initial,
     125                        'version'    => SAFE_MEDIA_CLEANER_VERSION,
     126                        'restPath'   => '/' . Controller::NS,
     127                        'locale'     => str_replace( '_', '-', get_user_locale() ),
     128                        'pageUrl'    => self::page_url(),
     129                        'reviewUrl'  => 'https://wordpress.org/support/plugin/rapid-media-reclaim/reviews/#new-post',
     130                        'sourceUrl'  => 'https://wordpress.org/plugins/rapid-media-reclaim/',
     131                        'maxIds'     => Controller::MAX_IDS,
     132                        'maxFileIds' => Controller::MAX_FILE_IDS,
     133                        'maxSelect'  => Controller::MAX_SELECT,
     134                        'summary'    => $payload['summary'],
     135                        'scan'       => $payload['scan'],
     136                        'settings'   => $payload['settings'],
     137                        'initial'    => $initial,
    137138                );
    138139        }
  • rapid-media-reclaim/trunk/includes/class-index.php

    r3794616 r3814937  
    2929
    3030                $last = get_option( 'safe_media_cleaner_last_scan', null );
    31                 $base = self::base_sql();
     31                $base = self::base_sql( array(), false );
    3232
    3333                // One pass over the library: status, confidence and size per attachment.
    … …  
    3838                        "SELECT s.status, s.confidence, COUNT(*) AS items, COALESCE(SUM(s.bytes), 0) AS bytes
    3939                        FROM ( SELECT {$base['status']} AS status, {$base['confidence']} AS confidence,
    40                                 COALESCE(fb.b, 0) AS bytes, {$base['shared']} AS is_copy
     40                                {$base['bytes']} AS bytes, {$base['shared']} AS is_copy
    4141                                {$base['from']} ) s
    4242                        WHERE s.is_copy = 0
    … …  
    7575                return array(
    7676                        'scanned'                 => self::generation() > 0,
     77                        'storage'                 => Storage::status(),
     78                        'index_pending'           => Deferred_Index::pending(),
     79                        'index_fault'             => (bool) Deferred_Index::fault_token(),
    7780                        'recovery_ids'            => Quarantine::orphan_ids( true ),
    7881                        'unresolved_recovery_ids' => Quarantine::orphan_ids(),
    … …  
    9396
    9497                $args = self::normalize_args( $args );
    95                 $base = self::base_sql();
     98                $base = self::base_sql( $args['ids'], '' !== $args['search'] || 'name' === $args['orderby'] );
    9699
    97100                $where = array();
    … …  
    130133
    131134                $inner = "SELECT p.ID AS id, p.post_title AS title, p.post_mime_type AS mime, p.post_date_gmt AS date,
    132                                 COALESCE(f.meta_value, '') AS file,
    133                                 {$base['status']} AS status, {$base['confidence']} AS confidence, COALESCE(fb.b, 0) AS bytes,
     135                                {$base['file']} AS file,
     136                                {$base['status']} AS status, {$base['confidence']} AS confidence, {$base['bytes']} AS bytes,
    134137                                {$base['shared']} AS is_copy
    135138                                {$base['from']}";
    … …  
    184187                }
    185188
    186                 $item            = $result['items'][0];
    187                 $refs            = self::refs( $id );
    188                 $item['refs']    = $refs['strong'];
    189                 $item['weak']    = $refs['weak'];
    190                 $last            = get_option( 'safe_media_cleaner_last_scan', null );
    191                 $item['checked'] = \SafeMediaCleaner\Scan\Adapter_Coverage::append( is_array( $last ) ? (array) ( $last['coverage'] ?? array() ) : array(), self::generation() );
    192                 $item['files']   = self::files( $id );
     189                $item                  = $result['items'][0];
     190                $refs                  = self::refs( $id );
     191                $item['refs']          = $refs['strong'];
     192                $item['weak']          = $refs['weak'];
     193                $last                  = get_option( 'safe_media_cleaner_last_scan', null );
     194                $item['checked']       = \SafeMediaCleaner\Scan\Adapter_Coverage::append( is_array( $last ) ? (array) ( $last['coverage'] ?? array() ) : array(), self::generation() );
     195                $item['files']         = self::files( $id );
     196                $item['index_pending'] = Deferred_Index::pending();
     197                $item['index_fault']   = (bool) Deferred_Index::fault_token();
    193198
    194199                return $item;
    … …  
    352357         * Evidence and sizes are aggregated once per query in derived tables rather
    353358         * than per row, so listing stays fast on large libraries.
    354          */
    355         private static function base_sql(): array {
     359         *
     360         * @param array $ids Optional attachment scope, applied before aggregation.
     361         * @param bool  $include_file Include filename metadata for search/name ordering.
     362         */
     363        private static function base_sql( array $ids = array(), bool $include_file = true ): array {
    356364                $quarantine_table = Installer::table( 'quarantine' );
    357365                global $wpdb;
    … …  
    360368                $files      = Installer::table( 'files' );
    361369                $generation = self::generation();
     370                $id_list    = implode( ',', array_map( 'absint', $ids ) );
     371                $scope      = $ids ? ' AND attachment_id IN (' . $id_list . ')' : '';
    362372                $new_after  = gmdate( 'Y-m-d H:i:s', time() - self::NEW_UPLOAD_SECONDS );
    363373
    364                 // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table names only.
     374                $file_join = $include_file ? "LEFT JOIN {$wpdb->postmeta} f ON f.post_id=p.ID AND f.meta_key='_wp_attached_file'" : '';
     375                // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table names and internal join fragments only.
    365376                $from = $wpdb->prepare(
    366377                        "FROM {$wpdb->posts} p
    367                         LEFT JOIN {$wpdb->postmeta} f ON f.post_id = p.ID AND f.meta_key = '_wp_attached_file'
    368                         LEFT JOIN {$wpdb->postmeta} k ON k.post_id = p.ID AND k.meta_key = '_safe_media_cleaner_keep'
    369                         LEFT JOIN ( SELECT attachment_id AS post_id, MAX(id) AS meta_value FROM {$quarantine_table} WHERE status = 'quarantined' GROUP BY attachment_id ) q ON q.post_id = p.ID
     378                        {$file_join}
     379                        LEFT JOIN (SELECT DISTINCT post_id,1 AS meta_value FROM {$wpdb->postmeta} WHERE meta_key='_safe_media_cleaner_keep' LIMIT 18446744073709551615) k ON k.post_id=p.ID
     380                        LEFT JOIN ( SELECT attachment_id AS post_id, MAX(id) AS meta_value FROM {$quarantine_table} WHERE status = 'quarantined' {$scope} GROUP BY attachment_id LIMIT 18446744073709551615 ) q ON q.post_id = p.ID
    370381                        LEFT JOIN (
    371382                                SELECT attachment_id,
    … …  
    373384                                        MAX( strength = 'weak' AND match_type IN ('id','url') ) AS weak_ref,
    374385                                        MAX( strength = 'weak' AND match_type = 'filename' ) AS weak_name
    375                                 FROM {$refs} WHERE generation = %d GROUP BY attachment_id
     386                                FROM {$refs} WHERE generation = %d {$scope} GROUP BY attachment_id LIMIT 18446744073709551615
    376387                        ) r ON r.attachment_id = p.ID
    377                         LEFT JOIN ( SELECT attachment_id, SUM(bytes) AS b FROM {$files} WHERE generation = %d GROUP BY attachment_id ) fb ON fb.attachment_id = p.ID",
     388                        LEFT JOIN ( SELECT attachment_id, SUM(bytes) AS b FROM {$files} WHERE generation = %d {$scope} GROUP BY attachment_id LIMIT 18446744073709551615 ) fb ON fb.attachment_id = p.ID",
    378389                        $generation,
    379390                        $generation
    380391                );
     392                // A non-restrictive LIMIT keeps full-library aggregates materialized instead
     393                // of a lateral aggregate lookup for each attachment on MariaDB. Values remain
     394                // live per query; no persistent status cache can outlive an evidence mutation.
     395                $copy_scope = $ids ? ' AND o2.attachment_id IN (' . $id_list . ')' : '';
    381396                // Copies: attachments whose original file also belongs to a lower ID.
    382397                $from .= $wpdb->prepare(
    … …  
    384399                                SELECT DISTINCT o2.attachment_id FROM {$files} o1
    385400                                JOIN {$files} o2 ON o2.path = o1.path AND o2.attachment_id > o1.attachment_id AND o2.generation = %d AND o2.kind = 'original'
    386                                 WHERE o1.generation = %d AND o1.kind = 'original'
     401                                WHERE o1.generation = %d AND o1.kind = 'original' {$copy_scope}
     402                                LIMIT 18446744073709551615
    387403                        ) cp ON cp.attachment_id = p.ID",
    388404                        $generation,
    … …  
    391407                // phpcs:enable
    392408                $from .= " WHERE p.post_type = 'attachment' AND p.post_status IN ('inherit','private','publish')";
     409                if ( $ids ) {
     410                        $from .= ' AND p.ID IN (' . $id_list . ')';
     411                }
    393412
    394413                $status = "CASE
    … …  
    408427                );
    409428
     429                if ( Deferred_Index::pending() || Deferred_Index::fault_token() || get_option( 'safe_media_cleaner_adapter_gap_' . $generation . '_database', false ) ) {
     430                        $confidence = "'low'"; }
     431
    410432                // True when a lower-ID attachment has the same original file (a translation copy).
    411433                $shared = '( cp.attachment_id IS NOT NULL )';
    412434
     435                $bytes = 'COALESCE(fb.b, 0)';
     436                if ( ! $ids && Status_Index::usable( $generation ) ) {
     437                        // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Only internal table identifiers; values are prepared.
     438                        $table  = Installer::table( 'status' );
     439                        $from   = $wpdb->prepare(
     440                                "FROM {$wpdb->posts} p
     441                        {$file_join}
     442                        LEFT JOIN (SELECT DISTINCT post_id,1 AS meta_value FROM {$wpdb->postmeta} WHERE meta_key='_safe_media_cleaner_keep' LIMIT 18446744073709551615) k ON k.post_id=p.ID
     443                        LEFT JOIN (SELECT attachment_id AS post_id,MAX(id) AS meta_value FROM {$quarantine_table} WHERE status='quarantined' GROUP BY attachment_id) q ON q.post_id=p.ID
     444                        LEFT JOIN {$table} r ON r.attachment_id=p.ID AND r.generation=%d
     445                        WHERE p.post_type='attachment' AND p.post_status IN ('inherit','private','publish')",
     446                                $generation
     447                        ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Internal identifiers only, generation prepared.
     448                        $bytes  = 'COALESCE(r.bytes,0)';
     449                        $shared = 'COALESCE(r.is_copy,0)';
     450                }
    413451                return array(
     452                        'file'       => $include_file ? "COALESCE(f.meta_value,'')" : 'NULL',
     453                        'bytes'      => $bytes,
    414454                        'from'       => $from,
    415455                        'status'     => $status,
    … …  
    511551                $ids = array_map( 'intval', wp_list_pluck( $rows, 'id' ) );
    512552                _prime_post_caches( $ids, false, true );
     553                update_meta_cache( 'post', $ids );
    513554                $quarantine = Quarantine::records_for( $ids );
    514555                $counts     = self::ref_counts( $ids );
    … …  
    520561                        $id   = (int) $row['id'];
    521562                        $mime = (string) $row['mime'];
    522                         $file = (string) $row['file'];
     563                        $file = (string) ( $row['file'] ?? get_post_meta( $id, '_wp_attached_file', true ) );
    523564                        $q    = $quarantine[ $id ] ?? null;
    524565
    … …  
    535576                                $age             = max( 0, time() - (int) strtotime( $q['created_at'] . ' UTC' ) );
    536577                                $quarantine_info = array(
    537                                         'id'          => (int) $q['id'],
    538                                         'batch'       => (string) $q['batch'],
    539                                         'since'       => gmdate( 'c', (int) strtotime( $q['created_at'] . ' UTC' ) ),
    540                                         'days'        => (int) floor( $age / DAY_IN_SECONDS ),
    541                                         'purge_ready' => $age >= $days * DAY_IN_SECONDS,
    542                                         'hits'        => (int) $q['hits'],
     578                                        'id'                => (int) $q['id'],
     579                                        'batch'             => (string) $q['batch'],
     580                                        'since'             => gmdate( 'c', (int) strtotime( $q['created_at'] . ' UTC' ) ),
     581                                        'days'              => (int) floor( $age / DAY_IN_SECONDS ),
     582                                        'purge_ready'       => $age >= $days * DAY_IN_SECONDS,
     583                                        'age_wait_complete' => $age >= $days * DAY_IN_SECONDS,
     584                                        'observation'       => Quarantine::observation( $id ),
     585                                        'hits'              => (int) $q['hits'],
    543586                                );
    544587                        }
    … …  
    607650                // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    608651
     652                $post_ids = array();
     653                foreach ( (array) $rows as $row ) {
     654                        if ( in_array( $row['source_type'], array( 'frontend', 'post_content', 'post_excerpt', 'featured_image', 'post_meta', 'builder', 'acf', 'woocommerce' ), true ) && $row['source_id'] ) {
     655                                $post_ids[] = (int) $row['source_id'];
     656                        }
     657                }
     658                if ( $post_ids ) {
     659                        _prime_post_caches( array_unique( $post_ids ), false, false );
     660                }
    609661                $out = array(
    610662                        'strong' => array(),
    … …  
    696748                        $source = array(
    697749                                'kind'     => 'media',
    698                                 'title'    => get_the_title( $sid ) ? get_the_title( $sid ) : sprintf( /* translators: %d: media ID */ __( 'Media #%d', 'rapid-media-reclaim' ), $sid ),
     750                                'title'    => get_the_title( $sid ) ? get_the_title( $sid ) : sprintf( /* translators: %d: attachment ID */ __( 'Media #%d', 'rapid-media-reclaim' ), $sid ),
    699751                                'subtitle' => __( 'Same file, used elsewhere (for example a translation)', 'rapid-media-reclaim' ),
    700752                                'edit_url' => get_edit_post_link( $sid, 'raw' ),
  • rapid-media-reclaim/trunk/includes/class-installer.php

    r3794616 r3814937  
    1515final class Installer {
    1616
    17         const DB_VERSION = '5';
     17        const DB_VERSION = '9';
    1818
    1919        /**
    2020         * Install plugin storage on activation.
    21          */
    22         public static function activate(): void {
     21         *
     22         * @param bool|null $network_wide Activate every network site.
     23         */
     24        public static function activate( ?bool $network_wide = false ): void {
     25                if ( $network_wide && is_multisite() ) {
     26                        self::network( 'activate' );
     27                        return;
     28                }
    2329                self::install();
     30                Routing_Window::interrupt( 'activation' );
     31                Routing_Window::repair();
    2432                Quarantine::ensure_dir();
     33                Deferred_Index::repair();
    2534        }
    2635
    2736        /**
    2837         * Unschedule plugin background work.
    29          */
    30         public static function deactivate(): void {
     38         *
     39         * @param bool|null $network_wide Deactivate every network site.
     40         */
     41        public static function deactivate( ?bool $network_wide = false ): void {
     42                if ( $network_wide && is_multisite() ) {
     43                        self::network( 'deactivate' );
     44                        return;
     45                }
    3146                wp_clear_scheduled_hook( Scan_Runner::CRON_HOOK );
     47                wp_clear_scheduled_hook( Scan_Runner::CLEANUP_HOOK );
     48                wp_clear_scheduled_hook( Status_Index::HOOK );
     49                wp_clear_scheduled_hook( Deferred_Index::HOOK );
     50                wp_clear_scheduled_hook( Maintenance::HOOK );
     51                wp_clear_scheduled_hook( Routing_Window::HOOK );
     52                Routing_Window::interrupt( 'deactivation' );
     53                // Legacy shared slot only; current challenges expire under their own ticket keys.
     54                delete_transient( Server_Watch::PROBE );
    3255                Scan_Runner::cancel();
    3356                delete_option( Request_Watcher::RATE_OPTION );
     57        }
     58
     59        /**
     60         * Run a fixed lifecycle method on every current network site in bounded pages.
     61         *
     62         * @param string $method Internal activate/deactivate method.
     63         * @throws \RuntimeException Failed network inventory.
     64         */
     65        private static function network( string $method ): void {
     66                global $wpdb;
     67                $after = 0;
     68                do {
     69                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Fresh keyset network lifecycle enumeration, at most one hundred IDs.
     70                        $ids = $wpdb->get_col( $wpdb->prepare( "SELECT blog_id FROM {$wpdb->blogs} WHERE blog_id>%d ORDER BY blog_id LIMIT 100", $after ) );
     71                        if ( $wpdb->last_error || ! is_array( $ids ) ) {
     72                                throw new \RuntimeException( 'safe_media_cleaner_network_inventory_failed' );
     73                        }
     74                        foreach ( $ids as $id ) {
     75                                $after = (int) $id;
     76                                switch_to_blog( $after );
     77                                try {
     78                                        self::$method( false );
     79                                } finally {
     80                                        restore_current_blog();
     81                                }
     82                        }
     83                        $count = count( $ids );
     84                } while ( 100 === $count );
     85        }
     86
     87        /**
     88         * Initialize a newly provisioned site only while this plugin is network active.
     89         *
     90         * @param \WP_Site $site Newly initialized site.
     91         */
     92        public static function new_site( \WP_Site $site ): void {
     93                if ( ! is_multisite() || ! array_key_exists( plugin_basename( SAFE_MEDIA_CLEANER_PATH . 'rapid-media-reclaim.php' ), (array) get_site_option( 'active_sitewide_plugins', array() ) ) ) {
     94                        return;
     95                }
     96                switch_to_blog( (int) $site->blog_id );
     97                try {
     98                        self::activate();
     99                } finally {
     100                        restore_current_blog();
     101                }
    34102        }
    35103
    … …  
    97165                global $wpdb;
    98166                return array(
    99                         'files'      => $wpdb->prefix . 'safe_media_cleaner_files',
    100                         'refs'       => $wpdb->prefix . 'safe_media_cleaner_refs',
    101                         'quarantine' => $wpdb->prefix . 'safe_media_cleaner_quarantine',
     167                        'ledger_payloads' => $wpdb->prefix . 'safe_media_cleaner_ledger_payloads',
     168                        'ledger_events'   => $wpdb->prefix . 'safe_media_cleaner_ledger_events',
     169                        'pending'         => $wpdb->prefix . 'safe_media_cleaner_pending',
     170                        'status'          => $wpdb->prefix . 'safe_media_cleaner_status',
     171                        'discovery'       => $wpdb->prefix . 'safe_media_cleaner_discovery',
     172                        'files'           => $wpdb->prefix . 'safe_media_cleaner_files',
     173                        'refs'            => $wpdb->prefix . 'safe_media_cleaner_refs',
     174                        'quarantine'      => $wpdb->prefix . 'safe_media_cleaner_quarantine',
    102175                );
    103176        }
    … …  
    135208                        KEY attachment (attachment_id,generation),
    136209                        KEY path (path(191)),
     210                        KEY shared_path (generation,kind,path(128),attachment_id),
    137211                        KEY name (generation,name),
    138212                        KEY generation (generation)
    … …  
    164238                        owner_id bigint(20) unsigned NOT NULL DEFAULT 0,
    165239                        purge_intent tinyint(1) unsigned NOT NULL DEFAULT 0,
     240                        ledger_pending tinyint(1) unsigned NOT NULL DEFAULT 0,
    166241                        status varchar(12) NOT NULL DEFAULT 'quarantined',
    167242                        files longtext NOT NULL,
    … …  
    177252                        KEY owner_id (owner_id,status),
    178253                        KEY status (status),
     254                        KEY ledger_pending (ledger_pending),
    179255                        KEY batch (batch)
    180256                        ) $charset;"
    181257                );
     258
     259                dbDelta(
     260                        "CREATE TABLE {$t['status']} (
     261                        generation int(10) unsigned NOT NULL,
     262                        attachment_id bigint(20) unsigned NOT NULL,
     263                        used tinyint(1) unsigned NOT NULL DEFAULT 0,
     264                        weak_ref tinyint(1) unsigned NOT NULL DEFAULT 0,
     265                        weak_name tinyint(1) unsigned NOT NULL DEFAULT 0,
     266                        bytes bigint(20) unsigned NOT NULL DEFAULT 0,
     267                        is_copy tinyint(1) unsigned NOT NULL DEFAULT 0,
     268                        PRIMARY KEY  (generation,attachment_id),
     269                        KEY flags (generation,is_copy,used,bytes)
     270                        ) $charset;"
     271                );
     272
     273                dbDelta(
     274                        "CREATE TABLE {$t['pending']} (
     275                        phase varchar(12) NOT NULL,
     276                        source_id bigint(20) unsigned NOT NULL,
     277                        revision char(32) NOT NULL,
     278                        queued_at datetime NOT NULL,
     279                        attempts int(10) unsigned NOT NULL DEFAULT 0,
     280                        PRIMARY KEY  (phase,source_id),
     281                        KEY queued (queued_at),
     282                        KEY attempts (attempts)
     283                        ) $charset;"
     284                );
     285
     286                dbDelta(
     287                        "CREATE TABLE {$t['ledger_payloads']} (
     288                        id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
     289                        version tinyint(3) unsigned NOT NULL DEFAULT 1,
     290                        payload_key char(64) NOT NULL,
     291                        root_key char(64) NOT NULL,
     292                        record_id bigint(20) unsigned NOT NULL,
     293                        attachment_id bigint(20) unsigned NOT NULL,
     294                        bytes bigint(20) unsigned NOT NULL DEFAULT 0,
     295                        manifest_files int(10) unsigned NOT NULL DEFAULT 0,
     296                        origin varchar(12) NOT NULL,
     297                        storage_state varchar(12) NOT NULL DEFAULT 'unknown',
     298                        updated_at datetime NOT NULL,
     299                        PRIMARY KEY  (id),
     300                        UNIQUE KEY payload_key (payload_key),
     301                        KEY root_key (root_key),
     302                        KEY record_id (record_id),
     303                        KEY storage (storage_state,bytes,updated_at)
     304                        ) $charset;"
     305                );
     306                dbDelta(
     307                        "CREATE TABLE {$t['ledger_events']} (
     308                        id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
     309                        version tinyint(3) unsigned NOT NULL DEFAULT 1,
     310                        payload_key char(64) NOT NULL,
     311                        record_id bigint(20) unsigned NOT NULL,
     312                        attachment_id bigint(20) unsigned NOT NULL,
     313                        operation varchar(12) NOT NULL,
     314                        result varchar(12) NOT NULL DEFAULT 'pending',
     315                        bytes bigint(20) unsigned NOT NULL DEFAULT 0,
     316                        coverage varchar(12) NOT NULL,
     317                        created_at datetime NOT NULL,
     318                        updated_at datetime NOT NULL,
     319                        PRIMARY KEY  (id),
     320                        UNIQUE KEY operation_payload (payload_key,operation),
     321                        KEY result (result,operation,bytes),
     322                        KEY record_id (record_id)
     323                        ) $charset;"
     324                );
     325                // No legacy statuses are imported as historical events.
     326                add_option( Operation_Ledger::STARTED, current_time( 'mysql', true ), '', false );
    182327
    183328                // Read on every request: keep these two tiny options autoloaded.
  • rapid-media-reclaim/trunk/includes/class-plugin.php

    r3794616 r3814937  
    2020        public static function boot(): void {
    2121                Installer::maybe_upgrade();
     22                add_action( 'wp_initialize_site', array( Installer::class, 'new_site' ), 200, 1 );
    2223                Scan_Runner::init();
     24                Status_Index::init();
    2325                Quarantine::init();
     26                Merge::init();
    2427                Request_Watcher::init();
     28                Recovery_Export::init();
     29                Recovery_Import::init();
     30                Csv_Export::init();
     31                Discovery_Jobs::init();
     32                Discovery_Csv::init();
     33                File_Epoch::init();
     34                File_Archive::init();
     35                Rest\File_Controller::init();
     36                Maintenance::init();
     37                Deferred_Index::init();
     38                Server_Watch::init();
     39                Routing_Window::init();
     40                Rest\Tools_Controller::init();
     41                Rest\Recovery_Controller::init();
     42                if ( defined( 'WP_CLI' ) && WP_CLI ) {
     43                        Cli::init();
     44                }
    2545
    2646                if ( class_exists( Scan\Incremental::class ) ) {
  • rapid-media-reclaim/trunk/includes/class-quarantine.php

    r3794616 r3814937  
    126126
    127127        /**
    128          * Quarantine eligible attachments under the operation lock.
    129          *
    130          * @param array $ids Ids.
    131          */
    132         public static function move( array $ids ): array {
     128         * Run imported recovery under the SAME lock and process guard as move/restore/purge.
     129         *
     130         * @param callable $callback Internal recovery operation.
     131         * @return mixed Operation result.
     132         * @throws \RuntimeException A concurrent/reentrant operation is running.
     133         */
     134        public static function recovery_operation( callable $callback ) {
    133135                global $wpdb;
    134136                $key = 'smc:' . md5( DB_NAME . ':' . $wpdb->prefix );
    135                 if ( self::$operating || self::core_deleting() || doing_action( 'delete_attachment' ) || doing_action( 'deleted_post' ) || '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $key ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
     137                if ( self::is_operating() || self::core_deleting() || doing_action( 'delete_attachment' ) || doing_action( 'deleted_post' ) || '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s,0)', $key ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Shared live media-operation lock.
     138                        throw new \RuntimeException( __( 'Another media operation is running. Retry shortly.', 'rapid-media-reclaim' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Encoded at presentation.
     139                }
     140                self::$operating = true;
     141                try {
     142                        return $callback();
     143                } finally {
     144                        self::$operating = false;
     145                        $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $key ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Release shared operation lock.
     146                }
     147        }
     148
     149        /**
     150         * Register imported payloads BEFORE copying, preserving existing matching records.
     151         *
     152         * @param array  $item Validated attachment plan.
     153         * @param string $batch Durable import batch.
     154         * @return array|\WP_Error Registered recovery row.
     155         */
     156        public static function recovery_record( array $item, string $batch ) {
     157                if ( ! self::$operating ) {
     158                        return new \WP_Error( 'safe_media_cleaner_lock', __( 'Recovery requires the media operation lock.', 'rapid-media-reclaim' ) );
     159                }
     160                $id  = $item['attachment_id'];
     161                $row = self::records_for( array( $id ) )[ $id ] ?? null;
     162                if ( $row ) {
     163                        $files    = self::manifest( $row );
     164                        $expected = array();
     165                        foreach ( $item['files'] as $file ) {
     166                                $expected[ $file['from'] ] = array( $file['bytes'], $file['sha256'] );
     167                        }
     168                        if ( is_wp_error( $files ) || count( $files ) !== count( $expected ) || (int) $row['owner_id'] !== $item['owner_id'] ) {
     169                                return new \WP_Error( 'safe_media_cleaner_conflict', __( 'Existing quarantine recovery differs from this backup. Review it in Quarantine first.', 'rapid-media-reclaim' ) );
     170                        }
     171                        foreach ( $files as $file ) {
     172                                if ( ( $expected[ $file['from'] ] ?? null ) !== array( (int) $file['bytes'], $file['sha256'] ?? '' ) ) {
     173                                        return new \WP_Error( 'safe_media_cleaner_conflict', __( 'Existing quarantine files differ from this backup.', 'rapid-media-reclaim' ) );
     174                                }
     175                        }
     176                        return $row;
     177                }
     178                $files = array();
     179                foreach ( $item['files'] as $file ) {
     180                        $files[] = array(
     181                                'from'   => $file['from'],
     182                                'to'     => $batch . '/' . $file['from'],
     183                                'bytes'  => $file['bytes'],
     184                                'sha256' => $file['sha256'],
     185                        );
     186                }
     187                if ( ! self::insert_record( $id, $batch, $files, array_sum( array_column( $files, 'bytes' ) ), $item['owner_id'] ) ) {
     188                        return new \WP_Error( 'safe_media_cleaner_manifest', __( 'Could not save recovery data. Retry before copying files.', 'rapid-media-reclaim' ) );
     189                }
     190                return self::records_for( array( $id ) )[ $id ];
     191        }
     192
     193        /**
     194         * Use normal identity-checked restore only inside the shared operation wrapper.
     195         *
     196         * @param int $id Registered payload owner.
     197         * @return int|\WP_Error Normal recovery result.
     198         */
     199        public static function recovery_restore( int $id ) {
     200                return self::$operating ? self::restore_one( $id ) : new \WP_Error( 'safe_media_cleaner_lock', __( 'Recovery requires the media operation lock.', 'rapid-media-reclaim' ) );
     201        }
     202
     203        /**
     204         * Check live ownership of imported file names using the normal ownership guard.
     205         *
     206         * @param array $files Payload entries.
     207         * @param array $ids Complete shared group.
     208         * @return true|\WP_Error Ownership result.
     209         */
     210        public static function recovery_ownership( array $files, array $ids ) {
     211                $folders = array();
     212                foreach ( $files as $file ) {
     213                        $dir               = dirname( $file['from'] );
     214                        $dir               = '.' === $dir ? '' : $dir . '/';
     215                        $folders[ $dir ][] = basename( $file['from'] );
     216                }
     217                foreach ( $folders as $dir => $names ) {
     218                        $claimed = self::claimed_names( $dir, $ids, $names );
     219                        if ( is_wp_error( $claimed ) ) {
     220                                return $claimed;
     221                        }
     222                        if ( $claimed ) {
     223                                return new \WP_Error( 'safe_media_cleaner_ownership', __( 'Another attachment owns a backup file name. Review that media before retrying.', 'rapid-media-reclaim' ) );
     224                        }
     225                }
     226                return true;
     227        }
     228
     229        /** Whether a quarantine/restore/purge operation owns this request. */
     230        public static function is_operating(): bool {
     231                return self::$operating || File_Recovery::is_operating(); }
     232
     233        /** Move selected files using existing guarded recovery manifests.
     234         *
     235         * @param array $ids Attachment IDs.
     236         * @return array Move results.
     237         */
     238        public static function move( array $ids ): array {
     239                foreach ( $ids as $id ) {
     240                        if ( Recovery_Import::is_protected( (int) $id ) ) {
     241                                return array(
     242                                        'moved'  => array(),
     243                                        'failed' => array( self::failure( (int) $id, __( 'Resume the pending backup recovery in Tools before changing this media.', 'rapid-media-reclaim' ) ) ),
     244                                        'bytes'  => 0,
     245                                );
     246                        }
     247                }
     248                foreach ( $ids as $id ) {
     249                        if ( Merge::is_protected( (int) $id ) && ! Merge_Retirement::allows( (int) $id ) ) {
     250                                return array(
     251                                        'moved'  => array(),
     252                                        'failed' => array( self::failure( (int) $id, __( 'This file is protected by a reference recovery journal. Roll back or finish reviewing that operation first.', 'rapid-media-reclaim' ), 'merge_protected' ) ),
     253                                        'bytes'  => 0,
     254                                );
     255                        }
     256                }
     257
     258                $storage_error = Storage::mutation_error();
     259                if ( $storage_error ) {
     260                        return array(
     261                                'moved'  => array(),
     262                                'failed' => array( self::failure( 0, $storage_error->get_error_message(), 'audit_only' ) ),
     263                                'bytes'  => 0,
     264                        );
     265                }
     266
     267                global $wpdb;
     268                $key = 'smc:' . md5( DB_NAME . ':' . $wpdb->prefix );
     269                if ( self::is_operating() || self::core_deleting() || doing_action( 'delete_attachment' ) || doing_action( 'deleted_post' ) || '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $key ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
    136270                        return array(
    137271                                'moved'  => array(),
    … …  
    156290         */
    157291        private static function move_locked( array $ids ): array {
     292                foreach ( $ids as $id ) {
     293                        if ( Merge::is_protected( (int) $id ) && ! Merge_Retirement::allows( (int) $id ) ) {
     294                                return array(
     295                                        'moved'  => array(),
     296                                        'failed' => array( self::failure( (int) $id, 'merge_protected', 'merge_protected' ) ),
     297                                        'bytes'  => 0,
     298                                );
     299                        }
     300                }
     301                foreach ( $ids as $id ) {
     302                        if ( Recovery_Import::is_protected( (int) $id ) ) {
     303                                return array(
     304                                        'moved'  => array(),
     305                                        'failed' => array( self::failure( (int) $id, __( 'Resume pending recovery in Tools first.', 'rapid-media-reclaim' ) ) ),
     306                                        'bytes'  => 0,
     307                                );
     308                        }
     309                }
    158310                $ids    = self::clean_ids( $ids );
    159                 $batch  = strtolower( wp_generate_password( 12, false ) );
     311                $batch  = Merge_Retirement::batch( $ids );
     312                $batch  = '' !== $batch ? $batch : strtolower( wp_generate_password( 12, false ) );
    160313                $result = array(
    161314                        'batch'  => $batch,
    … …  
    233386         */
    234387        public static function restore( array $ids ): array {
     388                foreach ( $ids as $id ) {
     389                        if ( Recovery_Import::is_protected( (int) $id ) ) {
     390                                return array(
     391                                        'restored' => array(),
     392                                        'failed'   => array( self::failure( (int) $id, __( 'Resume the pending backup recovery in Tools before changing this media.', 'rapid-media-reclaim' ) ) ),
     393                                        'bytes'    => 0,
     394                                );
     395                        }
     396                }
    235397                global $wpdb;
    236398                $key = 'smc:' . md5( DB_NAME . ':' . $wpdb->prefix );
    237                 if ( self::$operating || self::core_deleting() || doing_action( 'delete_attachment' ) || doing_action( 'deleted_post' ) || '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $key ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
     399                if ( self::is_operating() || self::core_deleting() || doing_action( 'delete_attachment' ) || doing_action( 'deleted_post' ) || '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $key ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
    238400                        return array(
    239401                                'restored' => array(),
    … …  
    258420         */
    259421        private static function restore_locked( array $ids ): array {
     422                foreach ( $ids as $id ) {
     423                        if ( Recovery_Import::is_protected( (int) $id ) ) {
     424                                return array(
     425                                        'restored' => array(),
     426                                        'failed'   => array( self::failure( (int) $id, __( 'Resume pending recovery in Tools first.', 'rapid-media-reclaim' ) ) ),
     427                                        'bytes'    => 0,
     428                                );
     429                        }
     430                }
    260431                $result  = array(
    261432                        'restored' => array(),
    … …  
    286457         *
    287458         * @param string $batch Batch.
    288          */
    289         public static function restore_batch( string $batch ): array {
     459         * @param int    $limit Optional attachment count per call.
     460         * @throws \RuntimeException Recovery batch state could not be verified.
     461         */
     462        public static function restore_batch( string $batch, int $limit = 0 ): array {
    290463                global $wpdb;
    291464                $batch = preg_replace( '/[^a-z0-9]/', '', strtolower( $batch ) );
    292465                // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    293                 $ids = $batch ? $wpdb->get_col(
    294                         $wpdb->prepare( 'SELECT attachment_id FROM ' . self::table() . ' WHERE batch = %s AND status = %s', $batch, 'quarantined' ) // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
     466                $limit_sql = $limit > 0 ? ' LIMIT ' . min( 500, $limit ) : '';
     467                $ids       = $batch ? $wpdb->get_col(
     468                        $wpdb->prepare( 'SELECT attachment_id FROM ' . self::table() . ' WHERE batch = %s AND status = %s ORDER BY id' . $limit_sql, $batch, 'quarantined' ) // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    295469                ) : array();
    296470                // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    297                 return self::restore( array_map( 'intval', (array) $ids ) );
     471                if ( $wpdb->last_error ) {
     472                        throw new \RuntimeException( __( 'Could not read the recovery batch. Retry the batch.', 'rapid-media-reclaim' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- REST JSON encodes the message.
     473                }
     474                $result = self::restore( array_map( 'intval', (array) $ids ) );
     475                if ( $limit > 0 ) {
     476                        $result['remaining'] = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM ' . self::table() . " WHERE batch=%s AND status='quarantined'", $batch ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Internal table and prepared batch value.
     477                        if ( $wpdb->last_error ) {
     478                                throw new \RuntimeException( __( 'Could not verify the remaining recovery records. Retry the batch.', 'rapid-media-reclaim' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- REST JSON encodes the message.
     479                        }
     480                }
     481                return $result;
    298482        }
    299483
    … …  
    302486         *
    303487         * @param array $ids Ids.
    304          * @param bool  $force Force.
     488         * @param bool  $force Deprecated; never bypasses waiting or backup requirements.
    305489         * @param bool  $retry_only Retry only.
    306490         */
    307491        public static function purge( array $ids, bool $force = false, bool $retry_only = false ): array {
     492                foreach ( $ids as $id ) {
     493                        if ( Recovery_Import::is_protected( (int) $id ) ) {
     494                                return array(
     495                                        'purged' => array(),
     496                                        'failed' => array( self::failure( (int) $id, __( 'Resume the pending backup recovery in Tools before changing this media.', 'rapid-media-reclaim' ) ) ),
     497                                        'bytes'  => 0,
     498                                );
     499                        }
     500                }
     501                $storage_error = Storage::mutation_error();
     502                if ( $storage_error ) {
     503                        return array(
     504                                'purged' => array(),
     505                                'failed' => array( self::failure( 0, $storage_error->get_error_message(), 'audit_only' ) ),
     506                                'bytes'  => 0,
     507                        );
     508                }
     509
    308510                global $wpdb;
    309511                $key = 'smc:' . md5( DB_NAME . ':' . $wpdb->prefix );
    310                 if ( self::$operating || self::core_deleting() || doing_action( 'delete_attachment' ) || doing_action( 'deleted_post' ) || '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $key ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
     512                if ( self::is_operating() || self::core_deleting() || doing_action( 'delete_attachment' ) || doing_action( 'deleted_post' ) || '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $key ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
    311513                        return array(
    312514                                'purged' => array(),
    … …  
    318520                try {
    319521                        do_action( 'safe_media_cleaner_operation_locked', 'purge', $ids );
    320                         return self::purge_locked( $ids, $force, $retry_only );
     522                        return self::purge_locked( $ids, $retry_only );
    321523                } finally {
    322524                        self::$operating = false;
    … …  
    329531         *
    330532         * @param array $ids Ids.
    331          * @param bool  $force Force.
    332533         * @param bool  $retry_only Retry only.
    333534         */
    334         private static function purge_locked( array $ids, bool $force = false, bool $retry_only = false ): array {
    335                 $result  = array(
     535        private static function purge_locked( array $ids, bool $retry_only = false ): array {
     536                foreach ( $ids as $id ) {
     537                        if ( Recovery_Import::is_protected( (int) $id ) ) {
     538                                return array(
     539                                        'purged' => array(),
     540                                        'failed' => array( self::failure( (int) $id, __( 'Resume pending recovery in Tools first.', 'rapid-media-reclaim' ) ) ),
     541                                        'bytes'  => 0,
     542                                );
     543                        }
     544                }
     545                $result                        = array(
    336546                        'purged' => array(),
    337547                        'failed' => array(),
    338548                        'bytes'  => 0,
    339549                );
    340                 $days    = (int) Settings::get()['quarantine_days'];
     550                $result['observation_warning'] = self::observation_warning();
     551                $result['observation']         = array();
     552                foreach ( self::clean_ids( $ids ) as $selected ) {
     553                        $result['observation'][ $selected ] = self::observation( $selected );
     554                }
    341555                $records = self::records_for( self::clean_ids( $ids ) );
    342556
    … …  
    351565                                continue;
    352566                        }
    353                         $age = time() - (int) strtotime( $record['created_at'] . ' UTC' );
    354                         if ( ! $force && $age < $days * DAY_IN_SECONDS ) {
    355                                 $result['failed'][] = self::failure(
    356                                         $id,
    357                                         sprintf(
    358                                                 /* translators: %d: number of days */
    359                                                 _n( 'This file has been in quarantine for less than %d day.', 'This file has been in quarantine for less than %d days.', $days, 'rapid-media-reclaim' ),
    360                                                 $days
    361                                         ),
    362                                         'too_recent'
    363                                 );
    364                                 continue;
    365                         }
    366567
    367568                        // The item may have come back into use after it was quarantined (for
    368569                        // example set as a featured image). Never delete it then, even when forced.
    369                         if ( ! $retry_only && get_post( $id ) && self::in_use_now( $id, $record ) ) {
     570                        if ( (int) ( $record['hits'] ?? 0 ) > 0 || ( get_post( $id ) && self::in_use_now( $id, $record ) ) ) {
    370571                                $result['failed'][] = self::failure( $id, __( 'This file is in use again (for example as a featured image or in content). Restore it instead of deleting it.', 'rapid-media-reclaim' ), 'in_use' );
    371572                                continue;
    … …  
    411612                        }
    412613
     614                        // Core translation callbacks may delete every sibling at once. Verify
     615                        // all members before any deletion intent is persisted or posts deleted.
     616                        $members = self::group_records( $id );
     617                        if ( ! isset( $members[ $id ] ) ) {
     618                                $result['failed'][] = self::failure( $id, __( 'Could not verify the complete recovery group. Nothing was deleted.', 'rapid-media-reclaim' ), 'recovery_unavailable' );
     619                                continue;
     620                        }
     621                        $eligible = true;
     622                        foreach ( $members as $member => $member_record ) {
     623                                if ( (int) ( $member_record['hits'] ?? 0 ) > 0 || ( get_post( $member ) && self::in_use_now( $member, $member_record ) ) ) {
     624                                        $result['failed'][] = self::failure( $id, __( 'A shared file is in use again. Restore the group instead of deleting it.', 'rapid-media-reclaim' ), 'in_use' );
     625                                        $eligible           = false;
     626                                        break;
     627                                }
     628                                $requirement = self::purge_requirement( $member, $member_record, $retry_only );
     629                                if ( $requirement ) {
     630                                        $result['failed'][] = self::failure( $id, $requirement->get_error_message(), $requirement->get_error_code() );
     631                                        $eligible           = false;
     632                                        break;
     633                                }
     634                        }
     635                        if ( ! $eligible ) {
     636                                continue;
     637                        }
    413638                        $purged = self::purge_one( $record, $retry_only );
    414639                        if ( is_wp_error( $purged ) ) {
    … …  
    420645                }
    421646                return $result;
     647        }
     648
     649        /**
     650         * Enforce immutable waiting and current recovery-backup requirements.
     651         *
     652         * An already authorized interrupted cleanup may resume without rebuilding a
     653         * backup from payloads it has already removed. Force is deliberately absent.
     654         *
     655         * @param int   $id Attachment ID.
     656         * @param array $record Current quarantine record under the operation lock.
     657         * @param bool  $retry_only Resume a previously authorized cleanup only.
     658         * @return \WP_Error|null A policy refusal, or null when requirements pass.
     659         */
     660        private static function purge_requirement( int $id, array $record, bool $retry_only ): ?\WP_Error {
     661                if ( $retry_only && ! empty( $record['purge_intent'] ) ) {
     662                        return null;
     663                }
     664                $days    = max( 14, min( 365, (int) Settings::get()['quarantine_days'] ) );
     665                $created = strtotime( (string) $record['created_at'] . ' UTC' );
     666                if ( false === $created || time() - $created < $days * DAY_IN_SECONDS ) {
     667                        return new \WP_Error(
     668                                'too_recent',
     669                                sprintf(
     670                                        /* translators: %d: minimum quarantine days. */
     671                                        __( 'Keep this file in quarantine for at least %d days before permanent deletion.', 'rapid-media-reclaim' ),
     672                                        $days
     673                                )
     674                        );
     675                }
     676                if ( ! Recovery_Export::is_backed_up( $id, $record ) ) {
     677                        return new \WP_Error( 'backup_required', __( 'Download and confirm a current recovery archive before permanent deletion.', 'rapid-media-reclaim' ) );
     678                }
     679                return null;
     680        }
     681
     682        /**
     683         * Fresh group observation facts. This never grants or removes manual purge permission.
     684         *
     685         * @param int $id Attachment ID.
     686         * @return array Conservative verification period.
     687         */
     688        public static function observation( int $id ): array {
     689                global $wpdb;
     690                $record = self::records_for( array( $id ) )[ $id ] ?? null;
     691                $failed = (bool) $wpdb->last_error || ! $record;
     692                wp_cache_delete( $id, 'post_meta' );
     693                $siblings = self::shared_with( $id );
     694                $failed   = $failed || (bool) $wpdb->last_error || count( $siblings ) > 500;
     695                $root     = (int) ( $record['owner_id'] ?? 0 );
     696                $root     = $root ? $root : $id;
     697                $ids      = self::clean_ids( array_merge( array( $id, $root ), $siblings ) );
     698                $table    = self::table();
     699                $rows     = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE status=%s AND (owner_id=%d OR attachment_id IN (" . implode( ',', $ids ) . ')) ORDER BY id LIMIT 501', 'quarantined', $root ), ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Bounded current group, internal table and integer-only IDs; never a scan cache.
     700                $failed   = $failed || (bool) $wpdb->last_error || ! is_array( $rows ) || count( (array) $rows ) > 500;
     701                $records  = array();
     702                foreach ( (array) $rows as $row ) {
     703                        $member                 = (int) $row['attachment_id'];
     704                        $row['recognized_seen'] = Request_Watcher::seen( $member );
     705                        $failed                 = $failed || (bool) $wpdb->last_error;
     706                        $records[ $member ]     = $row;
     707                }
     708                $failed = $failed || (bool) array_diff( $ids, array_keys( $records ) );
     709                if ( $failed ) {
     710                        Routing_Window::interrupt( 'group_unavailable' );
     711                        $records = array();
     712                }
     713                return Routing_Window::group( $records, Routing_Window::status(), time(), (int) Settings::get()['quarantine_days'] );
     714        }
     715
     716        /** Warning shared by manual deletion clients, irrespective of the age gate. */
     717        public static function observation_warning(): string {
     718                return __( 'Manual deletion may proceed with incomplete or browser-only routing verification. Quarantine age is separate from the verified window. No recognized requests does not prove that a file is unused. The minimum waiting period, usage and ownership checks, saved-backup confirmation and permissions still apply.', 'rapid-media-reclaim' );
    422719        }
    423720
    … …  
    573870         */
    574871        public static function guard_external_delete( $delete, $post, $force ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- Signature follows the pre_delete_attachment filter contract.
     872                if ( Recovery_Import::is_protected( (int) $post->ID ) ) {
     873                        return false;
     874                }
    575875                if ( isset( self::$purging[ (int) $post->ID ] ) ) {
    576876                        return $delete; }
    … …  
    625925
    626926                $files = self::attachment_files( $id );
     927                if ( is_wp_error( $files ) ) {
     928                        return $files; }
    627929                if ( ! $files ) {
    628930                        return new \WP_Error( 'safe_media_cleaner_no_files', __( 'No files were found for this media item.', 'rapid-media-reclaim' ) );
    … …  
    652954                        return new \WP_Error( 'safe_media_cleaner_manifest', __( 'Could not save recovery data. No files were moved.', 'rapid-media-reclaim' ) );
    653955                }
    654                 // Phase 1: link every file into quarantine. The public files are untouched,
    655                 // so any failure (no hard links on this filesystem, file owned by another
    656                 // user, disk full) is undone by removing only the links created here.
    657                 $linked = array();
     956                $ledger_record = self::records_for( array( $id ) )[ $id ];
    658957                foreach ( $moved as $file ) {
    659                         $from = $uploads . '/' . $file['from'];
    660                         $to   = $target . '/' . $file['to'];
    661                         if ( ! wp_mkdir_p( dirname( $to ) ) || ! self::link_file( $from, $to ) ) {
    662                                 self::abandon_move( $id, $linked, $target );
    663                                 return new \WP_Error( 'safe_media_cleaner_move_failed', __( 'This media item could not be moved (the server did not allow it). Recovery data has been retained if cleanup could not finish. Review this item before retrying.', 'rapid-media-reclaim' ) );
    664                         }
    665                         $linked[] = $file;
    666                 }
    667                 // Phase 2: remove the originals. If one cannot be removed, put back the
    668                 // ones already removed so the live site never loses a file.
    669                 $removed = array();
    670                 foreach ( $moved as $file ) {
    671                         if ( ! self::unlink_file( $uploads . '/' . $file['from'] ) ) {
    672                                 foreach ( $removed as $back ) {
    673                                         self::link_file( $target . '/' . $back['to'], $uploads . '/' . $back['from'] );
     958                        if ( ! Operation_Ledger::begin( $ledger_record, $file, 'quarantine' ) ) {
     959                                return Operation_Ledger::error();
     960                        }
     961                }
     962                $ledger_complete = false;
     963                try {
     964                        // Phase 1: link every file into quarantine. The public files are untouched,
     965                        // so any failure (no hard links on this filesystem, file owned by another
     966                        // user, disk full) is undone by removing only the links created here.
     967                        $linked = array();
     968                        foreach ( $moved as $file ) {
     969                                $from = $uploads . '/' . $file['from'];
     970                                $to   = $target . '/' . $file['to'];
     971                                if ( ! wp_mkdir_p( dirname( $to ) ) || ! self::link_file( $from, $to ) ) {
     972                                        self::abandon_move( $id, $linked, $target );
     973                                        return new \WP_Error( 'safe_media_cleaner_move_failed', __( 'This media item could not be moved (the server did not allow it). Recovery data has been retained if cleanup could not finish. Review this item before retrying.', 'rapid-media-reclaim' ) );
    674974                                }
    675                                 self::abandon_move( $id, $linked, $target );
    676                                 return new \WP_Error( 'safe_media_cleaner_move_failed', __( 'This media item could not be moved (a file could not be removed). Recovery data has been retained if cleanup could not finish. Review this item before retrying.', 'rapid-media-reclaim' ) );
    677                         }
    678                         $removed[] = $file;
    679                 }
    680 
     975                                $linked[] = $file;
     976                        }
     977                        // Phase 2: remove the originals. If one cannot be removed, put back the
     978                        // ones already removed so the live site never loses a file.
     979                        $removed = array();
     980                        foreach ( $moved as $file ) {
     981                                if ( ! self::unlink_file( $uploads . '/' . $file['from'] ) ) {
     982                                        foreach ( $removed as $back ) {
     983                                                self::link_file( $target . '/' . $back['to'], $uploads . '/' . $back['from'] );
     984                                        }
     985                                        self::abandon_move( $id, $linked, $target );
     986                                        return new \WP_Error( 'safe_media_cleaner_move_failed', __( 'This media item could not be moved (a file could not be removed). Recovery data has been retained if cleanup could not finish. Review this item before retrying.', 'rapid-media-reclaim' ) );
     987                                }
     988                                $removed[] = $file;
     989                        }
     990
     991                        $ledger_complete = true;
     992                } finally {
     993                        $ledger_saved = true;
     994                        foreach ( $moved as $file ) {
     995                                $ledger_saved = Operation_Ledger::finish( $ledger_record, $file, 'quarantine', $ledger_complete ? 'verified' : 'failed' ) && $ledger_saved;
     996                        }
     997                }
     998                if ( ! $ledger_saved ) {
     999                        return Operation_Ledger::error();
     1000                }
    6811001                do_action( 'safe_media_cleaner_quarantined', $id, $moved );
    6821002                return $bytes;
    … …  
    8261146                }
    8271147
    828                 $missing = array();
     1148                $ledger_saved = Operation_Ledger::mark( $record, true );
     1149                $missing      = array();
    8291150                foreach ( $files as $file ) {
    830                         $from = $source . '/' . $file['to'];
    831                         $to   = $uploads . '/' . $file['from'];
    832                         if ( ! self::inside( $from, self::uploads_dir() ) || ! self::inside( $to, $uploads ) ) {
    833                                 return new \WP_Error( 'safe_media_cleaner_path', __( 'Unsafe recovery path. Recovery data was retained.', 'rapid-media-reclaim' ) );
    834                         }
    835                         // A write-ahead identity makes interrupted moves/restores idempotent.
    836                         if ( is_file( $to ) && ! empty( $file['sha256'] ) && hash_equals( $file['sha256'], (string) hash_file( 'sha256', $to ) ) ) {
    837                                 if ( is_file( $from ) && ( ! hash_equals( $file['sha256'], (string) hash_file( 'sha256', $from ) ) || ! self::unlink_file( $from ) ) ) {
    838                                         return new \WP_Error( 'safe_media_cleaner_cleanup', __( 'Recovery cleanup incomplete. Retry restore.', 'rapid-media-reclaim' ) );
     1151                        $ledger_ready    = Operation_Ledger::begin( $record, $file, 'restore' );
     1152                        $ledger_source   = 'present' === Operation_Ledger::storage_state( $record, $file );
     1153                        $ledger_complete = false;
     1154                        try {
     1155
     1156                                $from = $source . '/' . $file['to'];
     1157                                $to   = $uploads . '/' . $file['from'];
     1158                                if ( ! self::inside( $from, self::uploads_dir() ) || ! self::inside( $to, $uploads ) ) {
     1159                                        return new \WP_Error( 'safe_media_cleaner_path', __( 'Unsafe recovery path. Recovery data was retained.', 'rapid-media-reclaim' ) );
    8391160                                }
    840                                 continue;
    841                         }
    842                         if ( file_exists( $to ) || ! is_file( $from ) || ( ! empty( $file['sha256'] ) && ! hash_equals( $file['sha256'], (string) hash_file( 'sha256', $from ) ) ) ) {
    843                                 return new \WP_Error( 'safe_media_cleaner_conflict', __( 'A recovery file is missing, changed, or its destination is occupied. Recovery data was retained.', 'rapid-media-reclaim' ) );
    844                         }
    845                         if ( ! wp_mkdir_p( dirname( $to ) ) || ! self::move_file( $from, $to ) ) {
    846                                 return new \WP_Error( 'safe_media_cleaner_restore_failed', __( 'Restore incomplete. Recovery data was retained; retry restore.', 'rapid-media-reclaim' ) );
    847                         }
     1161                                // A write-ahead identity makes interrupted moves/restores idempotent.
     1162                                if ( is_file( $to ) && (int) filesize( $to ) === (int) $file['bytes'] && ! empty( $file['sha256'] ) && hash_equals( $file['sha256'], (string) hash_file( 'sha256', $to ) ) ) {
     1163                                        if ( is_file( $from ) && ( ! hash_equals( $file['sha256'], (string) hash_file( 'sha256', $from ) ) || ! self::unlink_file( $from ) ) ) {
     1164                                                return new \WP_Error( 'safe_media_cleaner_cleanup', __( 'Recovery cleanup incomplete. Retry restore.', 'rapid-media-reclaim' ) );
     1165                                        }
     1166                                        $ledger_complete = true;
     1167                                        continue;
     1168                                }
     1169                                if ( file_exists( $to ) || ! is_file( $from ) || ( ! empty( $file['sha256'] ) && ! hash_equals( $file['sha256'], (string) hash_file( 'sha256', $from ) ) ) ) {
     1170                                        return new \WP_Error( 'safe_media_cleaner_conflict', __( 'A recovery file is missing, changed, or its destination is occupied. Recovery data was retained.', 'rapid-media-reclaim' ) );
     1171                                }
     1172                                if ( ! wp_mkdir_p( dirname( $to ) ) || ! self::move_file( $from, $to ) ) {
     1173                                        return new \WP_Error( 'safe_media_cleaner_restore_failed', __( 'Restore incomplete. Recovery data was retained; retry restore.', 'rapid-media-reclaim' ) );
     1174                                }
     1175                                $ledger_complete = true;
     1176                        } finally {
     1177                                $ledger_saved = $ledger_ready && Operation_Ledger::finish( $record, $file, 'restore', $ledger_complete ? ( $ledger_source ? 'verified' : 'unknown' ) : 'failed' ) && $ledger_saved;
     1178                        }
     1179                }
     1180                if ( ! $ledger_saved ) {
     1181                        return Operation_Ledger::error();
    8481182                }
    8491183
    … …  
    8671201                if ( get_post_meta( $id, self::META, true ) ) {
    8681202                        return new \WP_Error( 'safe_media_cleaner_meta', __( 'Could not clear recovery metadata. Retry restore.', 'rapid-media-reclaim' ) ); }
     1203                if ( ! Operation_Ledger::mark( $record, false ) ) {
     1204                        return Operation_Ledger::error();
     1205                }
    8691206                if ( ! self::update_record( (int) $record['id'], 'restored' ) ) {
    8701207                        return new \WP_Error( 'safe_media_cleaner_record', __( 'Files restored but recovery state could not be saved. Retry restore.', 'rapid-media-reclaim' ) ); }
    … …  
    9371274                                return new \WP_Error( 'safe_media_cleaner_purge_intent', __( 'Could not save permanent deletion authorization. Nothing was deleted.', 'rapid-media-reclaim' ) ); }
    9381275                }
     1276                foreach ( $files as $file ) {
     1277                        if ( ! Operation_Ledger::begin( $record, $file, 'remove' ) ) {
     1278                                return Operation_Ledger::error();
     1279                        }
     1280                }
     1281                if ( $files && ! Operation_Ledger::mark( $record, true ) ) {
     1282                        return Operation_Ledger::error();
     1283                }
    9391284                $group     = array_unique( array_merge( array( $id ), array_keys( $group_records ), self::shared_with( $id ) ) );
    9401285                $protected = array();
    … …  
    9581303                if ( ! self::delete_quarantined_files( $record ) ) {
    9591304                        return new \WP_Error( 'safe_media_cleaner_cleanup', __( 'Payload cleanup failed. Recovery record retained for retry.', 'rapid-media-reclaim' ) );
     1305                }
     1306                if ( $files && ! Operation_Ledger::mark( $record, false ) ) {
     1307                        return Operation_Ledger::error();
    9601308                }
    9611309                if ( ! self::update_record( (int) $record['id'], 'purged' ) ) {
    … …  
    10321380                $source = self::dir() . '/' . (int) $record['attachment_id'];
    10331381                foreach ( $files as $file ) {
    1034                         $path = $source . '/' . $file['to'];
    1035                         if ( ! self::inside( $path, self::uploads_dir() ) || ( file_exists( $path ) && ! self::unlink_file( $path ) ) ) {
    1036                                 return false; }
     1382                        if ( ! Operation_Ledger::begin( $record, $file, 'remove' ) ) {
     1383                                return false;
     1384                        }
     1385                        $path     = $source . '/' . $file['to'];
     1386                        $present  = 'present' === Operation_Ledger::storage_state( $record, $file );
     1387                        $unlinked = false;
     1388                        $removed  = self::inside( $path, self::uploads_dir() ) && ( ! file_exists( $path ) || ( $present && self::unlink_file( $path, $unlinked ) ) );
     1389                        $saved    = Operation_Ledger::finish( $record, $file, 'remove', $removed ? ( $present && $unlinked ? 'verified' : 'unknown' ) : 'failed' );
     1390                        if ( ! $removed || ! $saved ) {
     1391                                return false;
     1392                        }
    10371393                }
    10381394                self::remove_empty_dirs( $source );
    … …  
    10461402         *
    10471403         * @param int $id Id.
    1048          */
    1049         private static function attachment_files( int $id ): array {
     1404         * @return array|\WP_Error Files or a failed ownership check.
     1405         */
     1406        public static function attachment_files( int $id ) {
    10501407                $uploads  = self::uploads_dir();
    10511408                $attached = get_post_meta( $id, '_wp_attached_file', true );
    … …  
    10651422                // Files that belong to any other attachment in this folder are never ours,
    10661423                // even when their names look like one of our WebP/AVIF siblings.
    1067                 $claimed = self::claimed_names( $dir, array_merge( array( $id ), self::shared_with( $id ) ) );
     1424                $possible = array();
     1425                foreach ( $names as $name ) {
     1426                        $possible[] = $name;
     1427                        $stem       = preg_replace( '/\.[^.]+$/', '', $name );
     1428                        foreach ( array( 'webp', 'avif' ) as $ext ) {
     1429                                $possible[] = $name . '.' . $ext;
     1430                                $possible[] = $stem . '.' . $ext; }
     1431                }
     1432                $claimed = self::claimed_names( $dir, array_merge( array( $id ), self::shared_with( $id ) ), $possible );
     1433                if ( is_wp_error( $claimed ) ) {
     1434                        return $claimed; }
    10681435
    10691436                $files = array();
    … …  
    11391506         * @param string $dir     Relative folder with trailing slash, or ''.
    11401507         * @param array  $exclude Attachment IDs to ignore (the item and its copies).
    1141          */
    1142         private static function claimed_names( string $dir, array $exclude ): array {
     1508         * @param array  $candidates Optional names to retain.
     1509         * @return array|\WP_Error Ownership failure blocks the move.
     1510         */
     1511        private static function claimed_names( string $dir, array $exclude, array $candidates = array() ) {
    11431512                global $wpdb;
    1144                 $like = '' === $dir ? '%' : $wpdb->esc_like( $dir ) . '%';
    1145                 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Live ownership check before moving files; must not be cached.
    1146                 $rows    = $wpdb->get_results( $wpdb->prepare( "SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attached_file' AND meta_value LIKE %s", $like ) );
     1513                $like    = '' === $dir ? '%' : $wpdb->esc_like( $dir ) . '%';
    11471514                $exclude = array_flip( array_map( 'intval', $exclude ) );
     1515                $wanted  = array_flip( array_map( 'strtolower', $candidates ) );
    11481516                $claimed = array();
    1149                 foreach ( (array) $rows as $row ) {
    1150                         $other = (int) $row->post_id;
    1151                         $path  = ltrim( str_replace( '\\', '/', (string) $row->meta_value ), '/' );
    1152                         $odir  = dirname( $path );
    1153                         $odir  = '.' === $odir ? '' : $odir . '/';
    1154                         if ( isset( $exclude[ $other ] ) || $odir !== $dir ) {
    1155                                 continue;
    1156                         }
    1157                         foreach ( self::owned_names( $other, $path ) as $name ) {
    1158                                 $claimed[ strtolower( $name ) ] = true;
    1159                         }
    1160                 }
     1517                $cursor  = 0;
     1518                do {
     1519                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Live bounded ownership reads must not use the scan projection or a stale ownership cache.
     1520                        $rows = $wpdb->get_results( $wpdb->prepare( "SELECT meta_id,post_id,meta_value FROM {$wpdb->postmeta} WHERE meta_key='_wp_attached_file' AND meta_id>%d AND meta_value LIKE %s ORDER BY meta_id LIMIT 200", $cursor, $like ) );
     1521                        if ( $wpdb->last_error ) {
     1522                                return new \WP_Error( 'safe_media_cleaner_ownership', __( 'Could not verify file ownership. No files were moved.', 'rapid-media-reclaim' ) ); }
     1523                        $paths = array();
     1524                        foreach ( (array) $rows as $row ) {
     1525                                $cursor = (int) $row->meta_id;
     1526                                $other  = (int) $row->post_id;
     1527                                $path   = ltrim( str_replace( '\\', '/', (string) $row->meta_value ), '/' );
     1528                                $odir   = dirname( $path );
     1529                                $odir   = '.' === $odir ? '' : $odir . '/';
     1530                                if ( ! isset( $exclude[ $other ] ) && $odir === $dir ) {
     1531                                        $paths[ $other ] = $path; }
     1532                        }
     1533                        // Prime one bounded window, preserve metadata filters, and evict only
     1534                        // entries introduced here so root-level uploads cannot fill request memory.
     1535                        $introduced = array();
     1536                        foreach ( array_keys( $paths ) as $other ) {
     1537                                $found = false;
     1538                                wp_cache_get( $other, 'post_meta', false, $found );
     1539                                if ( ! $found ) {
     1540                                        $introduced[] = $other; }
     1541                        }
     1542                        try {
     1543                                if ( $paths ) {
     1544                                        update_meta_cache( 'post', array_keys( $paths ) ); }
     1545                                if ( $wpdb->last_error ) {
     1546                                        return new \WP_Error( 'safe_media_cleaner_ownership', __( 'Could not verify file ownership. No files were moved.', 'rapid-media-reclaim' ) ); }
     1547                                foreach ( $paths as $other => $path ) {
     1548                                        foreach ( self::owned_names( $other, $path ) as $name ) {
     1549                                                $name = strtolower( $name );
     1550                                                if ( ! $wanted || isset( $wanted[ $name ] ) ) {
     1551                                                        $claimed[ $name ] = true; }
     1552                                        }
     1553                                }
     1554                        } finally {
     1555                                foreach ( $introduced as $other ) {
     1556                                        wp_cache_delete( $other, 'post_meta' ); }
     1557                        }
     1558                        $count = count( (array) $rows );
     1559                } while ( 200 === $count );
    11611560                return $claimed;
    11621561        }
    … …  
    12101609        private static function in_use_now( int $id, array $record ): bool {
    12111610                global $wpdb;
    1212                 if ( (int) ( $record['hits'] ?? 0 ) > 0 || Index::usage_count( $id ) > 0 ) {
     1611                if ( (int) ( $record['hits'] ?? 0 ) > 0 || Request_Watcher::seen( $id ) > 0 || Index::usage_count( $id ) > 0 ) {
    12131612                        return true;
    12141613                }
    … …  
    12811680         *
    12821681         * @param string $path Path.
    1283          */
    1284         private static function unlink_file( string $path ): bool {
     1682         * @param bool   $unlinked Native syscall success receipt for accounting.
     1683         */
     1684        private static function unlink_file( string $path, bool &$unlinked = false ): bool {
     1685                $unlinked = false;
    12851686                if ( false === apply_filters( 'safe_media_cleaner_unlink_file_allowed', true, $path ) ) {
    12861687                        return false; }
    12871688                if ( ! self::inside( $path, self::uploads_dir() ) ) {
    12881689                        return false; }
    1289                 @unlink( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.unlink_unlink -- Delete the exact validated manifest path without third-party path filters; verify removal below.
     1690                $unlinked = @unlink( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.unlink_unlink -- Delete the exact validated manifest path without third-party path filters; verify removal below.
    12901691                clearstatcache( true, $path );
    12911692                return ! file_exists( $path );
  • rapid-media-reclaim/trunk/includes/class-request-watcher.php

    r3794616 r3814937  
    140140                $lock = 'safe_media_cleaner_watch_' . md5( DB_NAME . ':' . $wpdb->prefix );
    141141                if ( '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s,0)', $lock ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
     142                        Server_Watch::gap( 'browser_lock' );
    142143                        return $reply; }
    143144                try {
    … …  
    147148                        $count  = (int) ( ( $rate['minute'] ?? 0 ) === $minute ? ( $rate['count'] ?? 0 ) : 0 );
    148149                        if ( $count >= 60 || ! self::client_allowed() ) {
     150                                Server_Watch::gap( 'browser_rate' );
    149151                                return $reply; }
    150152                        $new_rate = array(
    … …  
    155157                        wp_cache_delete( self::RATE_OPTION, 'options' );
    156158                        if ( get_option( self::RATE_OPTION ) !== $new_rate ) {
     159                                Server_Watch::gap( 'browser_rate_persistence' );
    157160                                return $reply; }
    158161                        $ids           = array();
    159162                        $manifest_rows = self::manifest_rows();
    160163                        foreach ( array_keys( $paths ) as $path ) {
     164                                File_Quarantine::requested( $path );
    161165                                $ids = array_merge( $ids, self::matching_ids( $path, $manifest_rows ) ); }
     166                        if ( count( array_unique( $ids ) ) > 100 ) {
     167                                Server_Watch::gap( 'browser_owner_bound' );
     168                        }
    162169                        // Anonymous reports only count for media a visitor could actually see.
    163170                        $ids = array_values( array_filter( array_slice( array_unique( $ids ), 0, 100 ), array( __CLASS__, 'is_public' ) ) );
    … …  
    166173                        foreach ( $ids as $id ) {
    167174                                update_post_meta( $id, self::SEEN_META, time() );
     175                                if ( ! self::seen( $id ) ) {
     176                                        Server_Watch::gap( 'browser_hit_persistence' );
     177                                }
    168178                        }
    169179                        foreach ( array_unique( array_filter( array( Scan_Runner::current_generation(), Scan_Runner::building_generation() ) ) ) as $generation ) {
    170180                                self::write_evidence( $ids, (int) $generation ); }
    171181                        foreach ( $ids as $id ) {
    172                                 $wpdb->query( $wpdb->prepare( 'UPDATE ' . Installer::table( 'quarantine' ) . " SET hits=hits+1,last_hit_at=%s WHERE attachment_id=%d AND status='quarantined'", gmdate( 'Y-m-d H:i:s' ), $id ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     182                                $written = $wpdb->query( $wpdb->prepare( 'UPDATE ' . Installer::table( 'quarantine' ) . " SET hits=hits+1,last_hit_at=%s WHERE attachment_id=%d AND status='quarantined'", gmdate( 'Y-m-d H:i:s' ), $id ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     183                                if ( false === $written || $wpdb->last_error ) {
     184                                        Server_Watch::gap( 'browser_hit_sql' );
     185                                }
    173186                        }
    174187                        if ( ! empty( $settings['auto_restore'] ) && $ids ) {
    … …  
    176189                } catch ( \Throwable $error ) {
    177190                        // Public callers receive no database details or quarantine state.
     191                        Server_Watch::gap( 'browser_worker' );
    178192                        return $reply;
    179193                } finally {
    180                         $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock ) ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory locks must execute against the live connection and cannot be cached.
     194                        if ( '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- A failed unlock is a known interruption, never a cached result.
     195                                Server_Watch::gap( 'browser_unlock' );
     196                        }
     197                }
    181198                return $reply;
    182199        }
    … …  
    188205         */
    189206        public static function seen( int $id ): int {
     207                wp_cache_delete( $id, 'post_meta' );
    190208                return (int) get_post_meta( $id, self::SEEN_META, true );
    191209        }
    … …  
    221239                }
    222240                set_transient( $key, $count + 1, MINUTE_IN_SECONDS );
     241                if ( (int) get_transient( $key ) !== $count + 1 ) {
     242                        Server_Watch::gap( 'browser_client_rate_persistence' );
     243                        return false;
     244                }
    223245                return true;
    224246        }
    … …  
    231253                $table = Installer::table( 'quarantine' );
    232254                $rows  = $wpdb->get_results( $wpdb->prepare( "SELECT attachment_id,bytes,LEFT(files,%d) AS files FROM {$table} WHERE status=%s ORDER BY id DESC LIMIT 500", 16385, 'quarantined' ), ARRAY_A ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     255                if ( $wpdb->last_error || ! is_array( $rows ) || count( $rows ) >= 500 ) {
     256                        Server_Watch::gap( 'browser_manifest_sql_or_bound' );
     257                }
    233258                $out   = array();
    234259                $bytes = 0;
    … …  
    236261                        $length = strlen( $row['files'] );
    237262                        if ( $length > 16384 ) {
     263                                Server_Watch::gap( 'browser_manifest_bound' );
    238264                                continue; }
    239265                        if ( $bytes + $length > 1048576 ) {
     266                                Server_Watch::gap( 'browser_manifest_bound' );
    240267                                break; }
    241268                        $bytes          += $length;
    242                         $row['manifest'] = json_decode( $row['files'], true );
     269                        $row['manifest'] = json_decode( $row['files'], true, 32 );
     270                        if ( ! Server_Watch::valid_manifest( (string) $row['files'] ) ) {
     271                                Server_Watch::gap( 'browser_manifest_invalid' );
     272                                continue;
     273                        }
    243274                        unset( $row['files'] );
    244275                        if ( is_array( $row['manifest'] ) ) {
    … …  
    289320                $generation = Scan_Runner::current_generation();
    290321                $ids        = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT attachment_id FROM {$files} WHERE path = %s AND generation=%d LIMIT 100", strtolower( $path ), $generation ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     322                if ( $wpdb->last_error || count( (array) $ids ) >= 100 ) {
     323                        Server_Watch::gap( 'browser_lookup_sql_or_bound' );
     324                }
    291325                // Quarantined files can be absent from a later file map. Bound manifest work.
    292326                foreach ( $rows as $row ) {
    … …  
    339373         */
    340374        private static function write_evidence( array $ids, int $generation ): void {
     375                Status_Index::write(
     376                        array( $generation ),
     377                        static function () use ( $ids, $generation ) {
     378                                self::write_evidence_rows( $ids, $generation );
     379                        }
     380                );
     381        }
     382
     383        /**
     384         * Write observed evidence.
     385         *
     386         * @param array $ids IDs.
     387         * @param int   $generation Generation.
     388         * @throws \RuntimeException Evidence write failed.
     389         */
     390        private static function write_evidence_rows( array $ids, int $generation ): void {
    341391                global $wpdb;
    342392                if ( $generation < 1 ) {
  • rapid-media-reclaim/trunk/includes/class-scan-runner.php

    r3794616 r3814937  
    2020final class Scan_Runner {
    2121
    22         const OPTION    = 'safe_media_cleaner_scan_state';
    23         const LOCK      = 'safe_media_cleaner_scan_lock';
    24         const CRON_HOOK = 'safe_media_cleaner_scan_continue';
     22        const OPTION         = 'safe_media_cleaner_scan_state';
     23        const LOCK           = 'safe_media_cleaner_scan_lock';
     24        const CRON_HOOK      = 'safe_media_cleaner_scan_continue';
     25        const CLEANUP_HOOK   = 'safe_media_cleaner_index_cleanup';
     26        const CLEANUP_CURSOR = 'safe_media_cleaner_index_cleanup_cursor';
    2527
    2628        /** Seconds of work per step. */
    … …  
    3537        public static function init(): void {
    3638                add_action( self::CRON_HOOK, array( __CLASS__, 'cron_step' ) );
     39                add_action( self::CLEANUP_HOOK, array( __CLASS__, 'cleanup_old_index' ) );
    3740        }
    3841
    … …  
    130133
    131134                $state = array(
    132                         'status'      => 'running',
    133                         'generation'  => $generation,
    134                         'phases'      => $phases,
    135                         'phase_index' => 0,
    136                         'cursor'      => null,
    137                         'phase_done'  => 0,
    138                         'started_at'  => time(),
    139                         'finished_at' => null,
    140                         'error'       => null,
     135                        'status'            => 'running',
     136                        'generation'        => $generation,
     137                        'phases'            => $phases,
     138                        'phase_index'       => 0,
     139                        'cursor'            => null,
     140                        'phase_done'        => 0,
     141                        'started_at'        => time(),
     142                        'finished_at'       => null,
     143                        'error'             => null,
     144                        'incremental_fault' => Deferred_Index::fault_token(),
    141145                );
    142146                self::save( $state );
    … …  
    218222        public static function cron_step(): void {
    219223                // The admin screen may also be stepping; the lock keeps them apart.
    220                 self::step();
     224                try {
     225                        self::step();
     226                } finally {
     227                        self::repair_continuation();
     228                }
    221229        }
    222230
    … …  
    259267                                return self::abandon( (int) $state['generation'] );
    260268                        }
    261                         $state = self::finish( $state, $engine );
     269                        $state = self::finish( $state, $engine, $deadline );
    262270                }
    263271
    … …  
    282290         * @param array  $state State.
    283291         * @param Engine $engine Engine.
    284          */
    285         private static function finish( array $state, Engine $engine ): array {
     292         * @param float  $deadline Step deadline.
     293         */
     294        private static function finish( array $state, Engine $engine, float $deadline ): array {
    286295                $generation = (int) $state['generation'];
    287                 $previous   = self::current_generation();
    288 
    289                 Request_Watcher::replay( $generation );
    290                 self::link_shared_files( $generation );
     296
     297                if ( microtime( true ) >= $deadline ) {
     298                        return $state;
     299                }
     300                if ( empty( $state['watch_replayed'] ) ) {
     301                        Request_Watcher::replay( $generation );
     302                        $state['watch_replayed'] = true;
     303                }
     304                do {
     305                        $shared                 = self::link_shared_files( $generation, (int) ( $state['shared_cursor'] ?? 0 ) );
     306                        $state['shared_cursor'] = $shared['cursor'];
     307                        self::save( $state );
     308                        if ( ! self::still_running( $generation ) ) {
     309                                return self::abandon( $generation );
     310                        }
     311                } while ( ! $shared['done'] && microtime( true ) < $deadline );
     312                if ( ! $shared['done'] ) {
     313                        return $state;
     314                }
    291315                update_option( 'safe_media_cleaner_index_generation', $generation, false );
    292316                update_option(
    … …  
    306330                self::save( $state );
    307331
    308                 if ( $previous && $previous !== $generation ) {
    309                         self::delete_generation_rows( $previous );
    310                 }
    311                 self::delete_stale_rows( $generation );
     332                Deferred_Index::clear_fault( (string) ( $state['incremental_fault'] ?? '' ) );
     333                self::schedule_cleanup();
     334                Status_Index::schedule();
    312335
    313336                return $state;
    … …  
    319342         *
    320343         * @param int $generation Generation.
    321          */
    322         private static function link_shared_files( int $generation ): void {
     344         * @param int $after Last processed file-row ID.
     345         * @throws \RuntimeException Database read/write failure.
     346         */
     347        private static function link_shared_files( int $generation, int $after ): array {
    323348                global $wpdb;
    324349                $files = Installer::table( 'files' );
    325350                $refs  = Installer::table( 'refs' );
    326                 // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table names only.
    327                 // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    328                 $wpdb->query(
     351                // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Internal table identifiers; live cursor batches, values prepared.
     352                $ids = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM {$files} WHERE generation=%d AND kind='original' AND id>%d ORDER BY id LIMIT 500", $generation, $after ) );
     353                if ( $wpdb->last_error ) {
     354                        throw new \RuntimeException( 'Could not read shared-file inventory.' );
     355                }
     356                if ( ! $ids ) {
     357                        return array(
     358                                'cursor' => $after,
     359                                'done'   => true,
     360                        );
     361                }
     362                $list    = implode( ',', array_map( 'intval', $ids ) );
     363                $written = $wpdb->query(
    329364                        $wpdb->prepare(
    330                                 "INSERT INTO {$refs} (attachment_id, strength, source_type, source_id, source_key, context, match_type, generation)
    331                                 SELECT DISTINCT other.attachment_id, 'strong', 'shared_file', used.attachment_id, '', %s, 'id', %d
    332                                 FROM {$files} used
    333                                 JOIN {$files} other ON other.path = used.path AND other.attachment_id <> used.attachment_id
    334                                         AND other.generation = %d AND other.kind = 'original'
    335                                 WHERE used.generation = %d AND used.kind = 'original'
    336                                         AND EXISTS ( SELECT 1 FROM {$refs} r WHERE r.attachment_id = used.attachment_id AND r.generation = %d
    337                                                 AND r.strength = 'strong' AND r.source_type <> 'shared_file' )",
     365                                "INSERT INTO {$refs} (attachment_id,strength,source_type,source_id,source_key,context,match_type,generation)
     366                        SELECT DISTINCT other.attachment_id,'strong','shared_file',used.attachment_id,'',%s,'id',%d
     367                        FROM {$files} used
     368                        STRAIGHT_JOIN {$files} other ON other.generation=%d AND other.kind='original' AND other.path=used.path AND other.attachment_id<>used.attachment_id
     369                        WHERE used.id IN ({$list}) AND used.generation=%d AND used.kind='original'
     370                        AND EXISTS (SELECT 1 FROM {$refs} r WHERE r.attachment_id=used.attachment_id AND r.generation=%d AND r.strength='strong' AND r.source_type<>'shared_file')
     371                        AND NOT EXISTS (SELECT 1 FROM {$refs} r WHERE r.attachment_id=other.attachment_id AND r.generation=%d AND r.source_type='shared_file' AND r.source_id=used.attachment_id)",
    338372                                __( 'Shares its file with another media item', 'rapid-media-reclaim' ),
     373                                $generation,
    339374                                $generation,
    340375                                $generation,
    … …  
    343378                        )
    344379                );
    345                 // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    346                 // phpcs:enable
     380                // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
     381                if ( false === $written ) {
     382                        throw new \RuntimeException( 'Could not preserve shared-file usage evidence.' );
     383                }
     384                return array(
     385                        'cursor' => (int) max( $ids ),
     386                        'done'   => count( $ids ) < 500,
     387                );
    347388        }
    348389
    … …  
    359400                delete_option( 'safe_media_cleaner_adapter_gap_' . $generation . '_elementor' );
    360401                delete_option( 'safe_media_cleaner_adapter_gap_' . $generation . '_acf' );
    361                 foreach ( array( 'files', 'refs' ) as $name ) {
     402                delete_option( 'safe_media_cleaner_adapter_gap_' . $generation . '_database' );
     403                foreach ( array( 'files', 'refs', 'status' ) as $name ) {
    362404                        $table = Installer::table( $name );
    363405                        do {
    … …  
    367409        }
    368410
    369         /**
    370          * Remove rows left over from any generation other than the current one.
    371          *
    372          * @param int $generation Generation.
    373          */
    374         private static function delete_stale_rows( int $generation ): void {
     411        /** Queue cleanup separately from publishing a completed scan. */
     412        private static function schedule_cleanup(): void {
     413                if ( ! wp_next_scheduled( self::CLEANUP_HOOK ) ) {
     414                        wp_schedule_single_event( time() + 5, self::CLEANUP_HOOK );
     415                }
     416        }
     417
     418        /**
     419         * Delete obsolete index data with a two-second cooperative budget and four-query cap.
     420         *
     421         * Each SQL delete is limited to 1,000 rows. The scan lock protects publication
     422         * and generation reuse. Failed or busy work is retried without changing scan status.
     423         * A single database operation cannot be interrupted by the PHP deadline.
     424         *
     425         * @return array Cleanup progress, never a media deletion result.
     426         */
     427        public static function cleanup_old_index(): array {
    375428                global $wpdb;
    376                 // Per-generation bookkeeping of earlier, cancelled or abandoned scans.
    377                 $names = $wpdb->get_col( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'safe\\_media\\_cleaner\\_scan\\_coverage\\_%' OR option_name LIKE 'safe\\_media\\_cleaner\\_crawl\\_%' OR option_name LIKE 'safe\\_media\\_cleaner\\_adapter\\_%'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Option names by prefix; no API lists them.
    378                 foreach ( (array) $names as $name ) {
    379                         // Match generation numbers in scan coverage, crawl and adapter bookkeeping names.
    380                         if ( preg_match( '/_(?:coverage|crawl|gap)_(\d+)(?:_[a-z]+)?$/', $name, $m ) && (int) $m[1] !== $generation ) {
    381                                 delete_option( $name );
    382                         }
    383                 }
    384                 foreach ( array( 'files', 'refs' ) as $name ) {
    385                         $table = Installer::table( $name );
    386                         do {
    387                                 $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE generation <> %d LIMIT 5000", $generation ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    388                         } while ( $deleted > 0 );
    389                 }
     429                $result = array(
     430                        'deleted' => 0,
     431                        'pending' => false,
     432                        'error'   => false,
     433                );
     434                if ( ! self::lock() ) {
     435                        self::schedule_cleanup();
     436                        $result['pending'] = true;
     437                        return $result;
     438                }
     439                try {
     440                        wp_cache_delete( 'safe_media_cleaner_index_generation', 'options' );
     441                        wp_cache_delete( self::OPTION, 'options' );
     442                        $generation = self::current_generation();
     443                        $state      = self::raw();
     444                        $building   = 'running' === $state['status'] ? (int) $state['generation'] : $generation;
     445                        $deadline   = microtime( true ) + 2.0;
     446                        // Both protected generations are reread only after acquiring the scan lock.
     447                        // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Internal table names, prepared values, fresh bounded maintenance queries.
     448                        $delete_queries = 0;
     449                        foreach ( array( 'files', 'refs', 'status' ) as $name ) {
     450                                $table = Installer::table( $name );
     451                                for ( $batch = 0; $batch < 2; ++$batch ) {
     452                                        if ( microtime( true ) >= $deadline || $delete_queries >= 4 ) {
     453                                                $result['pending'] = true;
     454                                                break 2;
     455                                        }
     456                                        ++$delete_queries;
     457                                        $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE generation NOT IN (%d,%d) LIMIT 1000", $generation, $building ) );
     458                                        if ( false === $deleted ) {
     459                                                $result['error']   = true;
     460                                                $result['pending'] = true;
     461                                                break 2;
     462                                        }
     463                                        $result['deleted'] += $deleted;
     464                                        if ( $deleted < 1000 ) {
     465                                                break;
     466                                        }
     467                                        $result['pending'] = true;
     468                                }
     469                        }
     470                        if ( microtime( true ) >= $deadline ) {
     471                                $result['pending'] = true;
     472                        } else {
     473                                $cursor = (string) get_option( self::CLEANUP_CURSOR, '' );
     474                                $names  = $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE (option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s) AND option_name>%s ORDER BY option_name LIMIT 50", $wpdb->esc_like( 'safe_media_cleaner_scan_coverage_' ) . '%', $wpdb->esc_like( 'safe_media_cleaner_crawl_' ) . '%', $wpdb->esc_like( 'safe_media_cleaner_adapter_' ) . '%', $cursor ) );
     475                                if ( $wpdb->last_error ) {
     476                                        $result['error']   = true;
     477                                        $result['pending'] = true;
     478                                } else {
     479                                        foreach ( $names as $name ) {
     480                                                if ( microtime( true ) >= $deadline ) {
     481                                                        $result['pending'] = true;
     482                                                        break;
     483                                                }
     484                                                $cursor = $name;
     485                                                if ( preg_match( '/_(?:coverage|crawl|gap)_(\d+)(?:_[a-z]+)?$/', $name, $match ) && ! in_array( (int) $match[1], array( $generation, $building ), true ) ) {
     486                                                        delete_option( $name );
     487                                                }
     488                                        }
     489                                        $complete = ! $names || end( $names ) === $cursor;
     490                                        update_option( self::CLEANUP_CURSOR, $complete && 50 > count( $names ) ? '' : $cursor, false );
     491                                        $result['pending'] = $result['pending'] || ! $complete || 50 === count( $names );
     492                                }
     493                        }
     494                        // phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
     495                } finally {
     496                        self::unlock();
     497                }
     498                if ( $result['pending'] ) {
     499                        self::schedule_cleanup();
     500                }
     501                return $result;
    390502        }
    391503
    … …  
    402514        }
    403515
     516        /** Repair a missing event without running scan work in the maintenance request. */
     517        public static function repair_continuation(): void {
     518                wp_cache_delete( self::OPTION, 'options' );
     519                if ( 'running' === self::raw()['status'] ) {
     520                        self::schedule_cron();
     521                }
     522        }
     523
    404524        /**
    405525         * Schedule the next background scan step.
    … …  
    407527        private static function schedule_cron(): void {
    408528                if ( ! wp_next_scheduled( self::CRON_HOOK ) ) {
    409                         wp_schedule_single_event( time() + 60, self::CRON_HOOK );
     529                        wp_schedule_single_event( time() + 5, self::CRON_HOOK );
    410530                }
    411531        }
    … …  
    488608                        'status'      => $state['status'],
    489609                        'phase'       => $current ? $current['id'] : null,
    490                         'phase_label' => $current ? $current['label'] : null,
     610                        'phase_label' => 'running' === $state['status'] && $state['phase_index'] >= count( $phases ) ? __( 'Finalizing shared-file evidence', 'rapid-media-reclaim' ) : ( $current ? $current['label'] : null ),
    491611                        'phase_index' => (int) $state['phase_index'],
    492612                        'phase_count' => count( $phases ),
  • rapid-media-reclaim/trunk/includes/class-settings.php

    r3794616 r3814937  
    2929                        'frontend_crawl'  => false,
    3030                        'crawl_limit'     => 100,
     31                        'upload_aliases'  => array(),
    3132                );
    3233        }
    … …  
    5960                $values = array_merge( self::defaults(), array_intersect_key( $values, self::defaults() ) );
    6061                return array(
    61                         'quarantine_days' => max( 0, min( 365, (int) $values['quarantine_days'] ) ),
     62                        'quarantine_days' => max( 14, min( 365, (int) $values['quarantine_days'] ) ),
    6263                        'include_drafts'  => (bool) $values['include_drafts'],
    6364                        'include_trash'   => (bool) $values['include_trash'],
    … …  
    6667                        'frontend_crawl'  => rest_sanitize_boolean( $values['frontend_crawl'] ),
    6768                        'crawl_limit'     => max( 1, min( 500, (int) $values['crawl_limit'] ) ),
     69                        'upload_aliases'  => self::aliases( $values['upload_aliases'] ),
    6870                );
    6971        }
     72        /**
     73         * Validate explicit old/CDN upload roots; aliases never authorize network requests.
     74         *
     75         * @param mixed $values User-supplied roots.
     76         */
     77        public static function aliases( $values ): array {
     78                $out = array();
     79                foreach ( is_array( $values ) ? array_slice( $values, 0, 10 ) : array() as $value ) {
     80                        if ( ! is_string( $value ) || strlen( $value ) > 2048 ) {
     81                                continue;
     82                        }
     83                        $parts = wp_parse_url( $value );
     84                        if ( ! is_array( $parts ) || ! in_array( strtolower( $parts['scheme'] ?? '' ), array( 'http', 'https' ), true ) || empty( $parts['host'] ) || isset( $parts['user'] ) || isset( $parts['pass'] ) || isset( $parts['query'] ) || isset( $parts['fragment'] ) || preg_match( '~[\\\\\x00-\x20]|(?:^|/)\.{1,2}(?:/|$)~', $value ) ) {
     85                                continue;
     86                        }
     87                        $out[] = rtrim( esc_url_raw( $value, array( 'http', 'https' ) ), '/' );
     88                }
     89                return array_values( array_unique( array_filter( $out ) ) );
     90        }
    7091}
  • rapid-media-reclaim/trunk/includes/rest/class-controller.php

    r3794616 r3814937  
    2929
    3030        /** Most IDs accepted by one bulk request. */
    31         const MAX_IDS = 500;
     31        const MAX_IDS      = 500;
     32        const MAX_FILE_IDS = 10;
    3233
    3334        /** Most IDs returned by "select all matching". */
    … …  
    7273                );
    7374                $this->route( '/usage', $read, 'get_usage', array( 'ids' => $this->ids_arg( true ) ) );
    74                 $this->route( '/quarantine', $write, 'quarantine', array( 'ids' => $this->ids_arg( true ) ) );
     75                $this->route( '/quarantine', $write, 'quarantine', array( 'ids' => $this->ids_arg( true, self::MAX_FILE_IDS ) ) );
    7576                $this->route(
    7677                        '/restore',
    … …  
    7879                        'restore',
    7980                        array(
    80                                 'ids'   => $this->ids_arg( false ),
     81                                'ids'   => $this->ids_arg( false, self::MAX_FILE_IDS ),
    8182                                'batch' => array(
    8283                                        'type'      => 'string',
    … …  
    9596                                        'default' => false,
    9697                                ),
    97                                 'ids'        => $this->ids_arg( true ),
     98                                'ids'        => $this->ids_arg( true, self::MAX_FILE_IDS ),
    9899                                'force'      => array(
    99100                                        'type'    => 'boolean',
    … …  
    131132                                                'quarantine_days' => array(
    132133                                                        'type'    => 'integer',
    133                                                         'minimum' => 0,
     134                                                        'minimum' => 14,
    134135                                                        'maximum' => 365,
     136                                                ),
     137                                                'upload_aliases'  => array(
     138                                                        'type'     => 'array',
     139                                                        'maxItems' => 10,
     140                                                        'items'    => array(
     141                                                                'type'      => 'string',
     142                                                                'maxLength' => 2048,
     143                                                                'pattern'   => '^https?://',
     144                                                        ),
    135145                                                ),
    136146                                                'include_drafts'  => array( 'type' => 'boolean' ),
    … …  
    174184         */
    175185        public static function summary_payload(): array {
    176                 return array(
    177                         'summary'  => Index::summary(),
     186                $summary = Index::summary();
     187                \SafeMediaCleaner\Savings_Report::remember_estimate( $summary );
     188                return array(
     189                        'summary'  => $summary,
    178190                        'scan'     => Scan_Runner::state(),
    179191                        'settings' => Settings::get(),
    … …  
    337349                $ids   = (array) $request['ids'];
    338350                if ( '' !== $batch ) {
    339                         $result = Quarantine::restore_batch( $batch );
     351                        $result = Quarantine::restore_batch( $batch, self::MAX_FILE_IDS );
    340352                } elseif ( $ids ) {
    341353                        $result = Quarantine::restore( Index::with_copies( $ids ) );
    … …  
    409421                }
    410422                $values = array();
    411                 foreach ( array( 'quarantine_days', 'include_drafts', 'include_trash', 'request_watch', 'auto_restore', 'frontend_crawl', 'crawl_limit' ) as $key ) {
     423                foreach ( array( 'quarantine_days', 'include_drafts', 'include_trash', 'request_watch', 'auto_restore', 'frontend_crawl', 'crawl_limit', 'upload_aliases' ) as $key ) {
    412424                        if ( null !== $request->get_param( $key ) ) {
    413425                                $values[ $key ] = $request->get_param( $key );
    … …  
    420432                        'settings'     => $settings,
    421433                        // Changing what counts as use only takes effect after a new scan.
    422                         'needs_rescan' => $before['include_drafts'] !== $settings['include_drafts'] || $before['include_trash'] !== $settings['include_trash'] || $before['frontend_crawl'] !== $settings['frontend_crawl'] || $before['crawl_limit'] !== $settings['crawl_limit'],
     434                        'needs_rescan' => $before['include_drafts'] !== $settings['include_drafts'] || $before['include_trash'] !== $settings['include_trash'] || $before['frontend_crawl'] !== $settings['frontend_crawl'] || $before['crawl_limit'] !== $settings['crawl_limit'] || $before['upload_aliases'] !== $settings['upload_aliases'],
    423435                        'summary'      => Index::summary(),
    424436                );
    … …  
    488500         *
    489501         * @param bool $required Required.
    490          */
    491         private function ids_arg( bool $required ): array {
     502         * @param int  $limit Maximum request IDs.
     503         */
     504        private function ids_arg( bool $required, int $limit = self::MAX_IDS ): array {
    492505                return array(
    493506                        'type'              => 'array',
    … …  
    497510                        ),
    498511                        'minItems'          => $required ? 1 : 0,
    499                         'maxItems'          => self::MAX_IDS,
     512                        'maxItems'          => $limit,
    500513                        'required'          => $required,
    501                         'sanitize_callback' => static function ( $value ) {
    502                                 return array_slice( array_values( array_unique( array_filter( wp_parse_id_list( $value ) ) ) ), 0, self::MAX_IDS );
     514                        'sanitize_callback' => static function ( $value ) use ( $limit ) {
     515                                return array_slice( array_values( array_unique( array_filter( wp_parse_id_list( $value ) ) ) ), 0, $limit );
    503516                        },
    504517                        'validate_callback' => 'rest_validate_request_arg',
  • rapid-media-reclaim/trunk/includes/scan/class-acf-adapter.php

    r3794616 r3814937  
    1717         * Extract media evidence. Limits apply across the complete input walk.
    1818         *
    19          * @param mixed  $value Stored metadata value.
    20          * @param array  $field Trusted persisted field definition.
    21          * @param string $path Actual metadata storage key.
     19         * @param mixed      $value Stored metadata value.
     20         * @param array      $field Trusted persisted field definition.
     21         * @param string     $path Actual metadata storage key.
     22         * @param array|null $budget Shared owner counters.
    2223         * @return array References and distinct coverage issue reasons.
    2324         */
    24         public static function extract( $value, array $field, string $path = '' ): array {
    25                 $result  = array(
     25        public static function extract( $value, array $field, string $path = '', ?array &$budget = null ): array {
     26                if ( null === $budget ) {
     27                        $budget = array(
     28                                'nodes' => 0,
     29                                'bytes' => 0,
     30                                'refs'  => 0,
     31                        );
     32                }
     33                $result = array(
    2634                        'refs'   => array(),
    2735                        'issues' => array(),
    2836                );
    29                 $type    = isset( $field['type'] ) && is_string( $field['type'] ) ? $field['type'] : '';
     37                $type   = isset( $field['type'] ) && is_string( $field['type'] ) ? $field['type'] : '';
     38                if ( ! empty( $field['_structural_validated'] ) && in_array( $type, array( 'group', 'repeater', 'flexible_content' ), true ) ) {
     39                        return $result; // Owner validator consumed selectors; they are never references.
     40                }
    3041                $media   = in_array( $type, array( 'image', 'file', 'gallery' ), true );
    3142                $known   = in_array( $type, array( 'text', 'textarea', 'number', 'range', 'email', 'url', 'password', 'select', 'checkbox', 'radio', 'button_group', 'true_false', 'post_object', 'relationship', 'taxonomy', 'user', 'date_picker', 'date_time_picker', 'time_picker', 'color_picker', 'message', 'tab', 'accordion' ), true );
    … …  
    4152                        list( $item, $depth, $eligible ) = array_pop( $stack );
    4253                        ++$nodes;
    43                         if ( $depth > 24 || $nodes > 5000 || $bytes > 524288 ) {
     54                        ++$budget['nodes'];
     55                        if ( $depth > 24 || $nodes > 5000 || $bytes > 524288 || $budget['nodes'] > 5000 || $budget['bytes'] > 4194304 ) {
    4456                                $result['issues'][] = 'acf_budget_exceeded';
    4557                                break;
    … …  
    6476                                continue;
    6577                        }
    66                         $text   = trim( (string) $item );
    67                         $bytes += strlen( $text );
     78                        $text             = trim( (string) $item );
     79                        $bytes           += strlen( $text );
     80                        $budget['bytes'] += strlen( $text );
    6881                        if ( $bytes > 524288 ) {
    6982                                $result['issues'][] = 'acf_budget_exceeded';
    … …  
    112125                        }
    113126                        if ( $match ) {
    114                                 if ( count( $result['refs'] ) >= 1000 ) {
     127                                if ( $budget['refs'] >= 1000 ) {
    115128                                        $result['issues'][] = 'acf_reference_limit_exceeded';
    116129                                        break;
    117130                                }
     131                                ++$budget['refs'];
    118132                                $result['refs'][] = array(
    119133                                        'value'      => $item,
  • rapid-media-reclaim/trunk/includes/scan/class-adapter-coverage.php

    r3794616 r3814937  
    2626                $option = 'safe_media_cleaner_adapter_coverage_' . $generation;
    2727                $state  = get_option( $option, array() );
    28                 foreach ( array( 'elementor', 'acf' ) as $adapter ) {
     28                foreach ( array( 'elementor', 'acf', 'database' ) as $adapter ) {
    2929                        if ( empty( $reports[ $adapter ] ) ) {
    3030                                continue;
    … …  
    3535                        }
    3636                        $state[ $adapter ]['sources'] = min( 1000000, (int) ( $state[ $adapter ]['sources'] ?? 0 ) + (int) $reports[ $adapter ]['sources'] );
     37                        if ( 'database' === $adapter ) {
     38                                $examples = (array) ( $state[ $adapter ]['examples'] ?? array() );
     39                                foreach ( $reports[ $adapter ]['examples'] ?? array() as $sample ) {
     40                                        $sample = array(
     41                                                'phase' => sanitize_key( $sample['phase'] ?? '' ),
     42                                                'id'    => max( 0, (int) ( $sample['id'] ?? 0 ) ),
     43                                                'key'   => substr( sanitize_text_field( $sample['key'] ?? '' ), 0, 191 ),
     44                                        );
     45                                        if ( count( $examples ) < 20 && ! in_array( $sample, $examples, true ) ) {
     46                                                $examples[] = $sample; }
     47                                }
     48                                $state[ $adapter ]['examples'] = $examples;
     49                        }
    3750                        foreach ( $reports[ $adapter ]['issues'] as $reason => $count ) {
    3851                                // Reasons are adapter constants, never source text. Retain at most 16 keys.
    … …  
    5871                        'elementor' => __( 'Elementor structured media', 'rapid-media-reclaim' ),
    5972                        'acf'       => __( 'ACF typed fields', 'rapid-media-reclaim' ),
     73                        'database'  => __( 'Database source limits', 'rapid-media-reclaim' ),
    6074                );
    6175                $out    = array();
    … …  
    7488                                ),
    7589                        );
     90                        if ( 'database' === $adapter ) {
     91                                $examples = (array) ( $state[ $adapter ]['examples'] ?? array() );
     92                                $first    = get_option( 'safe_media_cleaner_adapter_gap_' . $generation . '_database', array() );
     93                                if ( ! $examples && is_array( $first ) && isset( $first['phase'] ) ) {
     94                                        $examples = array( $first ); }
     95                                $out[ count( $out ) - 1 ]['detail']['examples'] = $examples; }
    7696                }
    7797                return $out;
    … …  
    104124                        $coverage,
    105125                        static function ( $entry ) {
    106                                 return ! in_array( $entry['id'] ?? '', array( 'elementor_adapter', 'acf_adapter' ), true );
     126                                return ! in_array( $entry['id'] ?? '', array( 'elementor_adapter', 'acf_adapter', 'database_adapter' ), true );
    107127                        }
    108128                );
  • rapid-media-reclaim/trunk/includes/scan/class-database-scanner.php

    r3794616 r3814937  
    125125         */
    126126        private function eligible(): string {
     127                if ( 'options' === $this->phase ) {
     128                        global $wpdb;
     129                        return $wpdb->prepare( 'option_name NOT LIKE %s AND option_name NOT LIKE %s', $wpdb->esc_like( '_transient_' ) . '%', $wpdb->esc_like( '_site_transient_' ) . '%' );
     130                }
    127131                if ( 'posts' !== $this->phase ) {
    128132                        return '1=1';
    … …  
    149153         */
    150154        public static function option_allowed( string $name ): bool {
     155                if ( 'elementor_log' === $name ) {
     156                        return false;
     157                }
    151158                if ( preg_match( '/^(?:_transient_|_site_transient_|safe_media_cleaner_|_?connectors_)|^(?:cron|rewrite_rules|active_plugins)$|_user_roles$|(?:^|[_-])(?:api[_-]?keys?|access[_-]?tokens?|refresh[_-]?tokens?|tokens?|secrets?|passwords?|credentials?|private[_-]?keys?)(?:$|[_-])/i', $name ) ) {
    152159                        return false;
    … …  
    173180        public function scan( $cursor, int $limit, Ref_Collector $refs ) {
    174181                global $wpdb;
     182                if ( 'options' === $this->phase ) {
     183                        $limit = min( 2, $limit );
     184                }
    175185                list( $table, $pk ) = $this->table_info();
    176186                $where              = $this->eligible();
    … …  
    237247         * @param bool   $weak Weak.
    238248         * @param bool   $force_ids Force ids.
    239          */
    240         private function evidence( $value, string $type, int $id, string $key, string $context, bool $weak = false, bool $force_ids = false ): void {
    241                 $items = Extractor::extract( $value, $force_ids ? 'attachment_id' : $key, $context );
    242                 foreach ( $items as $item ) {
     249         * @param array  $budget Optional extraction budget shared by one stored record.
     250         * @param bool   $structural Whether this source contains structural selectors, never media IDs.
     251         * @throws \RuntimeException The cleanup restriction for a partly read value could not be saved.
     252         */
     253        private function evidence( $value, string $type, int $id, string $key, string $context, bool $weak = false, bool $force_ids = false, ?array &$budget = null, bool $structural = false ): void {
     254                $result = Extractor::extract_result( $value, $force_ids ? 'attachment_id' : $key, $context, $budget );
     255                if ( ! $result['complete'] ) {
     256                        // Evidence found before the limit is kept; the unread remainder pauses cleanup.
     257                        $this->source_gap( $id, $key, (string) array_key_first( $result['issues'] ) );
     258                }
     259                foreach ( $result['refs'] as $item ) {
     260                        if ( $structural && 'id' === $item['match_type'] ) {
     261                                continue; // A generic image-like name cannot turn a row count into media.
     262                        }
    243263                        $item['source_type'] = $type;
    244264                        $item['source_id']   = $id;
    … …  
    269289                        $field = 1 === count( $fields ) ? $fields[0] : null;
    270290                        // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Bounded stored definition, class hydration disabled.
    271                         $config            = $field && is_string( $field->post_content ) ? @unserialize(
     291                        $config = $field && is_string( $field->post_content ) ? @unserialize(
    272292                                $field->post_content,
    273293                                array(
    … …  
    276296                                )
    277297                        ) : array(); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Decode bounded existing field definitions with object hydration disabled.
     298                        // Read only definitions already registered by active ACF. Never include PHP
     299                        // files or ask ACF to load arbitrary paths while scanning.
     300                        if ( function_exists( 'acf_get_local_field' ) ) {
     301                                $local = acf_get_local_field( $key );
     302                                if ( is_array( $local ) && isset( $local['type'] ) && is_string( $local['type'] ) ) {
     303                                        $this->acf[ $key ] = array(
     304                                                'label' => isset( $local['label'] ) && is_string( $local['label'] ) ? substr( $local['label'], 0, 500 ) : '',
     305                                                'type'  => $local['type'],
     306                                        );
     307                                        return $this->acf[ $key ];
     308                                }
     309                        }
    278310                        $this->acf[ $key ] = array(
    279311                                'label' => $field ? $field->post_title : '',
    … …  
    282314                }
    283315                return $this->acf[ $key ];
     316        }
     317
     318        /**
     319         * Read a saved template without object hydration or unbounded metadata values.
     320         *
     321         * @param int $id Template ID.
     322         * @return array|null Bounded document, null if missing, ambiguous or unreadable.
     323         */
     324        private static function elementor_document( int $id ): ?array {
     325                global $wpdb;
     326                $rows = $wpdb->get_results( $wpdb->prepare( "SELECT m.meta_key,IF(OCTET_LENGTH(m.meta_value)<=524288,m.meta_value,NULL) AS meta_value FROM {$wpdb->postmeta} m INNER JOIN {$wpdb->posts} p ON p.ID=m.post_id WHERE p.ID=%d AND p.post_type='elementor_library' AND p.post_status NOT IN ('trash','auto-draft') AND m.meta_key IN ('_elementor_data','_elementor_page_settings') LIMIT 3", $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Prepared, byte-bounded dependency metadata lookup; no object hydration.
     327                $data = array();
     328                foreach ( $rows as $row ) {
     329                        if ( null === $row->meta_value || isset( $data[ $row->meta_key ] ) ) {
     330                                return null;
     331                        }
     332                        $data[ $row->meta_key ] = $row->meta_value;
     333                }
     334                if ( $wpdb->last_error || ! isset( $data['_elementor_data'] ) ) {
     335                        return null;
     336                }
     337                $settings = array();
     338                if ( ! empty( $data['_elementor_page_settings'] ) ) {
     339                        // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Bounded stored settings; object hydration disabled.
     340                        $settings = @unserialize(
     341                                $data['_elementor_page_settings'],
     342                                array(
     343                                        'allowed_classes' => false,
     344                                        'max_depth'       => 24,
     345                                )
     346                        );
     347                }
     348                $content = json_decode( $data['_elementor_data'], true, 25 );
     349                if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $content ) ) {
     350                        return null;
     351                }
     352                return array(
     353                        'content'       => $content,
     354                        'page_settings' => $settings,
     355                );
    284356        }
    285357
    … …  
    317389                        $this->pending[] = $ref;
    318390                }
     391        }
     392
     393        /**
     394         * Index Beaver Builder storage, including its stdClass nodes, without class hydration.
     395         *
     396         * Layout keys get typed photo, background and gallery evidence. Every Beaver value
     397         * that cannot be decoded completely (custom or incomplete classes, cycles, malformed
     398         * bytes, budgets) is a database source gap, which pauses mutations.
     399         *
     400         * @param string $value Raw stored value.
     401         * @param int    $id Post ID.
     402         * @param string $key Exact metadata key.
     403         * @param bool   $weak Whether source status requires weak evidence.
     404         * @return mixed Value for the generic walk: the plain decoded array when available.
     405         */
     406        private function beaver_evidence( string $value, int $id, string $key, bool $weak ) {
     407                $layout = in_array( $key, array( '_fl_builder_data', '_fl_builder_draft' ), true );
     408                if ( ! $layout && ! preg_match( '/^(?:a|O):[0-9]+:/', $value ) ) {
     409                        return $value;
     410                }
     411                $decoded = Builder_Adapter::beaver_decode( $value );
     412                $issues  = $decoded['issues'];
     413                if ( $layout ) {
     414                        $result = null === $decoded['value'] ? array(
     415                                'refs'   => array(),
     416                                'issues' => $issues,
     417                        ) : Builder_Adapter::extract( $decoded['value'], 'Beaver Builder' );
     418                        $this->adapter_evidence( $result, 'builders', 'builder', $id, $key, $weak );
     419                        $issues = $result['issues'];
     420                }
     421                // Unknown controls still reach the generic walk; any other issue left values unread.
     422                if ( array_diff( $issues, array( 'builder_custom_controls_not_resolved' ) ) ) {
     423                        $this->source_gap( $id, $key, 'beaver_source_unreadable' );
     424                }
     425                // Never send rejected serialized graphs to the generic decoder a second time.
     426                // The durable gap above preserves the restriction; only normalized arrays are safe.
     427                return $decoded['value'] ?? array();
     428        }
     429
     430        /**
     431         * Keep unread database values visible, even if a later worker is interrupted.
     432         *
     433         * @param int    $id Source ID.
     434         * @param string $key Metadata key or option name; values are never retained.
     435         * @param string $reason Machine reason constant, never source text.
     436         * @throws \RuntimeException The durable cleanup restriction could not be saved.
     437         */
     438        private function source_gap( int $id = 0, string $key = '', string $reason = 'database_source_budget_exceeded' ): void {
     439                $report = $this->adapter_reports['database'] ?? array(
     440                        'sources'  => 1,
     441                        'issues'   => array(),
     442                        'examples' => array(),
     443                );
     444                $sample = array(
     445                        'phase' => $this->phase,
     446                        'id'    => $id,
     447                        'key'   => substr( $key, 0, 191 ),
     448                );
     449                $option = 'safe_media_cleaner_adapter_gap_' . $this->generation . '_database';
     450                add_option( $option, $sample, '', false );
     451                if ( ! get_option( $option, false ) ) {
     452                        throw new \RuntimeException( __( 'Could not save the cleanup restriction for unread content. The scan was stopped.', 'rapid-media-reclaim' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Error data is encoded by REST/CLI and escaped at the admin boundary.
     453                }
     454                if ( count( $report['examples'] ) < 20 && ! in_array( $sample, $report['examples'], true ) ) {
     455                        $report['examples'][] = $sample; }
     456                $report['issues'][ $reason ]       = 1;
     457                $this->adapter_reports['database'] = $report;
    319458        }
    320459
    … …  
    363502                                }
    364503                                if ( null === $row->option_value ) {
     504                                        $this->source_gap( 0, $name );
    365505                                        continue;
    366506                                }
    … …  
    376516                                }
    377517                                if ( 0 === strpos( $name, 'theme_mods_' ) ) {
    378                                         $data = @unserialize( $row->option_value, array( 'allowed_classes' => false ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Read existing WordPress serialized metadata with object creation disabled; malformed stored values are ignored.
     518                                        // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Read existing WordPress serialized metadata with object creation disabled and bounded depth.
     519                                        $data = @unserialize(
     520                                                $row->option_value,
     521                                                array(
     522                                                        'allowed_classes' => false,
     523                                                        'max_depth'       => Extractor::MAX_DEPTH,
     524                                                )
     525                                        );
    379526                                        if ( is_array( $data ) ) {
     527                                                // One budget for the whole option: aliases can span several theme mods.
     528                                                $budget = Extractor::budget( array( 'source_bytes' => strlen( $row->option_value ) ) );
    380529                                                foreach ( $data as $key => $value ) {
    381                                                         $this->evidence( $value, 'theme_mod', 0, $name, __( 'Theme', 'rapid-media-reclaim' ) . ' · ' . ucwords( str_replace( '_', ' ', $key ) ), false, 'custom_logo' === $key );
     530                                                        $this->evidence( $value, 'theme_mod', 0, $name, __( 'Theme', 'rapid-media-reclaim' ) . ' · ' . ucwords( str_replace( '_', ' ', (string) $key ) ), false, 'custom_logo' === $key, $budget );
    382531                                                }
     532                                        } elseif ( preg_match( '/^a:\d+:/', $row->option_value ) ) {
     533                                                // Corrupt or too deep: read it as text, but never as fully checked.
     534                                                $this->source_gap( 0, $name, 'database_value_unreadable' );
     535                                                $this->evidence( $row->option_value, 'theme_mod', 0, $name, __( 'Theme', 'rapid-media-reclaim' ) );
    383536                                        }
    384537                                } else {
    … …  
    409562                                $mt     = $wpdb->{$kind . 'meta'};
    410563                                $column = $kind . '_id';
    411                                 $values = $wpdb->get_results( $wpdb->prepare( "SELECT {$column} AS owner_id,meta_key,meta_value FROM {$mt} WHERE {$column} IN (" . implode( ',', array_fill( 0, count( $ids ), '%d' ) ) . ')', $ids ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Bounded source inventory requires fresh reads; table/column fragments are internal allowlists and values use placeholders.
    412                                 if ( $wpdb->last_error ) {
    413                                         throw new \RuntimeException( 'Could not read source metadata.' );
    414                                 }
     564                                $in     = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
     565                                // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Metadata table/owner column are internal allowlists; IDs are prepared; payload reads are bounded.
     566                                $stats = $wpdb->get_row( $wpdb->prepare( "SELECT COUNT(*) AS n,COALESCE(SUM(OCTET_LENGTH(meta_value)),0) AS bytes FROM {$mt} WHERE {$column} IN ({$in})", $ids ) );
     567                                if ( $wpdb->last_error || ! $stats ) {
     568                                        throw new \RuntimeException( 'Could not measure source metadata.' );
     569                                }
     570                                if ( ( (int) $stats->n > 2000 || (int) $stats->bytes > 4194304 ) && count( $rows ) > 1 ) {
     571                                        // Split before fetching payloads; never load 25 large owners together.
     572                                        foreach ( $rows as $single ) {
     573                                                $this->process( array( $single ), $refs );
     574                                                $refs->flush(); }
     575                                        return;
     576                                }
     577                                $values = array();
     578                                if ( (int) $stats->n > 2000 || (int) $stats->bytes > 4194304 ) {
     579                                        $this->source_gap( (int) $ids[0] );
     580                                } else {
     581                                        // Recheck the combined budget inside the payload statement. A value
     582                                        // growing between measurement and fetch becomes NULL, not an OOM.
     583                                        $values = $wpdb->get_results( $wpdb->prepare( "SELECT m.{$column} AS owner_id,m.meta_key,IF(b.n<=2000 AND b.bytes<=4194304 AND OCTET_LENGTH(m.meta_value)<=2097152,m.meta_value,NULL) AS meta_value FROM {$mt} m CROSS JOIN (SELECT COUNT(*) AS n,COALESCE(SUM(OCTET_LENGTH(meta_value)),0) AS bytes FROM {$mt} WHERE {$column} IN ({$in})) b WHERE m.{$column} IN ({$in}) LIMIT 2001", array_merge( $ids, $ids ) ) );
     584                                        if ( $wpdb->last_error ) {
     585                                                throw new \RuntimeException( 'Could not read source metadata.' ); }
     586                                }
     587                                // phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, PluginCheck.Security.DirectDB.UnescapedDBParameter
     588
    415589                                foreach ( $values as $value ) {
     590                                        if ( null === $value->meta_value ) {
     591                                                $this->source_gap( (int) $value->owner_id, (string) $value->meta_key );
     592                                                continue; }
    416593                                        $meta[ $value->owner_id ][ $value->meta_key ][] = $value->meta_value;
    417594                                }
    418595                        }
     596                        $acf_catalog = 'posts' === $this->phase ? Acf_Structure::catalog() : array();
    419597                        foreach ( $rows as $row ) {
    420598                                $id   = (int) ( 'terms' === $this->phase ? $row->term_id : $row->ID );
    … …  
    427605                                        $weak    = 'trash' === $row->post_status || ( ! $settings['include_drafts'] && in_array( $row->post_status, array( 'draft', 'pending', 'future', 'private' ), true ) );
    428606                                        $builder = preg_match( '/\[(?:et_pb_|vc_)/', $row->post_content );
     607                                        if ( $builder ) {
     608                                                $shortcodes = Builder_Adapter::extract( $row->post_content, 'Divi / WPBakery' );
     609                                                $this->adapter_evidence( $shortcodes, 'shortcode_builders', 'builder', $id, '', $weak );
     610                                                if ( array_diff( $shortcodes['issues'], array( 'builder_custom_controls_not_resolved' ) ) ) {
     611                                                        $this->source_gap( $id, 'post_content', 'shortcode_source_unreadable' );
     612                                                }
     613                                        }
    429614                                        $this->evidence( $row->post_content, $builder ? 'builder' : 'post_content', $id, '', $builder ? __( 'Divi / WPBakery', 'rapid-media-reclaim' ) : __( 'Post content', 'rapid-media-reclaim' ), $weak );
    430615                                        $this->evidence( $row->post_excerpt, 'post_excerpt', $id, '', __( 'Post excerpt', 'rapid-media-reclaim' ), $weak );
    … …  
    434619                                                $this->evidence( $description, 'term_meta', $id, 'description', __( 'Term description', 'rapid-media-reclaim' ) );
    435620                                        }
     621                                }
     622                                $structure  = 'posts' === $this->phase ? Acf_Structure::inspect( $acf_catalog, $meta[ $id ] ?? array() ) : array(
     623                                        'fields' => array(),
     624                                        'issues' => array(),
     625                                );
     626                                $acf_budget = array(
     627                                        'nodes' => $structure['work'] ?? 0,
     628                                        'bytes' => 0,
     629                                        'refs'  => 0,
     630                                );
     631                                if ( $structure['issues'] ) {
     632                                        $this->source_gap( $id, '', 'database_acf_structure_incomplete' );
     633                                        $this->adapter_evidence(
     634                                                array(
     635                                                        'refs'   => array(),
     636                                                        'issues' => $structure['issues'],
     637                                                ),
     638                                                'acf',
     639                                                'acf',
     640                                                $id,
     641                                                '',
     642                                                $weak
     643                                        );
    436644                                }
    437645                                foreach ( $meta[ $id ] ?? array() as $key => $values ) {
    … …  
    473681
    474682                                        $field_key = $meta[ $id ][ '_' . $key ][0] ?? '';
    475                                         $acf       = is_string( $field_key ) && 0 === strpos( $field_key, 'field_' ) ? $this->acf_field( $field_key ) : null;
     683                                        $acf       = isset( $structure['fields'][ $key ] ) ? $structure['fields'][ $key ] : ( is_string( $field_key ) && 0 === strpos( $field_key, 'field_' ) ? $this->acf_field( $field_key ) : null );
     684                                        if ( isset( $structure['fields'][ $key ] ) ) {
     685                                                $structural_field = $structure['fields'][ $key ];
     686                                                // Registered local fields keep their existing reader precedence.
     687                                                if ( ! function_exists( 'acf_get_local_field' ) || ! acf_get_local_field( $structural_field['key'] ) ) {
     688                                                        $acf = $structural_field;
     689                                                } else {
     690                                                        $acf = $this->acf_field( $structural_field['key'] );
     691                                                }
     692                                        }
    476693                                        if ( $acf && 'posts' === $this->phase ) {
    477694                                                $type    = 'acf';
    … …  
    482699                                                // Adapters only add precise evidence. The generic walk below always
    483700                                                // runs too, so anything an adapter cannot model is still found.
     701                                                $generic = $value;
    484702                                                if ( 'posts' === $this->phase && '_elementor_data' === $key ) {
    485                                                         $this->adapter_evidence( Elementor_Adapter::extract( $value ), 'elementor', 'builder', $id, $key, $weak );
     703                                                        $result = Elementor_Dependencies::extract(
     704                                                                $value,
     705                                                                static function ( int $template ) {
     706                                                                        return self::elementor_document( $template );
     707                                                                },
     708                                                                $id
     709                                                        );
     710                                                        delete_post_meta( $id, '_safe_media_cleaner_elementor_dependency' );
     711                                                        foreach ( $result['dependencies'] as $dependency ) {
     712                                                                add_post_meta( $id, '_safe_media_cleaner_elementor_dependency', $dependency );
     713                                                        }
     714                                                        $this->adapter_evidence( $result, 'elementor', 'builder', $id, $key, $weak );
     715                                                } elseif ( in_array( $key, array( '_bricks_page_content_2', '_bricks_page_header_2', '_bricks_page_footer_2' ), true ) ) {
     716                                                        $this->adapter_evidence( Builder_Adapter::extract( $value, $context ), 'builders', 'builder', $id, $key, $weak );
     717                                                } elseif ( 'posts' === $this->phase && 0 === strpos( $key, '_fl_builder' ) && is_string( $value ) ) {
     718                                                        // The generic walk drops objects; give it Beaver's decoded plain arrays.
     719                                                        $generic = $this->beaver_evidence( $value, $id, $key, $weak );
    486720                                                } elseif ( $acf ) {
    487                                                         $this->adapter_evidence( Acf_Adapter::extract( $value, $acf, $key ), 'acf', 'posts' === $this->phase ? 'acf' : $type, $id, $key, $weak );
     721                                                        $result = Acf_Adapter::extract( $value, $acf, $key, $acf_budget );
     722                                                        if ( $result['issues'] && ( isset( $structure['fields'][ $key ] ) || in_array( $acf['type'], array( 'group', 'repeater', 'flexible_content' ), true ) ) ) {
     723                                                                $this->source_gap( $id, $key, 'database_acf_structure_incomplete' );
     724                                                        }
     725                                                        $this->adapter_evidence( $result, 'acf', 'posts' === $this->phase ? 'acf' : $type, $id, $key, $weak );
    488726                                                }
    489                                                 $this->evidence( $value, $type, $id, $key, $context, $weak, $force );
     727                                                $generic_budget = null;
     728                                                $selector       = $acf && in_array( $acf['type'], array( 'group', 'repeater', 'flexible_content' ), true );
     729                                                $this->evidence( $generic, $type, $id, $key, $context, $weak, $force, $generic_budget, $selector );
    490730                                        }
    491731                                }
  • rapid-media-reclaim/trunk/includes/scan/class-extractor.php

    r3794616 r3814937  
    1212}
    1313
    14 /** Extractor service. */
     14/**
     15 * Extractor service.
     16 *
     17 * Every top-level extraction runs under one shared work budget (values visited,
     18 * bytes inspected, unique evidence records, nested decodes and nesting depth).
     19 * Shared or cyclic decoded graphs, deep nesting and decode bombs exhaust that
     20 * budget; the result then reports why it is incomplete instead of looking fully
     21 * checked. See docs/EXTRACTION-LIMITS.md.
     22 */
    1523final class Extractor {
     24        /** Values (arrays and scalars) visited per extraction, at most. */
     25        const MAX_NODES = 1000000;
     26        /** Scalar and decoded bytes inspected per extraction, at most. */
     27        const MAX_BYTES = 16777216;
     28        /** Unique evidence records per extraction. */
     29        const MAX_REFS = 50000;
     30        /** Nested JSON/serialized decodes per extraction. */
     31        const MAX_DECODES = 20000;
     32        /** Nesting levels, including decoded strings and nested blocks. */
     33        const MAX_DEPTH = 40;
     34        /** Largest single string that is decoded as JSON or serialized data. */
     35        const MAX_DECODE_BYTES = 4194304;
     36        /** Largest scalar inspected; reject before normalization or regex allocation. */
     37        const MAX_STRING_BYTES = 4194304;
     38        /**
     39         * Raw string input amplification: inspected bytes may not exceed this multiple
     40         * of the top-level string length (plus a small floor). Nested encodings re-read
     41         * their substrings, so a few nesting levels fit; aliased large strings do not.
     42         */
     43        const AMPLIFICATION = 8;
     44        /**
     45         * Visited values per raw input byte. Unaliased JSON needs at least two bytes per
     46         * value and serialized data four, even across several nesting levels; alias
     47         * fan-out needs almost none.
     48         */
     49        const NODE_AMPLIFICATION = 2;
     50        /** Work floor for tiny string inputs. */
     51        const FLOOR = 1024;
     52        /** Short scalars are read once per extraction for each key and context. */
     53        const MEMO_BYTES = 512;
     54
    1655        /**
    1756         * Walk structured content and return unresolved evidence.
     57         *
     58         * Compatibility wrapper: the evidence may be partial. Callers that decide whether
     59         * media is unused or that verify a rewrite must use extract_result() instead.
    1860         *
    1961         * @param mixed  $value Value.
    … …  
    2466         */
    2567        public static function extract( $value, string $key = '', string $context = '', int $depth = 0 ): array {
    26                 if ( $depth > 40 || is_object( $value ) ) {
    27                         return array();
    28                 }
    29                 $out    = array();
    30                 $strong = (bool) preg_match( '/^(attachment_?id|image_?id|media_?id|backgroundMediaId|background_image_id|photo_id|photo|bg_image|thumbnail_id|_thumbnail_id|custom_logo|logo|site_icon|woocommerce_placeholder_image|ids|images|_product_image_gallery)$/i', $key );
    31                 if ( is_array( $value ) ) {
    32                         $paired = isset( $value['url'] ) || isset( $value['src'] );
    33                         foreach ( $value as $k => $v ) {
    34                                 $child_key = is_int( $k ) ? $key : (string) $k;
    35                                 if ( 'id' === $child_key && $paired && self::is_upload_url( (string) ( $value['url'] ?? $value['src'] ?? '' ) ) ) {
    36                                         $child_key = 'attachment_id';
    37                                 }
    38                                 $out = array_merge( $out, self::extract( $v, $child_key, $context, $depth + 1 ) );
    39                         }
    40                         return $out;
    41                 }
    42                 if ( ! is_scalar( $value ) ) {
    43                         return $out;
    44                 }
    45                 $s = str_replace( '\\/', '/', (string) $value );
    46                 if ( preg_match( '/^\d+(?:\s*,\s*\d+)*$/', $s ) && ( $strong || 'id' === $key ) ) {
    47                         foreach ( explode( ',', $s ) as $id ) {
    48                                 $out[] = self::ref( (int) $id, $strong ? 'strong' : 'weak', 'id', $context );
    49                         }
    50                 }
    51                 if ( strlen( $s ) < 2 ) {
    52                         return $out;
    53                 }
    54                 $decoded = json_decode( $s, true );
    55                 if ( is_array( $decoded ) ) {
    56                         return array_merge( $out, self::extract( $decoded, $key, $context, $depth + 1 ) );
    57                 }
    58                 if ( preg_match( '/^(a|s|i|b|d|N):|^N;/', $s ) ) {
    59                         $decoded = @unserialize( $s, array( 'allowed_classes' => false ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Read existing WordPress serialized metadata with object creation disabled; malformed stored values are ignored.
    60                         if ( false !== $decoded && $decoded !== $value ) {
    61                                 return array_merge( $out, self::extract( $decoded, $key, $context, $depth + 1 ) );
     68                $budget = self::budget();
     69                return self::run( $value, $key, $context, max( 0, $depth ), $budget )['refs'];
     70        }
     71
     72        /**
     73         * Walk structured content under a bounded budget and say whether it was complete.
     74         *
     75         * @param mixed      $value Stored value.
     76         * @param string     $key Field key.
     77         * @param string     $context Evidence context.
     78         * @param array|null $budget Optional shared budget from budget(); a fresh one when null.
     79         * @return array `refs`, `complete` (bool), `issues` (reason => count) and `work` counters.
     80         */
     81        public static function extract_result( $value, string $key = '', string $context = '', ?array &$budget = null ): array {
     82                if ( null === $budget ) {
     83                        $budget = self::budget();
     84                }
     85                return self::run( $value, $key, $context, 0, $budget );
     86        }
     87
     88        /**
     89         * Create a budget that several extractions of one source record can share.
     90         *
     91         * Limits can only be lowered (for tests and stricter callers); values above the
     92         * built-in maxima, non-integers and values below one are clamped.
     93         *
     94         * `source_bytes` is the raw length of the stored record the shared budget reads;
     95         * it applies the raw-input amplification limit to already decoded values too.
     96         *
     97         * @param array $limits Optional `nodes`, `bytes`, `refs`, `decodes`, `depth`, `source_bytes`.
     98         * @return array Budget state.
     99         */
     100        public static function budget( array $limits = array() ): array {
     101                if ( isset( $limits['source_bytes'] ) && is_int( $limits['source_bytes'] ) ) {
     102                        $raw  = max( 0, min( self::MAX_BYTES, $limits['source_bytes'] ) );
     103                        $work = array(
     104                                'nodes' => self::NODE_AMPLIFICATION * $raw + self::FLOOR,
     105                                'bytes' => self::AMPLIFICATION * $raw + self::FLOOR,
     106                        );
     107                        foreach ( $work as $name => $cap ) {
     108                                $limits[ $name ] = isset( $limits[ $name ] ) && is_int( $limits[ $name ] ) ? min( $cap, $limits[ $name ] ) : $cap;
     109                        }
     110                }
     111                $max = array(
     112                        'nodes'   => self::MAX_NODES,
     113                        'bytes'   => self::MAX_BYTES,
     114                        'refs'    => self::MAX_REFS,
     115                        'decodes' => self::MAX_DECODES,
     116                        'depth'   => self::MAX_DEPTH,
     117                );
     118                foreach ( $max as $name => $ceiling ) {
     119                        if ( isset( $limits[ $name ] ) && is_int( $limits[ $name ] ) ) {
     120                                $max[ $name ] = max( 1, min( $ceiling, $limits[ $name ] ) );
    62121                        }
    63122                }
    … …  
    67126                        $base_path = rtrim( (string) wp_parse_url( $uploads['baseurl'], PHP_URL_PATH ), '/' ) . '/';
    68127                }
    69                 $pattern = '~(?:https?://|//)[^\s<>"\'()]+|(?:/?[a-zA-Z0-9_.%-]+/)*uploads/[^\s<>"\'()]+|' . preg_quote( $base_path, '~' ) . '[^\s<>"\'()]+|(?<![\w/])\d{4}/\d{2}/[^\s<>"\'()]+~i';
    70                 if ( preg_match_all( $pattern, html_entity_decode( $s, ENT_QUOTES, 'UTF-8' ), $m ) ) {
     128                return array(
     129                        'max'       => $max,
     130                        'nodes'     => 0,
     131                        'bytes'     => 0,
     132                        'refs'      => 0,
     133                        'decodes'   => 0,
     134                        'objects'   => 0,
     135                        'issues'    => array(),
     136                        'stop'      => false,
     137                        'cap'       => null,
     138                        'base_path' => $base_path,
     139                );
     140        }
     141
     142        /**
     143         * Run one top-level extraction against a (possibly shared) budget.
     144         *
     145         * @param mixed  $value Stored value.
     146         * @param string $key Field key.
     147         * @param string $context Evidence context.
     148         * @param int    $depth Starting depth.
     149         * @param array  $budget Budget state.
     150         * @return array Result.
     151         */
     152        private static function run( $value, string $key, string $context, int $depth, array &$budget ): array {
     153                $before = $budget['issues'];
     154                $used   = array(
     155                        'nodes'   => $budget['nodes'],
     156                        'bytes'   => $budget['bytes'],
     157                        'objects' => $budget['objects'],
     158                );
     159                // A short raw string cannot legitimately expand into a huge graph.
     160                $cap = null;
     161                if ( is_string( $value ) ) {
     162                        $cap = array(
     163                                'nodes' => $budget['nodes'] + self::NODE_AMPLIFICATION * strlen( $value ) + self::FLOOR,
     164                                'bytes' => $budget['bytes'] + self::AMPLIFICATION * strlen( $value ) + self::FLOOR,
     165                        );
     166                }
     167                $saved         = $budget['cap'];
     168                $budget['cap'] = $cap;
     169                $out           = array();
     170                $seen          = array();
     171                if ( $budget['stop'] ) {
     172                        self::issue( $budget, 'extractor_budget_exhausted' );
     173                } else {
     174                        self::collect( $value, $key, $context, $depth, $budget, $out, $seen );
     175                }
     176                $budget['cap'] = $saved;
     177                $issues        = array();
     178                foreach ( $budget['issues'] as $reason => $count ) {
     179                        $delta = $count - (int) ( $before[ $reason ] ?? 0 );
     180                        if ( $delta > 0 ) {
     181                                $issues[ $reason ] = $delta;
     182                        }
     183                }
     184                return array(
     185                        'refs'     => $out,
     186                        'complete' => ! $issues,
     187                        'issues'   => $issues,
     188                        'work'     => array(
     189                                'nodes'   => $budget['nodes'] - $used['nodes'],
     190                                'bytes'   => $budget['bytes'] - $used['bytes'],
     191                                'refs'    => count( $out ),
     192                                'objects' => $budget['objects'] - $used['objects'],
     193                        ),
     194                );
     195        }
     196
     197        /**
     198         * Record an incomplete-extraction reason. Exhausted budgets stop all later work.
     199         *
     200         * @param array  $budget Budget state.
     201         * @param string $reason Machine reason constant.
     202         * @param bool   $stop Whether the shared budget is exhausted.
     203         */
     204        private static function issue( array &$budget, string $reason, bool $stop = false ): void {
     205                $budget['issues'][ $reason ] = (int) ( $budget['issues'][ $reason ] ?? 0 ) + 1;
     206                if ( $stop ) {
     207                        $budget['stop'] = true;
     208                }
     209        }
     210
     211        /**
     212         * Charge visited values and inspected bytes; false once a limit is exceeded.
     213         *
     214         * @param array $budget Budget state.
     215         * @param int   $nodes Values.
     216         * @param int   $bytes Bytes.
     217         * @return bool Whether work may continue.
     218         */
     219        private static function charge( array &$budget, int $nodes, int $bytes ): bool {
     220                $budget['nodes'] += $nodes;
     221                $budget['bytes'] += $bytes;
     222                $cap              = $budget['cap'];
     223                if ( $budget['nodes'] > $budget['max']['nodes'] || ( $cap && $budget['nodes'] > $cap['nodes'] ) ) {
     224                        self::issue( $budget, 'extractor_node_limit', true );
     225                        return false;
     226                }
     227                if ( $budget['bytes'] > $budget['max']['bytes'] || ( $cap && $budget['bytes'] > $cap['bytes'] ) ) {
     228                        self::issue( $budget, 'extractor_byte_limit', true );
     229                        return false;
     230                }
     231                return true;
     232        }
     233
     234        /**
     235         * Append evidence without copying the growing result for every nested value.
     236         *
     237         * @param mixed  $value Stored value.
     238         * @param string $key Field key.
     239         * @param string $context Evidence context.
     240         * @param int    $depth Recursion depth.
     241         * @param array  $budget Shared budget.
     242         * @param array  $out Evidence accumulator.
     243         * @param array  $seen Evidence already in $out.
     244         */
     245        private static function collect( $value, string $key, string $context, int $depth, array &$budget, array &$out, array &$seen ): void {
     246                if ( $budget['stop'] ) {
     247                        return;
     248                }
     249                if ( $depth > $budget['max']['depth'] ) {
     250                        // Deep or self-referencing data is never silently truncated.
     251                        self::issue( $budget, 'extractor_depth_limit' );
     252                        return;
     253                }
     254                if ( is_object( $value ) ) {
     255                        // Objects are never hydrated or walked. Their unread properties are a gap;
     256                        // builder adapters must normalize supported formats before the generic walk.
     257                        ++$budget['objects'];
     258                        self::issue( $budget, 'extractor_object_unread' );
     259                        return;
     260                }
     261                if ( is_array( $value ) ) {
     262                        if ( ! self::charge( $budget, 1 + count( $value ), 0 ) ) {
     263                                return;
     264                        }
     265                        // Each child is charged above and again when visited; refund the pre-charge.
     266                        $budget['nodes'] -= count( $value );
     267                        $paired           = isset( $value['url'] ) || isset( $value['src'] );
     268                        foreach ( $value as $k => $v ) {
     269                                if ( $budget['stop'] ) {
     270                                        return;
     271                                }
     272                                if ( ! self::charge( $budget, 0, strlen( (string) $k ) ) ) {
     273                                        return;
     274                                }
     275                                $child_key = is_int( $k ) ? $key : (string) $k;
     276                                if ( 'id' === $child_key && $paired && self::is_upload_url( (string) ( is_scalar( $value['url'] ?? null ) ? $value['url'] : ( is_scalar( $value['src'] ?? null ) ? $value['src'] : '' ) ), $budget ) ) {
     277                                        $child_key = 'attachment_id';
     278                                }
     279                                self::collect( $v, $child_key, $context, $depth + 1, $budget, $out, $seen );
     280                        }
     281                        return;
     282                }
     283                if ( ! is_scalar( $value ) ) {
     284                        return;
     285                }
     286                $raw = (string) $value;
     287                $cap = $budget['cap'];
     288                if ( strlen( $raw ) > self::MAX_STRING_BYTES || strlen( $raw ) > $budget['max']['bytes'] - $budget['bytes'] || ( $cap && strlen( $raw ) > $cap['bytes'] - $budget['bytes'] ) ) {
     289                        self::issue( $budget, 'extractor_byte_limit', true );
     290                        return;
     291                }
     292                $s = str_replace( '\\/', '/', $raw );
     293                if ( strlen( $raw ) <= self::MEMO_BYTES ) {
     294                        // Aliases revisit identical scalars: their evidence is already in $out.
     295                        $memo = "\0" . $key . "\0" . $context . "\0" . ( is_string( $value ) ? 's' : 'o' ) . $raw;
     296                        if ( isset( $seen[ $memo ] ) ) {
     297                                self::charge( $budget, 1, 0 );
     298                                return;
     299                        }
     300                        $seen[ $memo ] = true;
     301                }
     302                if ( ! self::charge( $budget, 1, strlen( $s ) ) ) {
     303                        return;
     304                }
     305                $strong = (bool) preg_match( '/^(attachment_?id|image_?id|media_?id|backgroundMediaId|background_image_id|photo_id|photo|bg_image|thumbnail_id|_thumbnail_id|custom_logo|logo|site_icon|woocommerce_placeholder_image|ids|images|_product_image_gallery)$/i', $key );
     306                if ( ( $strong || 'id' === $key ) && preg_match( '/^\d+(?:\s*,\s*\d+)*$/', $s ) ) {
     307                        foreach ( explode( ',', $s ) as $id ) {
     308                                self::add( $budget, $out, $seen, (int) $id, $strong ? 'strong' : 'weak', 'id', $context );
     309                        }
     310                }
     311                if ( strlen( $s ) < 2 ) {
     312                        return;
     313                }
     314                // PHP serialization counts original bytes, including JSON's escaped slashes.
     315                $decoded = self::decode( $raw, $depth, $budget );
     316                if ( $budget['stop'] ) {
     317                        return;
     318                }
     319                if ( null !== $decoded && $decoded !== $value ) {
     320                        self::collect( $decoded, $key, $context, $depth + 1, $budget, $out, $seen );
     321                        return;
     322                }
     323                $base_path = $budget['base_path'];
     324                $pattern   = '~(?:https?://|//)[^\s<>"\'()]+|(?<![a-zA-Z0-9_.%-])uploads/[^\s<>"\'()]+|' . preg_quote( $base_path, '~' ) . '[^\s<>"\'()]+|(?<![\w/])\d{4}/\d{2}/[^\s<>"\'()]+~i';
     325                $text      = html_entity_decode( $s, ENT_QUOTES, 'UTF-8' );
     326                if ( self::matches( $pattern, $text, $m, $budget ) ) {
    71327                        foreach ( $m[0] as $url ) {
    72                                 $out[] = self::ref( rtrim( $url, ',;]' ), 'strong', 'url', $context );
    73                         }
    74                 }
    75                 if ( preg_match_all( '/wp-image-(\d+)/', $s, $m ) ) {
     328                                self::add( $budget, $out, $seen, rtrim( $url, ',;]' ), 'strong', 'url', $context );
     329                                // The literal uploads marker avoids scanning an arbitrary prefix at
     330                                // every character. Retain both interpretations for ambiguous relative
     331                                // paths so an actual uploads/uploads directory is still protected.
     332                                if ( 0 === stripos( $url, 'uploads/' ) ) {
     333                                        self::add( $budget, $out, $seen, rtrim( rtrim( $base_path, '/' ) . '/' . substr( $url, 8 ), ',;]' ), 'strong', 'url', $context );
     334                                }
     335                        }
     336                }
     337                if ( self::matches( '/wp-image-(\d+)/', $s, $m, $budget ) ) {
    76338                        foreach ( $m[1] as $id ) {
    77                                 $out[] = self::ref( (int) $id, 'strong', 'id', $context );
    78                         }
    79                 }
    80                 if ( preg_match_all( '/\[(gallery|playlist|vc_gallery|vc_single_image|et_pb_\w+|video|audio)\b([^\]]*)\]/i', $s, $m, PREG_SET_ORDER ) ) {
     339                                self::add( $budget, $out, $seen, (int) $id, 'strong', 'id', $context );
     340                        }
     341                }
     342                if ( self::matches( '/\[(gallery|playlist|vc_gallery|vc_single_image|et_pb_\w+|video|audio)\b([^\]]*)\]/i', $s, $m, $budget, PREG_SET_ORDER ) ) {
    81343                        foreach ( $m as $shortcode ) {
    82                                 if ( preg_match_all( '/\b(ids|images|image|attachment_id)=["\']([\d, ]+)["\']/', $shortcode[2], $attrs, PREG_SET_ORDER ) ) {
     344                                if ( self::matches( '/\b(ids|images|image|attachment_id)=["\']([\d, ]+)["\']/', $shortcode[2], $attrs, $budget, PREG_SET_ORDER ) ) {
    83345                                        foreach ( $attrs as $attr ) {
    84346                                                foreach ( explode( ',', $attr[2] ) as $id ) {
    85                                                         $out[] = self::ref( (int) $id, 'strong', 'id', 'Shortcode · ' . $shortcode[1] );
     347                                                        self::add( $budget, $out, $seen, (int) $id, 'strong', 'id', 'Shortcode · ' . $shortcode[1] );
    86348                                                }
    87349                                        }
    … …  
    90352                }
    91353                if ( false !== strpos( $s, '<!-- wp:' ) && function_exists( 'parse_blocks' ) ) {
    92                         $out = array_merge( $out, self::blocks( parse_blocks( $s ) ) );
    93                 }
    94                 if ( preg_match_all( '~(?<![\w/])([\w%.-]+\.(?:jpe?g|png|gif|webp|avif|svg|pdf|mp4|mp3|woff2?))(?![\w])~i', $s, $m ) ) {
     354                        self::blocks( parse_blocks( $s ), $depth + 1, $budget, $out, $seen );
     355                }
     356                if ( self::matches( '~(?<![\w%./-])(\.*+[\w%-]++(?:\.++[\w%-]++)*\.++(?:jpe?g|png|gif|webp|avif|svg|pdf|mp4|mp3|woff2?))(?![\w])~i', $s, $m, $budget ) ) {
    95357                        foreach ( $m[1] as $name ) {
    96                                 $out[] = self::ref( $name, 'weak', 'filename', $context );
    97                         }
    98                 }
    99                 return $out;
    100         }
     358                                self::add( $budget, $out, $seen, $name, 'weak', 'filename', $context );
     359                        }
     360                }
     361        }
     362
     363        /**
     364         * Decode a JSON or serialized string without object hydration.
     365         *
     366         * @param string $s String.
     367         * @param int    $depth Current depth.
     368         * @param array  $budget Budget state.
     369         * @return mixed Decoded value, or null when the string is not decodable data.
     370         */
     371        private static function decode( string $s, int $depth, array &$budget ) {
     372                $start      = strspn( $s, " \t\n\r" );
     373                $json       = isset( $s[ $start ] ) && ( '[' === $s[ $start ] || '{' === $s[ $start ] );
     374                $serialized = (bool) preg_match( '/^(?:[asOC]:[0-9]+:|i:-?[0-9]+;|b:[01];|d:(?:[+\-]?(?:[0-9.]+(?:[eE][+\-]?[0-9]+)?|INF)|NAN);|N;)/', $s );
     375                if ( ! $json && ! $serialized ) {
     376                        return null;
     377                }
     378                if ( strlen( $s ) > self::MAX_DECODE_BYTES ) {
     379                        self::issue( $budget, 'extractor_decode_limit' );
     380                        return null;
     381                }
     382                if ( ++$budget['decodes'] > $budget['max']['decodes'] ) {
     383                        self::issue( $budget, 'extractor_decode_limit', true );
     384                        return null;
     385                }
     386                // Decoded children are deeper than the string itself.
     387                $levels = max( 1, $budget['max']['depth'] - $depth );
     388                if ( $json ) {
     389                        $decoded = json_decode( $s, true, $levels + 1 );
     390                        if ( JSON_ERROR_DEPTH === json_last_error() ) {
     391                                self::issue( $budget, 'extractor_depth_limit' );
     392                                return null;
     393                        }
     394                        if ( is_array( $decoded ) ) {
     395                                return $decoded;
     396                        }
     397                        if ( ! $serialized ) {
     398                                return null;
     399                        }
     400                }
     401                // A depth refusal is followed by a generic offset notice, so error_get_last()
     402                // cannot tell it apart from malformed text. Watch every decoder warning instead.
     403                $too_deep = false;
     404                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_set_error_handler -- Scoped to one decode; restored immediately; distinguishes a depth refusal from malformed text.
     405                set_error_handler(
     406                        static function ( $number, $message ) use ( &$too_deep ) {
     407                                if ( false !== stripos( (string) $message, 'depth' ) ) {
     408                                        $too_deep = true;
     409                                }
     410                                return true;
     411                        }
     412                );
     413                try {
     414                        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Read existing WordPress serialized metadata with object creation disabled and bounded depth; malformed stored values are read as text.
     415                        $decoded = unserialize(
     416                                $s,
     417                                array(
     418                                        'allowed_classes' => false,
     419                                        'max_depth'       => $levels + 1,
     420                                )
     421                        );
     422                } finally {
     423                        restore_error_handler();
     424                }
     425                if ( $too_deep ) {
     426                        self::issue( $budget, 'extractor_depth_limit' );
     427                        return null;
     428                }
     429                if ( false === $decoded ) {
     430                        // The recognition check above already excludes ordinary prose/CSS.
     431                        // Every recognized serialization prefix must report a failed decode.
     432                        if ( 'b:0;' !== $s ) {
     433                                self::issue( $budget, 'extractor_malformed_data' );
     434                        }
     435                        return null;
     436                }
     437                return $decoded;
     438        }
     439
     440        /**
     441         * Run a bounded pattern; a PCRE failure is reported instead of reading as "no match".
     442         *
     443         * @param string $pattern Pattern.
     444         * @param string $subject Subject.
     445         * @param mixed  $matches Matches.
     446         * @param array  $budget Budget state.
     447         * @param int    $flags Flags.
     448         * @return bool Whether anything matched.
     449         */
     450        private static function matches( string $pattern, string $subject, &$matches, array &$budget, int $flags = PREG_PATTERN_ORDER ): bool {
     451                $matches = array();
     452                $found   = preg_match_all( $pattern, $subject, $matches, $flags );
     453                if ( false === $found ) {
     454                        self::issue( $budget, 'extractor_pattern_error' );
     455                        return false;
     456                }
     457                return $found > 0;
     458        }
     459
    101460        /**
    102461         * Recognize an uploads URL without trusting its host.
    103462         *
    104463         * @param string $value Value.
     464         * @param array  $budget Budget state with the uploads path.
    105465         * @return bool Result.
    106466         */
    107         private static function is_upload_url( string $value ): bool {
     467        private static function is_upload_url( string $value, array $budget ): bool {
    108468                $value = str_replace( '\\/', '/', $value );
    109                 $path  = '/wp-content/uploads/';
    110                 if ( function_exists( 'wp_upload_dir' ) ) {
    111                         $uploads = wp_upload_dir();
    112                         $path    = rtrim( (string) wp_parse_url( $uploads['baseurl'], PHP_URL_PATH ), '/' ) . '/';
    113                 }
    114                 return false !== strpos( $value, $path ) || false !== strpos( $value, 'uploads/' );
    115         }
     469                return false !== strpos( $value, $budget['base_path'] ) || false !== strpos( $value, 'uploads/' );
     470        }
     471
    116472        /**
    117473         * Visit nested Gutenberg blocks with their block context.
    118474         *
    119475         * @param array $blocks Blocks.
    120          * @return array Result.
    121          */
    122         private static function blocks( array $blocks ): array {
    123                 $out = array();
     476         * @param int   $depth Nesting depth.
     477         * @param array $budget Shared budget.
     478         * @param array $out Evidence accumulator.
     479         * @param array $seen Evidence already in $out.
     480         */
     481        private static function blocks( array $blocks, int $depth, array &$budget, array &$out, array &$seen ): void {
     482                if ( $depth > $budget['max']['depth'] ) {
     483                        self::issue( $budget, 'extractor_depth_limit' );
     484                        return;
     485                }
    124486                foreach ( $blocks as $block ) {
    125                         $out = array_merge( $out, self::extract( $block['attrs'] ?? array(), '', 'Gutenberg · ' . ( $block['blockName'] ?? '' ) ), self::blocks( $block['innerBlocks'] ?? array() ) );
    126                         if ( isset( $block['attrs']['id'] ) ) {
    127                                 $out[] = self::ref( (int) $block['attrs']['id'], 'strong', 'id', 'Gutenberg · ' . $block['blockName'] );
    128                         }
    129                 }
    130                 return $out;
    131         }
    132         /**
    133          * Build one unresolved evidence record.
    134          *
     487                        if ( $budget['stop'] || ! self::charge( $budget, 1, 0 ) ) {
     488                                return;
     489                        }
     490                        $name = (string) ( $block['blockName'] ?? '' );
     491                        self::collect( $block['attrs'] ?? array(), '', 'Gutenberg · ' . $name, $depth + 1, $budget, $out, $seen );
     492                        self::blocks( $block['innerBlocks'] ?? array(), $depth + 1, $budget, $out, $seen );
     493                        if ( isset( $block['attrs']['id'] ) && is_scalar( $block['attrs']['id'] ) ) {
     494                                self::add( $budget, $out, $seen, (int) $block['attrs']['id'], 'strong', 'id', 'Gutenberg · ' . $name );
     495                        }
     496                }
     497        }
     498
     499        /**
     500         * Add one unique unresolved evidence record within the evidence budget.
     501         *
     502         * @param array  $budget Budget state.
     503         * @param array  $out Evidence accumulator.
     504         * @param array  $seen Evidence already in $out.
    135505         * @param mixed  $value Value.
    136506         * @param string $strength Strength.
    137507         * @param string $type Type.
    138508         * @param string $context Context.
    139          * @return array Result.
    140          */
    141         private static function ref( $value, string $strength, string $type, string $context ): array {
    142                 return array(
     509         */
     510        private static function add( array &$budget, array &$out, array &$seen, $value, string $strength, string $type, string $context ): void {
     511                if ( $budget['stop'] ) {
     512                        return;
     513                }
     514                $id = $strength . '|' . $type . '|' . $context . '|' . ( is_int( $value ) ? 'i' : 's' ) . $value;
     515                if ( isset( $seen[ $id ] ) ) {
     516                        return;
     517                }
     518                if ( ++$budget['refs'] > $budget['max']['refs'] ) {
     519                        self::issue( $budget, 'extractor_reference_limit', true );
     520                        return;
     521                }
     522                $seen[ $id ] = true;
     523                $out[]       = array(
    143524                        'value'      => $value,
    144525                        'strength'   => $strength,
  • rapid-media-reclaim/trunk/includes/scan/class-file-map.php

    r3794616 r3814937  
    2323         */
    2424        public static function refresh( array $ids, array $generations ): void {
     25                if ( class_exists( \SafeMediaCleaner\Status_Index::class ) ) {
     26                        \SafeMediaCleaner\Status_Index::write(
     27                                $generations,
     28                                static function () use ( $ids, $generations ) {
     29                                        self::write_refresh( $ids, $generations );
     30                                }
     31                        );
     32                } else {
     33                        self::write_refresh( $ids, $generations ); }
     34        }
     35
     36        /**
     37         * Replace authoritative file rows.
     38         *
     39         * @param array $ids IDs.
     40         * @param array $generations Generations.
     41         * @throws \RuntimeException Inventory read/write failed.
     42         */
     43        private static function write_refresh( array $ids, array $generations ): void {
    2544                global $wpdb;
    2645                if ( ! $ids || ! $generations ) {
  • rapid-media-reclaim/trunk/includes/scan/class-frontend-scanner.php

    r3794616 r3814937  
    11<?php
    22/**
    3  * Bounded anonymous HTML coverage of public posts and pages.
     3 * Bounded sitemap-led anonymous HTML and linked stylesheet coverage.
    44 *
    55 * @package SafeMediaCleaner
    … …  
    8585                $query    = new \WP_Query(
    8686                        array(
    87                                 'post_type'           => array( 'post', 'page' ),
     87                                'post_type'           => array_values( get_post_types( array( 'public' => true ) ) ),
    8888                                'post_status'         => 'publish',
    8989                                'has_password'        => false,
    … …  
    9898                );
    9999                $state    = array(
    100                         'ids'     => array_slice( $query->posts, 0, $limit ),
    101                         'limited' => count( $query->posts ) > $limit,
    102                         'results' => array(),
    103                         'limit'   => $limit,
     100                        'ids'             => array_slice( $query->posts, 0, $limit ),
     101                        'limited'         => count( $query->posts ) > $limit,
     102                        'results'         => array(),
     103                        'limit'           => $limit,
     104                        'urls'            => array(),
     105                        'sitemaps'        => array( home_url( '/wp-sitemap.xml' ), home_url( '/sitemap_index.xml' ) ),
     106                        'visited'         => array(),
     107                        'sitemap_failed'  => 0,
     108                        'sitemap_skipped' => 0,
     109                        'styles'          => array(),
     110                        'style_results'   => array(),
     111                        'external_styles' => 0,
    104112                );
    105113                if ( ! add_option( $this->option(), $state, '', false ) ) {
    … …  
    117125         */
    118126        public function total(): int {
    119                 return count( $this->state()['ids'] ); }
     127                $state = $this->state();
     128                return min( $state['limit'], count( $state['ids'] ) + count( $state['urls'] ?? array() ) ); }
    120129        /**
    121130         * Reject query permalinks, alternate origins, credentials and ambiguous paths.
    … …  
    134143                                return false; }
    135144                }
     145                $path = rawurldecode( $parts['path'] ?? '/' );
     146                if ( preg_match( '~(?:^|/)(?:wp-admin|wp-login\.php|wp-json|xmlrpc\.php)(?:/|$)|(?:^|/)\.\.(?:/|$)~i', $path ) || preg_match( '/[\\\\\x00-\x20\x7f]/', $path ) ) {
     147                        return false;
     148                }
    136149                $scheme      = strtolower( $parts['scheme'] ?? '' );
    137150                $home_scheme = strtolower( $home['scheme'] ?? '' );
    … …  
    153166                $state           = $this->state();
    154167                $offset          = max( 0, (int) $cursor );
    155                 if ( $offset >= count( $state['ids'] ) ) {
     168                if ( $limit > 0 && ! empty( $state['sitemaps'] ) ) {
     169                        $this->discover( $state );
     170                        if ( empty( $state['sitemaps'] ) ) {
     171                                $state['ids'] = array_values(
     172                                        array_filter(
     173                                                $state['ids'],
     174                                                static function ( $id ) use ( $state ) {
     175                                                        return ! in_array( (string) get_permalink( $id ), $state['urls'], true );
     176                                                }
     177                                        )
     178                                );
     179                                $state['ids'] = array_slice( $state['ids'], 0, max( 0, $state['limit'] - count( $state['urls'] ) ) );
     180                        }
     181                        $this->save( $state );
     182                        return $offset;
     183                }
     184                if ( $limit > 0 && ! empty( $state['styles'] ) ) {
     185                        $this->scan_style( $state, $refs );
     186                        $this->save( $state );
     187                        return $offset;
     188                }
     189                $inventory = array_merge( $state['urls'] ?? array(), $state['ids'] );
     190                if ( $offset >= count( $inventory ) ) {
    156191                        return null; }
    157192                if ( $limit < 1 ) {
    158193                        return $offset; }
    159                 $id = (int) $state['ids'][ $offset ];
     194                $entry = $inventory[ $offset ];
     195                $id    = is_int( $entry ) || ctype_digit( (string) $entry ) ? (int) $entry : (int) url_to_postid( $entry );
     196                $key   = is_string( $entry ) && ! ctype_digit( $entry ) ? $entry : $id;
    160197                // A committed coverage result also makes replay after a cursor-write failure safe.
    161                 if ( isset( $state['results'][ $id ] ) ) {
     198                if ( isset( $state['results'][ $key ] ) ) {
    162199                        $this->processed = 1;
    163                         return $offset + 1 >= count( $state['ids'] ) ? null : $offset + 1;
     200                        return $offset + 1 >= count( $inventory ) && empty( $state['styles'] ) ? null : $offset + 1;
    164201                }
    165202                $post   = get_post( $id );
    166                 $url    = (string) get_permalink( $id );
     203                $url    = is_string( $entry ) && ! ctype_digit( $entry ) ? $entry : (string) get_permalink( $id );
    167204                $result = 'skipped';
    168                 if ( $post && 'publish' === $post->post_status && '' === $post->post_password && in_array( $post->post_type, array( 'post', 'page' ), true ) && self::allowed_url( $url ) ) {
     205                if ( ( ! $id || ( $post && 'publish' === $post->post_status && '' === $post->post_password && is_post_type_viewable( $post->post_type ) ) ) && self::allowed_url( $url ) ) {
    169206                        $response = wp_safe_remote_get(
    170207                                $url,
    … …  
    188225                                $type = strtolower( (string) wp_remote_retrieve_header( $response, 'content-type' ) );
    189226                                if ( 200 === $code && 0 === strpos( $type, 'text/html' ) && strlen( $body ) < 1048576 ) {
    190                                         $items    = array_values(
     227                                        $extracted = Extractor::extract_result( $body );
     228                                        $items     = array_values(
    191229                                                array_filter(
    192                                                         Extractor::extract( $body ),
     230                                                        $extracted['refs'],
    193231                                                        static function ( $item ) {
    194232                                                                return 'url' === $item['match_type'];
    … …  
    196234                                                )
    197235                                        );
     236                                        if ( count( $items ) > 2000 ) {
     237                                                $state['limited'] = true;
     238                                                $items            = array_slice( $items, 0, 2000 );
     239                                        }
    198240                                        $resolved = $this->resolver->resolve_many( $items );
    199241                                        foreach ( $items as $index => $item ) {
    … …  
    201243                                                        $refs->add( $attachment, 'strong', 'frontend', $id, $url, __( 'Anonymous public HTML', 'rapid-media-reclaim' ), 'url' ); }
    202244                                        }
     245                                        $this->queue_styles( $state, $body, $url, $id );
    203246                                        // Evidence must be durable before the successful coverage marker.
    204247                                        $refs->flush();
    205                                         $result = 'success';
    206                                 }
    207                         }
    208                 }
    209                 $state['results'][ $id ] = $result;
     248                                        // URLs found before an extraction limit still protect media, but the
     249                                        // page is reported as partially read, never as a successful check.
     250                                        $result = $extracted['complete'] ? 'success' : 'partial';
     251                                        if ( ! $extracted['complete'] ) {
     252                                                $state['limited'] = true;
     253                                        }
     254                                }
     255                        }
     256                }
     257                $state['results'][ $key ] = $result;
    210258                update_option( $this->option(), $state, false );
    211259                if ( get_option( $this->option() ) !== $state ) {
    212260                        throw new \RuntimeException( __( 'Could not persist crawl progress.', 'rapid-media-reclaim' ) ); } // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception messages are data; REST JSON or the admin render boundary escapes output.
    213261                $this->processed = 1;
    214                 return $offset + 1 >= count( $state['ids'] ) ? null : $offset + 1;
    215         }
     262                return $offset + 1 >= count( $inventory ) && empty( $state['styles'] ) ? null : $offset + 1;
     263        }
     264
     265        /**
     266         * Queue bounded same-origin stylesheets linked from successfully fetched HTML.
     267         *
     268         * @param array  $state State.
     269         * @param string $html Public HTML.
     270         * @param string $page Page URL.
     271         * @param int    $id Source post ID, or zero for an archive.
     272         */
     273        private function queue_styles( array &$state, string $html, string $page, int $id ): void {
     274                if ( ! class_exists( '\DOMDocument' ) ) {
     275                        return;
     276                }
     277                $previous = libxml_use_internal_errors( true );
     278                $document = new \DOMDocument();
     279                $document->loadHTML( $html, LIBXML_NONET );
     280                libxml_clear_errors();
     281                libxml_use_internal_errors( $previous );
     282                $state['styles']          = $state['styles'] ?? array();
     283                $state['style_results']   = $state['style_results'] ?? array();
     284                $state['external_styles'] = $state['external_styles'] ?? 0;
     285                foreach ( $document->getElementsByTagName( 'link' ) as $link ) {
     286                        if ( ! in_array( 'stylesheet', preg_split( '/\s+/', strtolower( trim( $link->getAttribute( 'rel' ) ) ) ), true ) ) {
     287                                continue;
     288                        }
     289                        $url = \WP_Http::make_absolute_url( $link->getAttribute( 'href' ), $page );
     290                        // Stylesheet version queries are stripped, never forwarded to endpoints.
     291                        $url = preg_replace( '/[?#].*$/', '', $url );
     292                        if ( ! self::allowed_url( $url ) ) {
     293                                ++$state['external_styles'];
     294                                continue;
     295                        }
     296                        if ( isset( $state['styles'][ $url ] ) || isset( $state['style_results'][ $url ] ) ) {
     297                                continue;
     298                        }
     299                        if ( count( $state['styles'] ) + count( $state['style_results'] ) >= 20 ) {
     300                                $state['limited'] = true;
     301                                break;
     302                        }
     303                        $state['styles'][ $url ] = $id;
     304                }
     305        }
     306
     307        /**
     308         * Fetch one stylesheet; imports and JavaScript remain explicitly excluded.
     309         *
     310         * @param array         $state State.
     311         * @param Ref_Collector $refs Evidence collector.
     312         */
     313        private function scan_style( array &$state, Ref_Collector $refs ): void {
     314                $url = array_key_first( $state['styles'] );
     315                $id  = $state['styles'][ $url ];
     316                unset( $state['styles'][ $url ] );
     317                $state['style_results'][ $url ] = 'failed';
     318                if ( ! self::allowed_url( $url ) ) {
     319                        return;
     320                }
     321                $response = wp_safe_remote_get(
     322                        $url,
     323                        array(
     324                                'timeout'             => 5,
     325                                'redirection'         => 0,
     326                                'limit_response_size' => 1048576,
     327                                'cookies'             => array(),
     328                                'headers'             => array(
     329                                        'Accept'        => 'text/css',
     330                                        'Cookie'        => '',
     331                                        'Authorization' => '',
     332                                ),
     333                                'user-agent'          => 'Rapid Media Reclaim anonymous coverage crawler',
     334                        )
     335                );
     336                if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) || 0 !== strpos( strtolower( (string) wp_remote_retrieve_header( $response, 'content-type' ) ), 'text/css' ) ) {
     337                        return;
     338                }
     339                $body = wp_remote_retrieve_body( $response );
     340                if ( strlen( $body ) >= 1048576 ) {
     341                        return;
     342                }
     343                if ( preg_match_all( '~url\(\s*["\']?([^\s)"\']+)~i', $body, $matches ) ) {
     344                        $items = array();
     345                        foreach ( array_slice( $matches[1], 0, 2000 ) as $image ) {
     346                                $absolute = \WP_Http::make_absolute_url( $image, $url );
     347                                $items[]  = array(
     348                                        'value'      => $absolute,
     349                                        'match_type' => 'url',
     350                                        'strength'   => 'strong',
     351                                        'context'    => $url,
     352                                );
     353                        }
     354                        $resolved = $this->resolver->resolve_many( $items );
     355                        foreach ( $resolved as $attachments ) {
     356                                foreach ( $attachments as $attachment ) {
     357                                        $refs->add( $attachment, 'strong', 'frontend', $id, $url, __( 'Anonymous linked stylesheet', 'rapid-media-reclaim' ), 'url' );
     358                                }
     359                        }
     360                        $refs->flush();
     361                }
     362                $state['style_results'][ $url ] = 'success';
     363        }
     364
     365        /**
     366         * Persist progress before advancing the caller's cursor.
     367         *
     368         * @param array $state State.
     369         * @throws \RuntimeException When progress cannot be saved.
     370         */
     371        private function save( array $state ): void {
     372                update_option( $this->option(), $state, false );
     373                if ( get_option( $this->option() ) !== $state ) {
     374                        throw new \RuntimeException( __( 'Could not persist crawl progress.', 'rapid-media-reclaim' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- JSON data escaped by render boundary.
     375                }
     376        }
     377
     378        /**
     379         * Discover one sitemap per tick, with a twenty-document hard budget.
     380         *
     381         * XML is parsed without entity substitution, DTD loading or network access.
     382         *
     383         * @param array $state Durable state, modified by reference.
     384         */
     385        private function discover( array &$state ): void {
     386                $url                = array_shift( $state['sitemaps'] );
     387                $state['visited'][] = $url;
     388                if ( ! self::allowed_url( $url ) || ! class_exists( '\DOMDocument' ) ) {
     389                        ++$state['sitemap_failed'];
     390                        return;
     391                }
     392                $response = wp_safe_remote_get(
     393                        $url,
     394                        array(
     395                                'timeout'             => 5,
     396                                'redirection'         => 0,
     397                                'limit_response_size' => 1048576,
     398                                'cookies'             => array(),
     399                                'headers'             => array(
     400                                        'Accept'        => 'application/xml,text/xml',
     401                                        'Cookie'        => '',
     402                                        'Authorization' => '',
     403                                ),
     404                                'user-agent'          => 'Rapid Media Reclaim anonymous coverage crawler',
     405                        )
     406                );
     407                $body     = is_wp_error( $response ) ? '' : wp_remote_retrieve_body( $response );
     408                if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) || strlen( $body ) >= 1048576 || preg_match( '/<!DOCTYPE|<!ENTITY/i', $body ) ) {
     409                        ++$state['sitemap_failed'];
     410                        return;
     411                }
     412                $previous = libxml_use_internal_errors( true );
     413                $document = new \DOMDocument();
     414                $loaded   = $document->loadXML( $body, LIBXML_NONET );
     415                libxml_clear_errors();
     416                libxml_use_internal_errors( $previous );
     417                $root = $loaded && $document->documentElement ? $document->documentElement->localName : ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native DOM API property names.
     418                if ( ! in_array( $root, array( 'urlset', 'sitemapindex' ), true ) ) {
     419                        ++$state['sitemap_failed'];
     420                        return;
     421                }
     422                foreach ( $document->documentElement->childNodes as $node ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native DOM API property names.
     423                        if ( ! $node instanceof \DOMElement || ! in_array( $node->localName, array( 'url', 'sitemap' ), true ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native DOM API property names.
     424                                continue;
     425                        }
     426                        $location = '';
     427                        foreach ( $node->childNodes as $child ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native DOM API property names.
     428                                if ( $child instanceof \DOMElement && 'loc' === $child->localName ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native DOM API property names.
     429                                        $location = trim( $child->textContent ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native DOM API property names.
     430                                        break;
     431                                }
     432                        }
     433                        if ( strlen( $location ) > 2048 || ! self::allowed_url( $location ) ) {
     434                                ++$state['sitemap_skipped'];
     435                                continue;
     436                        }
     437                        if ( 'sitemapindex' === $root ) {
     438                                if ( in_array( $location, $state['visited'], true ) || in_array( $location, $state['sitemaps'], true ) ) {
     439                                        continue;
     440                                }
     441                                if ( count( $state['visited'] ) + count( $state['sitemaps'] ) >= 20 ) {
     442                                        $state['limited'] = true;
     443                                        continue;
     444                                }
     445                                $state['sitemaps'][] = $location;
     446                        } elseif ( ! in_array( $location, $state['urls'], true ) ) {
     447                                if ( count( $state['urls'] ) >= $state['limit'] ) {
     448                                        $state['limited'] = true;
     449                                        break;
     450                                }
     451                                $state['urls'][] = $location;
     452                        }
     453                }
     454        }
     455
    216456        /**
    217457         * Coverage.
    218458         *
    219          * @return array Explicit successful, failed, skipped, limited and pending coverage.
     459         * @return array Explicit successful, failed, skipped, partial, limited and pending coverage.
    220460         */
    221461        public function coverage(): array {
    222                 $state  = $this->state();
    223                 $counts = array_count_values( $state['results'] );
     462                $state     = $this->state();
     463                $inventory = array_merge( $state['urls'] ?? array(), $state['ids'] );
     464                $counts    = array_count_values( $state['results'] );
    224465                return array(
    225                         'total'   => count( $state['ids'] ),
    226                         'success' => $counts['success'] ?? 0,
    227                         'failed'  => $counts['failed'] ?? 0,
    228                         'skipped' => $counts['skipped'] ?? 0,
    229                         'pending' => count( $state['ids'] ) - count( $state['results'] ),
    230                         'limited' => (bool) $state['limited'],
    231                         'limit'   => $state['limit'],
     466                        'total'             => count( $inventory ),
     467                        'success'           => $counts['success'] ?? 0,
     468                        'failed'            => $counts['failed'] ?? 0,
     469                        'skipped'           => $counts['skipped'] ?? 0,
     470                        'partial'           => $counts['partial'] ?? 0,
     471                        'pending'           => count( $inventory ) - count( $state['results'] ),
     472                        'limited'           => (bool) $state['limited'],
     473                        'limit'             => $state['limit'],
     474                        'sitemap_pending'   => count( $state['sitemaps'] ?? array() ),
     475                        'sitemap_attempted' => count( $state['visited'] ?? array() ),
     476                        'sitemap_failed'    => $state['sitemap_failed'] ?? 0,
     477                        'sitemap_skipped'   => $state['sitemap_skipped'] ?? 0,
     478                        'javascript'        => false,
     479                        'style_pending'     => count( $state['styles'] ?? array() ),
     480                        'style_results'     => array_count_values( $state['style_results'] ?? array() ),
     481                        'external_styles'   => $state['external_styles'] ?? 0,
     482                        'css_imports'       => false,
    232483                );
    233484        }
  • rapid-media-reclaim/trunk/includes/scan/class-incremental.php

    r3794616 r3814937  
    1616/** Incremental service. */
    1717final class Incremental {
     18        /** Initialized request-owned queues; no extra database reads on page loads.
     19         *
     20         * @var array
     21         */
     22        private static $instances = array();
     23
     24        /** Flush known buffered source changes before an explicit retirement fence. */
     25        public static function flush_pending(): void {
     26                foreach ( self::$instances as $instance ) {
     27                        $instance->flush(); }
     28        }
     29
    1830        /**
    1931         * Coalesced incremental work.
    … …  
    2638         */
    2739        public function init(): void {
     40                self::$instances[ spl_object_hash( $this ) ] = $this;
    2841                add_action( 'save_post', array( $this, 'post' ), 10, 1 );
    2942                add_action( 'wp_after_insert_post', array( $this, 'post' ), 10, 1 );
    … …  
    3346                        'post_updated',
    3447                        function ( $id, $after, $before ) {
    35                                 if ( 'acf-field' === $before->post_type ) {
     48                                if ( in_array( $before->post_type, array( 'acf-field', 'acf-field-group' ), true ) ) {
    3649                                        $this->acf_definition_changed();
    3750                                }
    … …  
    5770                                $event . '_option',
    5871                                function ( $name ) {
    59                                         // Media settings change in the admin, the REST API or WP-CLI; front-end
    60                                         // requests update caches and counters only.
     72                                        // Option hooks retain their existing editing-context scope. Visitor
     73                                        // deferral covers post, term, user and attachment source changes.
    6174                                        if ( self::editing_context() && Database_Scanner::option_allowed( $name ) ) {
    6275                                                $this->enqueue( 'options', $name );
    … …  
    110123        }
    111124        /**
    112          * True for requests that can change which media is used (admin, REST, cron, WP-CLI).
     125         * Contexts retaining immediate indexing; visitor changes use the durable queue.
    113126         */
    114127        private static function editing_context(): bool {
    … …  
    129142         */
    130143        public function post( $id ): void {
    131                 if ( 'acf-field' === get_post_type( $id ) ) {
     144                if ( in_array( get_post_type( $id ), array( 'acf-field', 'acf-field-group' ), true ) ) {
    132145                        $this->acf_definition_changed();
    133146                }
    134147                if ( ! wp_is_post_revision( $id ) && ! wp_is_post_autosave( $id ) ) {
    135148                        $this->enqueue( 'posts', $id );
     149                }
     150        }
     151        /**
     152         * Refresh bounded owners of a saved Elementor document, including transitive edges.
     153         *
     154         * @param int $id Changed dependency ID.
     155         */
     156        private function dependents( int $id ): void {
     157                global $wpdb;
     158                if ( ! $this->generations() ) {
     159                        return;
     160                }
     161                $owners = self::read_ids( $wpdb->prepare( "SELECT DISTINCT post_id FROM {$wpdb->postmeta} WHERE meta_key=%s AND meta_value=%s LIMIT 101", '_safe_media_cleaner_elementor_dependency', (string) $id ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Prepared bounded dependency lookup; postmeta key is indexed.
     162                foreach ( array_slice( $owners, 0, 100 ) as $owner ) {
     163                        $this->enqueue( 'posts', (int) $owner );
     164                }
     165                if ( count( $owners ) > 100 || $wpdb->last_error ) {
     166                        foreach ( $this->generations() as $generation ) {
     167                                Adapter_Coverage::merge(
     168                                        $generation,
     169                                        array(
     170                                                'elementor' => array(
     171                                                        'sources' => 0,
     172                                                        'issues'  => array( 'elementor_dependency_refresh_requires_rescan' => 1 ),
     173                                                ),
     174                                        )
     175                                );
     176                        }
    136177                }
    137178        }
    … …  
    144185                                $generation,
    145186                                array(
    146                                         'acf' => array(
     187                                        'acf'      => array(
    147188                                                'sources' => 0,
    148189                                                'issues'  => array( 'acf_definition_changed' => 1 ),
    149190                                        ),
     191                                        'database' => array(
     192                                                'sources' => 0,
     193                                                'issues'  => array( 'database_acf_definition_changed' => 1 ),
     194                                        ),
    150195                                )
    151196                        );
    … …  
    165210        }
    166211        /**
    167          * * Write buffered work and clear the in-memory queue.
     212         * Write buffered work, retaining durable protection on a failed immediate edit.
     213         *
     214         * @throws \Throwable Immediate indexing could not finish.
    168215         */
    169216        public function flush(): void {
     217                if ( ! $this->queue ) {
     218                        return;
     219                }
     220                if ( ! self::editing_context() ) {
     221                        \SafeMediaCleaner\Deferred_Index::enqueue( $this->queue );
     222                        $this->queue = array();
     223                        return;
     224                }
     225                $snapshot = $this->queue;
     226                try {
     227                        $this->write_queue();
     228                } catch ( \Throwable $error ) {
     229                        // A failed immediate edit must not expose a partially rewritten index.
     230                        \SafeMediaCleaner\Deferred_Index::enqueue( $snapshot );
     231                        throw $error;
     232                }
     233        }
     234
     235        /** Write the buffered queue inside projection invalidation. */
     236        private function write_queue(): void {
     237                if ( ! $this->queue ) {
     238                        return; }
     239                if ( class_exists( \SafeMediaCleaner\Status_Index::class ) ) {
     240                        \SafeMediaCleaner\Status_Index::write(
     241                                $this->generations(),
     242                                function () {
     243                                        $this->flush_index();
     244                                }
     245                        );
     246                } else {
     247                        $this->flush_index(); }
     248        }
     249
     250        /**
     251         * Apply an internal durable source snapshot synchronously in the worker.
     252         *
     253         * @param array $sources Numeric IDs grouped by scanner phase.
     254         * @throws \InvalidArgumentException Invalid source kind.
     255         */
     256        public static function refresh_sources( array $sources ): void {
     257                $worker = new self();
     258                foreach ( $sources as $phase => $ids ) {
     259                        if ( ! in_array( $phase, array( 'posts', 'terms', 'users', 'files' ), true ) ) {
     260                                throw new \InvalidArgumentException( 'Invalid deferred source kind.' );
     261                        }
     262                        foreach ( $ids as $id ) {
     263                                $worker->enqueue( $phase, absint( $id ) );
     264                        }
     265                }
     266                $worker->write_queue();
     267        }
     268
     269        /**
     270         * Execute a prepared authoritative mutation and never mask a failure.
     271         *
     272         * @param string $sql Prepared internal SQL.
     273         * @throws \RuntimeException Evidence write failed.
     274         */
     275        private static function execute( string $sql ): void {
     276                global $wpdb;
     277                if ( false === $wpdb->query( $sql ) ) { // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared -- Callers prepare values against internal table identifiers.
     278                        throw new \RuntimeException( 'Could not update incremental evidence.' );
     279                }
     280        }
     281
     282        /**
     283         * Read an authoritative ID set or retain the pending source for retry.
     284         *
     285         * @param string $sql Prepared internal SQL.
     286         * @return array IDs.
     287         * @throws \RuntimeException Evidence read failed.
     288         */
     289        private static function read_ids( string $sql ): array {
     290                global $wpdb;
     291                $ids = $wpdb->get_col( $sql ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared -- Callers prepare values; no cached read can authorize acknowledging a job.
     292                if ( $wpdb->last_error ) {
     293                        throw new \RuntimeException( 'Could not read incremental evidence.' );
     294                }
     295                return $ids;
     296        }
     297
     298        /**
     299         * Distinguish a missing post from a failed core post lookup.
     300         *
     301         * @param int $id Source ID.
     302         * @return string|false Post type.
     303         * @throws \RuntimeException Core source identity could not be read.
     304         */
     305        private static function post_type( int $id ) {
     306                global $wpdb;
     307                $type = get_post_type( $id );
     308                if ( $wpdb->last_error ) {
     309                        throw new \RuntimeException( 'Could not read incremental source identity.' );
     310                }
     311                return $type;
     312        }
     313
     314        /** Refresh authoritative evidence and shared groups. */
     315        private function flush_index(): void {
     316                if ( ! $this->queue ) {
     317                        return;
     318                }
    170319                global $wpdb;
    171320                $generations = $this->generations();
     321                // Resolve saved-template owners once per changed post per flush, after all
     322                // metadata writes have settled. Never rescan dependency ownership per field.
     323                foreach ( $this->queue['posts'] ?? array() as $id ) {
     324                        $this->dependents( (int) $id );
     325                }
    172326                $queue       = $this->queue;
    173327                $this->queue = array();
    … …  
    178332                $files = $queue['files'] ?? array();
    179333                foreach ( $queue['posts'] ?? array() as $id ) {
    180                         if ( 'attachment' === get_post_type( $id ) ) {
     334                        if ( 'attachment' === self::post_type( (int) $id ) ) {
    181335                                $files[ $id ] = $id;
    182336                        }
    … …  
    184338                foreach ( $files as $id ) {
    185339                        File_Map::refresh( array( (int) $id ), $generations );
    186                         if ( 'attachment' !== get_post_type( $id ) ) {
     340                        if ( 'attachment' !== self::post_type( (int) $id ) ) {
    187341                                foreach ( $generations as $g ) {
    188342                                        foreach ( array( 'files', 'refs' ) as $name ) {
    189343                                                $table = Installer::table( $name );
    190                                                 $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE attachment_id=%d AND generation=%d", $id, $g ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     344                                                self::execute( $wpdb->prepare( "DELETE FROM {$table} WHERE attachment_id=%d AND generation=%d", $id, $g ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    191345                                        }
    192346                                }
    … …  
    210364                                        $args      = array_merge( array( $generation, $id ), $types[ $phase ] );
    211365                                        $in        = implode( ',', array_fill( 0, count( $types[ $phase ] ), '%s' ) );
    212                                         foreach ( $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT attachment_id FROM {$table} WHERE generation=%d AND {$condition} AND source_type IN ({$in})", $args ) ) as $before ) { // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     366                                        foreach ( self::read_ids( $wpdb->prepare( "SELECT DISTINCT attachment_id FROM {$table} WHERE generation=%d AND {$condition} AND source_type IN ({$in})", $args ) ) as $before ) { // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    213367                                                $affected[ (int) $before ] = true;
    214368                                        }
    215                                         $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE generation=%d AND {$condition} AND source_type IN (" . implode( ',', array_fill( 0, count( $types[ $phase ] ), '%s' ) ) . ')', $args ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     369                                        self::execute( $wpdb->prepare( "DELETE FROM {$table} WHERE generation=%d AND {$condition} AND source_type IN (" . implode( ',', array_fill( 0, count( $types[ $phase ] ), '%s' ) ) . ')', $args ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    216370                                        $scanner->one( $id, $refs );
    217371                                        $refs->flush();
    218                                         foreach ( $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT attachment_id FROM {$table} WHERE generation=%d AND {$condition} AND source_type IN ({$in})", $args ) ) as $after ) { // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     372                                        foreach ( self::read_ids( $wpdb->prepare( "SELECT DISTINCT attachment_id FROM {$table} WHERE generation=%d AND {$condition} AND source_type IN ({$in})", $args ) ) as $after ) { // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    219373                                                $affected[ (int) $after ] = true;
    220374                                        }
    … …  
    245399                                'intval',
    246400                                // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    247                                 $wpdb->get_col(
     401                                self::read_ids(
    248402                                        $wpdb->prepare(
    249403                                                "SELECT DISTINCT other.attachment_id FROM {$files} changed
    … …  
    259413                        foreach ( array_chunk( $group, 500 ) as $chunk ) {
    260414                                $list = implode( ',', $chunk );
    261                                 $wpdb->query( $wpdb->prepare( "DELETE FROM {$refs} WHERE generation=%d AND source_type='shared_file' AND attachment_id IN ({$list})", $generation ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
     415                                self::execute( $wpdb->prepare( "DELETE FROM {$refs} WHERE generation=%d AND source_type='shared_file' AND attachment_id IN ({$list})", $generation ) ); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    262416                                // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom index/recovery query requires current database state; identifiers are internal, values are prepared or integer-normalized.
    263                                 $wpdb->query(
     417                                self::execute(
    264418                                        $wpdb->prepare(
    265419                                                "INSERT INTO {$refs} (attachment_id,strength,source_type,source_id,source_key,context,match_type,generation)
  • rapid-media-reclaim/trunk/includes/scan/class-ref-collector.php

    r3794616 r3814937  
    7474         */
    7575        public function flush(): void {
     76                if ( class_exists( \SafeMediaCleaner\Status_Index::class ) ) {
     77                        \SafeMediaCleaner\Status_Index::write(
     78                                $this->generations,
     79                                function () {
     80                                        $this->write_flush();
     81                                }
     82                        );
     83                } else {
     84                        $this->write_flush(); }
     85        }
     86
     87        /**
     88         * Flush authoritative evidence rows.
     89         *
     90         * @throws \RuntimeException Evidence write failed.
     91         */
     92        private function write_flush(): void {
    7693                global $wpdb;
    7794                $table = Installer::table( 'refs' );
  • rapid-media-reclaim/trunk/includes/scan/class-theme-scanner.php

    r3794616 r3814937  
    2121        private $resolver;
    2222        /**
     23         * Target generation for durable coverage.
     24         *
     25         * @var int
     26         */
     27        private $generation;
     28        /**
    2329         * Sorted theme file inventory.
    2430         *
    … …  
    3844         */
    3945        public function __construct( int $generation ) {
    40                 $this->resolver = new Url_Resolver( $generation );
     46                $this->generation = $generation;
     47                $this->resolver   = new Url_Resolver( $generation );
    4148        }
    4249        /**
    … …  
    119126                                throw new \RuntimeException( 'Could not read theme file: ' . $key ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Error data is escaped by the REST JSON or admin rendering boundary.
    120127                        }
    121                         $items    = Extractor::extract( $content );
     128                        $result = Extractor::extract_result( $content );
     129                        if ( ! $result['complete'] ) {
     130                                $this->gap( $key, (string) array_key_first( $result['issues'] ) );
     131                        }
     132                        $items    = $result['refs'];
    122133                        $resolved = $this->resolver->resolve_many( $items );
    123134                        foreach ( $items as $i => $ref ) {
    … …  
    132143                return $next >= $this->total() ? null : $next;
    133144        }
     145
     146        /**
     147         * Keep a partly read theme file visible and pause cleanup, like an unread database value.
     148         *
     149         * @param string $key Theme-relative file path; contents are never retained.
     150         * @param string $reason Machine reason constant.
     151         * @throws \RuntimeException The durable cleanup restriction could not be saved.
     152         */
     153        private function gap( string $key, string $reason ): void {
     154                $sample = array(
     155                        'phase' => 'theme_files',
     156                        'id'    => 0,
     157                        'key'   => substr( $key, 0, 191 ),
     158                );
     159                $option = 'safe_media_cleaner_adapter_gap_' . $this->generation . '_database';
     160                add_option( $option, $sample, '', false );
     161                if ( ! get_option( $option, false ) ) {
     162                        throw new \RuntimeException( __( 'Could not save the cleanup restriction for unread content. The scan was stopped.', 'rapid-media-reclaim' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Error data is encoded by REST/CLI and escaped at the admin boundary.
     163                }
     164                Adapter_Coverage::merge(
     165                        $this->generation,
     166                        array(
     167                                'database' => array(
     168                                        'sources'  => 1,
     169                                        'issues'   => array( $reason => 1 ),
     170                                        'examples' => array( $sample ),
     171                                ),
     172                        )
     173                );
     174        }
    134175}
  • rapid-media-reclaim/trunk/includes/scan/class-url-resolver.php

    r3794616 r3814937  
    4040         * @param string $url Url.
    4141         * @param string $base_path Base path.
     42         * @param array  $aliases Explicit CDN/old upload roots.
    4243         * @return string Result.
    4344         */
    44         public static function normalize( string $url, string $base_path = '/wp-content/uploads' ): string {
    45                 $url = rawurldecode( html_entity_decode( str_replace( '\\/', '/', $url ), ENT_QUOTES, 'UTF-8' ) );
    46                 $url = preg_split( '/[?#]/', $url )[0];
     45        public static function normalize( string $url, string $base_path = '/wp-content/uploads', array $aliases = array() ): string {
     46                $url      = rawurldecode( html_entity_decode( str_replace( '\\/', '/', $url ), ENT_QUOTES, 'UTF-8' ) );
     47                $url      = preg_split( '/[?#]/', $url )[0];
     48                $rootless = preg_replace( '~^https?:~i', '', $url );
     49                usort(
     50                        $aliases,
     51                        static function ( $a, $b ) {
     52                                return strlen( $b ) <=> strlen( $a );
     53                        }
     54                );
     55                foreach ( $aliases as $alias ) {
     56                        $prefix = preg_replace( '~^https?:~i', '', rtrim( rawurldecode( $alias ), '/' ) ) . '/';
     57                        if ( 0 === strncasecmp( $rootless, $prefix, strlen( $prefix ) ) ) {
     58                                return strtolower( substr( $rootless, strlen( $prefix ) ) );
     59                        }
     60                }
    4761                $url = preg_replace( '~^(?:https?:)?//[^/]+~i', '', $url );
    4862                $url = str_replace( '\\', '/', $url );
    … …  
    87101                $base    = wp_parse_url( $uploads['baseurl'], PHP_URL_PATH );
    88102                $base    = $base ? $base : '/wp-content/uploads';
     103                $aliases = \SafeMediaCleaner\Settings::get()['upload_aliases'];
    89104                $paths   = array();
    90105                $ids     = array();
    … …  
    100115                                $ids[ (int) $ref['value'] ][] = $key;
    101116                        } elseif ( 'filename' !== $ref['match_type'] ) {
    102                                 foreach ( self::variants( self::normalize( (string) $ref['value'], $base ) ) as $p ) {
     117                                foreach ( self::variants( self::normalize( (string) $ref['value'], $base, $aliases ) ) as $p ) {
    103118                                        $paths[ $p ][] = $key;
    104119                                }
  • rapid-media-reclaim/trunk/languages/rapid-media-reclaim.pot

    r3794616 r3814937  
    33msgid ""
    44msgstr ""
    5 "Project-Id-Version: Rapid Media Reclaim 1.0.0\n"
    6 "Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/source\n"
     5"Project-Id-Version: Rapid Media Reclaim 1.1.0\n"
     6"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/rapid-media-reclaim\n"
    77"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
    88"Language-Team: LANGUAGE <LL@li.org>\n"
    … …  
    1010"Content-Type: text/plain; charset=UTF-8\n"
    1111"Content-Transfer-Encoding: 8bit\n"
    12 "POT-Creation-Date: 2026-10-22T10:56:31+00:00\n"
     12"POT-Creation-Date: 2026-11-21T06:46:51+00:00\n"
    1313"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
    1414"X-Generator: WP-CLI 2.12.0\n"
    … …  
    2020#: includes/admin/class-admin.php:55
    2121#: includes/admin/class-admin.php:56
    22 #: assets/js/app.js:1190
     22#: assets/js/app.js:1207
    2323msgid "Rapid Media Reclaim"
    24 msgstr ""
    25 
    26 #. Plugin URI of the plugin
    27 #: rapid-media-reclaim.php
    28 msgid "https://wordpress.org/plugins/rapid-media-reclaim/"
    2924msgstr ""
    3025
    3126#. Description of the plugin
    3227#: rapid-media-reclaim.php
    33 msgid "Find unused media with proof of where every file is used, move it to a reversible quarantine, and clean up only when you are sure."
     28msgid "Review potentially unused media with usage evidence, reversible quarantine and one-click restore before reclaiming storage."
    3429msgstr ""
    3530
    … …  
    6156
    6257#: includes/admin/class-media-library.php:71
    63 #: assets/js/app.js:1701
     58#: assets/js/app.js:2354
    6459msgid "In quarantine"
    6560msgstr ""
    … …  
    7873
    7974#: includes/admin/class-media-library.php:89
    80 #: assets/js/app.js:27
    81 #: assets/js/app.js:1465
    82 #: assets/js/app.js:1728
     75#: assets/js/app.js:28
     76#: assets/js/app.js:2118
     77#: assets/js/app.js:2381
    8378msgid "Kept"
    8479msgstr ""
    … …  
    8883msgstr ""
    8984
     85#: includes/class-acf-context.php:330
     86msgid "ACF definitions or hidden field keys changed. Restore the approved context or resolve this journal manually; later edits and the merge lease were preserved."
     87msgstr ""
     88
     89#: includes/class-cli.php:48
     90msgid "Supply positive attachment IDs separated by commas."
     91msgstr ""
     92
     93#: includes/class-cli.php:52
     94msgid "At most 100 attachments may be selected per command."
     95msgstr ""
     96
     97#: includes/class-cli.php:56
     98msgid "An attachment ID is outside the supported range."
     99msgstr ""
     100
     101#: includes/class-cli.php:74
     102msgid "Use --user=<administrator> with the plugin management capability."
     103msgstr ""
     104
     105#: includes/class-cli.php:77
     106msgid "Force operations are not supported."
     107msgstr ""
     108
     109#: includes/class-cli.php:85
     110msgid "You cannot manage one of the selected attachments."
     111msgstr ""
     112
     113#: includes/class-cli.php:120
     114msgid "Quarantine the approved duplicates after reviewing public pages/caches and saving the current backup? No permanent deletion."
     115msgstr ""
     116
     117#: includes/class-cli.php:164
     118msgid "Operation history is unavailable. Check database access and retry with the last CSV cursor."
     119msgstr ""
     120
     121#: includes/class-cli.php:185
     122msgid "You cannot permanently delete one of the selected attachments."
     123msgstr ""
     124
     125#: includes/class-cli.php:231
     126msgid "Unsupported command."
     127msgstr ""
     128
     129#: includes/class-csv-export.php:62
     130msgid "You cannot export this media inventory."
     131msgstr ""
     132
     133#: includes/class-discovery-csv.php:71
     134msgid "Review only; no deletion authorization. Best-effort walk of changing uploads. Ownership is an index snapshot, not live proof. Unindexed files may still be used. Excluded/skipped trees are not covered. At most 10000 examined rows and 30 seconds per export; continuation is in the completion row."
     135msgstr ""
     136
     137#: includes/class-discovery-csv.php:79
     138msgid "Index changed or unavailable; ownership snapshot is stale."
     139msgstr ""
     140
     141#: includes/class-discovery-csv.php:79
     142msgid "Unregistered size remains owned; not a deletion candidate."
     143msgstr ""
     144
     145#: includes/class-discovery-csv.php:79
     146msgid "Requires independent usage and ownership review."
     147msgstr ""
     148
     149#: includes/class-discovery-csv.php:112
     150msgid "You cannot download this uploads audit."
     151msgstr ""
     152
     153#: includes/class-discovery-csv.php:123
     154msgid "This audit is unavailable, expired or belongs to another user."
     155msgstr ""
     156
     157#: includes/class-discovery-csv.php:133
     158msgid "Export interrupted; do not treat this partial CSV as complete."
     159msgstr ""
     160
     161#: includes/class-discovery-jobs.php:72
     162msgid "Unsupported discovery task."
     163msgstr ""
     164
     165#: includes/class-discovery-jobs.php:90
     166msgid "Could not save discovery task."
     167msgstr ""
     168
     169#: includes/class-discovery-jobs.php:129
     170msgid "This discovery task is busy."
     171msgstr ""
     172
     173#: includes/class-discovery-jobs.php:159
     174msgid "Could not save discovery results. Retry this step."
     175msgstr ""
     176
     177#: includes/class-discovery-jobs.php:167
     178msgid "Could not advance discovery cursor."
     179msgstr ""
     180
     181#: includes/class-discovery-jobs.php:192
     182msgid "Could not read discovery results."
     183msgstr ""
     184
     185#: includes/class-discovery-jobs.php:330
     186msgid "Invalid discovery task."
     187msgstr ""
     188
     189#: includes/class-discovery-jobs.php:335
     190msgid "Discovery task expired or belongs to another user."
     191msgstr ""
     192
     193#: includes/class-discovery-jobs.php:362
     194msgid "You cannot run media discovery tasks."
     195msgstr ""
     196
     197#: includes/class-duplicate-scanner.php:268
     198msgid "Could not read attachment inventory."
     199msgstr ""
     200
     201#: includes/class-file-archive.php:160
     202msgid "This backup is unavailable or could not be verified. Refresh Tools and retry with the owning account."
     203msgstr ""
     204
    90205#. translators: %d: post ID
    91 #: includes/class-index.php:644
     206#: includes/class-index.php:696
    92207#, php-format
    93208msgid "(no title) #%d"
    94209msgstr ""
    95210
    96 #: includes/class-index.php:670
     211#: includes/class-index.php:722
    97212msgid "User profile"
    98213msgstr ""
    99214
    100 #: includes/class-index.php:686
    101 #: includes/scan/class-database-scanner.php:332
     215#: includes/class-index.php:738
     216#: includes/scan/class-database-scanner.php:508
    102217msgid "Site setting"
    103218msgstr ""
    104219
    105 #: includes/class-index.php:687
     220#: includes/class-index.php:739
    106221msgid "Theme setting"
    107222msgstr ""
    108223
    109 #: includes/class-index.php:688
    110 #: includes/scan/class-database-scanner.php:335
     224#: includes/class-index.php:740
     225#: includes/scan/class-database-scanner.php:511
    111226msgid "Widget"
    112227msgstr ""
    113228
    114 #: includes/class-index.php:689
    115 #: assets/js/app.js:70
     229#: includes/class-index.php:741
     230#: assets/js/app.js:71
    116231msgid "Site identity"
    117232msgstr ""
    118233
    119 #. translators: %d: media ID
    120234#. translators: %d: attachment ID
    121 #: includes/class-index.php:698
    122 #: assets/js/app.js:205
     235#: includes/class-index.php:750
     236#: assets/js/app.js:206
    123237#, php-format,js-format
    124238msgid "Media #%d"
    125239msgstr ""
    126240
    127 #. translators: %d: media ID
    128 #: includes/class-index.php:699
     241#. translators: %d: attachment ID
     242#: includes/class-index.php:751
    129243msgid "Same file, used elsewhere (for example a translation)"
    130244msgstr ""
    131245
    132 #: includes/class-index.php:707
     246#: includes/class-index.php:759
    133247msgid "Anonymous browser media error"
    134248msgstr ""
    135249
    136 #: includes/class-index.php:708
     250#: includes/class-index.php:760
    137251msgid "Conservative observation; page and visitor details are not stored."
    138252msgstr ""
    139253
    140 #: includes/class-index.php:717
     254#: includes/class-index.php:769
    141255msgid "Theme file"
    142256msgstr ""
    143257
     258#: includes/class-merge.php:68
     259msgid "Resolve existing reference journals before creating another merge."
     260msgstr ""
     261
     262#: includes/class-merge.php:71
     263msgid "Could not protect the merge payloads. Nothing was rewritten."
     264msgstr ""
     265
     266#: includes/class-merge.php:90
     267msgid "Select one canonical image and up to ten duplicates after a complete scan."
     268msgstr ""
     269
     270#: includes/class-merge.php:111
     271msgid "Every merge item must be editable, local and outside quarantine."
     272msgstr ""
     273
     274#: includes/class-merge.php:114
     275msgid "Translation/shared-file reference merges need a language mapping and are not supported yet. No references were changed."
     276msgstr ""
     277
     278#: includes/class-merge.php:118
     279msgid "A selected original cannot be fingerprinted safely."
     280msgstr ""
     281
     282#: includes/class-merge.php:122
     283msgid "Only distinct paths with byte-identical originals can be rewritten."
     284msgstr ""
     285
     286#: includes/class-merge.php:147
     287msgid "Merge references exceed the preview budget or could not be read."
     288msgstr ""
     289
     290#: includes/class-merge.php:393
     291msgid "Merge journal exceeds its bounded storage limit."
     292msgstr ""
     293
     294#: includes/class-merge.php:411
     295msgid "Preview changed, has unsupported references or contains no supported writes. Nothing was changed."
     296msgstr ""
     297
     298#: includes/class-merge.php:426
     299msgid "Could not save the merge recovery journal."
     300msgstr ""
     301
     302#: includes/class-merge.php:446
     303msgid "Another media operation is running."
     304msgstr ""
     305
     306#: includes/class-merge.php:504
     307msgid "ACF scan coverage is incomplete. Resolve unsupported sources and complete a new scan before applying this merge. The journal was retained."
     308msgstr ""
     309
     310#: includes/class-merge.php:512
     311msgid "A merge payload changed. Roll back before retrying."
     312msgstr ""
     313
     314#: includes/class-merge.php:527
     315msgid "Restore missing or changed merge payloads before rolling references back."
     316msgstr ""
     317
     318#: includes/class-merge.php:534
     319msgid "You can no longer edit a merge source."
     320msgstr ""
     321
     322#: includes/class-merge.php:540
     323msgid "A source changed after preview. Its edits were preserved; review the conflict before retrying."
     324msgstr ""
     325
     326#: includes/class-merge.php:545
     327msgid "A reference write did not persist. The journal was retained."
     328msgstr ""
     329
     330#: includes/class-merge.php:757
     331msgid "Complete or roll back the pending reference operation before starting another."
     332msgstr ""
     333
     334#: includes/class-merge.php:968
     335msgid "Repeated or missing metadata cannot be merged safely."
     336msgstr ""
     337
     338#: includes/class-merge.php:990
     339msgid "A source changed during the write. Its edits were preserved and the merge journal was retained."
     340msgstr ""
     341
     342#: includes/class-merge.php:1002
     343msgid "Could not save merge progress. Retry; the recovery journal is retained."
     344msgstr ""
     345
     346#: includes/class-merge.php:1013
     347msgid "Invalid merge journal."
     348msgstr ""
     349
     350#: includes/class-merge.php:1016
     351msgid "Merge journal is unavailable or belongs to another user."
     352msgstr ""
     353
     354#: includes/class-merge.php:1046
     355msgid "Only administrators can merge references."
     356msgstr ""
     357
     358#: includes/class-operation-ledger.php:213
     359msgid "Operation accounting is pending. Files and recovery manifests were retained. Retry in Quarantine; check database writes if this persists. Available originals can still be restored."
     360msgstr ""
     361
    144362#: includes/class-quarantine.php:138
    145 #: includes/class-quarantine.php:240
    146 #: includes/class-quarantine.php:313
     363#: includes/class-quarantine.php:272
     364#: includes/class-quarantine.php:402
     365#: includes/class-quarantine.php:515
    147366msgid "Another media operation is running. Retry shortly."
    148367msgstr ""
    149368
     369#: includes/class-quarantine.php:158
     370#: includes/class-quarantine.php:200
     371msgid "Recovery requires the media operation lock."
     372msgstr ""
     373
    150374#: includes/class-quarantine.php:169
     375msgid "Existing quarantine recovery differs from this backup. Review it in Quarantine first."
     376msgstr ""
     377
     378#: includes/class-quarantine.php:173
     379msgid "Existing quarantine files differ from this backup."
     380msgstr ""
     381
     382#: includes/class-quarantine.php:188
     383msgid "Could not save recovery data. Retry before copying files."
     384msgstr ""
     385
     386#: includes/class-quarantine.php:223
     387msgid "Another attachment owns a backup file name. Review that media before retrying."
     388msgstr ""
     389
     390#: includes/class-quarantine.php:243
     391#: includes/class-quarantine.php:392
     392#: includes/class-quarantine.php:496
     393msgid "Resume the pending backup recovery in Tools before changing this media."
     394msgstr ""
     395
     396#: includes/class-quarantine.php:252
     397msgid "This file is protected by a reference recovery journal. Roll back or finish reviewing that operation first."
     398msgstr ""
     399
     400#: includes/class-quarantine.php:305
     401#: includes/class-quarantine.php:426
     402#: includes/class-quarantine.php:540
     403msgid "Resume pending recovery in Tools first."
     404msgstr ""
     405
     406#: includes/class-quarantine.php:322
    151407msgid "The quarantine folder could not be created. Check that the uploads folder is writable."
    152408msgstr ""
    153409
    154 #: includes/class-quarantine.php:179
     410#: includes/class-quarantine.php:332
    155411msgid "Shared group operation incomplete. Restore the group before retrying."
    156412msgstr ""
    157413
    158414#. translators: %s: comma-separated media IDs
    159 #: includes/class-quarantine.php:189
     415#: includes/class-quarantine.php:342
    160416#, php-format
    161417msgid "This file is shared with media item %s (for example a translation). Select them together to quarantine them."
    162418msgstr ""
    163419
    164 #: includes/class-quarantine.php:203
     420#: includes/class-quarantine.php:356
    165421msgid "Could not save the shared recovery record."
    166422msgstr ""
    167423
    168 #: includes/class-quarantine.php:346
     424#: includes/class-quarantine.php:472
     425msgid "Could not read the recovery batch. Retry the batch."
     426msgstr ""
     427
     428#: includes/class-quarantine.php:478
     429msgid "Could not verify the remaining recovery records. Retry the batch."
     430msgstr ""
     431
     432#: includes/class-quarantine.php:560
    169433msgid "Only quarantined files can be deleted permanently."
    170434msgstr ""
    171435
    172 #: includes/class-quarantine.php:350
     436#: includes/class-quarantine.php:564
    173437msgid "No verified permanent deletion intent exists. Restore or review this recovery record; its payload was retained."
    174438msgstr ""
    175439
    176 #. translators: %d: number of days
    177 #: includes/class-quarantine.php:359
    178 #, php-format
    179 msgid "This file has been in quarantine for less than %d day."
    180 msgid_plural "This file has been in quarantine for less than %d days."
    181 msgstr[0] ""
    182 msgstr[1] ""
    183 
    184 #: includes/class-quarantine.php:370
     440#: includes/class-quarantine.php:571
    185441msgid "This file is in use again (for example as a featured image or in content). Restore it instead of deleting it."
    186442msgstr ""
    187443
    188444#. translators: %s: comma-separated media IDs
    189 #: includes/class-quarantine.php:389
     445#: includes/class-quarantine.php:590
    190446#, php-format
    191447msgid "Media item %s still uses this file and is not in quarantine. Restore this item, or quarantine that one too."
    … …  
    193449
    194450#. translators: %s: comma-separated media IDs
    195 #: includes/class-quarantine.php:404
     451#: includes/class-quarantine.php:605
    196452#, php-format
    197453msgid "This file is shared with quarantined media item %s. Delete them together."
    198454msgstr ""
    199455
    200 #: includes/class-quarantine.php:491
     456#: includes/class-quarantine.php:618
     457msgid "Could not verify the complete recovery group. Nothing was deleted."
     458msgstr ""
     459
     460#: includes/class-quarantine.php:624
     461msgid "A shared file is in use again. Restore the group instead of deleting it."
     462msgstr ""
     463
     464#. translators: %d: minimum quarantine days.
     465#: includes/class-quarantine.php:671
     466#, php-format
     467msgid "Keep this file in quarantine for at least %d days before permanent deletion."
     468msgstr ""
     469
     470#: includes/class-quarantine.php:677
     471msgid "Download and confirm a current recovery archive before permanent deletion."
     472msgstr ""
     473
     474#: includes/class-quarantine.php:718
     475msgid "Manual deletion may proceed with incomplete or browser-only routing verification. Quarantine age is separate from the verified window. No recognized requests does not prove that a file is unused. The minimum waiting period, usage and ownership checks, saved-backup confirmation and permissions still apply."
     476msgstr ""
     477
     478#: includes/class-quarantine.php:788
    201479msgid "Invalid quarantine directory setting. Recovery data retained."
    202480msgstr ""
    203481
    204 #: includes/class-quarantine.php:533
     482#: includes/class-quarantine.php:835
    205483msgid "Sorry, you are not allowed to view this file."
    206484msgstr ""
    207485
    208 #: includes/class-quarantine.php:615
     486#: includes/class-quarantine.php:920
    209487msgid "This media item no longer exists."
    210488msgstr ""
    211489
    212 #: includes/class-quarantine.php:618
     490#: includes/class-quarantine.php:923
    213491msgid "This file is already in quarantine."
    214492msgstr ""
    215493
    216 #: includes/class-quarantine.php:623
     494#: includes/class-quarantine.php:930
    217495msgid "No files were found for this media item."
    218496msgstr ""
    219497
    220 #: includes/class-quarantine.php:634
     498#: includes/class-quarantine.php:941
    221499msgid "Could not verify file identity."
    222500msgstr ""
    223501
    224 #: includes/class-quarantine.php:647
     502#: includes/class-quarantine.php:954
    225503msgid "Could not save recovery data. No files were moved."
    226504msgstr ""
    227505
    228 #: includes/class-quarantine.php:658
     506#: includes/class-quarantine.php:973
    229507msgid "This media item could not be moved (the server did not allow it). Recovery data has been retained if cleanup could not finish. Review this item before retrying."
    230508msgstr ""
    231509
    232 #: includes/class-quarantine.php:671
     510#: includes/class-quarantine.php:986
    233511msgid "This media item could not be moved (a file could not be removed). Recovery data has been retained if cleanup could not finish. Review this item before retrying."
    234512msgstr ""
    235513
    236 #: includes/class-quarantine.php:767
     514#: includes/class-quarantine.php:1092
    237515msgid "This file is not in quarantine."
    238516msgstr ""
    239517
    240 #: includes/class-quarantine.php:784
     518#: includes/class-quarantine.php:1109
    241519msgid "Shared recovery owner is missing. Recovery data was retained."
    242520msgstr ""
    243521
    244 #: includes/class-quarantine.php:795
     522#: includes/class-quarantine.php:1120
    245523msgid "Legacy recovery identity is missing or ambiguous. No files were moved; recovery data was retained."
    246524msgstr ""
    247525
    248 #: includes/class-quarantine.php:799
     526#: includes/class-quarantine.php:1124
    249527msgid "Legacy recovery payload could not be verified."
    250528msgstr ""
    251529
    252 #: includes/class-quarantine.php:819
     530#: includes/class-quarantine.php:1144
    253531msgid "Could not save verified legacy recovery identities. No files were moved."
    254532msgstr ""
    255533
    256 #: includes/class-quarantine.php:828
     534#: includes/class-quarantine.php:1159
    257535msgid "Unsafe recovery path. Recovery data was retained."
    258536msgstr ""
    259537
    260 #: includes/class-quarantine.php:833
     538#: includes/class-quarantine.php:1164
    261539msgid "Recovery cleanup incomplete. Retry restore."
    262540msgstr ""
    263541
    264 #: includes/class-quarantine.php:838
     542#: includes/class-quarantine.php:1170
    265543msgid "A recovery file is missing, changed, or its destination is occupied. Recovery data was retained."
    266544msgstr ""
    267545
    268 #: includes/class-quarantine.php:841
     546#: includes/class-quarantine.php:1173
    269547msgid "Restore incomplete. Recovery data was retained; retry restore."
    270548msgstr ""
    271549
    272 #: includes/class-quarantine.php:853
     550#: includes/class-quarantine.php:1192
    273551msgid "Could not clear shared recovery metadata. Retry restore."
    274552msgstr ""
    275553
    276 #: includes/class-quarantine.php:855
     554#: includes/class-quarantine.php:1194
    277555msgid "Could not save shared recovery state. Retry restore."
    278556msgstr ""
    279557
    280 #: includes/class-quarantine.php:863
     558#: includes/class-quarantine.php:1202
    281559msgid "Could not clear recovery metadata. Retry restore."
    282560msgstr ""
    283561
    284 #: includes/class-quarantine.php:865
     562#: includes/class-quarantine.php:1207
    285563msgid "Files restored but recovery state could not be saved. Retry restore."
    286564msgstr ""
    287565
    288 #: includes/class-quarantine.php:892
     566#: includes/class-quarantine.php:1234
    289567msgid "Shared recovery owner is missing. Restore the group before deleting."
    290568msgstr ""
    291569
    292 #: includes/class-quarantine.php:898
     570#: includes/class-quarantine.php:1240
    293571msgid "Quarantine is incomplete. Restore before deleting."
    294572msgstr ""
    295573
    296 #: includes/class-quarantine.php:904
     574#: includes/class-quarantine.php:1246
    297575msgid "Quarantine payload changed. Recovery data retained."
    298576msgstr ""
    299577
    300 #: includes/class-quarantine.php:912
     578#: includes/class-quarantine.php:1254
    301579msgid "A shared recovery record has no verified deletion intent. Restore or review the group first."
    302580msgstr ""
    303581
    304 #: includes/class-quarantine.php:932
     582#: includes/class-quarantine.php:1274
    305583msgid "Could not save permanent deletion authorization. Nothing was deleted."
    306584msgstr ""
    307585
    308 #: includes/class-quarantine.php:947
     586#: includes/class-quarantine.php:1297
    309587msgid "WordPress could not delete this media item."
    310588msgstr ""
    311589
    312 #: includes/class-quarantine.php:954
     590#: includes/class-quarantine.php:1304
    313591msgid "Payload cleanup failed. Recovery record retained for retry."
    314592msgstr ""
    315593
    316 #: includes/class-quarantine.php:957
     594#: includes/class-quarantine.php:1310
    317595msgid "Could not save cleanup state."
    318596msgstr ""
    319597
    320 #: includes/class-quarantine.php:999
     598#: includes/class-quarantine.php:1352
    321599msgid "Recovery manifest is corrupt. Data was retained."
    322600msgstr ""
    323601
    324 #: includes/class-quarantine.php:1003
     602#: includes/class-quarantine.php:1356
    325603msgid "Recovery manifest is unsafe. Data was retained."
    326604msgstr ""
    327605
    328 #: includes/class-request-watcher.php:315
     606#: includes/class-quarantine.php:1522
     607#: includes/class-quarantine.php:1546
     608msgid "Could not verify file ownership. No files were moved."
     609msgstr ""
     610
     611#: includes/class-recovery-archive.php:277
     612msgid "This archive is incomplete, unsafe or outside the supported recovery limits. No media was changed."
     613msgstr ""
     614
     615#: includes/class-recovery-attachments.php:118
     616msgid "WordPress inserted a different attachment ID. Recovery is paused for manual review. No files or posts were deleted."
     617msgstr ""
     618
     619#: includes/class-recovery-attachments.php:156
     620msgid "Another writer occupied the original attachment ID during recovery. WordPress created a different ID. Recovery is paused for manual review; no posts or files were deleted."
     621msgstr ""
     622
     623#: includes/class-recovery-attachments.php:232
     624msgid "An attachment ID, permission, or metadata changed, or reconstruction could not be verified. Recovery data was retained. Resolve the conflict and retry in Tools."
     625msgstr ""
     626
     627#: includes/class-recovery-export.php:35
     628msgid "Select between 1 and 100 recovery items."
     629msgstr ""
     630
     631#: includes/class-recovery-export.php:40
     632msgid "Some selected items no longer have recovery records."
     633msgstr ""
     634
     635#: includes/class-recovery-export.php:48
     636msgid "Include the payload owner and all shared media items in the export."
     637msgstr ""
     638
     639#: includes/class-recovery-export.php:52
     640msgid "Export shared media items together."
     641msgstr ""
     642
     643#: includes/class-recovery-export.php:57
     644msgid "Recovery manifest is incomplete. Restore or review this item first."
     645msgstr ""
     646
     647#: includes/class-recovery-export.php:61
     648msgid "Export requires verified manifests and files no larger than 64 MiB."
     649msgstr ""
     650
     651#: includes/class-recovery-export.php:65
     652msgid "Export at most 512 MiB per archive; use smaller selections."
     653msgstr ""
     654
     655#: includes/class-recovery-export.php:76
     656msgid "Export at most 5,000 payload files at once."
     657msgstr ""
     658
     659#: includes/class-recovery-export.php:106
     660msgid "Recovery metadata exceeds the bounded export limit."
     661msgstr ""
     662
     663#: includes/class-recovery-export.php:135
     664msgid "The PHP ZIP extension is required for recovery exports."
     665msgstr ""
     666
     667#: includes/class-recovery-export.php:142
     668msgid "Could not create private recovery archive."
     669msgstr ""
     670
     671#: includes/class-recovery-export.php:149
     672msgid "Could not save recovery manifest."
     673msgstr ""
     674
     675#: includes/class-recovery-export.php:166
     676msgid "Could not save export progress."
     677msgstr ""
     678
     679#: includes/class-recovery-export.php:184
     680msgid "This export is busy. Retry shortly."
     681msgstr ""
     682
     683#: includes/class-recovery-export.php:190
     684msgid "Recovery state changed. Start a new export."
     685msgstr ""
     686
     687#: includes/class-recovery-export.php:204
     688msgid "Could not save archive verification progress."
     689msgstr ""
     690
     691#: includes/class-recovery-export.php:210
     692msgid "Recovery archive is missing or damaged."
     693msgstr ""
     694
     695#: includes/class-recovery-export.php:217
     696msgid "A recovery payload is missing, changed or unreadable. Nothing was deleted."
     697msgstr ""
     698
     699#: includes/class-recovery-export.php:225
     700msgid "Archive write failed. Check private temporary storage."
     701msgstr ""
     702
     703#: includes/class-recovery-export.php:232
     704msgid "Could not save export progress. Retry this step."
     705msgstr ""
     706
     707#: includes/class-recovery-export.php:249
     708msgid "Could not verify archive."
     709msgstr ""
     710
     711#: includes/class-recovery-export.php:255
     712msgid "Archive payload is missing."
     713msgstr ""
     714
     715#: includes/class-recovery-export.php:262
     716msgid "Archive checksum verification failed."
     717msgstr ""
     718
     719#: includes/class-recovery-export.php:281
     720msgid "Download a current, complete recovery archive before confirming your saved backup."
     721msgstr ""
     722
     723#: includes/class-recovery-export.php:299
     724msgid "Could not save the backup receipt."
     725msgstr ""
     726
     727#: includes/class-recovery-export.php:387
     728msgid "Could not save the recovery delivery or confirmation receipt. Retry before deleting media."
     729msgstr ""
     730
     731#: includes/class-recovery-export.php:518
     732msgid "Invalid recovery export."
     733msgstr ""
     734
     735#: includes/class-recovery-export.php:522
     736msgid "Recovery export expired or belongs to another user."
     737msgstr ""
     738
     739#: includes/class-recovery-export.php:538
     740msgid "The original private export storage is unavailable. Restore that storage before retrying cleanup or downloading."
     741msgstr ""
     742
     743#: includes/class-recovery-export.php:544
     744msgid "Export storage is inside a public web root. Download and cleanup were refused."
     745msgstr ""
     746
     747#: includes/class-recovery-export.php:558
     748msgid "Private temporary storage must resolve to a local non-symlink directory."
     749msgstr ""
     750
     751#: includes/class-recovery-export.php:567
     752msgid "Recovery export storage must be outside every configured public web root."
     753msgstr ""
     754
     755#: includes/class-recovery-export.php:571
     756msgid "Private temporary storage is unavailable."
     757msgstr ""
     758
     759#: includes/class-recovery-export.php:575
     760msgid "Recovery export storage must be private."
     761msgstr ""
     762
     763#: includes/class-recovery-export.php:587
     764msgid "You cannot export recovery data."
     765msgstr ""
     766
     767#: includes/class-recovery-export.php:631
     768msgid "This export is busy. Retry the download shortly."
     769msgstr ""
     770
     771#: includes/class-recovery-export.php:635
     772msgid "Recovery export is not ready."
     773msgstr ""
     774
     775#: includes/class-recovery-export.php:639
     776msgid "Recovery export is unavailable."
     777msgstr ""
     778
     779#: includes/class-recovery-format.php:262
     780msgid "This backup contains unsupported attachment fields or metadata. No recovery changes were made."
     781msgstr ""
     782
     783#: includes/class-recovery-import-plan.php:34
     784msgid "This backup belongs to a different site. Recovery is not a migration tool."
     785msgstr ""
     786
     787#: includes/class-recovery-import-plan.php:47
     788msgid "This older backup lacks original association and alt-text context. It can only repair existing attachment records."
     789msgstr ""
     790
     791#: includes/class-recovery-import-plan.php:50
     792msgid "The original ID is occupied, its file or metadata differs, or you cannot edit it. Review the existing media first."
     793msgstr ""
     794
     795#: includes/class-recovery-import-plan.php:53
     796msgid "The original parent or author is missing, changed, or cannot be edited by you. Recovery cannot detach or reassign this attachment."
     797msgstr ""
     798
     799#. translators: 1: attachment ID, 2: recovery conflict
     800#: includes/class-recovery-import-plan.php:56
     801#, php-format
     802msgid "Attachment #%1$d: %2$s"
     803msgstr ""
     804
     805#: includes/class-recovery-import-plan.php:88
     806msgid "Existing edit backups are not covered by this archive. Preserve and review them before recovery."
     807msgstr ""
     808
     809#. translators: %s: upload-relative file name
     810#: includes/class-recovery-import-plan.php:102
     811#, php-format
     812msgid "File %s is occupied or has an unsafe parent directory. Keep the current file and resolve the conflict before retrying."
     813msgstr ""
     814
     815#. translators: %d: attachment ID
     816#: includes/class-recovery-import-plan.php:127
     817#, php-format
     818msgid "Attachment #%d has different or incomplete quarantine recovery data. Review it in Quarantine before importing."
     819msgstr ""
     820
     821#: includes/class-recovery-import-store.php:149
     822msgid "Recovery is unavailable, expired, belongs to another user, or its progress could not be saved. Retry from Tools with an authorized account."
     823msgstr ""
     824
     825#: includes/class-recovery-import.php:44
     826msgid "Choose a valid recovery ZIP upload within the server upload limit. Filesystem paths and incomplete uploads are not accepted."
     827msgstr ""
     828
     829#: includes/class-recovery-import.php:48
     830msgid "Too many recovery uploads remain. Finish active recovery or allow expired previews to be cleaned up before uploading again."
     831msgstr ""
     832
     833#: includes/class-recovery-import.php:52
     834msgid "The uploaded ZIP could not be read safely. Upload it again."
     835msgstr ""
     836
     837#: includes/class-recovery-import.php:72
     838msgid "The private recovery upload could not be saved. No media was changed."
     839msgstr ""
     840
     841#: includes/class-recovery-import.php:113
     842#: includes/class-recovery-import.php:279
     843msgid "Recovery finished but its protection could not be released. Retry from Tools."
     844msgstr ""
     845
     846#: includes/class-recovery-import.php:130
     847msgid "Finish verifying this ZIP before previewing recovery."
     848msgstr ""
     849
     850#: includes/class-recovery-import.php:150
     851msgid "Review a verified preview and explicitly confirm that this is your trusted backup."
     852msgstr ""
     853
     854#: includes/class-recovery-import.php:155
     855msgid "Recovery conditions changed or conflicts remain. Refresh the preview, resolve conflicts and confirm again."
     856msgstr ""
     857
     858#: includes/class-recovery-import.php:159
     859msgid "Finish the active recovery job before confirming another backup."
     860msgstr ""
     861
     862#: includes/class-recovery-import.php:162
     863msgid "Could not reserve recovery. Retry confirmation."
     864msgstr ""
     865
     866#: includes/class-recovery-import.php:193
     867msgid "Recovery ownership changed. Progress was retained for review."
     868msgstr ""
     869
     870#: includes/class-recovery-import.php:204
     871msgid "The backup site identity no longer matches. Recovery was paused."
     872msgstr ""
     873
     874#: includes/class-recovery-import.php:243
     875msgid "Recovery manifest is incomplete. All data was retained."
     876msgstr ""
     877
     878#: includes/class-recovery-import.php:270
     879msgid "Recovery files are available but quarantine state still needs review. Retry to finish."
     880msgstr ""
     881
     882#: includes/class-recovery-import.php:311
     883msgid "A recovered file failed its final identity check. Progress was retained; retry recovery."
     884msgstr ""
     885
     886#: includes/class-recovery-payload.php:201
     887msgid "A recovery file is changed, occupied, unsafe, or could not be copied or cleaned up. All recovery progress was retained. Resolve the conflict and retry."
     888msgstr ""
     889
     890#: includes/class-request-watcher.php:349
    329891msgid "Browser evidence is busy; retry the scan."
    330892msgstr ""
    331893
    332 #: includes/class-request-watcher.php:348
     894#: includes/class-request-watcher.php:398
    333895msgid "Public browser media error report"
    334896msgstr ""
    335897
    336 #: includes/class-request-watcher.php:349
     898#: includes/class-request-watcher.php:399
    337899msgid "Could not preserve browser usage evidence."
    338900msgstr ""
    339901
    340 #: includes/class-scan-runner.php:88
     902#: includes/class-savings-report.php:47
     903msgid "A media operation is running. Refresh the report after it finishes; totals are currently unknown."
     904msgstr ""
     905
     906#: includes/class-savings-report.php:48
     907msgid "Refresh Tools to retry the report."
     908msgstr ""
     909
     910#: includes/class-savings-report.php:93
     911msgid "Tracking starts with this ledger. Earlier statuses do not prove deletion. Storage is the last identity-checked observation; external changes may remain unknown until reconciliation. Backups and physical disk allocation are not measured."
     912msgstr ""
     913
     914#: includes/class-savings-report.php:94
     915msgid "Retry incomplete operations in Quarantine. Database failures require checking writes; hourly maintenance observes up to 20 tracked payloads under the media lock. Large or unsafe payloads remain unknown. Unknown historical removals cannot be reconstructed."
     916msgstr ""
     917
     918#: includes/class-scan-runner.php:91
    341919msgid "The scan engine is not available."
    342920msgstr ""
    343921
    344 #: includes/class-scan-runner.php:96
     922#: includes/class-scan-runner.php:99
    345923msgid "The previous scan is still stopping. Try again in a few seconds."
    346924msgstr ""
    347925
    348 #: includes/class-scan-runner.php:338
    349 #: includes/scan/class-incremental.php:272
     926#: includes/class-scan-runner.php:372
     927#: includes/scan/class-incremental.php:426
    350928msgid "Shares its file with another media item"
    351929msgstr ""
    352930
    353 #: includes/rest/class-controller.php:163
     931#: includes/class-scan-runner.php:610
     932msgid "Finalizing shared-file evidence"
     933msgstr ""
     934
     935#: includes/class-server-watch.php:102
     936msgid "Same-origin missing uploads that reach WordPress; periodic GIF canary only."
     937msgstr ""
     938
     939#: includes/class-server-watch.php:106
     940msgid "Routing canary checks only. No known interruption in routing verification does not mean continuous traffic capture. Other extensions, CDN and browser caches, upstream requests and encoded paths can bypass observation. A total database outage cannot promise durable knowledge of interruptions."
     941msgstr ""
     942
     943#: includes/class-server-watch.php:117
     944msgid "This site uses a custom uploads or installation path. Ask your host to route missing uploads to the WordPress front controller and deny every quarantine path, then run the routing test."
     945msgstr ""
     946
     947#: includes/class-server-watch.php:122
     948msgid "Have your hosting administrator adapt these examples to existing rules, validate the configuration and rerun the routing test. Never overwrite a live configuration. A GIF canary does not verify every static/CDN rule."
     949msgstr ""
     950
     951#: includes/class-storage.php:22
     952msgid "Uploads storage is unavailable, not local, symlinked or not writable."
     953msgstr ""
     954
     955#. translators: %s: storage provider
     956#: includes/class-storage.php:32
     957#, php-format
     958msgid "%s requires audit-only mode; remote media mutations are unsupported."
     959msgstr ""
     960
     961#: includes/class-storage.php:39
     962msgid "An offloaded-media plugin is active. Cleanup is limited to read-only auditing."
     963msgstr ""
     964
     965#: includes/class-storage.php:44
     966msgid "Some stored content exceeded scan limits. Resolve these values and run a complete scan before cleaning up."
     967msgstr ""
     968
     969#: includes/class-storage.php:47
     970msgid "Some usage updates could not be saved. Run a complete scan before cleaning up."
     971msgstr ""
     972
     973#: includes/class-storage.php:52
     974msgid "Background usage indexing could not finish. Cleanup is paused. Check scheduled tasks or ask your hosting provider for help."
     975msgstr ""
     976
     977#: includes/class-storage.php:53
     978msgid "Usage updates are pending. Cleanup is paused until background indexing finishes."
     979msgstr ""
     980
     981#: includes/rest/class-controller.php:173
    354982msgid "Sorry, you are not allowed to manage media cleanup on this site."
    355983msgstr ""
    356984
    357 #: includes/rest/class-controller.php:292
     985#: includes/rest/class-controller.php:304
    358986msgid "This file no longer exists in the Media Library."
    359987msgstr ""
    360988
    361 #: includes/rest/class-controller.php:343
     989#: includes/rest/class-controller.php:355
    362990msgid "Choose at least one file to restore."
    363991msgstr ""
    364992
    365 #: includes/rest/class-controller.php:366
     993#: includes/rest/class-controller.php:378
    366994msgid "You are not allowed to delete this media item."
    367995msgstr ""
    368996
    369 #: includes/rest/class-controller.php:408
     997#: includes/rest/class-controller.php:420
    370998msgid "Only administrators can change these settings."
    371999msgstr ""
    3721000
    373 #: includes/rest/class-controller.php:465
     1001#: includes/rest/class-controller.php:477
    3741002msgid "Something went wrong on the server. Please try again."
    3751003msgstr ""
    3761004
    377 #: includes/scan/class-adapter-coverage.php:58
     1005#: includes/rest/class-recovery-controller.php:89
     1006msgid "You need media recovery permission and a current session. Reload this page and try again."
     1007msgstr ""
     1008
     1009#: includes/rest/class-recovery-controller.php:96
     1010msgid "The recovery request is invalid. Upload a ZIP through Tools and use its saved preview."
     1011msgstr ""
     1012
     1013#: includes/rest/class-tools-controller.php:63
     1014msgid "Select up to ten images for visual review."
     1015msgstr ""
     1016
     1017#: includes/rest/class-tools-controller.php:67
     1018msgid "Visual review requires attachment IDs."
     1019msgstr ""
     1020
     1021#: includes/rest/class-tools-controller.php:100
     1022msgid "Confirm that you saved the recovery backup."
     1023msgstr ""
     1024
     1025#: includes/scan/class-adapter-coverage.php:71
    3781026msgid "Elementor structured media"
    3791027msgstr ""
    3801028
    381 #: includes/scan/class-adapter-coverage.php:59
     1029#: includes/scan/class-adapter-coverage.php:72
    3821030msgid "ACF typed fields"
     1031msgstr ""
     1032
     1033#: includes/scan/class-adapter-coverage.php:73
     1034msgid "Database source limits"
    3831035msgstr ""
    3841036
    … …  
    3991051msgstr ""
    4001052
    401 #: includes/scan/class-database-scanner.php:339
     1053#: includes/scan/class-database-scanner.php:452
     1054#: includes/scan/class-theme-scanner.php:162
     1055msgid "Could not save the cleanup restriction for unread content. The scan was stopped."
     1056msgstr ""
     1057
     1058#: includes/scan/class-database-scanner.php:515
    4021059msgid "Site icon"
    4031060msgstr ""
    4041061
    405 #: includes/scan/class-database-scanner.php:345
     1062#: includes/scan/class-database-scanner.php:530
     1063#: includes/scan/class-database-scanner.php:535
    4061064msgid "Theme"
    4071065msgstr ""
    4081066
    409 #: includes/scan/class-database-scanner.php:393
     1067#: includes/scan/class-database-scanner.php:614
    4101068msgid "Divi / WPBakery"
    4111069msgstr ""
    4121070
    413 #: includes/scan/class-database-scanner.php:393
     1071#: includes/scan/class-database-scanner.php:614
    4141072msgid "Post content"
    4151073msgstr ""
    4161074
    417 #: includes/scan/class-database-scanner.php:394
     1075#: includes/scan/class-database-scanner.php:615
    4181076msgid "Post excerpt"
    4191077msgstr ""
    4201078
    421 #: includes/scan/class-database-scanner.php:398
     1079#: includes/scan/class-database-scanner.php:619
    4221080msgid "Term description"
    4231081msgstr ""
    4241082
    425 #: includes/scan/class-database-scanner.php:415
     1083#: includes/scan/class-database-scanner.php:659
    4261084msgid "Featured image"
    4271085msgstr ""
    4281086
    429 #: includes/scan/class-database-scanner.php:420
     1087#: includes/scan/class-database-scanner.php:664
    4301088msgid "WooCommerce · Product images"
    4311089msgstr ""
    … …  
    4391097msgstr ""
    4401098
    441 #: includes/scan/class-frontend-scanner.php:108
     1099#: includes/scan/class-frontend-scanner.php:116
    4421100msgid "Could not persist crawl inventory."
    4431101msgstr ""
    4441102
    445 #: includes/scan/class-frontend-scanner.php:201
     1103#: includes/scan/class-frontend-scanner.php:243
    4461104msgid "Anonymous public HTML"
    4471105msgstr ""
    4481106
    449 #: includes/scan/class-frontend-scanner.php:212
     1107#: includes/scan/class-frontend-scanner.php:260
     1108#: includes/scan/class-frontend-scanner.php:374
    4501109msgid "Could not persist crawl progress."
    4511110msgstr ""
    4521111
    453 #: includes/scan/class-theme-scanner.php:56
     1112#: includes/scan/class-frontend-scanner.php:357
     1113msgid "Anonymous linked stylesheet"
     1114msgstr ""
     1115
     1116#: includes/scan/class-theme-scanner.php:63
    4541117msgid "Active theme and parent theme files"
    4551118msgstr ""
    4561119
    4571120#: uninstall.php:31
    458 #: uninstall.php:61
     1121#: uninstall.php:75
    4591122msgid "Another Rapid Media Reclaim operation is running. Try again in a minute."
    4601123msgstr ""
    4611124
    462 #: uninstall.php:39
     1125#: uninstall.php:35
     1126msgid "Resume pending backup recovery in Tools before uninstalling. Its files, journals and protections were retained."
     1127msgstr ""
     1128
     1129#: uninstall.php:38
     1130msgid "Standalone file recovery is incomplete. Its manifests, payloads and guards were retained."
     1131msgstr ""
     1132
     1133#: uninstall.php:50
    4631134msgid "The database could not be read."
    4641135msgstr ""
    4651136
    466 #: uninstall.php:42
     1137#: uninstall.php:53
    4671138msgid "Some quarantined media could not be restored automatically."
    4681139msgstr ""
    4691140
    470 #: uninstall.php:45
     1141#: uninstall.php:56
     1142msgid "Complete or roll back pending reference merges before uninstalling."
     1143msgstr ""
     1144
     1145#: uninstall.php:59
    4711146msgid "The quarantine folder still contains files."
    4721147msgstr ""
    4731148
    4741149#: uninstall.php:85
     1150msgid "Private recovery archives could not be removed. Retry cleanup before uninstalling."
     1151msgstr ""
     1152
     1153#: uninstall.php:102
    4751154msgid "The quarantine folder could not be removed. Recovery data was retained."
    4761155msgstr ""
    4771156
    478 #: uninstall.php:129
     1157#: uninstall.php:144
     1158msgid "Network recovery inventory could not be verified. All remaining recovery data was retained."
     1159msgstr ""
     1160
     1161#: uninstall.php:172
    4791162msgid "Rapid Media Reclaim was not deleted, so your quarantined media stays recoverable."
    4801163msgstr ""
    4811164
    482 #: uninstall.php:129
     1165#: uninstall.php:172
    4831166msgid "Activate the plugin, restore or delete the items in its Quarantine tab, then delete the plugin again."
    4841167msgstr ""
    4851168
    486 #: uninstall.php:130
    487 #: uninstall.php:150
     1169#: uninstall.php:173
     1170#: uninstall.php:193
    4881171msgid "Plugin not deleted"
    4891172msgstr ""
    4901173
    491 #: assets/js/app.js:24
    492 #: assets/js/app.js:1453
    493 #: assets/js/app.js:1721
     1174#: assets/js/app.js:25
     1175#: assets/js/app.js:2106
     1176#: assets/js/app.js:2374
    4941177msgid "Unused"
    4951178msgstr ""
    4961179
    497 #: assets/js/app.js:25
    498 #: assets/js/app.js:1301
     1180#: assets/js/app.js:26
     1181#: assets/js/app.js:1235
     1182#: assets/js/app.js:1954
    4991183msgid "Quarantine"
    5001184msgstr ""
    5011185
    502 #: assets/js/app.js:26
    503 #: assets/js/app.js:1458
     1186#: assets/js/app.js:27
     1187#: assets/js/app.js:2111
    5041188msgid "In use"
    5051189msgstr ""
    5061190
    507 #: assets/js/app.js:28
     1191#: assets/js/app.js:29
    5081192msgid "All"
    5091193msgstr ""
    5101194
    511 #: assets/js/app.js:33
     1195#: assets/js/app.js:34
    5121196msgid "All types"
    5131197msgstr ""
    5141198
    515 #: assets/js/app.js:34
     1199#: assets/js/app.js:35
    5161200msgid "Images"
    5171201msgstr ""
    5181202
    519 #: assets/js/app.js:35
     1203#: assets/js/app.js:36
    5201204msgid "Video"
    5211205msgstr ""
    5221206
    523 #: assets/js/app.js:36
     1207#: assets/js/app.js:37
    5241208msgid "Audio"
    5251209msgstr ""
    5261210
    527 #: assets/js/app.js:37
     1211#: assets/js/app.js:38
    5281212msgid "Documents"
    5291213msgstr ""
    5301214
    531 #: assets/js/app.js:38
     1215#: assets/js/app.js:39
    5321216msgid "Other"
    5331217msgstr ""
    5341218
    535 #: assets/js/app.js:42
     1219#: assets/js/app.js:43
    5361220msgid "Largest first"
    5371221msgstr ""
    5381222
    539 #: assets/js/app.js:43
     1223#: assets/js/app.js:44
    5401224msgid "Newest first"
    5411225msgstr ""
    5421226
    543 #: assets/js/app.js:44
     1227#: assets/js/app.js:45
    5441228msgid "Oldest first"
    5451229msgstr ""
    5461230
    547 #: assets/js/app.js:45
     1231#: assets/js/app.js:46
    5481232msgid "Name (A–Z)"
    5491233msgstr ""
    5501234
    551 #: assets/js/app.js:49
     1235#: assets/js/app.js:50
    5521236msgid "High confidence"
    5531237msgstr ""
    5541238
    555 #: assets/js/app.js:50
     1239#: assets/js/app.js:51
    5561240msgid "Medium confidence"
    5571241msgstr ""
    5581242
    559 #: assets/js/app.js:51
     1243#: assets/js/app.js:52
    5601244msgid "Low confidence"
    5611245msgstr ""
    5621246
    563 #: assets/js/app.js:55
     1247#: assets/js/app.js:56
    5641248msgid "Post and page content"
    5651249msgstr ""
    5661250
    567 #: assets/js/app.js:56
     1251#: assets/js/app.js:57
    5681252msgid "Excerpts"
    5691253msgstr ""
    5701254
    571 #: assets/js/app.js:57
     1255#: assets/js/app.js:58
    5721256msgid "Featured images"
    5731257msgstr ""
    5741258
    575 #: assets/js/app.js:58
     1259#: assets/js/app.js:59
    5761260msgid "Custom fields"
    5771261msgstr ""
    5781262
    579 #: assets/js/app.js:59
     1263#: assets/js/app.js:60
    5801264msgid "Page builders"
    5811265msgstr ""
    5821266
    583 #: assets/js/app.js:60
     1267#: assets/js/app.js:61
    5841268msgid "ACF fields"
    5851269msgstr ""
    5861270
    587 #: assets/js/app.js:61
     1271#: assets/js/app.js:62
    5881272msgid "WooCommerce"
    5891273msgstr ""
    5901274
    591 #: assets/js/app.js:62
     1275#: assets/js/app.js:63
    5921276msgid "Site settings"
    5931277msgstr ""
    5941278
    595 #: assets/js/app.js:63
     1279#: assets/js/app.js:64
    5961280msgid "Customizer"
    5971281msgstr ""
    5981282
    599 #: assets/js/app.js:64
     1283#: assets/js/app.js:65
    6001284msgid "Widgets"
    6011285msgstr ""
    6021286
    603 #: assets/js/app.js:65
     1287#: assets/js/app.js:66
    6041288msgid "Categories and terms"
    6051289msgstr ""
    6061290
    607 #: assets/js/app.js:66
     1291#: assets/js/app.js:67
    6081292msgid "User profiles"
    6091293msgstr ""
    6101294
    611 #: assets/js/app.js:67
     1295#: assets/js/app.js:68
    6121296msgid "Theme files"
    6131297msgstr ""
    6141298
    615 #: assets/js/app.js:68
     1299#: assets/js/app.js:69
    6161300msgid "Public HTML crawl"
    6171301msgstr ""
    6181302
    619 #: assets/js/app.js:69
     1303#: assets/js/app.js:70
    6201304msgid "Browser error report"
    6211305msgstr ""
    6221306
    623 #: assets/js/app.js:71
     1307#: assets/js/app.js:72
    6241308msgid "Shared file (translations and copies)"
    6251309msgstr ""
    6261310
    627 #: assets/js/app.js:88
     1311#: assets/js/app.js:89
    6281312msgid "Matched by ID"
    6291313msgstr ""
    6301314
    631 #: assets/js/app.js:89
     1315#: assets/js/app.js:90
    6321316msgid "Matched by URL"
    6331317msgstr ""
    6341318
    635 #: assets/js/app.js:90
     1319#: assets/js/app.js:91
    6361320msgid "Matched by file name"
    6371321msgstr ""
    6381322
    639 #: assets/js/app.js:94
     1323#: assets/js/app.js:95
    6401324msgid "Draft"
    6411325msgstr ""
    6421326
    643 #: assets/js/app.js:95
     1327#: assets/js/app.js:96
    6441328msgid "Pending review"
    6451329msgstr ""
    6461330
    647 #: assets/js/app.js:96
     1331#: assets/js/app.js:97
    6481332msgid "Private"
    6491333msgstr ""
    6501334
    651 #: assets/js/app.js:97
     1335#: assets/js/app.js:98
    6521336msgid "Scheduled"
    6531337msgstr ""
    6541338
    655 #: assets/js/app.js:98
     1339#: assets/js/app.js:99
    6561340msgid "In trash"
    6571341msgstr ""
    6581342
    659 #: assets/js/app.js:99
     1343#: assets/js/app.js:100
    6601344msgid "Auto draft"
    6611345msgstr ""
    6621346
    663 #: assets/js/app.js:100
     1347#: assets/js/app.js:101
    6641348msgid "Revision"
    6651349msgstr ""
    6661350
    667 #: assets/js/app.js:105
    668 #: assets/js/app.js:622
     1351#: assets/js/app.js:106
     1352#: assets/js/app.js:624
    6691353msgid "Move to quarantine"
    6701354msgstr ""
    6711355
    672 #: assets/js/app.js:111
     1356#: assets/js/app.js:112
     1357#: assets/js/app.js:1235
    6731358msgid "Restore"
    6741359msgstr ""
    6751360
    676 #: assets/js/app.js:117
     1361#: assets/js/app.js:118
    6771362msgid "Keep"
    6781363msgstr ""
    6791364
    680 #: assets/js/app.js:123
     1365#: assets/js/app.js:124
    6811366msgid "Unkeep"
    6821367msgstr ""
    6831368
    684 #: assets/js/app.js:129
    685 #: assets/js/app.js:668
     1369#: assets/js/app.js:130
     1370#: assets/js/app.js:667
    6861371msgid "Delete permanently"
    6871372msgstr ""
    6881373
    689 #: assets/js/app.js:339
    690 #: assets/js/app.js:1342
    691 #: assets/js/app.js:1952
    692 #: assets/js/app.js:2364
     1374#: assets/js/app.js:340
     1375#: assets/js/app.js:1995
     1376#: assets/js/app.js:2605
     1377#: assets/js/app.js:3030
    6931378msgid "Try again"
    6941379msgstr ""
    6951380
    6961381#. translators: 1: number selected, 2: total matching
    697 #: assets/js/app.js:511
     1382#: assets/js/app.js:512
    6981383#, js-format
    6991384msgid "Selected the first %1$s of %2$s files. Act on these, then select the rest."
    … …  
    7011386
    7021387#. translators: %s: number of files
    703 #: assets/js/app.js:573
    704 #: assets/js/app.js:2017
     1388#: assets/js/app.js:575
     1389#: assets/js/app.js:2670
    7051390#, js-format
    7061391msgid "%s file"
    … …  
    7101395
    7111396#. translators: 1: number of files, 2: size, e.g. "12 files (48.2 MB)"
    712 #: assets/js/app.js:576
     1397#: assets/js/app.js:578
    7131398#, js-format
    7141399msgid "%1$s file (%2$s)"
    … …  
    7171402msgstr[1] ""
    7181403
    719 #: assets/js/app.js:586
     1404#: assets/js/app.js:588
    7201405msgid "Files are moved out of the public uploads folder. Pages that still use them would show a missing image. Restore anytime from the Quarantine tab."
    7211406msgstr ""
    7221407
    723 #: assets/js/app.js:590
     1408#: assets/js/app.js:592
    7241409msgid "Nothing is deleted. Media Library entries stay in place."
    7251410msgstr ""
    7261411
    727 #: assets/js/app.js:591
     1412#: assets/js/app.js:593
    7281413msgid "One click restores every file and image size."
    7291414msgstr ""
    7301415
    7311416#. translators: %s: number of files
    732 #: assets/js/app.js:603
     1417#: assets/js/app.js:605
    7331418#, js-format
    7341419msgid "%s of these files has medium or low confidence. Open it to review the evidence if you are unsure."
    … …  
    7381423
    7391424#. translators: %s: "12 files (48.2 MB)"
    740 #: assets/js/app.js:618
     1425#: assets/js/app.js:620
    7411426#, js-format
    7421427msgid "Move %s to quarantine?"
    7431428msgstr ""
    7441429
    745 #: assets/js/app.js:632
     1430#: assets/js/app.js:634
    7461431msgid "The files are deleted from the server and their Media Library entries are removed. This can’t be undone."
    7471432msgstr ""
    7481433
     1434#: assets/js/app.js:635
     1435msgid "Routing verification may be incomplete, expired or browser-only. Quarantine age is separate from the verified window. No recognized requests does not prove that a file is unused. Saved-backup confirmation and all deletion checks still apply."
     1436msgstr ""
     1437
    7491438#. translators: 1: number of files, 2: number of days
    750 #: assets/js/app.js:646
     1439#: assets/js/app.js:649
    7511440#, js-format
    7521441msgid "%1$s of these files has been in quarantine for less than %2$s days. Waiting gives you time to notice anything that breaks."
    … …  
    7561445
    7571446#. translators: %s: number of files
    758 #: assets/js/app.js:659
    759 #, js-format
    760 msgid "Delete all %s anyway"
    761 msgstr ""
    762 
    763 #: assets/js/app.js:659
    764 msgid "Delete anyway"
    765 msgstr ""
    766 
    767 #. translators: %s: number of files
    768 #: assets/js/app.js:667
     1447#: assets/js/app.js:666
    7691448#, js-format
    7701449msgid "Delete %s ready file"
    … …  
    7741453
    7751454#. translators: %s: "5 files (12 MB)"
    776 #: assets/js/app.js:677
     1455#: assets/js/app.js:676
    7771456#, js-format
    7781457msgid "Delete %s permanently?"
    7791458msgstr ""
    7801459
    781 #: assets/js/app.js:682
     1460#: assets/js/app.js:681
    7821461msgid "I understand this can’t be undone"
    7831462msgstr ""
    7841463
    7851464#. translators: 1: "3 files couldn't be moved", 2: reason
    786 #: assets/js/app.js:773
     1465#: assets/js/app.js:769
    7871466#, js-format
    7881467msgid "%1$s: %2$s"
    … …  
    7901469
    7911470#. translators: 1: done, 2: total
    792 #: assets/js/app.js:816
     1471#: assets/js/app.js:812
    7931472#, js-format
    7941473msgid "Working… %1$s of %2$s files"
    … …  
    7961475
    7971476#. translators: %s: "12 files (48.2 MB)"
    798 #: assets/js/app.js:825
     1477#: assets/js/app.js:821
    7991478#, js-format
    8001479msgid "Moved %s to quarantine"
    8011480msgstr ""
    8021481
    803 #: assets/js/app.js:828
    804 #: assets/js/app.js:888
     1482#: assets/js/app.js:824
     1483#: assets/js/app.js:884
    8051484msgid "Undo"
    8061485msgstr ""
    8071486
    808 #: assets/js/app.js:836
     1487#: assets/js/app.js:832
    8091488msgid "Some files are shared with other media items, for example translations. They can only be quarantined together."
    8101489msgstr ""
    8111490
    812 #: assets/js/app.js:838
     1491#: assets/js/app.js:834
    8131492msgid "Move them together"
    8141493msgstr ""
    8151494
    816 #: assets/js/app.js:843
    817 #: assets/js/app.js:845
     1495#. translators: %s: number of files
     1496#: assets/js/app.js:839
     1497#: assets/js/app.js:841
    8181498#, js-format
    8191499msgid "%s file couldn’t be moved"
    … …  
    8231503
    8241504#. translators: %s: "3 files (12 MB)"
    825 #: assets/js/app.js:853
     1505#: assets/js/app.js:849
    8261506#, js-format
    8271507msgid "Restored %s"
    8281508msgstr ""
    8291509
    830 #: assets/js/app.js:858
     1510#. translators: %s: number of files
     1511#: assets/js/app.js:854
    8311512#, js-format
    8321513msgid "%s file couldn’t be restored"
    … …  
    8361517
    8371518#. translators: %s: "5 files (12 MB)"
    838 #: assets/js/app.js:867
     1519#: assets/js/app.js:863
    8391520#, js-format
    8401521msgid "Deleted %s permanently"
    8411522msgstr ""
    8421523
    843 #: assets/js/app.js:872
     1524#. translators: %s: number of files
     1525#: assets/js/app.js:868
    8441526#, js-format
    8451527msgid "%s file couldn’t be deleted"
    … …  
    8491531
    8501532#. translators: %s: number of files
    851 #: assets/js/app.js:886
     1533#: assets/js/app.js:882
    8521534#, js-format
    8531535msgid "Kept %s file. It won’t be listed as unused."
    … …  
    8571539
    8581540#. translators: %s: number of files
    859 #: assets/js/app.js:887
     1541#: assets/js/app.js:883
    8601542#, js-format
    8611543msgid "%s file is no longer kept."
    … …  
    8641546msgstr[1] ""
    8651547
    866 #: assets/js/app.js:891
     1548#. translators: %s: number of files
     1549#: assets/js/app.js:887
    8671550#, js-format
    8681551msgid "%s file couldn’t be updated"
    … …  
    8721555
    8731556#. translators: %s: number of files
    874 #: assets/js/app.js:922
     1557#: assets/js/app.js:935
    8751558#, js-format
    8761559msgid "Undone for %s file."
    … …  
    8801563
    8811564#. translators: %s: "12 files (48.2 MB)"
    882 #: assets/js/app.js:1025
     1565#: assets/js/app.js:1040
    8831566#, js-format
    8841567msgid "Scan complete. Found %s that look unused."
    8851568msgstr ""
    8861569
    887 #: assets/js/app.js:1028
     1570#: assets/js/app.js:1043
    8881571msgid "Scan complete. No unused media found."
    8891572msgstr ""
    8901573
    891 #: assets/js/app.js:1050
     1574#: assets/js/app.js:1065
    8921575msgid "Scan cancelled. Your previous results are unchanged."
    8931576msgstr ""
    8941577
    8951578#. translators: %s: seconds
    896 #: assets/js/app.js:1086
     1579#: assets/js/app.js:1101
    8971580#, js-format
    8981581msgid "Connection lost. Retrying in %s s…"
    8991582msgstr ""
    9001583
    901 #: assets/js/app.js:1101
     1584#: assets/js/app.js:1116
    9021585msgid "Summary"
    9031586msgstr ""
    9041587
    905 #: assets/js/app.js:1102
     1588#: assets/js/app.js:1117
    9061589msgid "Views"
    9071590msgstr ""
    9081591
    909 #: assets/js/app.js:1107
     1592#: assets/js/app.js:1122
    9101593msgid "Selection"
    9111594msgstr ""
    9121595
    913 #: assets/js/app.js:1112
     1596#: assets/js/app.js:1127
    9141597msgid "Free and open source"
    9151598msgstr ""
    9161599
    917 #: assets/js/app.js:1114
     1600#: assets/js/app.js:1129
    9181601msgid "Leave a review"
    9191602msgstr ""
    9201603
    921 #: assets/js/app.js:1159
     1604#: assets/js/app.js:1175
    9221605msgid "Scanning…"
    9231606msgstr ""
    9241607
    9251608#. translators: %s: relative time, e.g. "3 minutes ago"
    926 #: assets/js/app.js:1164
     1609#: assets/js/app.js:1180
    9271610#, js-format
    9281611msgid "Last scanned %s"
    9291612msgstr ""
    9301613
    931 #: assets/js/app.js:1176
     1614#: assets/js/app.js:1185
     1615msgid "Tools"
     1616msgstr ""
     1617
     1618#: assets/js/app.js:1193
    9321619msgid "Rescan"
    9331620msgstr ""
    9341621
    935 #: assets/js/app.js:1181
    936 #: assets/js/app.js:2726
     1622#: assets/js/app.js:1198
     1623#: assets/js/app.js:3402
    9371624msgid "Settings"
    9381625msgstr ""
    9391626
     1627#: assets/js/app.js:1226
     1628msgid "Loading storage and observation status…"
     1629msgstr ""
     1630
     1631#: assets/js/app.js:1228
     1632#: assets/js/app.js:1246
     1633msgid "Space saved report"
     1634msgstr ""
     1635
     1636#: assets/js/app.js:1234
     1637msgid "Operation history unavailable. Check database access."
     1638msgstr ""
     1639
     1640#: assets/js/app.js:1235
     1641msgid "Permanent removal"
     1642msgstr ""
     1643
     1644#: assets/js/app.js:1235
     1645msgid "Verified"
     1646msgstr ""
     1647
     1648#: assets/js/app.js:1235
     1649msgid "Failed"
     1650msgstr ""
     1651
     1652#: assets/js/app.js:1235
     1653msgid "Pending"
     1654msgstr ""
     1655
     1656#: assets/js/app.js:1235
     1657#: assets/js/app.js:1243
     1658#: assets/js/app.js:1248
     1659#: assets/js/app.js:1249
     1660#: assets/js/app.js:1256
     1661#: assets/js/app.js:1259
     1662msgid "Unknown"
     1663msgstr ""
     1664
     1665#: assets/js/app.js:1235
     1666msgid "Tracked"
     1667msgstr ""
     1668
     1669#: assets/js/app.js:1235
     1670msgid "Legacy"
     1671msgstr ""
     1672
     1673#: assets/js/app.js:1235
     1674msgid "Imported backup"
     1675msgstr ""
     1676
     1677#: assets/js/app.js:1236
     1678msgid "No tracked operations yet. Earlier activity is unknown."
     1679msgstr ""
     1680
     1681#: assets/js/app.js:1241
     1682msgid "Load operation history"
     1683msgstr ""
     1684
     1685#: assets/js/app.js:1245
     1686msgid "Estimated reclaimable"
     1687msgstr ""
     1688
     1689#: assets/js/app.js:1245
     1690msgid "Media Library quarantine storage"
     1691msgstr ""
     1692
     1693#: assets/js/app.js:1245
     1694msgid "Media Library verified removed"
     1695msgstr ""
     1696
     1697#: assets/js/app.js:1247
     1698msgid "Logical bytes only. Physical disk allocation: not measured. Estimated reclaimable bytes do not authorize deletion."
     1699msgstr ""
     1700
     1701#. translators: 1: tracking start UTC, 2: pending file operations, 3: unknown operations, 4: untracked active recovery records
     1702#: assets/js/app.js:1248
     1703#, js-format
     1704msgid "Tracking started: %1$s UTC. Pending: %2$s. Unknown operations: %3$s. Untracked active records: %4$s."
     1705msgstr ""
     1706
     1707#. translators: 1: inventory estimate observation UTC, 2: oldest storage observation UTC
     1708#: assets/js/app.js:1249
     1709#, js-format
     1710msgid "Inventory estimate observed: %1$s UTC. Oldest storage observation: %2$s UTC."
     1711msgstr ""
     1712
     1713#: assets/js/app.js:1251
     1714#: assets/js/app.js:1257
     1715msgid "Routing verification"
     1716msgstr ""
     1717
     1718#: assets/js/app.js:1254
     1719msgid "PHP routing checked"
     1720msgstr ""
     1721
     1722#: assets/js/app.js:1254
     1723msgid "Browser reports only"
     1724msgstr ""
     1725
     1726#: assets/js/app.js:1254
     1727msgid "Unavailable"
     1728msgstr ""
     1729
     1730#: assets/js/app.js:1258
     1731msgid "No known interruption in routing verification"
     1732msgstr ""
     1733
     1734#: assets/js/app.js:1258
     1735msgid "Routing verification incomplete, expired or paused"
     1736msgstr ""
     1737
     1738#. translators: 1: mode, 2: start date, 3: last success date, 4: expiry date, 5: interruptions
     1739#: assets/js/app.js:1259
     1740#, js-format
     1741msgid "Mode: %1$s. Window start: %2$s. Last successful check: %3$s. Expires: %4$s. Interruptions: %5$s."
     1742msgstr ""
     1743
     1744#. translators: 1: elapsed verification days, 2: required days
     1745#: assets/js/app.js:1260
     1746#, js-format
     1747msgid "Site routing period: %1$s of %2$s days. Each quarantined group also starts no earlier than its latest member."
     1748msgstr ""
     1749
     1750#. translators: %s: most recent interruption date
     1751#: assets/js/app.js:1261
     1752#, js-format
     1753msgid "Latest known interruption: %s. Any interruption restarts the period after a new successful routing check."
     1754msgstr ""
     1755
     1756#: assets/js/app.js:1267
     1757msgid "Routing status unavailable. Refresh Tools before relying on a previous check."
     1758msgstr ""
     1759
     1760#: assets/js/app.js:1271
     1761msgid "Reference job"
     1762msgstr ""
     1763
     1764#: assets/js/app.js:1279
     1765msgid "This audit selection is stale or unfinished. Run a fresh scan and uploads audit."
     1766msgstr ""
     1767
     1768#: assets/js/app.js:1280
     1769msgid "This saved row cannot be reviewed. Choose a supported image or PDF in a fresh audit."
     1770msgstr ""
     1771
     1772#: assets/js/app.js:1281
     1773msgid "The file changed, disappeared or exceeds the 16 MiB live-review limit. Start a fresh audit or review it manually."
     1774msgstr ""
     1775
     1776#: assets/js/app.js:1282
     1777msgid "Your server needs the PHP GD imaging extension for local visual search."
     1778msgstr ""
     1779
     1780#: assets/js/app.js:1283
     1781msgid "The media inventory could not be read. Check database access and retry this step."
     1782msgstr ""
     1783
     1784#: assets/js/app.js:1284
     1785msgid "Saved visual search data is unreadable. Start a new search; originals were not changed."
     1786msgstr ""
     1787
     1788#: assets/js/app.js:1285
     1789msgid "Visual results could not be read. Retry after checking database access."
     1790msgstr ""
     1791
     1792#: assets/js/app.js:1286
     1793msgid "Saved visual results are invalid. Start a new search; originals were not changed."
     1794msgstr ""
     1795
     1796#: assets/js/app.js:1287
     1797msgid "Uploads storage changed or this is an older audit. Start a new uploads audit; no files were changed."
     1798msgstr ""
     1799
     1800#: assets/js/app.js:1288
     1801msgid "Choose a valid category, alphanumeric extension and minimum byte count."
     1802msgstr ""
     1803
     1804#: assets/js/app.js:1289
     1805msgid "The audit is finishing a step. Retry cancellation shortly."
     1806msgstr ""
     1807
     1808#: assets/js/app.js:1290
     1809msgid "Cancellation could not be saved. Retry after checking database access."
     1810msgstr ""
     1811
     1812#: assets/js/app.js:1291
     1813msgid "Prepare duplicate quarantine and complete its new scan before continuing."
     1814msgstr ""
     1815
     1816#: assets/js/app.js:1292
     1817msgid "Wait for the current scan to finish, then prepare duplicate quarantine."
     1818msgstr ""
     1819
     1820#: assets/js/app.js:1293
     1821msgid "Usage evidence still references a duplicate. Review it and keep the file available."
     1822msgstr ""
     1823
     1824#: assets/js/app.js:1294
     1825msgid "Regenerate this reference job’s supported builder caches first. Unsupported builder caches keep quarantine blocked."
     1826msgstr ""
     1827
     1828#: assets/js/app.js:1295
     1829msgid "Generated cache files changed. Regenerate them, prepare duplicate quarantine again and complete a new scan."
     1830msgstr ""
     1831
     1832#: assets/js/app.js:1296
     1833msgid "Download and confirm a current duplicate backup before quarantine."
     1834msgstr ""
     1835
     1836#: assets/js/app.js:1297
     1837msgid "Image variants or edit backups could not be matched safely. Originals remain available for review."
     1838msgstr ""
     1839
     1840#: assets/js/app.js:1298
     1841msgid "Completion could not be saved. Refresh Quarantine and use reference rollback; recovery data was retained."
     1842msgstr ""
     1843
     1844#: assets/js/app.js:1299
     1845msgid "Recovery ownership changed. Review the quarantine records before restoring this reference job."
     1846msgstr ""
     1847
     1848#: assets/js/app.js:1300
     1849msgid "This duplicate group exceeds the current limit of 100 files or 64 MiB. Originals remain available."
     1850msgstr ""
     1851
     1852#: assets/js/app.js:1301
     1853msgid "Another reference recovery journal protects this media. Resolve that operation first."
     1854msgstr ""
     1855
     1856#: assets/js/app.js:1302
     1857msgid "A duplicate is kept, shared, already quarantined or unavailable. Review its recovery state first."
     1858msgstr ""
     1859
     1860#: assets/js/app.js:1303
     1861msgid "Storage or usage indexing needs review. Complete pending work before quarantine."
     1862msgstr ""
     1863
     1864#: assets/js/app.js:1304
     1865msgid "A source changed after this merge. Resolve its reference recovery job before quarantine."
     1866msgstr ""
     1867
     1868#: assets/js/app.js:1306
     1869msgid "The task could not finish. No media was deleted."
     1870msgstr ""
     1871
     1872#: assets/js/app.js:1320
     1873#: assets/js/app.js:1708
     1874msgid "Saved uploads audits"
     1875msgstr ""
     1876
     1877#: assets/js/app.js:1320
     1878msgid "Choose a saved uploads audit"
     1879msgstr ""
     1880
     1881#: assets/js/app.js:1327
     1882#: assets/js/app.js:1537
     1883msgid "Paused or running"
     1884msgstr ""
     1885
     1886#: assets/js/app.js:1327
     1887msgid "Walk finished"
     1888msgstr ""
     1889
     1890#: assets/js/app.js:1327
     1891#: assets/js/app.js:1537
     1892msgid "Cancelled"
     1893msgstr ""
     1894
     1895#: assets/js/app.js:1332
     1896msgid "Standalone recovery job"
     1897msgstr ""
     1898
     1899#: assets/js/app.js:1332
     1900msgid "Choose standalone recovery"
     1901msgstr ""
     1902
     1903#: assets/js/app.js:1335
     1904msgid "Backup preparation"
     1905msgstr ""
     1906
     1907#: assets/js/app.js:1335
     1908msgid "Backed up — originals still live"
     1909msgstr ""
     1910
     1911#: assets/js/app.js:1335
     1912msgid "Interrupted quarantine — review or restore"
     1913msgstr ""
     1914
     1915#: assets/js/app.js:1335
     1916#: assets/js/app.js:2114
     1917msgid "Quarantined"
     1918msgstr ""
     1919
     1920#: assets/js/app.js:1335
     1921msgid "Recovery needs retry"
     1922msgstr ""
     1923
     1924#: assets/js/app.js:1335
     1925msgid "Restored"
     1926msgstr ""
     1927
     1928#: assets/js/app.js:1335
     1929msgid "Authorized deletion needs retry"
     1930msgstr ""
     1931
     1932#: assets/js/app.js:1335
     1933msgid "Permanently deleted — ZIP required for recovery"
     1934msgstr ""
     1935
     1936#: assets/js/app.js:1335
     1937msgid "Discard needs retry"
     1938msgstr ""
     1939
     1940#: assets/js/app.js:1336
     1941msgid "Verified private recovery preview"
     1942msgstr ""
     1943
     1944#: assets/js/app.js:1346
     1945msgid "The review expired, content changed or a saved backup is missing. Download/confirm the backup and run fresh checks."
     1946msgstr ""
     1947
     1948#: assets/js/app.js:1347
     1949msgid "Enable request watching and automatic restore in Settings, then verify request routing before quarantine."
     1950msgstr ""
     1951
     1952#: assets/js/app.js:1348
     1953msgid "A current reference, possible owner, recorded request or storage restriction blocks quarantine. Keep this file."
     1954msgstr ""
     1955
     1956#: assets/js/app.js:1349
     1957msgid "Download and save this backup before confirming it."
     1958msgstr ""
     1959
     1960#: assets/js/app.js:1350
     1961msgid "A different file occupies the original path, or recovery bytes are missing. Nothing was overwritten. Keep both files and resolve the conflict before retrying."
     1962msgstr ""
     1963
     1964#: assets/js/app.js:1351
     1965msgid "The original changed during capture. The replacement and backup were retained. Restore or ask your administrator to resolve the conflict."
     1966msgstr ""
     1967
     1968#: assets/js/app.js:1352
     1969msgid "Verify this backup and explicitly trust its origin before restoring. Cross-site backups also need adoption confirmation."
     1970msgstr ""
     1971
     1972#: assets/js/app.js:1353
     1973msgid "The file or its attributes changed. Restore this preparation and create a fresh audit/backup."
     1974msgstr ""
     1975
     1976#: assets/js/app.js:1355
     1977msgid "Recovery records are retained. Refresh the list; restore or retry after resolving the problem."
     1978msgstr ""
     1979
     1980#: assets/js/app.js:1358
     1981msgid "Wait for the current standalone recovery operation."
     1982msgstr ""
     1983
     1984#: assets/js/app.js:1371
     1985msgid "Resume backup preparation"
     1986msgstr ""
     1987
     1988#: assets/js/app.js:1377
     1989msgid "Download standalone recovery ZIP"
     1990msgstr ""
     1991
     1992#: assets/js/app.js:1381
     1993msgid "I trust the source of this ZIP and reviewed every destination below."
     1994msgstr ""
     1995
     1996#: assets/js/app.js:1382
     1997msgid "I explicitly approve importing these paths from a different site."
     1998msgstr ""
     1999
     2000#: assets/js/app.js:1383
     2001msgid "Trust this backup"
     2002msgstr ""
     2003
     2004#: assets/js/app.js:1384
     2005msgid "Confirm backup trust and any cross-site adoption first."
     2006msgstr ""
     2007
     2008#: assets/js/app.js:1387
     2009msgid "Discard untrusted upload"
     2010msgstr ""
     2011
     2012#: assets/js/app.js:1388
     2013msgid "Discard this recovery upload?"
     2014msgstr ""
     2015
     2016#: assets/js/app.js:1388
     2017msgid "Only this untrusted upload and its private verified copies will be removed. Public files are untouched. Keep your original ZIP."
     2018msgstr ""
     2019
     2020#: assets/js/app.js:1388
     2021msgid "Discard upload"
     2022msgstr ""
     2023
     2024#: assets/js/app.js:1389
     2025msgid "Untrusted upload discarded. Public files were not changed."
     2026msgstr ""
     2027
     2028#: assets/js/app.js:1394
     2029msgid "I downloaded and saved this recovery ZIP outside this server."
     2030msgstr ""
     2031
     2032#: assets/js/app.js:1395
     2033msgid "Confirm saved standalone backup"
     2034msgstr ""
     2035
     2036#: assets/js/app.js:1396
     2037msgid "Save your backup and confirm it first."
     2038msgstr ""
     2039
     2040#: assets/js/app.js:1399
     2041msgid "Resume standalone checks"
     2042msgstr ""
     2043
     2044#: assets/js/app.js:1399
     2045msgid "Check before standalone quarantine"
     2046msgstr ""
     2047
     2048#. translators: %s: checked stored rows
     2049#: assets/js/app.js:1403
     2050#: assets/js/app.js:1426
     2051#, js-format
     2052msgid "%s stored rows checked. Closing pauses; resume this saved recovery job later."
     2053msgstr ""
     2054
     2055#: assets/js/app.js:1409
     2056msgid "I reviewed the public pages, relevant theme/plugin behavior and caches. These checks cannot prove the file is unused."
     2057msgstr ""
     2058
     2059#: assets/js/app.js:1410
     2060msgid "Quarantine this standalone file"
     2061msgstr ""
     2062
     2063#: assets/js/app.js:1411
     2064msgid "Review the public pages and caches first."
     2065msgstr ""
     2066
     2067#: assets/js/app.js:1412
     2068msgid "Quarantine this standalone file?"
     2069msgstr ""
     2070
     2071#: assets/js/app.js:1412
     2072msgid "Its public URL will become unavailable until restored. A saved ZIP, fresh checks, request watching and verified routing are required. Static/CDN/cache paths may bypass observation. No permanent deletion occurs."
     2073msgstr ""
     2074
     2075#: assets/js/app.js:1412
     2076msgid "Move file to quarantine"
     2077msgstr ""
     2078
     2079#: assets/js/app.js:1418
     2080msgid "Restore standalone files"
     2081msgstr ""
     2082
     2083#: assets/js/app.js:1421
     2084msgid "The routing-check window is complete. This does not prove continuous request capture or non-usage."
     2085msgstr ""
     2086
     2087#: assets/js/app.js:1421
     2088msgid "Permanent deletion is blocked until the routing-check window is complete, with at least 14 days and no recorded requests."
     2089msgstr ""
     2090
     2091#: assets/js/app.js:1422
     2092msgid "Run fresh checks before permanent deletion"
     2093msgstr ""
     2094
     2095#: assets/js/app.js:1430
     2096msgid "Permanently delete standalone quarantine copies"
     2097msgstr ""
     2098
     2099#: assets/js/app.js:1431
     2100msgid "Permanently delete this standalone file?"
     2101msgstr ""
     2102
     2103#: assets/js/app.js:1431
     2104msgid "Both server recovery copies will be deleted. Recovery will require your downloaded ZIP. Review public pages, dynamic uses and caches first; routing checks cannot prove non-usage. Any replacement at the original public path is kept."
     2105msgstr ""
     2106
     2107#: assets/js/app.js:1431
     2108msgid "Permanently delete copies"
     2109msgstr ""
     2110
     2111#: assets/js/app.js:1436
     2112msgid "Content changed during review. Restart checks."
     2113msgstr ""
     2114
     2115#: assets/js/app.js:1436
     2116msgid "A possible stored reference or owner blocks quarantine. Keep the file."
     2117msgstr ""
     2118
     2119#: assets/js/app.js:1436
     2120msgid "Some content could not be fully checked. Resolve the source limit before quarantine."
     2121msgstr ""
     2122
     2123#: assets/js/app.js:1437
     2124msgid "Permissions:"
     2125msgstr ""
     2126
     2127#: assets/js/app.js:1438
     2128msgid "Stored-source checks are current for five minutes. They establish eligibility for manual quarantine, not non-usage or purge permission."
     2129msgstr ""
     2130
     2131#: assets/js/app.js:1438
     2132msgid "Stored-source checks are pending."
     2133msgstr ""
     2134
     2135#: assets/js/app.js:1439
     2136msgid "A request was recorded. This path is protected from re-quarantine."
     2137msgstr ""
     2138
     2139#: assets/js/app.js:1440
     2140msgid "Deletion completed. Removed bytes are unknown because a verified receipt was interrupted."
     2141msgstr ""
     2142
     2143#. translators: %s: logical original bytes removed
     2144#: assets/js/app.js:1440
     2145#, js-format
     2146msgid "Verified removal: %s logical original bytes, counted once. Recovery ZIPs and physical allocation are excluded."
     2147msgstr ""
     2148
     2149#: assets/js/app.js:1443
     2150msgid "Standalone recovery ZIP"
     2151msgstr ""
     2152
     2153#: assets/js/app.js:1444
     2154msgid "Standalone file recovery"
     2155msgstr ""
     2156
     2157#: assets/js/app.js:1445
     2158msgid "Standalone files are separate from Media Library counts. Prepare a backup from an uploads-audit row, then select its recovery job here. Archives preserve ordinary file permissions and modification times; ownership, ACLs and directory attributes are not reconstructed. Permanent deletion needs a saved backup, fresh review, a completed routing-check window of at least 14 days and a separate confirmation. Quarantine retains recovery copies and does not free disk space."
     2159msgstr ""
     2160
     2161#: assets/js/app.js:1446
     2162msgid "Open standalone recovery"
     2163msgstr ""
     2164
     2165#: assets/js/app.js:1448
     2166msgid "Choose a standalone recovery ZIP first."
     2167msgstr ""
     2168
     2169#: assets/js/app.js:1453
     2170msgid "Upload standalone recovery ZIP"
     2171msgstr ""
     2172
     2173#: assets/js/app.js:1455
     2174msgid "Load older standalone recovery records"
     2175msgstr ""
     2176
     2177#: assets/js/app.js:1461
     2178msgid "Some recovery records could not be read. Keep all backups and ask your administrator to review storage; uninstall remains blocked for unresolved data."
     2179msgstr ""
     2180
     2181#: assets/js/app.js:1473
     2182msgid "Wait for the current live check to finish."
     2183msgstr ""
     2184
     2185#: assets/js/app.js:1479
     2186msgid "Possible current metadata owner found. Keep this file."
     2187msgstr ""
     2188
     2189#: assets/js/app.js:1480
     2190msgid "Possible stored reference found. Keep this file."
     2191msgstr ""
     2192
     2193#: assets/js/app.js:1481
     2194msgid "The live check is incomplete. No cleanup approval was issued."
     2195msgstr ""
     2196
     2197#: assets/js/app.js:1482
     2198msgid "No match in the checked stored sources. This does not establish that the file is unused."
     2199msgstr ""
     2200
     2201#. translators: %s: inspected database rows
     2202#: assets/js/app.js:1486
     2203#, js-format
     2204msgid "%s stored rows checked. Checks are bounded and are not an atomic snapshot. Theme/PHP code, custom tables, network options, caches and external usage may remain unchecked. No files were moved."
     2205msgstr ""
     2206
     2207#: assets/js/app.js:1488
     2208msgid "Additional matches were found; only the first 20 are shown."
     2209msgstr ""
     2210
     2211#: assets/js/app.js:1489
     2212msgid "Coverage limits:"
     2213msgstr ""
     2214
     2215#: assets/js/app.js:1490
     2216msgid "Storage or indexing restrictions also block cleanup."
     2217msgstr ""
     2218
     2219#: assets/js/app.js:1495
     2220msgid "Check current ownership and references"
     2221msgstr ""
     2222
     2223#: assets/js/app.js:1496
     2224msgid "Prepare standalone recovery backup"
     2225msgstr ""
     2226
     2227#: assets/js/app.js:1498
     2228msgid "Review required"
     2229msgstr ""
     2230
     2231#: assets/js/app.js:1499
     2232msgid "An unregistered size is still owned. Do not delete it based on its size name."
     2233msgstr ""
     2234
     2235#: assets/js/app.js:1504
     2236msgid "All categories"
     2237msgstr ""
     2238
     2239#: assets/js/app.js:1504
     2240msgid "Indexed original"
     2241msgstr ""
     2242
     2243#: assets/js/app.js:1504
     2244msgid "Indexed derivative"
     2245msgstr ""
     2246
     2247#: assets/js/app.js:1504
     2248msgid "Indexed shared path"
     2249msgstr ""
     2250
     2251#: assets/js/app.js:1504
     2252msgid "Possible old derivative — review"
     2253msgstr ""
     2254
     2255#: assets/js/app.js:1504
     2256msgid "No indexed owner — review"
     2257msgstr ""
     2258
     2259#: assets/js/app.js:1504
     2260msgid "Ownership unavailable"
     2261msgstr ""
     2262
     2263#: assets/js/app.js:1505
     2264msgid "Ownership category"
     2265msgstr ""
     2266
     2267#: assets/js/app.js:1506
     2268msgid "Extension, e.g. jpg"
     2269msgstr ""
     2270
     2271#: assets/js/app.js:1506
     2272msgid "File extension"
     2273msgstr ""
     2274
     2275#: assets/js/app.js:1507
     2276msgid "Minimum file bytes"
     2277msgstr ""
     2278
     2279#: assets/js/app.js:1509
     2280msgid "Download filtered audit CSV"
     2281msgstr ""
     2282
     2283#: assets/js/app.js:1519
     2284msgid "Ownership comes from the saved index generation, not a live usage check. No indexed owner does not mean unused. Each page examines at most 100 saved rows; filtered pages can be empty."
     2285msgstr ""
     2286
     2287#: assets/js/app.js:1519
     2288msgid "The index changed or was unavailable. These ownership hints are stale; start a new scan and audit before reviewing them."
     2289msgstr ""
     2290
     2291#: assets/js/app.js:1521
     2292msgid "No matching files in this page. Continue if more rows are available."
     2293msgstr ""
     2294
     2295#: assets/js/app.js:1525
     2296msgid "Apply audit filters"
     2297msgstr ""
     2298
     2299#: assets/js/app.js:1526
     2300msgid "Next audit page"
     2301msgstr ""
     2302
     2303#: assets/js/app.js:1527
     2304msgid "Uploads audit — review only"
     2305msgstr ""
     2306
     2307#: assets/js/app.js:1527
     2308msgid "This best-effort walk excludes known caches, backups, protected plugin downloads and symlinks. Files may change during the walk. Audit categories never authorize removal. Supported files can begin a separate backup and fresh-review workflow."
     2309msgstr ""
     2310
     2311#: assets/js/app.js:1527
     2312msgid "Minimum bytes"
     2313msgstr ""
     2314
     2315#: assets/js/app.js:1530
     2316#: assets/js/app.js:1707
     2317msgid "Saved visual searches"
     2318msgstr ""
     2319
     2320#: assets/js/app.js:1530
     2321msgid "Choose a visual search"
     2322msgstr ""
     2323
     2324#: assets/js/app.js:1537
     2325msgid "Finished"
     2326msgstr ""
     2327
     2328#: assets/js/app.js:1542
     2329msgid "Visual results view"
     2330msgstr ""
     2331
     2332#: assets/js/app.js:1542
     2333msgid "Review suggestions"
     2334msgstr ""
     2335
     2336#: assets/js/app.js:1542
     2337msgid "Skipped images"
     2338msgstr ""
     2339
     2340#. translators: 1: checked images, 2: skipped images, 3: suggestions
     2341#: assets/js/app.js:1552
     2342#, js-format
     2343msgid "%1$s images checked; %2$s skipped; %3$s suggestions saved."
     2344msgstr ""
     2345
     2346#: assets/js/app.js:1552
     2347msgid "Search finished within its criteria. Suggestions still need human review."
     2348msgstr ""
     2349
     2350#: assets/js/app.js:1552
     2351msgid "Coverage is partial: the search may be paused, cancelled, skipped images or reached a limit. Matching images may be missing."
     2352msgstr ""
     2353
     2354#: assets/js/app.js:1555
     2355msgid "This image could not be compared within the local permissions, format or resource limits."
     2356msgstr ""
     2357
     2358#. translators: %s: difference score out of 64
     2359#: assets/js/app.js:1557
     2360#, js-format
     2361msgid "Visual difference score: %s / 64. Lower scores suggest closer appearance, not identical files."
     2362msgstr ""
     2363
     2364#: assets/js/app.js:1559
     2365msgid "No results in this page. This does not establish that any media is unused."
     2366msgstr ""
     2367
     2368#: assets/js/app.js:1564
     2369msgid "Next visual results page"
     2370msgstr ""
     2371
     2372#: assets/js/app.js:1565
     2373msgid "Visually similar images — review only"
     2374msgstr ""
     2375
     2376#: assets/js/app.js:1565
     2377msgid "These are captured visual suggestions, not exact duplicates. Re-encoded or resized images can differ in quality and metadata. Media may change during or after the search. Review originals before acting; visual suggestions never authorize merging or deletion."
     2378msgstr ""
     2379
     2380#: assets/js/app.js:1570
     2381msgid "An audit is already running here. Wait, cancel it or close Tools to pause it."
     2382msgstr ""
     2383
     2384#. translators: 1: images checked, 2: signatures compared
     2385#: assets/js/app.js:1578
     2386#, js-format
     2387msgid "Local visual search: %1$s images checked; %2$s signatures compared. Closing pauses this task."
     2388msgstr ""
     2389
     2390#. translators: %s: processed file count
     2391#: assets/js/app.js:1578
     2392#, js-format
     2393msgid "Read-only discovery: %s files checked. Closing pauses this task."
     2394msgstr ""
     2395
     2396#: assets/js/app.js:1585
     2397msgid "Visual search saved. Review suggestions and coverage below."
     2398msgstr ""
     2399
     2400#. translators: 1: files, 2: skipped entries
     2401#: assets/js/app.js:1586
     2402#, js-format
     2403msgid "Audit saved: %1$s files; %2$s skipped entries. Results expire after 24 hours."
     2404msgstr ""
     2405
     2406#. translators: 1: processed files, 2: skipped entries
     2407#: assets/js/app.js:1589
     2408#, js-format
     2409msgid "Checked %1$s files; %2$s entries skipped. Results are for review only. Showing the first 100 rows."
     2410msgstr ""
     2411
     2412#: assets/js/app.js:1590
     2413msgid "Ownership review required"
     2414msgstr ""
     2415
     2416#. translators: %s: number of duplicate groups
     2417#: assets/js/app.js:1591
     2418#, js-format
     2419msgid "Exact duplicate groups found: %s. Shared attachment paths count as one file."
     2420msgstr ""
     2421
     2422#: assets/js/app.js:1594
     2423msgid "Find exact duplicates"
     2424msgstr ""
     2425
     2426#: assets/js/app.js:1595
     2427msgid "Find visually similar images"
     2428msgstr ""
     2429
     2430#: assets/js/app.js:1596
     2431msgid "Compare selected images"
     2432msgstr ""
     2433
     2434#: assets/js/app.js:1598
     2435msgid "Select up to ten images before opening Tools."
     2436msgstr ""
     2437
     2438#: assets/js/app.js:1600
     2439msgid "Visual signatures are suggestions only. They never authorize a merge."
     2440msgstr ""
     2441
     2442#: assets/js/app.js:1603
     2443msgid "Preview selected reference merge"
     2444msgstr ""
     2445
     2446#: assets/js/app.js:1605
     2447msgid "Select a canonical attachment and up to ten exact duplicates first."
     2448msgstr ""
     2449
     2450#: assets/js/app.js:1607
     2451msgid "Choose the attachment to keep"
     2452msgstr ""
     2453
     2454#: assets/js/app.js:1607
     2455msgid "This rewrites supported references only. Original attachments and files are retained. Unsupported sources block the operation; generated builder caches and retirement require separate review."
     2456msgstr ""
     2457
     2458#: assets/js/app.js:1607
     2459msgid "Build read-only preview"
     2460msgstr ""
     2461
     2462#. translators: 1: supported source writes, 2: unsupported references
     2463#: assets/js/app.js:1613
     2464#, js-format
     2465msgid "Preview: %1$s supported source writes, %2$s unsupported references. No files will be removed."
     2466msgstr ""
     2467
     2468#: assets/js/app.js:1614
     2469msgid "Before"
     2470msgstr ""
     2471
     2472#: assets/js/app.js:1614
     2473msgid "After"
     2474msgstr ""
     2475
     2476#: assets/js/app.js:1615
     2477msgid "The operation is blocked. Unsupported or missing writers must be resolved before any changes."
     2478msgstr ""
     2479
     2480#: assets/js/app.js:1616
     2481msgid "Apply these reference changes?"
     2482msgstr ""
     2483
     2484#: assets/js/app.js:1616
     2485msgid "A recovery journal retains the original source values. Later editor changes are preserved as conflicts during rollback. The original files stay in place."
     2486msgstr ""
     2487
     2488#: assets/js/app.js:1616
     2489msgid "I reviewed the canonical attachment and these source changes."
     2490msgstr ""
     2491
     2492#: assets/js/app.js:1616
     2493msgid "Apply reference changes"
     2494msgstr ""
     2495
     2496#. translators: 1: completed source writes, 2: total source writes
     2497#: assets/js/app.js:1620
     2498#, js-format
     2499msgid "Reference changes: %1$s of %2$s sources."
     2500msgstr ""
     2501
     2502#: assets/js/app.js:1621
     2503msgid "Reference job saved. Original files are retained. Roll back from Tools if needed; complete a fresh scan and cache review before considering retirement."
     2504msgstr ""
     2505
     2506#: assets/js/app.js:1623
     2507msgid "Roll back last reference merge"
     2508msgstr ""
     2509
     2510#: assets/js/app.js:1625
     2511msgid "There is no reference job to roll back."
     2512msgstr ""
     2513
     2514#: assets/js/app.js:1627
     2515msgid "Roll back reference changes?"
     2516msgstr ""
     2517
     2518#: assets/js/app.js:1627
     2519msgid "Only sources that still match the saved written values can be restored. Later editor changes will be preserved and reported as conflicts."
     2520msgstr ""
     2521
     2522#: assets/js/app.js:1627
     2523msgid "Roll back"
     2524msgstr ""
     2525
     2526#: assets/js/app.js:1630
     2527msgid "Reference rollback saved. Quarantined duplicates were restored first; later editor changes remain protected."
     2528msgstr ""
     2529
     2530#: assets/js/app.js:1635
     2531msgid "Regenerate merge caches"
     2532msgstr ""
     2533
     2534#: assets/js/app.js:1638
     2535#: assets/js/app.js:1651
     2536msgid "Select a completed reference job first."
     2537msgstr ""
     2538
     2539#. translators: 1: attempted posts, 2: affected posts
     2540#: assets/js/app.js:1644
     2541#, js-format
     2542msgid "Cache generation: %1$s of %2$s posts."
     2543msgstr ""
     2544
     2545#: assets/js/app.js:1646
     2546msgid "This reference job has no builder caches to regenerate. Original files remain protected."
     2547msgstr ""
     2548
     2549#: assets/js/app.js:1646
     2550msgid "Supported cache assets regenerated. Review the public pages and run a fresh scan. Original files remain protected. Duplicate quarantine requires a separate saved-backup confirmation."
     2551msgstr ""
     2552
     2553#: assets/js/app.js:1646
     2554msgid "Some caches need manual review. You can retry after resolving the builder or source issue. Reference changes and recovery journals are retained."
     2555msgstr ""
     2556
     2557#: assets/js/app.js:1654
     2558msgid "Prepare duplicate quarantine and rescan"
     2559msgstr ""
     2560
     2561#: assets/js/app.js:1657
     2562msgid "Preparing a fresh usage scan. No files are being moved."
     2563msgstr ""
     2564
     2565#. translators: %s: scan percentage
     2566#: assets/js/app.js:1663
     2567#, js-format
     2568msgid "Checking duplicate usage: %s%%."
     2569msgstr ""
     2570
     2571#: assets/js/app.js:1667
     2572msgid "Complete a fresh scan before backing up duplicates."
     2573msgstr ""
     2574
     2575#: assets/js/app.js:1669
     2576msgid "Fresh scan complete. Next use “Back up merged duplicates”, download the ZIP and review the published pages and relevant caches before confirming quarantine."
     2577msgstr ""
     2578
     2579#: assets/js/app.js:1671
     2580msgid "Back up merged duplicates"
     2581msgstr ""
     2582
     2583#. translators: 1: completed files, 2: total files
     2584#: assets/js/app.js:1676
     2585#, js-format
     2586msgid "Building duplicate backup: %1$s of %2$s files."
     2587msgstr ""
     2588
     2589#: assets/js/app.js:1686
     2590msgid "Quarantine merged duplicates?"
     2591msgstr ""
     2592
     2593#: assets/js/app.js:1686
     2594msgid "Only this job’s duplicate files will move to protected quarantine. The canonical media stays live. Rollback restores these files before restoring references. Permanent deletion remains blocked by the recovery journal."
     2595msgstr ""
     2596
     2597#: assets/js/app.js:1686
     2598msgid "Move duplicates to quarantine"
     2599msgstr ""
     2600
     2601#: assets/js/app.js:1689
     2602msgid "Duplicates moved to quarantine. Use reference rollback to restore files before restoring their references. No media was permanently deleted."
     2603msgstr ""
     2604
     2605#: assets/js/app.js:1689
     2606msgid "Quarantine needs recovery review. Files were restored where possible and the journal was retained. Use reference rollback to resolve the operation."
     2607msgstr ""
     2608
     2609#: assets/js/app.js:1695
     2610msgid "Confirm backup and quarantine duplicates"
     2611msgstr ""
     2612
     2613#: assets/js/app.js:1698
     2614msgid "Backup verified. Download and save it before confirming; an archive left on this server expires after 24 hours."
     2615msgstr ""
     2616
     2617#: assets/js/app.js:1699
     2618msgid "Download duplicate recovery ZIP"
     2619msgstr ""
     2620
     2621#: assets/js/app.js:1699
     2622#: assets/js/app.js:1739
     2623msgid "I downloaded and saved this recovery backup."
     2624msgstr ""
     2625
     2626#: assets/js/app.js:1699
     2627msgid "I reviewed the published pages and cleared relevant page and CDN caches."
     2628msgstr ""
     2629
     2630#: assets/js/app.js:1702
     2631msgid "Start a new uploads audit"
     2632msgstr ""
     2633
     2634#: assets/js/app.js:1703
     2635msgid "Resume or browse audit"
     2636msgstr ""
     2637
     2638#: assets/js/app.js:1704
     2639msgid "Audit stopped. Saved results remain available until expiry. No media files changed."
     2640msgstr ""
     2641
     2642#: assets/js/app.js:1704
     2643msgid "Cancel selected audit"
     2644msgstr ""
     2645
     2646#: assets/js/app.js:1705
     2647msgid "Resume or browse visual search"
     2648msgstr ""
     2649
     2650#: assets/js/app.js:1706
     2651msgid "Visual search stopped. Saved suggestions remain available until expiry. No media was changed."
     2652msgstr ""
     2653
     2654#: assets/js/app.js:1706
     2655msgid "Cancel selected visual search"
     2656msgstr ""
     2657
     2658#: assets/js/app.js:1709
     2659msgid "Only recent jobs are listed. Saved task tokens still work in WP-CLI until expiry."
     2660msgstr ""
     2661
     2662#: assets/js/app.js:1710
     2663msgid "Test request routing"
     2664msgstr ""
     2665
     2666#: assets/js/app.js:1711
     2667msgid "Testing one missing-upload route…"
     2668msgstr ""
     2669
     2670#: assets/js/app.js:1714
     2671msgid "Routing check succeeded. The verification period is separate from quarantine age."
     2672msgstr ""
     2673
     2674#: assets/js/app.js:1714
     2675msgid "Routing was not verified. Review the status and hosting examples."
     2676msgstr ""
     2677
     2678#: assets/js/app.js:1716
     2679msgid "Export selected quarantine"
     2680msgstr ""
     2681
     2682#: assets/js/app.js:1718
     2683msgid "Select between 1 and 100 quarantined media items, including their shared copies, before opening Tools."
     2684msgstr ""
     2685
     2686#. translators: 1: export phase, 2: completed files, 3: total files
     2687#: assets/js/app.js:1723
     2688#, js-format
     2689msgid "Recovery export: %1$s, %2$s of %3$s files. Closing pauses this task."
     2690msgstr ""
     2691
     2692#: assets/js/app.js:1728
     2693msgid "Archive checksums verified. Download it and confirm you have saved the backup. The private download expires in 24 hours."
     2694msgstr ""
     2695
     2696#: assets/js/app.js:1729
     2697msgid "Download recovery ZIP"
     2698msgstr ""
     2699
     2700#: assets/js/app.js:1734
     2701msgid "Saved backup confirmed. The minimum waiting period and all usage checks still apply."
     2702msgstr ""
     2703
     2704#: assets/js/app.js:1737
     2705msgid "Confirm saved backup"
     2706msgstr ""
     2707
     2708#: assets/js/app.js:1741
     2709msgid "Saved backup recovery"
     2710msgstr ""
     2711
     2712#: assets/js/app.js:1742
     2713msgid "Recovery ZIP"
     2714msgstr ""
     2715
     2716#: assets/js/app.js:1746
     2717msgid "Verifying files"
     2718msgstr ""
     2719
     2720#: assets/js/app.js:1747
     2721msgid "Recovering attachment records"
     2722msgstr ""
     2723
     2724#: assets/js/app.js:1748
     2725msgid "Saving recovery records"
     2726msgstr ""
     2727
     2728#: assets/js/app.js:1749
     2729msgid "Preparing verified files"
     2730msgstr ""
     2731
     2732#: assets/js/app.js:1750
     2733msgid "Restoring media"
     2734msgstr ""
     2735
     2736#: assets/js/app.js:1756
     2737msgid "Verification paused"
     2738msgstr ""
     2739
     2740#: assets/js/app.js:1756
     2741msgid "Ready to preview"
     2742msgstr ""
     2743
     2744#: assets/js/app.js:1756
     2745msgid "Recovery paused"
     2746msgstr ""
     2747
     2748#: assets/js/app.js:1756
     2749msgid "Recovery complete"
     2750msgstr ""
     2751
     2752#: assets/js/app.js:1756
     2753msgid "Manual review needed"
     2754msgstr ""
     2755
     2756#: assets/js/app.js:1756
     2757msgid "Unsupported backup"
     2758msgstr ""
     2759
     2760#: assets/js/app.js:1756
     2761msgid "Upload incomplete"
     2762msgstr ""
     2763
     2764#. translators: 1: saved recovery number, 2: status, 3: number of media items
     2765#: assets/js/app.js:1757
     2766#, js-format
     2767msgid "Backup %1$s · %2$s · %3$s items"
     2768msgstr ""
     2769
     2770#: assets/js/app.js:1757
     2771msgid "Review needed"
     2772msgstr ""
     2773
     2774#. translators: 1: recovery phase, 2: completed entries, 3: total entries
     2775#: assets/js/app.js:1763
     2776#, js-format
     2777msgid "%1$s: %2$s of %3$s. Closing pauses this task; resume here after reloading."
     2778msgstr ""
     2779
     2780#: assets/js/app.js:1769
     2781msgid "Recovery complete. Original IDs, file bytes and supported core fields were verified. Existing associations and alt text were preserved; recreated records use verified original contexts. Plugin-specific and taxonomy metadata are not restored. Run a fresh scan."
     2782msgstr ""
     2783
     2784#: assets/js/app.js:1773
     2785msgid "Recovery preparation needs manual review after an interruption. Your backup and existing media are preserved. Ask your site administrator to review this recovery before continuing."
     2786msgstr ""
     2787
     2788#. translators: %s: unexpected attachment ID
     2789#: assets/js/app.js:1774
     2790#, js-format
     2791msgid "An attachment ID was taken during recovery. Review attachment #%s with your site administrator. Files and recovery records were retained."
     2792msgstr ""
     2793
     2794#: assets/js/app.js:1777
     2795msgid "This upload cannot be restored. Upload a complete supported backup."
     2796msgstr ""
     2797
     2798#: assets/js/app.js:1779
     2799msgid "Will restore"
     2800msgstr ""
     2801
     2802#: assets/js/app.js:1779
     2803msgid "Identical file already present"
     2804msgstr ""
     2805
     2806#: assets/js/app.js:1779
     2807msgid "Conflict: current file will be kept"
     2808msgstr ""
     2809
     2810#: assets/js/app.js:1780
     2811msgid "Recreate the original attachment ID"
     2812msgstr ""
     2813
     2814#: assets/js/app.js:1780
     2815msgid "Repair matching existing attachment"
     2816msgstr ""
     2817
     2818#. translators: 1: image width, 2: image height, 3: number of image sizes
     2819#: assets/js/app.js:1780
     2820#, js-format
     2821msgid "Metadata: %1$s × %2$s; %3$s sizes."
     2822msgstr ""
     2823
     2824#. translators: %s: number of saved edit backups
     2825#: assets/js/app.js:1780
     2826#, js-format
     2827msgid "Saved edit backups: %s."
     2828msgstr ""
     2829
     2830#. translators: %s: shared file owner attachment ID
     2831#: assets/js/app.js:1780
     2832#, js-format
     2833msgid "Shared files with attachment #%s."
     2834msgstr ""
     2835
     2836#: assets/js/app.js:1782
     2837msgid "Read-only recovery preview"
     2838msgstr ""
     2839
     2840#: assets/js/app.js:1782
     2841msgid "Recovery covers file bytes, core file metadata and supported attachment fields. New backups also preserve original parent, author and alt text for recreated records. Existing records keep their current associations and alt text. Plugin-specific metadata and taxonomies are unsupported. This is not a full site backup."
     2842msgstr ""
     2843
     2844#: assets/js/app.js:1782
     2845msgid "Files and current destinations"
     2846msgstr ""
     2847
     2848#: assets/js/app.js:1783
     2849msgid "Resolve these conflicts, then refresh the preview. Current files and records are preserved."
     2850msgstr ""
     2851
     2852#: assets/js/app.js:1783
     2853msgid "Preview verified. Nothing has been restored yet. Review the files and attachment IDs before confirming."
     2854msgstr ""
     2855
     2856#: assets/js/app.js:1789
     2857msgid "Restore this trusted backup?"
     2858msgstr ""
     2859
     2860#: assets/js/app.js:1789
     2861msgid "Only restore a backup you created and trust. Checksums verify file consistency, not its creator. Existing files are never replaced. Recovery keeps the original attachment IDs and does not delete media."
     2862msgstr ""
     2863
     2864#: assets/js/app.js:1789
     2865msgid "This is a reinstall of the same site. Adopt the backup identity for this matching site address."
     2866msgstr ""
     2867
     2868#: assets/js/app.js:1789
     2869msgid "Files are prepared in protected Quarantine storage. Nginx needs the documented access rules from your host; the ZIP itself remains outside public web storage."
     2870msgstr ""
     2871
     2872#: assets/js/app.js:1789
     2873msgid "I reviewed this preview and confirm this is my trusted recovery backup."
     2874msgstr ""
     2875
     2876#: assets/js/app.js:1789
     2877msgid "Confirm and restore"
     2878msgstr ""
     2879
     2880#: assets/js/app.js:1791
     2881msgid "Confirm same-site backup identity adoption before restoring."
     2882msgstr ""
     2883
     2884#: assets/js/app.js:1797
     2885msgid "Review and confirm recovery"
     2886msgstr ""
     2887
     2888#: assets/js/app.js:1802
     2889msgid "Recovery paused. Resolve the problem and resume this saved backup."
     2890msgstr ""
     2891
     2892#: assets/js/app.js:1805
     2893msgid "Upload and verify ZIP"
     2894msgstr ""
     2895
     2896#: assets/js/app.js:1806
     2897msgid "Choose one recovery ZIP first."
     2898msgstr ""
     2899
     2900#: assets/js/app.js:1808
     2901msgid "Uploading to private recovery storage…"
     2902msgstr ""
     2903
     2904#: assets/js/app.js:1813
     2905msgid "Resume or refresh preview"
     2906msgstr ""
     2907
     2908#: assets/js/app.js:1815
     2909msgid "Upload a backup or choose a saved recovery first."
     2910msgstr ""
     2911
     2912#: assets/js/app.js:1818
     2913msgid "Recover from a backup ZIP"
     2914msgstr ""
     2915
     2916#: assets/js/app.js:1818
     2917msgid "Upload → verify → preview → confirm → restore. Idle previews expire after 24 hours. Confirmed recovery remains available after closing or reloading."
     2918msgstr ""
     2919
     2920#: assets/js/app.js:1821
     2921msgid "Media tools"
     2922msgstr ""
     2923
     2924#: assets/js/app.js:1821
     2925msgid "Discovery results never delete or merge files. Request routing verification covers one path; CDN and browser caches remain outside observation."
     2926msgstr ""
     2927
     2928#: assets/js/app.js:1821
     2929#: assets/js/app.js:2827
     2930msgid "Close"
     2931msgstr ""
     2932
     2933#: assets/js/app.js:1824
     2934msgid "Local storage available. Advanced mutation features remain subject to recovery checks."
     2935msgstr ""
     2936
     2937#: assets/js/app.js:1827
     2938msgid "Download operation CSV"
     2939msgstr ""
     2940
     2941#: assets/js/app.js:1830
     2942msgid "Server setup examples (for your hosting administrator)"
     2943msgstr ""
     2944
     2945#: assets/js/app.js:1833
     2946msgid "Download inventory CSV"
     2947msgstr ""
     2948
     2949#: assets/js/app.js:1873
     2950msgid "Audit-only mode: cleanup is disabled"
     2951msgstr ""
     2952
     2953#: assets/js/app.js:1874
     2954msgid "Show affected sources"
     2955msgstr ""
     2956
     2957#: assets/js/app.js:1875
     2958msgid "Post / page"
     2959msgstr ""
     2960
     2961#: assets/js/app.js:1875
     2962msgid "Term"
     2963msgstr ""
     2964
     2965#: assets/js/app.js:1875
     2966msgid "User"
     2967msgstr ""
     2968
     2969#: assets/js/app.js:1875
     2970msgid "Setting"
     2971msgstr ""
     2972
    9402973#. translators: %s: number of files
    941 #: assets/js/app.js:1233
     2974#: assets/js/app.js:1886
    9422975#, js-format
    9432976msgid "Deleting %s file was interrupted"
    … …  
    9462979msgstr[1] ""
    9472980
    948 #: assets/js/app.js:1234
    949 msgid "A permanent delete stopped before it finished. Retry to complete it; nothing else is affected."
    950 msgstr ""
    951 
    952 #: assets/js/app.js:1239
     2981#: assets/js/app.js:1887
     2982msgid "A previously authorized permanent deletion stopped before it finished. Routing verification may be incomplete or browser-only. Retry continues that authorization; it does not complete a verified window."
     2983msgstr ""
     2984
     2985#: assets/js/app.js:1892
    9532986msgid "Interrupted cleanup completed."
    9542987msgstr ""
    9552988
    956 #: assets/js/app.js:1243
     2989#: assets/js/app.js:1896
    9572990msgid "Retry"
    9582991msgstr ""
    9592992
    9602993#. translators: %s: number of records
    961 #: assets/js/app.js:1252
     2994#: assets/js/app.js:1905
    9622995#, js-format
    9632996msgid "%s quarantine record needs review"
    … …  
    9662999msgstr[1] ""
    9673000
    968 #: assets/js/app.js:1253
     3001#: assets/js/app.js:1906
    9693002msgid "These records no longer match a media item, and their files could not be verified. Nothing was deleted. Check your backups before acting on them."
    9703003msgstr ""
    9713004
    972 #: assets/js/app.js:1254
     3005#: assets/js/app.js:1907
    9733006msgid "Show record IDs"
    9743007msgstr ""
    9753008
    976 #: assets/js/app.js:1265
     3009#: assets/js/app.js:1918
    9773010msgid "Public page check was partial"
    9783011msgstr ""
    9793012
    980 #: assets/js/app.js:1265
     3013#: assets/js/app.js:1918
    9813014msgid "Public pages checked"
    9823015msgstr ""
    9833016
    984 #: assets/js/app.js:1266
     3017#: assets/js/app.js:1919
    9853018msgid "Pages that were not loaded were still covered by the database scan."
    9863019msgstr ""
    9873020
    988 #: assets/js/app.js:1267
     3021#: assets/js/app.js:1920
    9893022msgid "Adjust page limit"
    9903023msgstr ""
    9913024
    992 #: assets/js/app.js:1290
     3025#: assets/js/app.js:1943
    9933026msgid "Find unused media, with proof."
    9943027msgstr ""
    9953028
    996 #: assets/js/app.js:1294
     3029#: assets/js/app.js:1947
    9973030msgid "Rapid Media Reclaim checks everywhere WordPress can use a file and shows you the evidence before anything moves."
    9983031msgstr ""
    9993032
    1000 #: assets/js/app.js:1299
     3033#: assets/js/app.js:1952
    10013034msgid "Scan"
    10023035msgstr ""
    10033036
    1004 #: assets/js/app.js:1299
     3037#: assets/js/app.js:1952
    10053038msgid "Posts, page builders, custom fields, settings and theme files."
    10063039msgstr ""
    10073040
    1008 #: assets/js/app.js:1300
     3041#: assets/js/app.js:1953
    10093042msgid "Review evidence"
    10103043msgstr ""
    10113044
    1012 #: assets/js/app.js:1300
     3045#: assets/js/app.js:1953
    10133046msgid "See where each file is used, or why it looks unused."
    10143047msgstr ""
    10153048
    1016 #: assets/js/app.js:1301
     3049#: assets/js/app.js:1954
    10173050msgid "Unused files move to a safe folder. Nothing is deleted."
    10183051msgstr ""
    10193052
    1020 #: assets/js/app.js:1307
     3053#: assets/js/app.js:1960
    10213054msgid "Scan media library"
    10223055msgstr ""
    10233056
    10243057#. translators: %s: number of files
    1025 #: assets/js/app.js:1313
     3058#: assets/js/app.js:1966
    10263059#, js-format
    10273060msgid "Your library has %s file. Scanning is read-only."
    … …  
    10303063msgstr[1] ""
    10313064
    1032 #: assets/js/app.js:1339
     3065#: assets/js/app.js:1992
    10333066msgid "The scan stopped"
    10343067msgstr ""
    10353068
    1036 #: assets/js/app.js:1341
     3069#: assets/js/app.js:1994
    10373070msgid "Reload page"
    10383071msgstr ""
    10393072
    1040 #: assets/js/app.js:1344
     3073#: assets/js/app.js:1997
    10413074msgid "Something went wrong while scanning."
    10423075msgstr ""
    10433076
    1044 #: assets/js/app.js:1345
     3077#: assets/js/app.js:1998
    10453078msgid "Your previous results are unchanged."
    10463079msgstr ""
    10473080
    10483081#. translators: 1: step number, 2: number of steps, 3: what is being checked
    1049 #: assets/js/app.js:1361
     3082#: assets/js/app.js:2014
    10503083#, js-format
    10513084msgid "Step %1$s of %2$s · %3$s"
    10523085msgstr ""
    10533086
    1054 #: assets/js/app.js:1366
     3087#: assets/js/app.js:2019
    10553088msgid "Preparing…"
    10563089msgstr ""
    10573090
    1058 #: assets/js/app.js:1381
     3091#: assets/js/app.js:2034
    10593092msgid "Scanning your media library"
    10603093msgstr ""
    10613094
    1062 #: assets/js/app.js:1385
     3095#: assets/js/app.js:2038
    10633096msgid "Elapsed time"
    10643097msgstr ""
    10653098
    1066 #: assets/js/app.js:1389
     3099#: assets/js/app.js:2042
    10673100msgid "Cancelling…"
    10683101msgstr ""
    10693102
    1070 #: assets/js/app.js:1389
     3103#: assets/js/app.js:2042
    10713104#: assets/js/ui.js:201
    10723105msgid "Cancel"
    10733106msgstr ""
    10743107
    1075 #: assets/js/app.js:1399
     3108#: assets/js/app.js:2052
    10763109msgid "Scan progress"
    10773110msgstr ""
    10783111
    10793112#. translators: 1: items checked, 2: total items, 3: percent
    1080 #: assets/js/app.js:1412
     3113#: assets/js/app.js:2065
    10813114#, js-format
    10823115msgid "%1$s of %2$s items checked · %3$s%%"
    10833116msgstr ""
    10843117
    1085 #: assets/js/app.js:1420
     3118#: assets/js/app.js:2073
    10863119msgid "Your current results stay available while the scan runs."
    10873120msgstr ""
    10883121
    1089 #: assets/js/app.js:1420
     3122#: assets/js/app.js:2073
    10903123msgid "Scanning only reads your site. You can leave this page; the scan continues in the background."
    10913124msgstr ""
    10923125
    10933126#. translators: %s: size
    1094 #: assets/js/app.js:1455
     3127#: assets/js/app.js:2108
    10953128#, js-format
    10963129msgid "%s reclaimable"
    10973130msgstr ""
    10983131
    1099 #: assets/js/app.js:1455
     3132#: assets/js/app.js:2108
    11003133msgid "Nothing to clean"
    11013134msgstr ""
    11023135
    1103 #: assets/js/app.js:1458
     3136#: assets/js/app.js:2111
    11043137msgid "With proof of use"
    11053138msgstr ""
    11063139
    1107 #: assets/js/app.js:1461
    1108 msgid "Quarantined"
    1109 msgstr ""
    1110 
    11113140#. translators: %s: size
    1112 #: assets/js/app.js:1463
     3141#: assets/js/app.js:2116
    11133142#, js-format
    11143143msgid "%s · restore anytime"
    11153144msgstr ""
    11163145
    1117 #: assets/js/app.js:1463
     3146#: assets/js/app.js:2116
    11183147msgid "Restore anytime"
    11193148msgstr ""
    11203149
    1121 #: assets/js/app.js:1465
     3150#: assets/js/app.js:2118
    11223151msgid "Protected from cleanup"
    11233152msgstr ""
    11243153
    1125 #: assets/js/app.js:1562
     3154#: assets/js/app.js:2215
    11263155msgid "Search by file name or title"
    11273156msgstr ""
    11283157
    1129 #: assets/js/app.js:1582
     3158#: assets/js/app.js:2235
    11303159msgid "File type"
    11313160msgstr ""
    11323161
    1133 #: assets/js/app.js:1587
     3162#: assets/js/app.js:2240
    11343163msgid "Confidence"
    11353164msgstr ""
    11363165
    1137 #: assets/js/app.js:1588
     3166#: assets/js/app.js:2241
    11383167msgid "Any confidence"
    11393168msgstr ""
    11403169
    1141 #: assets/js/app.js:1599
     3170#: assets/js/app.js:2252
    11423171msgid "What does confidence mean?"
    11433172msgstr ""
    11443173
    1145 #: assets/js/app.js:1600
     3174#: assets/js/app.js:2253
    11463175msgid "How sure we are that a file is unused. High: no trace found anywhere. Medium: only its file name was mentioned, or it was uploaded in the last day. Low: something still points to it by ID or URL in a place that doesn’t count as use, like a trashed post."
    11473176msgstr ""
    11483177
    1149 #: assets/js/app.js:1603
     3178#: assets/js/app.js:2256
    11503179msgid "Sort by"
    11513180msgstr ""
    11523181
    1153 #: assets/js/app.js:1612
     3182#: assets/js/app.js:2265
    11543183msgid "Layout"
    11553184msgstr ""
    11563185
    1157 #: assets/js/app.js:1613
     3186#: assets/js/app.js:2266
    11583187msgid "Grid view"
    11593188msgstr ""
    11603189
    1161 #: assets/js/app.js:1614
     3190#: assets/js/app.js:2267
    11623191msgid "List view"
    11633192msgstr ""
    11643193
    1165 #: assets/js/app.js:1633
     3194#: assets/js/app.js:2286
    11663195msgid "Search media"
    11673196msgstr ""
    11683197
    1169 #: assets/js/app.js:1704
    1170 msgid "Ready to delete"
     3198#: assets/js/app.js:2357
     3199msgid "Waiting period met"
    11713200msgstr ""
    11723201
    11733202#. translators: 1: current day, 2: total days, e.g. "Day 3 of 14"
    1174 #: assets/js/app.js:1707
     3203#: assets/js/app.js:2360
    11753204#, js-format
    11763205msgid "Day %1$s of %2$s"
    … …  
    11783207
    11793208#. translators: %s: number of places
    1180 #: assets/js/app.js:1712
     3209#: assets/js/app.js:2365
    11813210#, js-format
    11823211msgid "Used in %s place"
    … …  
    11863215
    11873216#. translators: %s: number of translated copies sharing the file
    1188 #: assets/js/app.js:1742
     3217#: assets/js/app.js:2395
    11893218#, js-format
    11903219msgid "Shared by %s translation"
    … …  
    11943223
    11953224#. translators: 1: pages loaded, 2: pages in the crawl
    1196 #: assets/js/app.js:1758
     3225#: assets/js/app.js:2411
    11973226#, js-format
    11983227msgid "%1$s of %2$s loaded"
    … …  
    12003229
    12013230#. translators: %s: number of pages
    1202 #: assets/js/app.js:1761
     3231#: assets/js/app.js:2414
    12033232#, js-format
    12043233msgid "%s couldn’t be loaded"
    … …  
    12083237
    12093238#. translators: %s: number of pages
    1210 #: assets/js/app.js:1765
     3239#: assets/js/app.js:2418
    12113240#, js-format
    12123241msgid "%s skipped (private or protected)"
    … …  
    12163245
    12173246#. translators: %s: number of pages
    1218 #: assets/js/app.js:1769
     3247#: assets/js/app.js:2422
    12193248#, js-format
    12203249msgid "%s not reached"
    … …  
    12243253
    12253254#. translators: %s: page limit
    1226 #: assets/js/app.js:1773
     3255#: assets/js/app.js:2426
    12273256#, js-format
    12283257msgid "site has more than the %s-page limit"
    … …  
    12303259
    12313260#. translators: %s: file name
    1232 #: assets/js/app.js:1788
    1233 #: assets/js/app.js:1809
     3261#: assets/js/app.js:2441
     3262#: assets/js/app.js:2462
    12343263#, js-format
    12353264msgid "Select %s"
    … …  
    12373266
    12383267#. translators: %s: file name
    1239 #: assets/js/app.js:1790
     3268#: assets/js/app.js:2443
    12403269#, js-format
    12413270msgid "View details for %s"
    12423271msgstr ""
    12433272
    1244 #: assets/js/app.js:1852
     3273#: assets/js/app.js:2505
    12453274msgid "Select"
    12463275msgstr ""
    12473276
    1248 #: assets/js/app.js:1853
     3277#: assets/js/app.js:2506
    12493278msgid "File"
    12503279msgstr ""
    12513280
    1252 #: assets/js/app.js:1854
    1253 #: assets/js/app.js:2620
     3281#: assets/js/app.js:2507
     3282#: assets/js/app.js:3294
    12543283msgid "Type"
    12553284msgstr ""
    12563285
    1257 #: assets/js/app.js:1855
     3286#: assets/js/app.js:2508
    12583287msgid "Size"
    12593288msgstr ""
    12603289
    1261 #: assets/js/app.js:1856
     3290#: assets/js/app.js:2509
    12623291msgid "Status"
    12633292msgstr ""
    12643293
    1265 #: assets/js/app.js:1857
    1266 #: assets/js/app.js:2621
     3294#: assets/js/app.js:2510
     3295#: assets/js/app.js:3295
    12673296msgid "Uploaded"
    12683297msgstr ""
    12693298
    1270 #: assets/js/app.js:1914
     3299#: assets/js/app.js:2567
    12713300msgid "No files match your filters"
    12723301msgstr ""
    12733302
    1274 #: assets/js/app.js:1915
     3303#: assets/js/app.js:2568
    12753304msgid "Try a different search or file type."
    12763305msgstr ""
    12773306
    1278 #: assets/js/app.js:1916
     3307#: assets/js/app.js:2569
    12793308msgid "Clear filters"
    12803309msgstr ""
    12813310
    1282 #: assets/js/app.js:1920
     3311#: assets/js/app.js:2573
    12833312msgid "No unused media found"
    12843313msgstr ""
    12853314
    1286 #: assets/js/app.js:1920
    1287 msgid "Your library is clean. Every file is used somewhere or marked Keep."
    1288 msgstr ""
    1289 
    1290 #: assets/js/app.js:1921
     3315#: assets/js/app.js:2573
     3316msgid "Other files may be in use, marked Keep, or in quarantine."
     3317msgstr ""
     3318
     3319#: assets/js/app.js:2574
    12913320msgid "Quarantine is empty"
    12923321msgstr ""
    12933322
    1294 #: assets/js/app.js:1921
     3323#: assets/js/app.js:2574
    12953324msgid "Files you move to quarantine wait here, ready to restore with one click."
    12963325msgstr ""
    12973326
    1298 #: assets/js/app.js:1922
     3327#: assets/js/app.js:2575
    12993328msgid "No files in use yet"
    13003329msgstr ""
    13013330
    1302 #: assets/js/app.js:1922
     3331#: assets/js/app.js:2575
    13033332msgid "Files that are used on your site appear here with proof of where."
    13043333msgstr ""
    13053334
    1306 #: assets/js/app.js:1923
     3335#: assets/js/app.js:2576
    13073336msgid "Nothing kept"
    13083337msgstr ""
    13093338
    1310 #: assets/js/app.js:1923
     3339#: assets/js/app.js:2576
    13113340msgid "Mark files as Keep to protect them from cleanup, for example images used in newsletters or apps."
    13123341msgstr ""
    13133342
    1314 #: assets/js/app.js:1924
     3343#: assets/js/app.js:2577
    13153344msgid "Your Media Library is empty"
    13163345msgstr ""
    13173346
    1318 #: assets/js/app.js:1924
     3347#: assets/js/app.js:2577
    13193348msgid "Upload files in Media → Add New and scan again."
    13203349msgstr ""
    13213350
    1322 #: assets/js/app.js:1950
     3351#: assets/js/app.js:2603
    13233352msgid "Couldn’t load files"
    13243353msgstr ""
    13253354
    1326 #: assets/js/app.js:1982
     3355#: assets/js/app.js:2635
    13273356msgid "Select all loaded files"
    13283357msgstr ""
    13293358
    13303359#. translators: %s: number of files
    1331 #: assets/js/app.js:1993
     3360#: assets/js/app.js:2646
    13323361#, js-format
    13333362msgid "%s matching file selected."
    … …  
    13363365msgstr[1] ""
    13373366
    1338 #: assets/js/app.js:1997
     3367#: assets/js/app.js:2650
    13393368msgid "Clear selection"
    13403369msgstr ""
    13413370
    1342 #: assets/js/app.js:2004
     3371#: assets/js/app.js:2657
    13433372msgid "Selecting…"
    13443373msgstr ""
    13453374
    13463375#. translators: %s: number of files
    1347 #: assets/js/app.js:2005
     3376#: assets/js/app.js:2658
    13483377#, js-format
    13493378msgid "Select all %s matching files"
    13503379msgstr ""
    13513380
    1352 #: assets/js/app.js:2011
     3381#: assets/js/app.js:2664
    13533382msgid "Select all"
    13543383msgstr ""
    13553384
    13563385#. translators: 1: shown, 2: total
    1357 #: assets/js/app.js:2016
     3386#: assets/js/app.js:2669
    13583387#, js-format
    13593388msgid "Showing %1$s of %2$s"
    13603389msgstr ""
    13613390
    1362 #: assets/js/app.js:2034
    1363 #: assets/js/app.js:2294
     3391#: assets/js/app.js:2687
     3392#: assets/js/app.js:2951
    13643393msgid "Loading…"
    13653394msgstr ""
    13663395
    1367 #: assets/js/app.js:2034
     3396#: assets/js/app.js:2687
    13683397msgid "Load more"
    13693398msgstr ""
    13703399
    13713400#. translators: 1: action, 2: count
    1372 #: assets/js/app.js:2084
     3401#: assets/js/app.js:2737
    13733402#, js-format
    13743403msgid "%1$s (%2$s)"
    … …  
    13763405
    13773406#. translators: %s: number of files
    1378 #: assets/js/app.js:2100
     3407#: assets/js/app.js:2753
    13793408#, js-format
    13803409msgid "%s selected"
    … …  
    13833412msgstr[1] ""
    13843413
    1385 #: assets/js/app.js:2103
     3414#: assets/js/app.js:2756
    13863415msgid "Clear"
    13873416msgstr ""
    13883417
    1389 #: assets/js/app.js:2103
     3418#: assets/js/app.js:2756
    13903419msgid "selection"
    13913420msgstr ""
    13923421
    1393 #: assets/js/app.js:2172
     3422#: assets/js/app.js:2825
    13943423msgid "Previous file"
    13953424msgstr ""
    13963425
    1397 #: assets/js/app.js:2173
     3426#: assets/js/app.js:2826
    13983427msgid "Next file"
    13993428msgstr ""
    14003429
    1401 #: assets/js/app.js:2174
    1402 msgid "Close"
    1403 msgstr ""
    1404 
    1405 #: assets/js/app.js:2174
     3430#: assets/js/app.js:2827
    14063431msgid "Close (Esc)"
    14073432msgstr ""
    14083433
    1409 #: assets/js/app.js:2294
     3434#: assets/js/app.js:2951
    14103435msgid "File not found"
    14113436msgstr ""
    14123437
    14133438#. translators: %s: date
    1414 #: assets/js/app.js:2411
     3439#: assets/js/app.js:3077
    14153440#, js-format
    14163441msgid "In quarantine since %s."
    14173442msgstr ""
    14183443
    1419 #: assets/js/app.js:2413
    1420 msgid "It can be deleted permanently whenever you’re ready."
     3444#: assets/js/app.js:3079
     3445msgid "The waiting period has passed. A saved recovery backup, usage checks and explicit confirmation are still required."
    14213446msgstr ""
    14223447
    14233448#. translators: 1: "Day 3 of 14", 2: date
    1424 #: assets/js/app.js:2414
    1425 #, js-format
    1426 msgid "%1$s. It can be deleted permanently from %2$s."
     3449#: assets/js/app.js:3080
     3450#, js-format
     3451msgid "%1$s. The waiting period ends on %2$s; all other safety checks still apply."
     3452msgstr ""
     3453
     3454#: assets/js/app.js:3083
     3455msgid "At the last check, the verified window was complete with no known interruption in routing verification. This does not prove disuse or grant deletion permission."
     3456msgstr ""
     3457
     3458#. translators: 1: elapsed routing-check days, 2: required days
     3459#: assets/js/app.js:3083
     3460#, js-format
     3461msgid "Verified routing period: %1$s of %2$s days. Incomplete, unknown or paused verification is separate from waiting age. Manual deletion still requires every existing check."
    14273462msgstr ""
    14283463
    14293464#. translators: %s: number of places
    1430 #: assets/js/app.js:2427
     3465#: assets/js/app.js:3094
    14313466#, js-format
    14323467msgid "The latest scan found this file in %s place. It shows as missing there until you restore it."
    … …  
    14353470msgstr[1] ""
    14363471
    1437 #: assets/js/app.js:2441
     3472#: assets/js/app.js:3108
    14383473msgid "You marked this file Keep. It is never listed as unused or moved by bulk actions."
    14393474msgstr ""
    14403475
    1441 #: assets/js/app.js:2451
     3476#: assets/js/app.js:3118
    14423477msgid "Why we think it’s unused"
    14433478msgstr ""
    14443479
    1445 #: assets/js/app.js:2453
     3480#: assets/js/app.js:3120
    14463481msgid "Evidence"
    14473482msgstr ""
    14483483
    14493484#. translators: %s: number of signals
    1450 #: assets/js/app.js:2475
     3485#: assets/js/app.js:3142
    14513486#, js-format
    14523487msgid "%s weak signal"
    … …  
    14553490msgstr[1] ""
    14563491
    1457 #: assets/js/app.js:2476
     3492#: assets/js/app.js:3143
    14583493msgid "These don’t count as use, but they lower our confidence. Check them before removing the file."
    14593494msgstr ""
    14603495
    1461 #: assets/js/app.js:2487
     3496#: assets/js/app.js:3154
    14623497msgid "The latest scan found no use of this file."
    14633498msgstr ""
    14643499
    1465 #: assets/js/app.js:2492
     3500#: assets/js/app.js:3160
     3501msgid "Some usage updates could not be saved. Run a complete scan before relying on this result or cleaning up."
     3502msgstr ""
     3503
     3504#: assets/js/app.js:3162
     3505msgid "Usage updates are waiting for background indexing. This result may be stale; cleanup is paused until indexing finishes."
     3506msgstr ""
     3507
     3508#: assets/js/app.js:3164
     3509msgid "Some stored content could not be checked within scan limits. This file may still be in use. Resolve the affected sources and rescan before cleaning up."
     3510msgstr ""
     3511
     3512#: assets/js/app.js:3166
    14663513msgid "No trace of this file was found anywhere we checked."
    14673514msgstr ""
    14683515
    1469 #: assets/js/app.js:2494
     3516#: assets/js/app.js:3168
    14703517msgid "Something still points to this file by ID or URL in a place that doesn’t count as use, such as a trashed post. Review the weak signals below."
    14713518msgstr ""
    14723519
    1473 #: assets/js/app.js:2496
     3520#: assets/js/app.js:3170
    14743521msgid "It was uploaded less than a day ago and may be about to be used."
    14753522msgstr ""
    14763523
    1477 #: assets/js/app.js:2498
     3524#: assets/js/app.js:3172
    14783525msgid "Only its file name was mentioned somewhere, which is not proof of use. Review the weak signals below."
    14793526msgstr ""
    14803527
    1481 #: assets/js/app.js:2512
     3528#: assets/js/app.js:3186
    14823529msgid "Details about what was checked appear after the next scan."
    14833530msgstr ""
    14843531
    1485 #: assets/js/app.js:2526
     3532#: assets/js/app.js:3200
     3533msgid "Incomplete · stored values exceeded scan limits"
     3534msgstr ""
     3535
     3536#: assets/js/app.js:3200
    14863537msgid "Checked · some values read as plain data"
    14873538msgstr ""
    14883539
    1489 #: assets/js/app.js:2526
     3540#: assets/js/app.js:3200
    14903541msgid "Checked"
    14913542msgstr ""
    14923543
    14933544#. translators: %s: number of items
    1494 #: assets/js/app.js:2527
     3545#: assets/js/app.js:3201
    14953546#, js-format
    14963547msgid "Not found in %s checked"
    … …  
    14993550msgstr[1] ""
    15003551
    1501 #: assets/js/app.js:2528
     3552#: assets/js/app.js:3202
    15023553msgid "Not found"
    15033554msgstr ""
    15043555
    15053556#. translators: %s: number
    1506 #: assets/js/app.js:2562
     3557#: assets/js/app.js:3236
    15073558#, js-format
    15083559msgid "Show %s more"
    15093560msgstr ""
    15103561
    1511 #: assets/js/app.js:2583
     3562#: assets/js/app.js:3257
    15123563msgid "Edit"
    15133564msgstr ""
    15143565
    1515 #: assets/js/app.js:2586
     3566#: assets/js/app.js:3260
    15163567msgid "View"
    15173568msgstr ""
    15183569
    1519 #: assets/js/app.js:2606
     3570#: assets/js/app.js:3280
    15203571msgid "Edit in Media Library"
    15213572msgstr ""
    15223573
    1523 #: assets/js/app.js:2609
     3574#: assets/js/app.js:3283
    15243575msgid "Open file"
    15253576msgstr ""
    15263577
    1527 #: assets/js/app.js:2614
     3578#: assets/js/app.js:3288
    15283579msgid "Details"
    15293580msgstr ""
    15303581
    1531 #: assets/js/app.js:2618
     3582#: assets/js/app.js:3292
    15323583msgid "File name"
    15333584msgstr ""
    15343585
    1535 #: assets/js/app.js:2619
     3586#: assets/js/app.js:3293
    15363587msgid "Title"
    15373588msgstr ""
    15383589
    1539 #: assets/js/app.js:2622
     3590#: assets/js/app.js:3296
    15403591msgid "Total size"
    15413592msgstr ""
    15423593
    1543 #: assets/js/app.js:2623
     3594#: assets/js/app.js:3297
    15443595msgid "ID"
    15453596msgstr ""
    15463597
    1547 #: assets/js/app.js:2624
     3598#: assets/js/app.js:3298
    15483599msgid "Translations"
    15493600msgstr ""
    15503601
    1551 #: assets/js/app.js:2624
     3602#: assets/js/app.js:3298
    15523603msgid "Actions apply to all of them."
    15533604msgstr ""
    15543605
    1555 #: assets/js/app.js:2647
     3606#: assets/js/app.js:3321
    15563607msgid "Original"
    15573608msgstr ""
    15583609
    1559 #: assets/js/app.js:2650
     3610#: assets/js/app.js:3324
    15603611msgid "Original (before scaling)"
    15613612msgstr ""
    15623613
    1563 #: assets/js/app.js:2653
     3614#: assets/js/app.js:3327
    15643615msgid "Edit backup"
    15653616msgstr ""
    15663617
    15673618#. translators: %s: number of files
    1568 #: assets/js/app.js:2660
     3619#: assets/js/app.js:3334
    15693620#, js-format
    15703621msgid "%s file on disk"
    … …  
    15743625
    15753626#. translators: %s: number of bytes
    1576 #: assets/js/app.js:2674
     3627#: assets/js/app.js:3348
    15773628#, js-format
    15783629msgid "%s byte"
    … …  
    15813632msgstr[1] ""
    15823633
    1583 #: assets/js/app.js:2703
     3634#: assets/js/app.js:3377
    15843635msgid "Count drafts as use"
    15853636msgstr ""
    15863637
    1587 #: assets/js/app.js:2703
     3638#: assets/js/app.js:3377
    15883639msgid "Files used only in drafts, private or scheduled posts are treated as in use."
    15893640msgstr ""
    15903641
    1591 #: assets/js/app.js:2704
     3642#: assets/js/app.js:3379
    15923643msgid "Count trashed posts as weak evidence"
    15933644msgstr ""
    15943645
    1595 #: assets/js/app.js:2704
     3646#: assets/js/app.js:3379
    15963647msgid "Files used only in trashed posts get lower confidence instead of high."
    15973648msgstr ""
    15983649
    1599 #: assets/js/app.js:2706
     3650#: assets/js/app.js:3381
    16003651msgid "Watch public browser media errors"
    16013652msgstr ""
    16023653
    1603 #: assets/js/app.js:2706
     3654#: assets/js/app.js:3381
    16043655msgid "Opt in to bounded anonymous same-origin error reports. No IP addresses or browsing history are stored. Static server/CDN requests are not intercepted; coverage is incomplete."
    16053656msgstr ""
    16063657
    1607 #: assets/js/app.js:2707
     3658#: assets/js/app.js:3382
    16083659msgid "Automatically restore reported files"
    16093660msgstr ""
    16103661
    1611 #: assets/js/app.js:2707
     3662#: assets/js/app.js:3382
    16123663msgid "Requires watching. Any visitor who requests a quarantined file’s address can bring it back, so quarantine stops being permanent for public files. Unattached media and media attached to published, non-password-protected content can be restored."
    16133664msgstr ""
    16143665
    1615 #: assets/js/app.js:2708
     3666#: assets/js/app.js:3383
    16163667msgid "Crawl public page HTML during scans"
    16173668msgstr ""
    16183669
    1619 #: assets/js/app.js:2708
     3670#: assets/js/app.js:3383
    16203671msgid "Anonymous same-origin public posts/pages only. No login, redirects or JavaScript. Failed and skipped pages remain coverage gaps."
    16213672msgstr ""
    16223673
    1623 #: assets/js/app.js:2716
     3674#: assets/js/app.js:3391
    16243675msgid "Quarantine period"
    16253676msgstr ""
    16263677
    1627 #: assets/js/app.js:2717
     3678#: assets/js/app.js:3392
    16283679msgid "days"
    16293680msgstr ""
    16303681
    1631 #: assets/js/app.js:2718
    1632 msgid "How long files wait in quarantine before they can be deleted permanently without an extra warning."
    1633 msgstr ""
    1634 
    1635 #: assets/js/app.js:2722
     3682#: assets/js/app.js:3393
     3683msgid "How long files wait in quarantine before they can be deleted permanently. A verified, saved recovery backup is also required."
     3684msgstr ""
     3685
     3686#: assets/js/app.js:3395
     3687msgid "Old or CDN uploads roots (one URL per line, up to 10)"
     3688msgstr ""
     3689
     3690#: assets/js/app.js:3398
    16363691msgid "Maximum public pages per scan (1–500)"
    16373692msgstr ""
    16383693
    1639 #: assets/js/app.js:2728
     3694#: assets/js/app.js:3404
    16403695msgid "Save settings"
    16413696msgstr ""
    16423697
    1643 #: assets/js/app.js:2734
    1644 msgid "Enter a number of days between 0 and 365."
    1645 msgstr ""
    1646 
    1647 #: assets/js/app.js:2737
     3698#: assets/js/app.js:3410
     3699msgid "Enter a number of days between 14 and 365."
     3700msgstr ""
     3701
     3702#: assets/js/app.js:3413
    16483703msgid "Enter a page limit between 1 and 500."
    16493704msgstr ""
    16503705
    1651 #: assets/js/app.js:2752
     3706#: assets/js/app.js:3428
    16523707msgid "Settings saved. Rescan to apply them to your results."
    16533708msgstr ""
    16543709
    1655 #: assets/js/app.js:2753
     3710#: assets/js/app.js:3429
    16563711msgid "Rescan now"
    16573712msgstr ""
    16583713
    1659 #: assets/js/app.js:2756
     3714#: assets/js/app.js:3432
    16603715msgid "Settings saved."
    16613716msgstr ""
    16623717
    1663 #: assets/js/app.js:2773
     3718#: assets/js/app.js:3449
    16643719msgid "Selection cleared."
    16653720msgstr ""
    … …  
    16893744msgstr ""
    16903745
    1691 #: assets/js/ui.js:271
     3746#: assets/js/ui.js:273
    16923747#: assets/js/util.js:302
    16933748msgid "Something went wrong. Please try again."
  • rapid-media-reclaim/trunk/rapid-media-reclaim.php

    r3794616 r3814937  
    33 * Plugin Name:       Rapid Media Reclaim
    44 * Description:       Review potentially unused media with usage evidence, reversible quarantine and one-click restore before reclaiming storage.
    5  * Version:           1.0.0
     5 * Version:           1.1.0
    66 * Author:            Nazim Husain
    77 * Author URI:        https://nazimansari.com
    … …  
    3030}
    3131
    32 define( 'SAFE_MEDIA_CLEANER_VERSION', '1.0.0' );
     32define( 'SAFE_MEDIA_CLEANER_VERSION', '1.1.0' );
    3333define( 'SAFE_MEDIA_CLEANER_FILE', __FILE__ );
    3434define( 'SAFE_MEDIA_CLEANER_PATH', plugin_dir_path( __FILE__ ) );
  • rapid-media-reclaim/trunk/readme.txt

    r3794616 r3814937  
    55Requires at least: 6.0
    66Tested up to: 7.1
    7 Stable tag: 1.0.0
     7Stable tag: 1.1.0
    88Requires PHP: 7.4
    99License: GPLv2 or later
    … …  
    25252. **Review the evidence.** Open any file to see where it is used, or why it looks unused.
    26263. **Quarantine.** Move unused files out of the public uploads folder. Pages keep working if the scan was right; if a file was still needed, restore it with one click.
    27 4. **Delete when you are sure.** After the quarantine period (14 days by default), delete quarantined files permanently.
     274. **Delete when you are sure.** After at least 14 days in quarantine, export and save a verified recovery backup before confirming permanent deletion. Requests or current usage block deletion.
    2828
    2929= Where it looks =
    … …  
    3131* Gutenberg blocks (image, gallery, cover, media & text, file, video, audio and more), reusable blocks, templates and template parts.
    3232* Classic editor content, `wp-image-` classes and gallery, video, audio and playlist shortcodes.
    33 * Page builders: Elementor, Bricks, Beaver Builder, Divi, WPBakery and Oxygen.
    34 * Advanced Custom Fields image, file and gallery fields, including repeaters, even when ACF is inactive.
     33* Page builders: Elementor, Bricks, Beaver Builder, Divi, WPBakery and Oxygen, including media in Divi and WPBakery shortcodes.
     34* Advanced Custom Fields image, file and gallery fields, including repeaters, groups and flexible content, even when ACF is inactive.
    3535* WooCommerce product galleries, variation images, category thumbnails and the placeholder image.
    3636* Site icon, custom logo, header and background images, widgets and other settings.
    3737* Term and user meta, and files referenced directly in your theme's code.
    38 * Every image size, scaled and rotated originals, edited copies, and WebP/AVIF versions. Files served from a CDN or staging domain are recognised too.
     38* Every image size, scaled and rotated originals, edited copies, and WebP/AVIF versions. Files served from a CDN or staging domain are recognised too, and you can list old or CDN uploads addresses in Settings.
    3939* Translations: media items that share one file (WPML, Polylang) count as used when any of them is.
    4040
    … …  
    5656* A warning when you delete a media item that is still in use.
    5757* "Keep" marks for files you never want listed as unused.
    58 * Scans run in small batches, continue in the background if you close the page, and keep your previous results visible until a rescan finishes.
     58* Scans run in small batches, continue in the background if you close the page, and keep your previous results visible until a rescan finishes. Content changes made outside the admin are re-indexed in a guarded background queue.
     59* Recovery ZIPs: export quarantined media as a private, checksummed ZIP and restore it later with its original attachment IDs. Existing files are never overwritten.
     60* A space saved report and operation history, with CSV exports of the media inventory, operations and audits.
     61* WP-CLI commands for administrators (`wp rapid-media-reclaim scan`, `status`, `quarantine`, `restore`, `export`, `report` and more), with `--dry-run`.
     62* Multisite: network activation and deactivation, and setup of new sites.
     63
     64= Tools (new in 1.1) =
     65Open Tools from the plugin screen. Each task runs in bounded steps, can be paused or cancelled, and saves its progress.
     66
     67* **Exact duplicates.** Find byte-identical copies, preview the reference changes, and point supported content (core blocks and classic content, Elementor, Beaver Builder, Bricks, ACF fields, Divi and WPBakery shortcodes) at the copy you keep. Every merge can be rolled back. Supported Elementor and Beaver Builder caches can be regenerated for the affected posts. Merged duplicates move to quarantine only after a fresh scan and a saved recovery backup. Unsupported sources block the merge.
     68* **Visually similar images.** A local, review-only search for images that look alike (requires the PHP GD extension). Suggestions never merge or delete anything.
     69* **Uploads audit.** A saved, review-only walk of the uploads folder that sorts files by ownership, with filters and CSV export. Supported images and PDFs that are not in the Media Library can be backed up, checked again, quarantined and restored; permanent deletion needs a saved backup, a completed routing-check period of at least 14 days and a separate confirmation.
     70* **Request routing check.** Test whether a missing-upload request reaches WordPress, and track a verified routing-check period for optional server request watching.
    5971
    6072= Watching, crawling and privacy =
    6173Both features are disabled by default. Enable them in Media > Rapid Media Reclaim > Settings.
    6274
    63 **Browser watching** reports up to 10 failed same-origin uploads per report, up to 60 reports per site and 10 per visitor per minute. Reports only count for media on published, non-password-protected content. For each reported attachment, only the time it was last reported is stored. No visitor IP, referrer, user agent, page URL or response body is stored; to apply the per-visitor limit, a salted hash of the visitor's IP is kept for one minute. Public tokens stay valid for up to two days, so cached pages keep working. Tokens are public and replayable, so reports are hints, not proof of human use. Reports never return media IDs, paths, quarantine contents or restore outcomes.
     75**Browser watching** reports up to 10 failed same-origin uploads per report, up to 60 reports per site and 10 per visitor per minute. Reports count for unattached media and media attached to published, non-password-protected content. For each reported attachment, only the time it was last reported is stored. No visitor IP, referrer, user agent, page URL or response body is stored; to apply the per-visitor limit, a salted hash of the visitor's IP is kept for one minute. Public tokens stay valid for up to two days, so cached pages keep working. Tokens are public and replayable, so reports are hints, not proof of human use. Reports never return media IDs, paths, quarantine contents or restore outcomes.
    6476
    6577**Automatic restore** is separately opt-in. When it is on, any visitor who requests the address of a quarantined public file can bring that file back, so quarantine is no longer permanent for public files. Unattached media is eligible, as is media attached to published content without a password. Media attached to private, draft or password-protected content is excluded.
    … …  
    6779Static requests handled by a web server or CDN never reach PHP. The observer covers only opted-in anonymous public HTML visits with JavaScript, common image, video and source errors, and retries once. It cannot cover CSS backgrounds, offline clients, cached pages without the script, all embeds, logged-in or private content, external CDNs or requests outside the browser. No server configuration is changed.
    6880
    69 **The optional crawler** fetches at most 100 public posts and pages by default (configurable from 1 to 500), without credentials or JavaScript. Requests use same-origin, published, non-password-protected permalinks, with no query strings, no redirects, five second timeouts and a 1 MiB response limit. It does not follow arbitrary links, submit forms, crawl archives or custom post types, or fetch external URLs. Failed, skipped, capped and pending pages are shown as coverage gaps. Loopback restrictions, plain permalinks and redirects may prevent coverage. Review evidence and back up before cleanup.
     81**Server request watching** can observe exact quarantined upload paths only when the missing request reaches WordPress. Tools includes a signed routing canary; it verifies one route for 24 hours, not all file types or your CDN. Recognized requests are counted and protect the media before any opt-in restore. Flag-only is the default. The plugin never changes server configuration. Static handlers, CDN/browser caches, encoded paths, rate limits and capped manifest lookups can bypass observation. A lack of observed requests is never proof of disuse.
     82
     83**The optional crawler** discovers conventional same-origin sitemaps and falls back to published public post types. It checks at most 100 public pages by default (configurable 1–500) and up to 20 linked same-origin stylesheets. Requests omit credentials and JavaScript, with no redirects, five-second timeouts and a 1 MiB response limit. Sitemap XML entities/DTDs are rejected. Failed, skipped, capped and pending work is shown as coverage gaps. JavaScript-only images, CSS imports and external stylesheets remain outside coverage.
    7084
    7185**Recovery records** remain until all files are restored or payload cleanup completes. Interrupted moves and restores can be retried using the recorded SHA-256 identity. Unsupported hard links fail closed. Uninstall retains recovery data and access guards if any restore is unresolved; resolve it before uninstalling.
    … …  
    8195
    8296= Will this delete my images? =
    83 Not without you asking twice. Scanning changes nothing. Quarantining moves files to a protected folder and can be undone. Only the "Delete permanently" action in the quarantine removes files.
     97Not without you asking twice. Scanning changes nothing. Quarantining moves files to a protected folder and can be undone. Only explicitly confirmed permanent-deletion actions remove files. Standalone file cleanup in Tools follows its own backup and fresh-review steps.
    8498
    8599= What happens to a page that still uses a quarantined file? =
    … …  
    87101
    88102= Do I still need a backup? =
    89 Keep a recent backup before cleanup. Quarantine and supplemental coverage reduce risk but do not replace backups or review.
     103Keep a recent database and uploads backup. Recovery exports are private, owner-bound ZIPs with checksums and expire after one day on the server. Save them before confirming backup retention. Exports currently support 64 MiB per file and 512 MiB per archive; larger files require manual recovery. Quarantine and supplemental coverage do not replace independent backups or review.
    90104
    91105= Does it work with my page builder? =
    92 Elementor, Bricks, Beaver Builder, Divi, WPBakery and Oxygen are supported, and any data that stores media as links or IDs in post meta or settings is checked as well. Unrecognized builder formats or inaccessible sources may be missed entirely; review evidence and keep uncertain files.
     106Readers cover bounded recognized Elementor, Bricks, Beaver Builder, Divi and WPBakery structures, with generic fallback for other stored links and IDs, including Oxygen. Typed duplicate writers cover a narrower set of controls. Rendering of licensed premium builders has not been qualified. Unrecognized builder formats or inaccessible sources may be missed entirely; review evidence and keep uncertain files.
    93107
    94108= Is it slow on large sites? =
    … …  
    110124No. Every feature is free.
    111125
     126== Screenshots ==
     127
     1281. Review potentially unused media with usage categories and confidence. Synthetic demo media shown.
     1292. Configure the quarantine period, old or CDN uploads addresses, draft handling and opt-in browser error watching, with coverage limits explained.
     1303. Review quarantined media before restoring it or considering permanent deletion. Synthetic demo media shown.
     131
    112132== Changelog ==
     133
     134= 1.1.0 =
     135* New: Tools panel with resumable, cancellable background tasks.
     136* New: Exact-duplicate finder. Preview, apply and roll back reference changes in core blocks and content, Elementor, Beaver Builder, Bricks, ACF and Divi/WPBakery shortcodes, regenerate supported Elementor and Beaver Builder caches, and quarantine merged duplicates after a fresh scan and saved backup.
     137* New: Review-only search for visually similar images (requires PHP GD).
     138* New: Saved uploads audits with ownership categories, filters and CSV export. Supported standalone images and PDFs outside the Media Library can be backed up, quarantined, restored and, after a verified waiting period, permanently deleted.
     139* New: Private, checksummed recovery ZIPs for quarantined media, with verified, trust-confirmed restore that keeps original attachment IDs and never overwrites files.
     140* New: Optional server request watching (flag-only by default) and a request routing check with a tracked verification period.
     141* New: Space saved report, operation history and CSV exports.
     142* New: WP-CLI commands for administrators, with `--dry-run`.
     143* New: Setting for old or CDN uploads addresses (up to 10).
     144* New: Multisite network activation, deactivation and new-site setup.
     145* Improved: Bounded background indexing; content changes made outside the admin are re-indexed in a guarded queue.
     146* Improved: Deeper evidence for Bricks, Beaver Builder, Divi/WPBakery shortcodes and ACF field structures, with clearer incomplete-scan warnings.
     147* Improved: The crawler reads same-origin sitemaps, falls back to all public post types and checks up to 20 linked same-origin stylesheets.
     148* Improved: Browser watching also counts reports for unattached media.
     149* Changed: Permanent deletion now requires at least 14 days in quarantine and a downloaded, confirmed recovery backup. Recorded requests or current usage block deletion.
     150* Fixed: Stronger recovery and concurrency safeguards. Interrupted moves and restores resume safely, replacement files are preserved, and uninstall keeps recovery data while anything is unresolved.
    113151
    114152= 1.0.0 =
    … …  
    121159* Optional public-page crawl and browser error watching, both off by default.
    122160* "Used in" column and delete warning in the Media Library.
     161
     162== Upgrade Notice ==
     163
     164= 1.1.0 =
     165Adds duplicate merging with rollback, visual similarity, uploads audits, recovery ZIPs and WP-CLI. Permanent deletion now needs 14+ days in quarantine and a saved recovery backup. Back up before upgrading.
  • rapid-media-reclaim/trunk/uninstall.php

    r3794616 r3814937  
    3232        }
    3333        try {
     34                if ( ! SafeMediaCleaner\Recovery_Import::uninstall_ready() ) {
     35                        return __( 'Resume pending backup recovery in Tools before uninstalling. Its files, journals and protections were retained.', 'rapid-media-reclaim' );
     36                }
     37                if ( ! SafeMediaCleaner\File_Recovery::uninstall_ready() ) {
     38                        return __( 'Standalone file recovery is incomplete. Its manifests, payloads and guards were retained.', 'rapid-media-reclaim' );
     39                }
    3440                wp_clear_scheduled_hook( 'safe_media_cleaner_scan_continue' );
     41                wp_clear_scheduled_hook( SafeMediaCleaner\Maintenance::HOOK );
     42                wp_clear_scheduled_hook( SafeMediaCleaner\Routing_Window::HOOK );
     43                wp_clear_scheduled_hook( SafeMediaCleaner\Scan_Runner::CLEANUP_HOOK );
     44                wp_clear_scheduled_hook( SafeMediaCleaner\Status_Index::HOOK );
     45                wp_clear_scheduled_hook( SafeMediaCleaner\Deferred_Index::HOOK );
    3546                SafeMediaCleaner\Scan_Runner::cancel();
    3647                $table  = SafeMediaCleaner\Installer::table( 'quarantine' );
    … …  
    4152                if ( $exists === $table && ! SafeMediaCleaner\Installer::restore_for_uninstall() ) {
    4253                        return __( 'Some quarantined media could not be restored automatically.', 'rapid-media-reclaim' );
     54                }
     55                if ( ! SafeMediaCleaner\Merge::uninstall_ready() ) {
     56                        return __( 'Complete or roll back pending reference merges before uninstalling.', 'rapid-media-reclaim' );
    4357                }
    4458                if ( ! SafeMediaCleaner\Installer::quarantine_directory_clear() ) {
    … …  
    6781                if ( '' !== $error ) {
    6882                        return $error;
     83                }
     84                if ( ! SafeMediaCleaner\Recovery_Export::remove_for_uninstall() ) {
     85                        return __( 'Private recovery archives could not be removed. Retry cleanup before uninstalling.', 'rapid-media-reclaim' );
    6986                }
    7087                $dir = get_option( 'safe_media_cleaner_quarantine_dir' );
    … …  
    95112                delete_metadata( 'post', 0, '_safe_media_cleaner_quarantine_id', '', true );
    96113                delete_metadata( 'post', 0, '_safe_media_cleaner_watch_seen', '', true );
     114                delete_metadata( 'post', 0, '_safe_media_cleaner_backup', '', true );
     115                delete_metadata( 'post', 0, '_safe_media_cleaner_merge_guard', '', true );
    97116                wp_clear_scheduled_hook( 'safe_media_cleaner_scan_continue' );
     117                wp_clear_scheduled_hook( SafeMediaCleaner\Maintenance::HOOK );
     118                wp_clear_scheduled_hook( SafeMediaCleaner\Routing_Window::HOOK );
     119                wp_clear_scheduled_hook( SafeMediaCleaner\Scan_Runner::CLEANUP_HOOK );
     120                wp_clear_scheduled_hook( SafeMediaCleaner\Status_Index::HOOK );
     121                wp_clear_scheduled_hook( SafeMediaCleaner\Deferred_Index::HOOK );
    98122                return '';
    99123        } finally {
    … …  
    102126}
    103127
    104 $safe_media_cleaner_sites = is_multisite() ? get_sites(
    105         array(
    106                 'fields' => 'ids',
    107                 'number' => 0,
    108         )
    109 ) : array( get_current_blog_id() );
     128/**
     129 * Enumerate network sites in constant-memory, fresh keyset pages.
     130 *
     131 * @return \Generator Site IDs, including archived sites with recovery data.
     132 */
     133function safe_media_cleaner_uninstall_sites(): \Generator {
     134        if ( ! is_multisite() ) {
     135                yield get_current_blog_id();
     136                return;
     137        }
     138        global $wpdb;
     139        $after = 0;
     140        do {
     141                // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Fresh bounded network recovery enumeration, not a cached site inventory.
     142                $ids = $wpdb->get_col( $wpdb->prepare( "SELECT blog_id FROM {$wpdb->blogs} WHERE blog_id>%d ORDER BY blog_id LIMIT 100", $after ) );
     143                if ( $wpdb->last_error || ! is_array( $ids ) ) {
     144                        wp_die( esc_html__( 'Network recovery inventory could not be verified. All remaining recovery data was retained.', 'rapid-media-reclaim' ) );
     145                }
     146                foreach ( $ids as $id ) {
     147                        $after = (int) $id;
     148                        yield $after;
     149                }
     150                $count = count( $ids );
     151        } while ( 100 === $count );
     152}
    110153
    111154// 1. Restore and verify every site before removing anything anywhere.
    112155$safe_media_cleaner_problems = array();
    113 foreach ( $safe_media_cleaner_sites as $safe_media_cleaner_site ) {
     156foreach ( safe_media_cleaner_uninstall_sites() as $safe_media_cleaner_site ) {
    114157        if ( is_multisite() ) {
    115158                switch_to_blog( (int) $safe_media_cleaner_site );
    … …  
    137180
    138181// 2. Every site is clear: remove the plugin's data.
    139 foreach ( $safe_media_cleaner_sites as $safe_media_cleaner_site ) {
     182foreach ( safe_media_cleaner_uninstall_sites() as $safe_media_cleaner_site ) {
    140183        if ( is_multisite() ) {
    141184                switch_to_blog( (int) $safe_media_cleaner_site );
Note: See TracChangeset for help on using the changeset viewer.