'Clearer',
'simpler' => 'Simpler',
'formal' => 'More formal',
'friendly' => 'Friendlier',
);
/** The backend refuses more than this many blocks in one request; the editor never sends more. */
const MAX_BLOCKS = 40;
/**
* Every user action that sends data to the backend (P4). One entry per backend call site, each
* verbatim in readme.txt's External services section; `scripts/check-alto-parity.py` enforces both.
*/
const RUAC_SEND_TRIGGERS = array(
'when you click "Rewrite selected blocks" or "Rewrite selection" in the editor',
'when you submit your email address',
);
public function __construct() {
add_action( 'admin_menu', array( $this, 'menu' ) );
add_action( 'admin_init', array( $this, 'register' ) );
add_action( 'admin_post_altorewrite_contact', array( $this, 'submit_contact' ) ); // EC2
add_action( 'add_meta_boxes', array( $this, 'meta_box' ) );
add_action( 'wp_ajax_altorewrite_rewrite', array( $this, 'ajax_rewrite' ) );
add_action( 'enqueue_block_editor_assets', array( $this, 'block_editor_assets' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'classic_editor_assets' ) );
add_action( 'admin_notices', array( $this, 'work_surface_review_prompt' ) );
add_action( 'admin_notices', array( $this, 'quota_notices' ) );
// W1: signpost activation with a Settings link and a sentence saying where to go.
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'action_links' ) );
add_action( 'admin_notices', array( $this, 'ruac_welcome' ) );
}
/* ---------------- settings ---------------- */
private function opts() {
$o = wp_parse_args(
get_option( self::OPT, array() ),
array(
'backend_url' => self::DEFAULT_BACKEND,
'license_key' => '',
'tone' => 'clearer',
)
);
// SEC1: filter on READ as well as on save, so a stored http:// URL is never honoured.
$o['backend_url'] = $this->https_or_default( $o['backend_url'] );
if ( ! isset( self::TONES[ $o['tone'] ] ) ) {
$o['tone'] = 'clearer';
}
return $o;
}
/** The backend URL must be https: the licence key and post content travel in the request body. */
private function https_or_default( $url ) {
$scheme = wp_parse_url( trim( (string) $url ), PHP_URL_SCHEME );
return ( is_string( $scheme ) && 'https' === strtolower( $scheme ) )
? trim( (string) $url )
: self::DEFAULT_BACKEND;
}
/**
* EC2: send the release-notes address the user just submitted from the settings card. A send
* trigger of its own (P4): the address travels once, on this request only.
*/
public function submit_contact() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( 'Not allowed' );
}
check_admin_referer( 'ruac_capture_submit_altorewrite' );
// EC3: an unticked box sends nothing. The browser's `required` can be bypassed; this cannot.
if ( ! isset( $_POST['ruac_capture_consent'] ) || '1' !== sanitize_key( wp_unslash( $_POST['ruac_capture_consent'] ) ) ) {
wp_safe_redirect( altorewrite_shared_capture_outcome_url( 'altorewrite', 'unticked' ) );
exit;
}
$email = isset( $_POST['ruac_capture_email'] ) ? sanitize_email( wp_unslash( $_POST['ruac_capture_email'] ) ) : '';
if ( ! is_email( $email ) ) {
wp_safe_redirect( altorewrite_shared_capture_outcome_url( 'altorewrite', 'invalid' ) );
exit;
}
$o = $this->opts();
$res = wp_remote_post(
trailingslashit( $o['backend_url'] ) . 'v1/contact',
array(
'timeout' => 15,
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode(
array(
'email' => $email,
'siteId' => $this->site_id(),
'product' => 'altorewrite',
'version' => self::VERSION,
'consent' => altorewrite_shared_capture_consent( 'AltoRewrite' ), // EC3: the wording ticked, recorded
)
),
)
);
$ok = ! is_wp_error( $res ) && 200 === (int) wp_remote_retrieve_response_code( $res );
if ( $ok ) {
altorewrite_shared_capture_submitted( 'altorewrite' );
}
wp_safe_redirect( altorewrite_shared_capture_outcome_url( 'altorewrite', $ok ? 'sent' : 'failed' ) );
exit;
}
private function site_id() {
return substr( md5( home_url() ), 0, 16 );
}
public function register() {
register_setting( 'altorewrite', self::OPT, array( $this, 'sanitize' ) );
}
public function sanitize( $in ) {
$tone = sanitize_key( $in['tone'] ?? 'clearer' );
return array(
'backend_url' => $this->https_or_default( esc_url_raw( $in['backend_url'] ?? self::DEFAULT_BACKEND ) ),
'license_key' => altorewrite_shared_sanitize_license_key( $in, $this->opts()['license_key'] ?? '' ),
'tone' => isset( self::TONES[ $tone ] ) ? $tone : 'clearer',
);
}
public function menu() {
add_options_page( 'AltoRewrite', 'AltoRewrite', 'manage_options', 'altorewrite', array( $this, 'settings_page' ) );
}
public function settings_page() {
$o = $this->opts();
?>
AltoRewrite: AI Content Rewriter
This plugin connects to an external service. To write a rewrite, AltoRewrite
sends data to the Really Useful App Company API
(), which uses an AI provider
(Anthropic) to generate the text.
What is sent: the post title and the text you selected, plus a site ID (a hash of your site URL), which we treat as personal data, for usage counting. When: only when you
click "Rewrite selected blocks" in the block editor or "Rewrite selection" in the classic editor.
Nothing is sent until you act. If you choose to give us an email address for release notes and product updates, it is sent on its own, only when you submit it.
AI-generated content can be inaccurate. Read each rewrite before you apply it. Nothing changes in your post until you apply a rewrite and save.
opts();
$res = wp_remote_post(
trailingslashit( $o['backend_url'] ) . 'v1/rewrite',
array(
// The backend rewrites each block in its own call, in parallel. Its measured worst case
// is about 23 s (one long CJK block at the size limit; ruac-backend RW1 record), so 20 s,
// AltoSum's figure, would cut off a request the backend was about to answer.
'timeout' => 45,
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode(
array(
'product' => self::PRODUCT,
'version' => self::VERSION,
'siteId' => $this->site_id(),
// MEAS4: furthest state this installation's review prompt reached.
'reviewPrompt' => function_exists( 'altorewrite_shared_review_state' )
? altorewrite_shared_review_state( 'altorewrite' )
: '',
// EC2: furthest state the email-capture card reached; never the address.
'capturePrompt' => function_exists( 'altorewrite_shared_capture_state' )
? altorewrite_shared_capture_state( 'altorewrite' )
: '',
'licenseKey' => $o['license_key'],
'title' => $title,
'blocks' => $blocks,
'tone' => $tone,
)
),
)
);
if ( is_wp_error( $res ) ) {
return $res;
}
$code = wp_remote_retrieve_response_code( $res );
$body = json_decode( wp_remote_retrieve_body( $res ), true );
if ( 200 !== (int) $code ) {
$msg = isset( $body['error'] ) ? $body['error'] : 'Request failed.';
// A 402 carries the usage block: keep it, so the panel can show the wall and the upgrade.
altorewrite_shared_remember_usage( 'altorewrite', $body );
return new WP_Error(
'altorewrite_api',
$msg,
array(
'status' => (int) $code,
'code' => is_array( $body ) ? ( $body['code'] ?? null ) : null,
)
);
}
altorewrite_shared_remember_usage( 'altorewrite', $body );
altorewrite_shared_review_bump( 'altorewrite' ); // Count a successful generation for the review prompt.
return $body;
}
/**
* The blocks the editor sent: a JSON array of strings, each a block's inner HTML. Null when the
* request carries anything else. Each is filtered as post content would be (wp_kses_post), so a
* tag the post could not hold is not sent.
*
* @return string[]|null
*/
private function posted_blocks() {
$raw = isset( $_POST['blocks'] ) ? wp_unslash( $_POST['blocks'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.NonceVerification.Missing -- JSON, decoded and each string filtered with wp_kses_post below; the nonce is checked by ajax_rewrite, the only caller, before this runs.
$blocks = json_decode( is_string( $raw ) ? $raw : '', true );
// A list, not a JSON object: an object decodes to an associative array that would read as blocks.
if ( ! is_array( $blocks ) || ! $blocks || count( $blocks ) > self::MAX_BLOCKS || array_values( $blocks ) !== $blocks ) {
return null;
}
$clean = array();
foreach ( $blocks as $block ) {
if ( ! is_string( $block ) ) {
return null;
}
$clean[] = wp_kses_post( $block );
}
return $clean;
}
/** A block's HTML with runs of whitespace collapsed, so a reflowed copy compares equal. */
private static function squash( $html ) {
return trim( preg_replace( '/\s+/u', ' ', (string) $html ) );
}
/**
* The backend's reply, made safe to put in the editor. A block the backend did not rewrite comes
* back as the user's own text from the REQUEST, never the reply's copy of it, and every rewritten
* block is filtered with wp_kses_post. A reply whose block count does not match is refused whole:
* a shifted reply would put text in the wrong block (the defect ruac-backend RW1 designed out).
*
* @return array|null { blocks: string[], rewritten: bool[], usedFallback: bool }
*/
private function usable_reply( $data, $sent ) {
$blocks = isset( $data['blocks'] ) && is_array( $data['blocks'] ) ? array_values( $data['blocks'] ) : array();
$rewritten = isset( $data['rewritten'] ) && is_array( $data['rewritten'] ) ? array_values( $data['rewritten'] ) : array();
if ( count( $blocks ) !== count( $sent ) || count( $rewritten ) !== count( $sent ) ) {
return null;
}
$out = array( 'blocks' => array(), 'rewritten' => array() );
foreach ( $sent as $i => $original ) {
$ai = true === $rewritten[ $i ] && is_string( $blocks[ $i ] ) && '' !== trim( wp_strip_all_tags( $blocks[ $i ] ) );
// Text that came back as sent is still the user's own: labelling it AI-generated would be
// a false claim (the AG5 class; the RW1 walk, 2026-11-10, a heading returned word for word).
$ai = $ai && self::squash( $blocks[ $i ] ) !== self::squash( $original );
$out['blocks'][] = $ai ? wp_kses_post( $blocks[ $i ] ) : $original;
$out['rewritten'][] = $ai;
}
// The backend's own flag, read rather than inferred: it is what says whether the AI wrote any of it.
$out['usedFallback'] = ! empty( $data['usedFallback'] ) || ! in_array( true, $out['rewritten'], true );
return $out;
}
/**
* What the editor gets back when the backend refuses a rewrite. QW2: the box's fresh state goes
* back with the error, so at the limit the panel shows the wall. RP1: when it does show the wall,
* the error line is left out, because the wall already says the allowance is spent.
*
* @param WP_Error $error The refusal from call_backend().
* @return array{message:string,walled:bool,quota_html:string}
*/
private function refusal_reply( $error ) {
$state = altorewrite_shared_usage_state( 'altorewrite', '' !== altorewrite_shared_key_fingerprint( 'altorewrite' ) );
$walled = $state['walled'] && ! $state['paid'];
return array(
'message' => $walled ? '' : $error->get_error_message(),
'walled' => $walled,
'quota_html' => altorewrite_shared_quota_box_html( $this->quota_args() ),
);
}
public function ajax_rewrite() {
check_ajax_referer( 'altorewrite_rewrite', 'nonce' );
$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) ) {
wp_send_json_error( array( 'message' => 'Permission denied.' ), 403 );
}
$blocks = $this->posted_blocks();
if ( null === $blocks ) {
wp_send_json_error( array( 'message' => 'Select some text to rewrite first.' ), 400 );
}
$tone = isset( $_POST['tone'] ) ? sanitize_key( wp_unslash( $_POST['tone'] ) ) : '';
$tone = isset( self::TONES[ $tone ] ) ? $tone : $this->opts()['tone'];
$title = isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '';
$data = $this->call_backend( $title, $blocks, $tone );
if ( is_wp_error( $data ) ) {
wp_send_json_error( $this->refusal_reply( $data ), 400 );
}
$reply = $this->usable_reply( $data, $blocks );
if ( null === $reply ) {
wp_send_json_error( array( 'message' => 'The rewrite came back in a shape we could not use. Nothing changed.' ), 400 );
}
$reply['quota_html'] = altorewrite_shared_quota_box_html( $this->quota_args() );
wp_send_json_success( $reply );
}
/* ---------------- editor surfaces ---------------- */
/** What both editor scripts need, as one object. */
private function script_data( $post_id ) {
return array(
'action' => 'altorewrite_rewrite',
'nonce' => wp_create_nonce( 'altorewrite_rewrite' ),
'postId' => (int) $post_id,
'tones' => self::TONES,
'tone' => $this->opts()['tone'],
'maxBlocks' => self::MAX_BLOCKS,
'quotaHtml' => altorewrite_shared_quota_box_html( $this->quota_args() ),
'settingsUrl' => admin_url( 'options-general.php?page=altorewrite' ),
);
}
/** The block editor's panel, only on the post and page editor (not the site or widget editors). */
public function block_editor_assets() {
$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
if ( ! $screen || 'post' !== $screen->base || ! in_array( $screen->post_type, array( 'post', 'page' ), true ) ) {
return;
}
$post = get_post();
if ( ! $post || ! current_user_can( 'edit_post', $post->ID ) ) {
return;
}
wp_enqueue_script(
'altorewrite-editor',
plugins_url( 'altorewrite-editor.js', __FILE__ ),
array( 'wp-plugins', 'wp-edit-post', 'wp-element', 'wp-components', 'wp-data', 'wp-util' ),
self::VERSION,
true
);
wp_add_inline_script( 'altorewrite-editor', 'window.altorewriteData = ' . wp_json_encode( $this->script_data( $post->ID ) ) . ';', 'before' );
}
/** The classic editor's box script. The box itself is hidden in the block editor (__back_compat_meta_box). */
public function classic_editor_assets( $hook ) {
if ( 'post.php' !== $hook && 'post-new.php' !== $hook ) {
return;
}
$screen = get_current_screen();
if ( ! $screen || $screen->is_block_editor() || ! in_array( $screen->post_type, array( 'post', 'page' ), true ) ) {
return;
}
$post = get_post();
if ( ! $post ) {
return;
}
wp_enqueue_script( 'altorewrite-classic', plugins_url( 'altorewrite-classic.js', __FILE__ ), array( 'jquery', 'wp-util' ), self::VERSION, true );
wp_add_inline_script( 'altorewrite-classic', 'window.altorewriteData = ' . wp_json_encode( $this->script_data( $post->ID ) ) . ';', 'before' );
}
public function meta_box() {
add_meta_box(
'altorewrite_box',
'AltoRewrite',
array( $this, 'render_meta_box' ),
array( 'post', 'page' ),
'side',
'default',
array( '__back_compat_meta_box' => true )
);
}
/** The classic editor's box. Its controls are wired by altorewrite-classic.js. */
public function render_meta_box( $post ) {
$o = $this->opts();
echo '
Select text in the editor, choose a tone, then click Rewrite selection.
';
echo '
';
echo '';
echo '';
echo altorewrite_shared_quota_box_html( $this->quota_args() ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- built from escaped parts.
echo '';
}
/**
* Arguments for the shared free-allowance notices (QW1). AltoRewrite has no automatic work, so
* nothing is named as paused beyond the rewrites themselves, the wall stays off the Dashboard,
* and the near-limit line lives only in the plugin's own editor box (WordPress.org Guideline 11).
*
* @return array
*/
private function quota_args() {
return array(
'slug' => 'altorewrite',
'name' => 'AltoRewrite',
'noun' => 'rewrites',
'cta' => 'Upgrade to Pro',
'paused' => '',
'capability' => 'edit_posts',
'work_screens' => array( 'post', 'page' ),
'wall_on_dashboard' => false,
'near_limit_notice' => false,
);
}
public function quota_notices() {
altorewrite_shared_quota_notices( $this->quota_args() );
}
/** P3: the review prompt reaches the screen where the work happens, not only Settings. */
public function work_surface_review_prompt() {
$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
if ( ! $screen || 'post' !== $screen->base || ! in_array( $screen->post_type, array( 'post', 'page' ), true ) ) {
return;
}
altorewrite_shared_review_prompt( 'altorewrite', 'AltoRewrite' );
}
public function action_links( $links ) {
return altorewrite_shared_settings_link( $links, admin_url( 'options-general.php?page=altorewrite' ) );
}
public function ruac_welcome() {
altorewrite_shared_welcome_notice( array(
'slug' => 'altorewrite',
'name' => 'AltoRewrite',
'capability' => 'edit_posts',
'body' => 'Open any post and select the blocks or text you want to change. In the block editor, click the AltoRewrite pen icon at the top right; in the classic editor, use the AltoRewrite box beside the editor.',
'settings_url' => admin_url( 'options-general.php?page=altorewrite' ),
// Guideline 11: greet on the screens a new install lands on, not on every admin screen.
'screens' => array( 'plugins', 'dashboard' ),
) );
}
}
register_activation_hook( __FILE__, 'altorewrite_on_activate' );
function altorewrite_on_activate() {
// W1: arm the welcome notice; without this the notice renders for nobody.
altorewrite_shared_welcome_arm( 'altorewrite' );
}
new AltoRewrite();