Import Widget Logic Rules (Phase A server-rendered screen).
*
* @package GateForge
*/
namespace GateForge\Admin;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use GateForge\Import\Export_File_Reader;
use GateForge\Import\Importer;
use GateForge\Import\Legacy_Detector;
use GateForge\Import\Lifecycle;
use GateForge\Import\Snippet_Generator;
use GateForge\Rules\Rule;
use GateForge\Runtime\Explain_Mode;
use GateForge\Storage\Widget_Store;
/**
* Scan, dry-run report, report download and bare Apply. Every handler
* checks a per-action nonce and edit_theme_options before doing anything.
* The React import app is Phase B; this screen is the gate-time UI.
*/
final class Import_Page {
const SLUG = 'gateforge-import';
const TIP_JAR = 'https://lockerforge.com/tip-jar/';
/**
* Hook in.
*/
public static function register() {
add_action( 'admin_menu', array( __CLASS__, 'menu' ) );
add_action( 'admin_post_gtfg_scan', array( __CLASS__, 'handle_scan' ) );
add_action( 'admin_post_gtfg_apply', array( __CLASS__, 'handle_apply' ) );
add_action( 'admin_post_gtfg_download_report', array( __CLASS__, 'handle_download' ) );
add_action( 'admin_post_gtfg_retry', array( __CLASS__, 'handle_retry' ) );
add_action( 'admin_post_gtfg_undo', array( __CLASS__, 'handle_undo' ) );
add_action( 'admin_post_gtfg_remove_legacy', array( __CLASS__, 'handle_remove' ) );
add_action( 'admin_post_gtfg_snippet', array( __CLASS__, 'handle_snippet' ) );
add_action( 'admin_post_gtfg_export_rules', array( __CLASS__, 'handle_export' ) );
add_filter( 'plugin_action_links_' . plugin_basename( GATEFORGE_FILE ), array( __CLASS__, 'plugin_links' ) );
add_action( 'admin_notices', array( __CLASS__, 'legacy_notice' ) );
}
/**
* Plugins-list "Tip Jar" action link.
*
* @param array $links Links.
* @return array
*/
public static function plugin_links( $links ) {
$links[] = '' . esc_html__( 'Tip Jar', 'gateforge' ) . '';
return $links;
}
/**
* Menu.
*/
public static function menu() {
add_management_page( __( 'Import Widget Logic Rules', 'gateforge' ), __( 'Import Widget Logic Rules', 'gateforge' ), 'edit_theme_options', self::SLUG, array( __CLASS__, 'render' ) );
}
/**
* CUJ 7 notice, on our screen and the widgets screen.
*/
public static function legacy_notice() {
$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
if ( ! $screen || ! in_array( $screen->id, \GateForge\Plugin::admin_screens( array( 'tools_page_' . self::SLUG, 'widgets' ) ), true ) || ! current_user_can( 'edit_theme_options' ) ) {
return;
}
if ( Legacy_Detector::is_active() ) {
echo '
' . esc_html__( 'Widget Logic is still active. GateForge will not scan or import while it runs. Deactivate Widget Logic first; its data stays in place and GateForge never changes it.', 'gateforge' ) . '
';
}
}
/**
* Verify capability and nonce for a handler.
*
* @param string $action Nonce action.
*/
private static function verify( $action ) {
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_die( esc_html__( 'You are not allowed to do this.', 'gateforge' ), 403 );
}
check_admin_referer( $action );
}
/**
* Redirect back to the screen.
*
* @param string $msg Message key.
*/
private static function back( $msg ) {
wp_safe_redirect(
add_query_arg(
array(
'page' => self::SLUG,
'gtfg_msg' => $msg,
),
admin_url( 'tools.php' )
)
);
exit;
}
/**
* Scan handler (optional export-file upload, read from the PHP temp file only).
*/
public static function handle_scan() {
self::verify( 'gtfg_import_scan' );
if ( ! Legacy_Detector::allows( 'scan' ) ) {
self::back( 'legacy_active' );
}
$entries = null;
$rejected = array();
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in verify().
if ( isset( $_FILES['gtfg_export_file']['tmp_name'] ) && '' !== $_FILES['gtfg_export_file']['tmp_name'] ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- verified; the reader validates every field.
$read = Export_File_Reader::read_upload( (array) $_FILES['gtfg_export_file'] );
if ( ! $read['ok'] ) {
self::back( 'file_' . sanitize_key( $read['error'] ) );
}
$entries = $read['entries'];
$rejected = isset( $read['rejected'] ) && is_array( $read['rejected'] ) ? $read['rejected'] : array();
}
( new Importer() )->dry_run( $entries, true, $rejected );
self::back( 'scanned' );
}
/**
* Apply handler: report token + override row IDs only.
*/
public static function handle_apply() {
self::verify( 'gtfg_import_apply' );
// phpcs:disable WordPress.Security.NonceVerification.Missing -- verified in verify().
$token = isset( $_POST['gtfg_token'] ) ? sanitize_text_field( wp_unslash( $_POST['gtfg_token'] ) ) : '';
$overrides = array();
if ( isset( $_POST['gtfg_override'] ) && is_array( $_POST['gtfg_override'] ) ) {
foreach ( wp_unslash( $_POST['gtfg_override'] ) as $id ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- each ID is pattern-checked below.
if ( is_string( $id ) && preg_match( '/^[a-f0-9]{16}$/', $id ) ) {
$overrides[] = $id;
}
}
}
$retranslate = array();
if ( isset( $_POST['gtfg_retranslate'] ) && is_array( $_POST['gtfg_retranslate'] ) ) {
foreach ( wp_unslash( $_POST['gtfg_retranslate'] ) as $id ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- each ID is pattern-checked below.
if ( is_string( $id ) && preg_match( '/^[a-f0-9]{16}$/', $id ) ) {
$retranslate[] = $id;
}
}
}
// phpcs:enable
$result = ( new Importer() )->apply( $token, $overrides, get_current_user_id(), $retranslate );
self::back( ! empty( $result['ok'] ) ? 'applied' : 'apply_' . sanitize_key( $result['error'] ) );
}
/**
* Download the stored report as an attachment.
*/
public static function handle_download() {
self::verify( 'gtfg_download_report' );
$report = ( new Importer() )->read_report();
nocache_headers();
header( 'Content-Type: application/json; charset=utf-8' );
header( 'X-Content-Type-Options: nosniff' );
header( 'Content-Disposition: attachment; filename="gateforge-import-report.json"' );
unset( $report['lock'], $report['export_entries'] );
echo wp_json_encode( $report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
exit;
}
/**
* Widget IDs from a POSTed list, pattern-checked.
*
* @param string $key Field.
* @return array
*/
private static function posted_widget_ids( $key ) {
$out = array();
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- callers run verify() first.
if ( isset( $_POST[ $key ] ) && is_array( $_POST[ $key ] ) ) {
foreach ( wp_unslash( $_POST[ $key ] ) as $id ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- pattern-checked below.
if ( is_string( $id ) && preg_match( '/^[A-Za-z0-9_\-]{1,190}$/', $id ) ) {
$out[] = $id;
}
}
}
return $out;
}
/**
* Retry handler.
*/
public static function handle_retry() {
self::verify( 'gtfg_import_retry' );
$r = ( new Lifecycle() )->retry( null, get_current_user_id() );
self::back( ! empty( $r['ok'] ) ? 'retried_' . (int) $r['retried'] . '_improved_' . (int) $r['improved'] : 'retry_' . sanitize_key( $r['error'] ) );
}
/**
* Undo handler.
*/
public static function handle_undo() {
self::verify( 'gtfg_import_undo' );
$r = ( new Lifecycle() )->undo( self::posted_widget_ids( 'gtfg_undo_edited' ) );
self::back( ! empty( $r['ok'] ) ? 'undone_' . (int) $r['removed'] : 'undo_' . sanitize_key( $r['error'] ) );
}
/**
* Remove Widget Logic data handler (typed confirmation).
*/
public static function handle_remove() {
self::verify( 'gtfg_import_remove_legacy' );
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in verify().
$confirm = isset( $_POST['gtfg_confirm'] ) ? sanitize_text_field( wp_unslash( $_POST['gtfg_confirm'] ) ) : '';
$r = ( new Lifecycle() )->remove_legacy( $confirm );
self::back( ! empty( $r['ok'] ) ? 'removed_' . (int) $r['removed_keys'] : 'remove_' . sanitize_key( $r['error'] ) );
}
/**
* Snippet download: plain text attachment, never written to disk (9.3).
*/
public static function handle_snippet() {
self::verify( 'gtfg_import_snippet' );
$stored = ( new Importer() )->read_report();
$rows = isset( $stored['dry_run']['rows'] ) ? $stored['dry_run']['rows'] : array();
$extra = isset( $stored['dry_run']['allowed_functions'] ) && is_array( $stored['dry_run']['allowed_functions'] ) ? $stored['dry_run']['allowed_functions'] : array();
$gen = Snippet_Generator::generate( $rows, $extra );
nocache_headers();
header( 'Content-Type: text/plain; charset=utf-8' );
header( 'X-Content-Type-Options: nosniff' );
header( 'Content-Disposition: attachment; filename="' . Snippet_Generator::FILENAME . '"' );
echo $gen['text']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- plain-text download built only from var_export()ed validated values (9.2).
exit;
}
/**
* Rule export download (10.9): read-only JSON.
*/
public static function handle_export() {
self::verify( 'gtfg_export_rules' );
nocache_headers();
header( 'Content-Type: application/json; charset=utf-8' );
header( 'X-Content-Type-Options: nosniff' );
header( 'Content-Disposition: attachment; filename="gateforge-rules.json"' );
echo wp_json_encode( Rule_Export::build(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
exit;
}
/**
* A small POST form with a nonce and one button.
*
* @param string $action admin-post action.
* @param string $nonce Nonce action.
* @param string $label Button label.
* @param string $inner Extra trusted HTML (already escaped).
*/
private static function action_form( $action, $nonce, $label, $inner = '' ) {
echo '';
}
/**
* After-import tools: Retry, Undo, export, Remove.
*
* @param array $stored Stored report.
* @param bool $blocked Old plugin active.
*/
private static function render_after_import( array $stored, $blocked ) {
echo '
' . esc_html__( 'Remove is not possible: the scan of this site is incomplete, so GateForge cannot confirm every legacy rule is archived.', 'gateforge' ) . '
' . esc_html__( 'Remove is not possible yet: these legacy rules are not in the GateForge archive and would be lost. Run Scan and Apply again first.', 'gateforge' ) . '
';
foreach ( $plan['not_archived'] as $n ) {
echo '
' . esc_html__( 'Deactivate Widget Logic before removing its data.', 'gateforge' ) . '
';
return;
}
echo '
' . esc_html(
sprintf(
/* translators: 1: number of legacy rule locations, 2: confirmation word. */
__( 'This permanently deletes %1$d Widget Logic rule locations and its options. GateForge keeps its own archive copy, so Undo still works. Type %2$s to confirm.', 'gateforge' ),
count( $plan['locations'] ),
Lifecycle::CONFIRM_PHRASE
)
) . '
' . esc_html__( 'GateForge reads your Widget Logic rules and turns them into visibility rules without running any stored PHP. Nothing changes until you press Apply. Visibility is not security.', 'gateforge' ) . '
';
}
/**
* Scan completeness (R-3): a truncated scan is never shown as complete.
*
* @param array $report Report.
*/
private static function render_truncated( array $report ) {
if ( empty( $report['truncated'] ) ) {
return;
}
$read = isset( $report['options_read'] ) ? (int) $report['options_read'] : 0;
if ( isset( $report['truncated_reason'] ) && 'option_name_limit' === $report['truncated_reason'] ) {
$text = sprintf(
/* translators: 1: most widget settings one scan lists, 2: widget settings read. */
__( 'This scan is incomplete: the site has more widget settings than the %1$d one scan lists, so it stopped there. It read %2$d widget settings; any after that point are not in this report.', 'gateforge' ),
isset( $report['option_name_cap'] ) ? (int) $report['option_name_cap'] : 0,
$read
);
} else {
$text = sprintf(
/* translators: 1: widget settings read, 2: widget settings listed. */
__( 'This scan is incomplete: PHP memory ran short after %1$d of %2$d widget settings were read; the rest are not in this report.', 'gateforge' ),
$read,
isset( $report['options_listed'] ) ? (int) $report['options_listed'] : 0
);
}
echo '
' . esc_html(
$text . ' ' . __( 'Apply only covers the rows below, and Remove Widget Logic data stays unavailable until a scan completes.', 'gateforge' )
) . '
';
}
/**
* Export-file entries that match no widget on this site (G-2, R-1): one
* record per entry with its original expression. They are not imported and
* cannot be applied until a widget with that ID exists.
*
* @param array $report Report.
*/
private static function render_unmatched( array $report ) {
$records = isset( $report['unmatched'] ) && is_array( $report['unmatched'] ) ? $report['unmatched'] : array();
if ( ! $records && ! empty( $report['unmatched_file_ids'] ) && is_array( $report['unmatched_file_ids'] ) ) {
foreach ( $report['unmatched_file_ids'] as $id ) {
$records[] = array(
'widget_id' => (string) $id,
'source' => '',
'summary' => '',
);
}
}
if ( ! $records ) {
return;
}
echo '
' . esc_html(
sprintf(
/* translators: %1$d: number of export file entries. */
_n( '%1$d entry in the export file matches no widget on this site, so it was not imported:', '%1$d entries in the export file match no widget on this site, so they were not imported:', count( $records ), 'gateforge' ),
count( $records )
)
) . '
' . esc_html__( 'Unmatched: no widget with this ID. Not applied.', 'gateforge' ) . '
';
}
echo '
';
if ( count( $records ) > 500 ) {
echo '
' . esc_html(
sprintf(
/* translators: %1$d: number of entries not listed. */
__( 'and %1$d more (see the downloaded report).', 'gateforge' ),
count( $records ) - 500
)
) . '
';
}
echo '
' . esc_html__( 'Add those widgets to this site with the same IDs, then scan again; they then appear as normal rows that Apply can import. The downloaded report keeps every entry with its original text.', 'gateforge' ) . '
' . esc_html(
sprintf(
/* translators: %1$d: number of rejected lines. */
_n( '%1$d line in the export file was not read:', '%1$d lines in the export file were not read:', count( $rej ) + count( $skip ), 'gateforge' ),
count( $rej ) + count( $skip )
)
) . '
';
}
/**
* Plain text for a reader rejection code.
*
* @param string $code Code.
* @param string $type Decoded type, for value_not_string.
* @return string
*/
private static function reject_text( $code, $type ) {
switch ( $code ) {
case 'value_not_string':
/* translators: %1$s: JSON value type such as integer or array. */
return sprintf( __( 'the value is not rule text (type: %1$s), so it was not imported', 'gateforge' ), '' !== $type ? $type : __( 'unknown', 'gateforge' ) );
case 'no_tab':
return __( 'no tab between the widget ID and the rule', 'gateforge' );
case 'invalid_json':
return __( 'the rule is not valid JSON text', 'gateforge' );
case 'bad_key':
return __( 'the widget ID has characters a widget ID cannot have', 'gateforge' );
case 'line_too_long':
return __( 'the line is too long', 'gateforge' );
default:
return $code;
}
}
/**
* Render the dry-run report.
*
* @param array $report Report.
* @param bool $blocked Old plugin active.
*/
private static function render_report( array $report, $blocked ) {
$t = $report['totals'];
echo '
' . esc_html(
sprintf(
/* translators: %1$d: number of widgets. */
__( '%1$d widgets will be locked hidden when their rule cannot be checked, because the rule depends on who the visitor is. A condition snippet for their custom functions can unlock them.', 'gateforge' ),
(int) $report['locked_hidden']
)
) . '
' . esc_html__( 'GateForge never runs stored code. To keep using your own site functions, install this generated file yourself in wp-content/mu-plugins/. It needs file access, and code in it runs with full site rights.', 'gateforge' ) . '