'GET', 'callback' => array( __CLASS__, 'conditions' ), 'permission_callback' => static function () { return current_user_can( 'edit_posts' ); }, 'args' => array(), ) ); register_rest_route( self::NS, '/import/scan', array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'scan' ), 'permission_callback' => array( __CLASS__, 'can_import' ), 'args' => array( 'nonce' => array( 'type' => 'string', 'required' => true, 'pattern' => '^[a-f0-9]{10}$', ), ), ) ); register_rest_route( self::NS, '/import/apply', array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'apply' ), 'permission_callback' => array( __CLASS__, 'can_import' ), 'args' => array( 'nonce' => array( 'type' => 'string', 'required' => true, 'pattern' => '^[a-f0-9]{10}$', ), 'token' => array( 'type' => 'string', 'required' => true, 'pattern' => '^[a-f0-9]{64}$', ), 'overrides' => array( 'type' => 'array', 'default' => array(), 'maxItems' => 5000, 'items' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{16}$', ), ), 'retranslate' => array( 'type' => 'array', 'default' => array(), 'maxItems' => 5000, 'items' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{16}$', ), ), ), ) ); $nonce = array( 'type' => 'string', 'required' => true, 'pattern' => '^[a-f0-9]{10}$', ); $wids = array( 'type' => 'array', 'default' => array(), 'maxItems' => 5000, 'items' => array( 'type' => 'string', 'pattern' => '^[A-Za-z0-9_\\-]{1,190}$', ), ); register_rest_route( self::NS, '/import/retry', array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'retry' ), 'permission_callback' => array( __CLASS__, 'can_import' ), 'args' => array( 'nonce' => $nonce, 'widget_ids' => $wids, ), ) ); register_rest_route( self::NS, '/import/undo', array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'undo' ), 'permission_callback' => array( __CLASS__, 'can_import' ), 'args' => array( 'nonce' => $nonce, 'include_edited' => $wids, ), ) ); register_rest_route( self::NS, '/import/remove-legacy', array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'remove_legacy' ), 'permission_callback' => array( __CLASS__, 'can_import' ), 'args' => array( 'nonce' => $nonce, 'confirm' => array( 'type' => 'string', 'required' => true, 'maxLength' => 20, ), ), ) ); register_rest_route( self::NS, '/import/snippet', array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'snippet' ), 'permission_callback' => array( __CLASS__, 'can_import' ), 'args' => array(), ) ); register_rest_route( self::NS, '/export', array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'export' ), 'permission_callback' => array( __CLASS__, 'can_import' ), 'args' => array(), ) ); register_rest_route( self::NS, '/rules/validate', array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'validate' ), 'permission_callback' => static function () { return current_user_can( 'edit_posts' ); }, 'args' => array( 'rule' => array( 'type' => 'object', 'required' => true, ), ), ) ); register_rest_route( self::NS, '/widget-rule', array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'widget_rule' ), 'permission_callback' => array( __CLASS__, 'can_import' ), 'args' => array( 'nonce' => $nonce, 'widget_id' => array( 'type' => 'string', 'required' => true, 'pattern' => '^[A-Za-z0-9_\-]{1,190}$', ), 'rule_json' => array( 'type' => 'string', 'required' => true, 'maxLength' => Widget_Copyover::MAX_BYTES, ), ), ) ); } /** * Shared check for destructive routes: cookie auth, then the per-action nonce. * * @param \WP_REST_Request $request Request. * @param string $action Nonce action. * @return true|\WP_Error */ private static function destructive_ok( $request, $action ) { if ( ! self::cookie_authenticated() ) { return new \WP_Error( 'gtfg_cookie_required', __( 'This action must be done from the dashboard while logged in.', 'gateforge' ), array( 'status' => 403 ) ); } if ( false === wp_verify_nonce( (string) $request['nonce'], $action ) ) { return new \WP_Error( 'gtfg_bad_nonce', __( 'The form expired. Reload the page and try again.', 'gateforge' ), array( 'status' => 403 ) ); } return true; } /** * Map a lifecycle result to a response. * * @param array $result Result. * @param string $prefix Error code prefix. * @return \WP_REST_Response|\WP_Error */ private static function result( array $result, $prefix ) { if ( empty( $result['ok'] ) ) { return new \WP_Error( $prefix . $result['error'], $result['error'], array_merge( array( 'status' => 409 ), $result ) ); } return rest_ensure_response( $result ); } /** * POST /import/retry. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function retry( $request ) { $ok = self::destructive_ok( $request, 'gtfg_import_retry' ); if ( true !== $ok ) { return $ok; } $ids = (array) $request['widget_ids']; return self::result( ( new Lifecycle() )->retry( $ids ? $ids : null, get_current_user_id() ), 'gtfg_retry_' ); } /** * POST /import/undo. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function undo( $request ) { $ok = self::destructive_ok( $request, 'gtfg_import_undo' ); if ( true !== $ok ) { return $ok; } return self::result( ( new Lifecycle() )->undo( (array) $request['include_edited'] ), 'gtfg_undo_' ); } /** * POST /import/remove-legacy. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function remove_legacy( $request ) { $ok = self::destructive_ok( $request, 'gtfg_import_remove_legacy' ); if ( true !== $ok ) { return $ok; } return self::result( ( new Lifecycle() )->remove_legacy( (string) $request['confirm'] ), 'gtfg_remove_' ); } /** * GET /import/snippet (text in JSON; the download itself is the admin-post attachment). * * @return \WP_REST_Response */ public static function 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(); return rest_ensure_response( Snippet_Generator::generate( $rows, $extra ) ); } /** * GET /export. * * @return \WP_REST_Response */ public static function export() { return rest_ensure_response( Rule_Export::build() ); } /** * POST /rules/validate: state, limits, printed text and summary. Writes nothing. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response */ public static function validate( $request ) { $raw = $request['rule']; $rule = Rule::from_stored( is_array( $raw ) ? $raw : null, 'block' ); if ( Rule::STATE_OK !== $rule->state ) { return rest_ensure_response( array( 'valid' => false, 'reason' => Rule::STATE_NONE === $rule->state ? 'no_rule' : $rule->invalid_reason, ) ); } if ( $rule->over_limit() ) { return rest_ensure_response( array( 'valid' => false, 'reason' => 'too_large', ) ); } $problems = array(); self::problems( $rule->tree, $problems ); return rest_ensure_response( array( 'valid' => true, 'read_only' => $rule->read_only, 'unauthorized' => ! empty( $rule->ext['gateforge']['unauthorized'] ), 'printed' => Printer::print_tree( $rule->tree ), 'summary' => Summarizer::summarize( $rule->tree ), 'problems' => array_slice( $problems, 0, 20 ), ) ); } /** * POST /widget-rule: save or clear one classic widget's rule, sent by the * block widgets editor panel (GF-B1 round 2). * * The panel cannot ride the widget's own save. Core builds the instance * it stores from the widget's form fields only (WP_Widget::update_callback * reads $_POST["widget-"], which WP_REST_Widgets_Controller:: * save_widget() synthesises from form_data or from an instance encoded * out of form data), and the widget's update() then drops any key it does * not know — so a rule carried in a block attribute never reaches * Widget_Copyover::carry(). This route therefore runs the identical * validated save path (Widget_Copyover::save_from_builder: schema and * registry validation, limits, risk stamping, anti-planting, read-only * and over-limit handling) and stores the result through Widget_Store — * the same end state as a classic-form or Customizer save. Block widgets * are refused: their rules live in their content and are stamped by * carry()'s content branch. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function widget_rule( $request ) { $ok = self::destructive_ok( $request, 'gtfg_widget_rule' ); if ( true !== $ok ) { return $ok; } $wid = (string) $request['widget_id']; if ( 0 === strpos( $wid, 'block-' ) ) { return new \WP_Error( 'gtfg_block_widget_rule', __( 'Block widgets keep their rules in their content. This route is for classic widgets.', 'gateforge' ), array( 'status' => 400 ) ); } $inst = Widget_Store::instance( $wid ); if ( null === $inst ) { return new \WP_Error( 'gtfg_widget_not_found', __( 'That widget has not been saved yet. Save the widget area once, then set the rule.', 'gateforge' ), array( 'status' => 404 ) ); } $old_raw = array_key_exists( Widget_Store::KEY, $inst ) ? $inst[ Widget_Store::KEY ] : null; $field = (string) $request['rule_json']; if ( Widget_Copyover::CLEAR === $field ) { if ( ! Widget_Store::write_rule( $wid, null ) ) { return new \WP_Error( 'gtfg_widget_not_found', __( 'That widget has not been saved yet. Save the widget area once, then set the rule.', 'gateforge' ), array( 'status' => 404 ) ); } } else { $saved = Widget_Copyover::save_from_builder( $field, $old_raw ); if ( null === $saved ) { // Same contract as carry(): null means the stored rule is // kept — a newer-schema rule is never rewritten, and a // submission that does not decode to a rule array never // replaces it. (Invalid or over-limit rules that DO decode // are stored as written by save_from_builder, exactly as on // the form path, and fail closed at evaluation.) The panel // resyncs to the stored state carried in the error data. return new \WP_Error( 'gtfg_rule_kept', __( 'The stored rule was kept unchanged.', 'gateforge' ), array_merge( array( 'status' => 409 ), self::widget_rule_state( $wid ) ) ); } if ( ! Widget_Store::write_rule( $wid, $saved ) ) { return new \WP_Error( 'gtfg_widget_not_found', __( 'That widget has not been saved yet. Save the widget area once, then set the rule.', 'gateforge' ), array( 'status' => 404 ) ); } } if ( Schedule::uses_schedule( $old_raw ) ) { Saved_Rules::widgets_changed(); } return rest_ensure_response( array_merge( array( 'saved' => true ), self::widget_rule_state( $wid ) ) ); } /** * The stored-rule state of one widget, for /widget-rule responses: the * panel resyncs from this instead of trusting what it sent. * * @param string $wid Widget ID. * @return array */ private static function widget_rule_state( $wid ) { $raw = Widget_Store::rule( $wid ); $rule = Rule::from_stored( $raw, 'widget' ); $ok = Rule::STATE_OK === $rule->state; return array( 'widget_id' => $wid, 'rule' => is_array( $raw ) ? $raw : null, 'summary' => $ok ? Summarizer::summarize( $rule->tree ) : ( null === $raw ? '' : __( 'This rule cannot be read, so the widget is hidden.', 'gateforge' ) ), 'imported' => $ok && is_array( $rule->import ), 'read_only' => $rule->read_only, ); } /** * Builder hints: conditions that are not registered here or whose values do * not fit the condition (the rule is still saved as written). * * @param mixed $node Node. * @param array $problems Output (by reference). */ private static function problems( $node, array &$problems ) { if ( ! is_array( $node ) ) { return; } if ( isset( $node['cond'] ) && is_string( $node['cond'] ) ) { $reg = Registry::instance(); $def = $reg->get( $node['cond'] ); if ( null === $def ) { $problems[] = array( 'cond' => $node['cond'], 'code' => 'condition_unavailable', /* translators: %1$s: condition name. */ 'message' => sprintf( __( '%1$s is not available on this site. It is kept unchanged and counts as unknown.', 'gateforge' ), $node['cond'] ), ); } elseif ( true !== $reg->validate_args( $node['cond'], isset( $node['args'] ) ? $node['args'] : array() ) ) { $problems[] = array( 'cond' => $node['cond'], 'code' => 'bad_arguments', /* translators: %1$s: condition label. */ 'message' => sprintf( __( '%1$s: the values do not fit this condition yet, so it counts as unknown.', 'gateforge' ), $def['label'] ), ); } return; } foreach ( isset( $node['items'] ) && is_array( $node['items'] ) ? $node['items'] : array() as $c ) { self::problems( $c, $problems ); } if ( isset( $node['item'] ) ) { self::problems( $node['item'], $problems ); } } /** * Capability for import routes. * * @return bool */ public static function can_import() { return current_user_can( 'edit_theme_options' ); } /** * Was this request authenticated by the login cookie (not an Application Password). * * @return bool */ public static function cookie_authenticated() { if ( did_action( 'application_password_did_authenticate' ) ) { return false; } $uid = wp_validate_auth_cookie( '', 'logged_in' ); return $uid && get_current_user_id() === (int) $uid; } /** * GET /conditions. * * @return \WP_REST_Response */ public static function conditions() { $out = array(); foreach ( Registry::instance()->all() as $name => $def ) { $out[] = array( 'name' => $name, 'label' => $def['label'], 'group' => $def['group'], 'risk' => $def['risk'], 'source' => $def['source'], 'params' => $def['params'], 'entity' => $def['entity'], ); } return rest_ensure_response( $out ); } /** * POST /import/scan (multipart; optional "file"). * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function scan( $request ) { // R-4: scan writes the stored import report, so it gets the same cookie // authentication and nonce check as the other import routes. $ok = self::destructive_ok( $request, 'gtfg_import_scan' ); if ( true !== $ok ) { return $ok; } if ( ! Legacy_Detector::allows( 'scan' ) ) { return new \WP_Error( 'gtfg_legacy_active', __( 'Deactivate Widget Logic before scanning.', 'gateforge' ), array( 'status' => 409 ) ); } $entries = null; $rejected = array(); $files = $request->get_file_params(); if ( isset( $files['file'] ) && is_array( $files['file'] ) && ! empty( $files['file']['tmp_name'] ) ) { $read = Export_File_Reader::read_upload( $files['file'] ); if ( ! $read['ok'] ) { return new \WP_Error( 'gtfg_bad_file', $read['error'], array( 'status' => 400 ) ); } $entries = $read['entries']; $rejected = isset( $read['rejected'] ) && is_array( $read['rejected'] ) ? $read['rejected'] : array(); } return rest_ensure_response( ( new Importer() )->dry_run( $entries, true, $rejected ) ); } /** * POST /import/apply. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function apply( $request ) { if ( ! self::cookie_authenticated() ) { return new \WP_Error( 'gtfg_cookie_required', __( 'This action must be done from the dashboard while logged in.', 'gateforge' ), array( 'status' => 403 ) ); } if ( false === wp_verify_nonce( (string) $request['nonce'], 'gtfg_import_apply' ) ) { return new \WP_Error( 'gtfg_bad_nonce', __( 'The form expired. Reload the page and try again.', 'gateforge' ), array( 'status' => 403 ) ); } $result = ( new Importer() )->apply( (string) $request['token'], (array) $request['overrides'], get_current_user_id(), (array) $request['retranslate'] ); if ( empty( $result['ok'] ) ) { return new \WP_Error( 'gtfg_apply_' . $result['error'], $result['error'], array( 'status' => 409 ) ); } return rest_ensure_response( $result ); } }