scan( $export_entries ); $translator = new Translator(); $rows = array(); $totals = array( 'translated' => 0, 'translated_pattern' => 0, 'partial' => 0, 'untranslated' => 0, ); $locked = 0; $snippet = array(); foreach ( $scan['strings'] as $s ) { $tr = $translator->translate( $s['source'] ); ++$totals[ $tr['status'] ]; $has_unknown = 'translated' !== $tr['status'] && 'translated_pattern' !== $tr['status']; if ( $has_unknown && 'audience' === $tr['risk'] ) { ++$locked; } $fns = $this->unknown_functions( $tr['tree'] ); $current = Rule::from_stored( Widget_Store::rule( $s['widget_id'] ) ); $cur_imp = ( Rule::STATE_OK === $current->state && is_array( $current->import ) ) ? $current->import : null; $changed = $cur_imp && ! empty( $cur_imp['edited'] ) && isset( $cur_imp['source_hash'] ) && hash( 'sha256', $s['source'] ) !== $cur_imp['source_hash']; foreach ( $fns as $fn ) { $snippet[ $fn ] = true; } $rows[] = array( 'row' => substr( hash( 'sha256', $s['ref'] ), 0, 16 ), 'widget_id' => $s['widget_id'], 'ref' => $s['ref'], 'location' => $s['location'], 'sidebar' => $s['sidebar'], 'title' => $s['title'], 'inactive' => $s['inactive'], 'orphan' => $s['orphan'], 'source' => $s['source'], 'source_hash' => hash( 'sha256', $s['source'] ), 'status' => $tr['status'], 'confidence' => self::confidence( $tr['status'] ), 'reasons' => $tr['reasons'], 'detail' => $tr['detail'], 'notes' => $tr['notes'], 'risk' => $tr['risk'], 'risk_terms' => $tr['risk_terms'], 'tree' => $tr['tree'], 'printed' => Printer::print_tree( $tr['tree'] ), 'summary' => Summarizer::summarize( $tr['tree'] ), 'when_unsure' => $has_unknown ? ( 'audience' === $tr['risk'] ? 'locked_hidden' : 'hidden_unless_show_when_unsure' ) : 'not_applicable', 'can_override' => $has_unknown && 'location' === $tr['risk'], 'snippet_fns' => $fns, 'change_flag' => $this->change_flag( $s['source'], $tr['status'], $scan['six_x_evidence'] ), // 8.9: "Source changed since import" on an edited rule; default Keep my edit. 'source_changed_edited' => (bool) $changed, ); } // R-1: export-file entries that match no widget, kept as explicit report // records with the original expression. They are never Apply rows: Apply // only walks $rows, and a later scan turns an entry into a normal row once // a widget with that ID exists. $unmatched = array(); foreach ( $scan['unmatched_entries'] as $u ) { $tr = $translator->translate( $u['source'] ); $unmatched[] = array( 'row' => substr( hash( 'sha256', 'unmatched:' . $u['widget_id'] ), 0, 16 ), 'widget_id' => $u['widget_id'], 'ref' => 'file:' . $u['widget_id'], 'source' => $u['source'], 'source_hash' => hash( 'sha256', $u['source'] ), 'status' => 'unmatched', 'reason' => 'widget_not_found', 'apply_eligible' => false, 'would_be' => $tr['status'], 'summary' => Summarizer::summarize( $tr['tree'] ), ); } $report = array( 'version' => GATEFORGE_VERSION, 'rows' => $rows, 'totals' => $totals, 'locked_hidden' => $locked, 'snippet_candidates' => array_keys( $snippet ), 'conflicts' => $scan['conflicts'], 'globals' => $this->map_globals( $scan['globals'] ), 'settings_6x' => null !== $scan['settings_6x'], 'block_attr_rules' => $scan['block_attr_rules'], 'unmatched_file_ids' => $scan['unmatched_file_ids'], 'unmatched' => $unmatched, 'file_rejected' => array_values( $file_rejected ), 'file_skipped' => $scan['file_skipped'], 'allowed_functions' => $scan['allowed_functions'], 'widget_content' => $scan['widget_content'], 'truncated' => $scan['truncated'], 'truncated_reason' => $scan['truncated_reason'], 'options_found' => $scan['options_found'], 'options_listed' => $scan['options_listed'], 'options_read' => $scan['options_read'], 'option_name_cap' => $scan['option_name_cap'], ); $report['token'] = self::token( $report ); if ( $store ) { $stored = $this->read_report(); $stored['dry_run'] = $report; $stored['token'] = $report['token']; $stored['created'] = time(); $stored['export_entries'] = is_array( $export_entries ) ? $export_entries : null; $stored['export_rejected'] = array_values( $file_rejected ); update_option( self::REPORT_OPTION, $stored, false ); } return $report; } /** * Bare Apply. The request carries only the report token and override row IDs (F6). * * @param string $token Report token from the dry run the admin saw. * @param array $overrides Row IDs to switch to "Show when unsure". * @param int $user_id Acting user (capability already verified by the caller). * @param array $retranslate Row IDs flagged source_changed_edited that the admin chose to re-translate. * @return array{ok:bool, error?:string, written?:int, skipped?:array, archive_added?:int} */ public function apply( $token, array $overrides, $user_id, array $retranslate = array() ) { if ( ! Legacy_Detector::allows( 'apply' ) ) { return array( 'ok' => false, 'error' => 'legacy_plugin_active', ); } $lock = $this->lock(); if ( ! $lock ) { return array( 'ok' => false, 'error' => 'busy', ); } try { $stored = $this->read_report(); if ( empty( $stored['token'] ) || ! is_string( $token ) || ! hash_equals( (string) $stored['token'], $token ) ) { return array( 'ok' => false, 'error' => 'unknown_token', ); } // Re-verify server-side: a fresh scan must give the same report. $entries = isset( $stored['export_entries'] ) && is_array( $stored['export_entries'] ) ? $stored['export_entries'] : null; $rejects = isset( $stored['export_rejected'] ) && is_array( $stored['export_rejected'] ) ? $stored['export_rejected'] : array(); $fresh = $this->dry_run( $entries, false, $rejects ); if ( ! hash_equals( $fresh['token'], $token ) ) { return array( 'ok' => false, 'error' => 'stale_report', ); } $by_row = array(); foreach ( $fresh['rows'] as $r ) { $by_row[ $r['row'] ] = $r; } $ov = array(); foreach ( $overrides as $id ) { $id = is_string( $id ) ? $id : ''; if ( ! isset( $by_row[ $id ] ) ) { return array( 'ok' => false, 'error' => 'unknown_override_row', ); } if ( 'location' !== $by_row[ $id ]['risk'] || ! $by_row[ $id ]['can_override'] ) { return array( 'ok' => false, 'error' => 'override_refused_audience', ); } $ov[ $id ] = true; } $re = array(); foreach ( $retranslate as $id ) { $id = is_string( $id ) ? $id : ''; if ( ! isset( $by_row[ $id ] ) || empty( $by_row[ $id ]['source_changed_edited'] ) ) { return array( 'ok' => false, 'error' => 'unknown_retranslate_row', ); } $re[ $id ] = true; } $written = 0; $skipped = array(); $now = time(); foreach ( $fresh['rows'] as $r ) { $existing = Rule::from_stored( Widget_Store::rule( $r['widget_id'] ) ); if ( Rule::STATE_NONE !== $existing->state ) { $imp = is_array( $existing->import ) ? $existing->import : null; if ( ! $imp ) { $skipped[] = array( 'widget_id' => $r['widget_id'], 'why' => 'existing_rule_kept', ); continue; } if ( ! empty( $imp['edited'] ) && ! ( ! empty( $r['source_changed_edited'] ) && isset( $re[ $r['row'] ] ) ) ) { $skipped[] = array( 'widget_id' => $r['widget_id'], 'why' => ! empty( $r['source_changed_edited'] ) ? 'source_changed_kept_edit' : 'existing_rule_kept', ); continue; } $same_override = ( isset( $imp['override'] ) ? $imp['override'] : null ) === ( isset( $ov[ $r['row'] ] ) ? 'show' : null ); if ( isset( $imp['source_hash'] ) && $imp['source_hash'] === $r['source_hash'] && $same_override ) { $skipped[] = array( 'widget_id' => $r['widget_id'], 'why' => 'unchanged', ); continue; } } $rule = Rule::from_tree( $r['tree'] ); $rule->import = array( 'source' => $r['source'], 'source_ref' => $r['ref'], 'source_hash' => $r['source_hash'], 'status' => $r['status'], 'reasons' => $r['reasons'], 'risk' => $r['risk'], 'risk_terms' => $r['risk_terms'], 'override' => isset( $ov[ $r['row'] ] ) ? 'show' : null, 'edited' => false, 'imported_at' => $now, ); $prepared = Rule_Saver::prepare( $rule, Rule::STATE_NONE === $existing->state ? null : $existing, 'widget', (int) $user_id ); if ( Widget_Store::write_rule( $r['widget_id'], $prepared->to_array() ) ) { ++$written; } else { $skipped[] = array( 'widget_id' => $r['widget_id'], 'why' => 'instance_not_found', ); } } $scan = ( new Scanner() )->scan( $entries ); $archived = Legacy_Archive::append( $scan['strings'], array( Scanner::LEGACY_OPTION => get_option( Scanner::LEGACY_OPTION, null ), Scanner::LEGACY_SETTINGS => get_option( Scanner::LEGACY_SETTINGS, null ), ) ); $stored_before = $this->read_report(); $settings_changed = isset( $stored_before['imported_settings'] ) && is_array( $stored_before['imported_settings'] ) ? $stored_before['imported_settings'] : array(); if ( ! empty( $fresh['globals']['main_query_fix'] ) && ! Settings::get( 'main_query_fix' ) ) { // Record the value before import once, so Undo can restore it. if ( ! array_key_exists( 'main_query_fix', $settings_changed ) ) { $settings_changed['main_query_fix'] = false; } Settings::update( array( 'main_query_fix' => true ) ); } $result = array( 'ok' => true, 'written' => $written, 'skipped' => $skipped, 'archive_added' => $archived, 'at' => $now, // R-1 and R-3: say what this Apply did not cover. 'unmatched_not_applied' => count( $fresh['unmatched'] ), 'scan_truncated' => (bool) $fresh['truncated'], ); $stored = $this->read_report(); $stored['applied'] = $result; $stored['imported_settings'] = $settings_changed; unset( $stored['lock'] ); update_option( self::REPORT_OPTION, $stored, false ); return $result; } finally { $this->unlock( $lock ); } } /** * Stored report. * * @return array */ public function read_report() { wp_cache_delete( self::REPORT_OPTION, 'options' ); $r = get_option( self::REPORT_OPTION, array() ); return is_array( $r ) ? $r : array(); } /** * Report token: hash of the canonical report without volatile parts. * * @param array $report Report. * @return string */ public static function token( array $report ) { unset( $report['token'] ); return hash( 'sha256', (string) Rule::json( Rule::canon( $report ) ) ); } /** * Confidence label (merge note C-11). * * @param string $status Status. * @return string */ public static function confidence( $status ) { $map = array( 'translated' => 'Exact', 'translated_pattern' => 'Review', 'partial' => 'Partial', 'untranslated' => 'Review', ); return isset( $map[ $status ] ) ? $map[ $status ] : 'Review'; } /** * Map legacy globals per the design table. * * @param array $g Globals. * @return array */ private function map_globals( array $g ) { return array( 'main_query_fix' => ! empty( $g['widget_logic-options-wp_reset_query'] ), 'load_point_recorded' => isset( $g['widget_logic-options-load_point'] ) ? (string) $g['widget_logic-options-load_point'] : '', 'show_errors_recorded' => ! empty( $g['widget_logic-options-show_errors'] ), 'filter_recorded' => ! empty( $g['widget_logic-options-filter'] ), 'raw_keys' => array_keys( $g ), ); } /** * Unknown function names in a tree. * * @param mixed $node Node. * @return array */ private function unknown_functions( $node ) { $out = array(); if ( ! is_array( $node ) ) { return $out; } if ( array_key_exists( 'unknown', $node ) ) { if ( isset( $node['reason'] ) && 'unknown_function' === $node['reason'] && preg_match( '/^\s*!*\s*([A-Za-z_][A-Za-z0-9_]*)\s*\(/', (string) $node['unknown'], $m ) ) { $out[] = strtolower( $m[1] ); } return $out; } foreach ( isset( $node['items'] ) && is_array( $node['items'] ) ? $node['items'] : array() as $c ) { $out = array_merge( $out, $this->unknown_functions( $c ) ); } if ( isset( $node['item'] ) ) { $out = array_merge( $out, $this->unknown_functions( $node['item'] ) ); } return array_values( array_unique( $out ) ); } /** * F28 change flag. * * @param string $source String. * @param string $status Status. * @param bool $six_evidence 6.x settings option exists. * @return string '' | 'will_show_again' | 'may_change_old_version_unknown' */ private function change_flag( $source, $status, $six_evidence ) { if ( ! $this->six_x_would_refuse( $source ) ) { return ''; } if ( ! in_array( $status, array( 'translated', 'translated_pattern', 'partial' ), true ) ) { return ''; } return $six_evidence ? 'will_show_again' : 'may_change_old_version_unknown'; } /** * Would the Widget Logic 6.x parser refuse this string (so the widget is * hidden there today)? Approximation of the 6.9 tokenizer: it accepts only * calls to whitelisted functions with literal arguments, "!", "&&", "||" * and parentheses. * * @param string $source String. * @return bool */ public function six_x_would_refuse( $source ) { $lex = Lexer::tokenize( $source ); if ( ! $lex['ok'] ) { return true; } $toks = $lex['tokens']; $n = count( $toks ); for ( $i = 0; $i < $n; $i++ ) { $t = $toks[ $i ]; switch ( $t['type'] ) { case 'ident': $is_call = $i + 1 < $n && '(' === $toks[ $i + 1 ]['value']; if ( $is_call && ! in_array( $t['value'], self::WL69_WHITELIST, true ) ) { return true; } break; case 'int': case 'sq': case 'dq': break; case 'kw': if ( ! in_array( $t['value'], array( 'array', 'true', 'false', 'null' ), true ) ) { return true; } break; case 'punct': if ( in_array( $t['value'], array( ';', '=>' ), true ) ) { return true; } if ( ',' === $t['value'] && $i + 1 < $n && ')' === $toks[ $i + 1 ]['value'] ) { return true; } break; default: return true; } } return false; } /** * Take the option-based mutex with an expiry (compare-and-swap inside * gtfg_import_report, so no extra option is ever written). * * @return string|false Lock token. */ public function lock() { global $wpdb; $cur = $this->read_report(); if ( empty( $cur ) && false === get_option( self::REPORT_OPTION, false ) ) { add_option( self::REPORT_OPTION, array(), '', false ); $cur = $this->read_report(); } if ( isset( $cur['lock']['expires'] ) && (int) $cur['lock']['expires'] > time() ) { return false; } $token = wp_generate_password( 20, false ); $new = $cur; $new['lock'] = array( 'token' => $token, 'expires' => time() + self::LOCK_SECONDS, ); $done = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET option_value = %s WHERE option_name = %s AND option_value = %s", maybe_serialize( $new ), self::REPORT_OPTION, maybe_serialize( $cur ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- atomic compare-and-swap for the import mutex. wp_cache_delete( self::REPORT_OPTION, 'options' ); wp_cache_delete( 'notoptions', 'options' ); wp_cache_delete( 'alloptions', 'options' ); return 1 === (int) $done ? $token : false; } /** * Release the mutex. * * @param string $token Lock token. */ public function unlock( $token ) { $cur = $this->read_report(); if ( isset( $cur['lock']['token'] ) && hash_equals( (string) $cur['lock']['token'], (string) $token ) ) { unset( $cur['lock'] ); update_option( self::REPORT_OPTION, $cur, false ); } } }