array( 'integer', 'string' ), 'description' => 'A content id from wp_list_content / wp_search_content, or "options:" for an options page.', ); public static function register( Tools $tools ) { $tools->register( 'wp_update_field', array( 'description' => 'Change one field of a page/post or options page, using a path exactly as returned by wp_get_content. A restore point is saved first. Returns the value before and after. Tell the person what changed.' . Read_Tools::SITE_DATA, 'input_schema' => array( 'type' => 'object', 'properties' => array( 'id' => self::ID_SCHEMA, 'path' => array( 'type' => 'string' ), 'value' => array( 'description' => 'The new value, of the field\'s type: text, a number, true/false, an image id, or {"url","title","target"} for links.' ), 'expected' => array( 'description' => 'Optional: the value you read with wp_get_content. If the field holds something else now (someone edited or reordered the page since), nothing is changed.' ), ), 'required' => array( 'id', 'path', 'value' ), 'additionalProperties' => false, ), 'handler' => array( self::class, 'update_field' ), ) ); $tools->register( 'wp_replace_text', array( 'description' => 'Replace a piece of text in a page/post (or options page) wherever it appears in its editable fields — "change X to Y". Refuses when the text appears more than once unless all is true, listing where it was found; a path limits it to one field. A restore point is saved before each changed field.' . Read_Tools::SITE_DATA, 'input_schema' => array( 'type' => 'object', 'properties' => array( 'id' => self::ID_SCHEMA, 'find' => array( 'type' => 'string' ), 'replace' => array( 'type' => 'string' ), 'path' => array( 'type' => 'string', 'description' => 'Optional: only this field.' ), 'all' => array( 'type' => 'boolean', 'description' => 'Replace every occurrence (default false: exactly one must exist).' ), ), 'required' => array( 'id', 'find', 'replace' ), 'additionalProperties' => false, ), 'handler' => array( self::class, 'replace_text' ), ) ); $tools->register( 'wp_create_draft', array( 'description' => 'Create a new page/post (or other content type) as a draft — never published: the person reviews it in WordPress or asks to publish it with wp_update_status. Optional HTML body and excerpt.', 'input_schema' => array( 'type' => 'object', 'properties' => array( 'post_type' => array( 'type' => 'string' ), 'title' => array( 'type' => 'string' ), 'body' => array( 'type' => 'string', 'description' => 'HTML for the body.' ), 'excerpt' => array( 'type' => 'string' ), ), 'required' => array( 'post_type', 'title' ), 'additionalProperties' => false, ), 'handler' => array( self::class, 'create_draft' ), ) ); $tools->register( 'wp_update_status', array( 'description' => 'Publish, unpublish (draft), send for review (pending), make private, or move to the trash. Needs the matching WordPress permission. Always confirm with the person first.', 'input_schema' => array( 'type' => 'object', 'properties' => array( 'id' => array( 'type' => array( 'integer', 'string' ) ), 'status' => array( 'type' => 'string', 'enum' => array( 'draft', 'pending', 'publish', 'private', 'trash' ) ), ), 'required' => array( 'id', 'status' ), 'additionalProperties' => false, ), 'handler' => array( self::class, 'update_status' ), ) ); } private static function is_options( $id ) { return is_string( $id ) && 0 === strpos( $id, 'options:' ); } /** Result shape shared by the write tools: what changed, how to see it, how to undo it. */ private static function done( $id, array $changes, $message ) { $out = array( 'id' => $id, 'changes' => $changes, 'message' => $message, ); if ( ! self::is_options( $id ) ) { $out['link'] = get_permalink( (int) $id ); } $snapshots = array_filter( array_column( $changes, 'snapshot_id' ) ); foreach ( array_unique( $snapshots ) as $snapshot ) { Snapshots::seal( (int) $snapshot ); // what this change left: its undo may put back exactly the state before } if ( $snapshots ) { $out['undo'] = 'wp_restore_snapshot with snapshot_id ' . min( $snapshots ) . ' puts it back as it was before.'; } return apply_filters( 'adibridge_write_result', $out, $id ); } public static function update_field( array $args ) { // Only someone who may write the target can make others wait for it. return Lock::with( Snapshots::authorise( $args['id'] ), static function () use ( $args ) { return self::update_field_locked( $args ); } ); } private static function update_field_locked( array $args ) { $id = $args['id']; if ( array_key_exists( 'expected', $args ) ) { $now = self::is_options( $id ) ? Content::option_field( substr( $id, 8 ), $args['path'] ) : Content::field( Content::post( $id ), $args['path'] ); if ( ! Field_Types::still( $now['value'], $args['expected'] ) ) { throw new Tool_Error( esc_html( "{$args['path']} changed since you read it (it now holds " . wp_json_encode( $now['value'] ) . '). Nothing was changed; read the page again with wp_get_content.' ) ); } } $change = self::is_options( $id ) ? Content::option_update( substr( $id, 8 ), $args['path'], $args['value'] ) : Content::update( Content::post( $id ), $args['path'], $args['value'] ); return self::done( self::is_options( $id ) ? $id : (int) $id, array( $change ), "Changed {$args['path']}." ); } /** * Tags (with quoted attribute values, which may hold ">"), comments (block settings included) * and shortcodes ([gallery link="…"], [et_pb_image src="…"], registered or not): what * wp_replace_text never rewrites in a field that holds HTML. */ const MARKUP = '/(|<\/?[a-zA-Z](?:[^>"\']|"[^"]*"|\'[^\']*\')*>|\[\/?[a-zA-Z_][\w-]*(?:[^\]"\']|"[^"]*"|\'[^\']*\')*\])/s'; public static function replace_text( array $args ) { // Only someone who may write the target can make others wait for it. return Lock::with( Snapshots::authorise( $args['id'] ), static function () use ( $args ) { return self::replace_text_locked( $args ); } ); } private static function replace_text_locked( array $args ) { $id = $args['id']; $find = (string) $args['find']; if ( '' === $find ) { throw new Tool_Error( 'Say what text to find.' ); } $all = ! empty( $args['all'] ); $options = self::is_options( $id ); $slug = $options ? substr( $id, 8 ) : null; $post = $options ? null : Content::post( $id ); $fields = $options ? Content::option_fields( $slug ) : Content::fields( $post ); $replace = (string) $args['replace']; // The text may be stored with HTML entities (& as &): look for every spelling at once, // longest first, and put the replacement back in the spelling that was found. $needles = array_unique( array( $find, esc_html( $find ), htmlspecialchars( $find, ENT_NOQUOTES ) ) ); usort( $needles, static function ( $a, $b ) { return strlen( $b ) - strlen( $a ); } ); $pattern = '/' . implode( '|', array_map( static function ( $n ) { return preg_quote( $n, '/' ); }, $needles ) ) . '/'; // Where it occurs, in writable text fields only (never raw stored data). $hits = array(); $hidden = array(); foreach ( $fields as $field ) { if ( ! $field['writable'] || ! is_string( $field['value'] ) || ! in_array( $field['type'], array( 'text', 'textarea', 'html', 'url', 'email' ), true ) ) { continue; } // Store data (prices, sale dates, SKU) is never rewritten by a text replacement: one field at a time, with wp_update_field. if ( 0 === strpos( $field['path'], 'woocommerce:' ) ) { continue; } if ( isset( $args['path'] ) && $args['path'] !== $field['path'] ) { continue; } // A web or email address is one value: replace in all of it. Anything else may hold HTML. $markup = ! in_array( $field['type'], array( 'url', 'email' ), true ); list( $value, $count, $in_markup ) = self::replace_in( $field['value'], $pattern, $find, $replace, $markup ); if ( $count ) { $hits[] = array( 'field' => $field, 'value' => $value, 'count' => $count ); } if ( $in_markup ) { $hidden[] = $field['path'] . ( $in_markup > 1 ? " ({$in_markup}×)" : '' ); } } $total = array_sum( array_column( $hits, 'count' ) ); if ( 0 === $total ) { if ( $hidden ) { throw new Tool_Error( esc_html( "\"$find\" only appears inside markup — a link address, image source, class name, block setting or [shortcode] — in " . implode( ', ', $hidden ) . ', not in text a visitor reads. Nothing was changed. To change it there, read the field with wp_get_content and set its new value with wp_update_field.' ) ); } throw new Tool_Error( esc_html( "\"$find\" doesn't appear in any editable field" . ( isset( $args['path'] ) ? " of {$args['path']}" : '' ) . '. Use wp_search_content to find where the text lives (it may be inside a word with different formatting, or in a read-only field).' ) ); } if ( $total > 1 && ! $all ) { $where = implode( ', ', array_map( static function ( $h ) { return $h['field']['path'] . ( $h['count'] > 1 ? " ({$h['count']}×)" : '' ); }, $hits ) ); $how = isset( $args['path'] ) ? 'Pass all=true to replace every occurrence in that field.' : 'Pass a path to change one field, or all=true to replace every occurrence.'; throw new Tool_Error( esc_html( "\"$find\" appears $total times ($where). Nothing was changed. $how" ) ); } // Every field must be able to take its new value before any is written: a refusal at the // third field must not leave the first two changed. foreach ( $hits as $hit ) { if ( $options ) { Content::check_option_update( $slug, $hit['field']['path'], $hit['value'] ); } else { Content::check_update( $post, $hit['field']['path'], $hit['value'] ); } } // One restore point for the whole replacement: it is the undo and the roll-back point, and a // replacement over more fields than the history cap can't prune it (or older history). $target = $options ? $id : $post->ID; $snapshot = Snapshots::take( $target, 'wp_replace_text "' . $find . '"', $find, 'before_replace' ); $changes = array(); foreach ( $hits as $hit ) { try { $changes[] = $options ? Content::option_update( $slug, $hit['field']['path'], $hit['value'], $snapshot ) : Content::update( $post, $hit['field']['path'], $hit['value'], $snapshot ); } catch ( Tool_Error $e ) { self::undo_partial( $snapshot, $changes, count( $hits ), $hit['field']['path'], $e ); } catch ( \Throwable $e ) { // Another plugin's save hook failed: put the earlier fields back all the same. Log::line( 'wp_replace_text failed at ' . $hit['field']['path'] . ': ' . Tool_Error::text( $e ) . ' @ ' . $e->getFile() . ':' . $e->getLine() ); self::undo_partial( $snapshot, $changes, count( $hits ), $hit['field']['path'], new Tool_Error( esc_html( 'the site failed while saving it (' . Log::where() . ').' ) ) ); } } Snapshots::kept( $target ); $message = "Replaced $total occurrence" . ( 1 === $total ? '' : 's' ) . " of \"$find\"."; if ( $hidden ) { $message .= ' Left as they are: occurrences inside markup (link addresses, image sources, block settings, [shortcodes]) in ' . implode( ', ', $hidden ) . '.'; } return self::done( $options ? $id : (int) $id, $changes, $message ); } /** * Replace $pattern in the text of $value but never inside its tags or comments — a link's * href, an image's src, a class, a block's settings: "2023 → 2024" must not rewrite * /news-2023/. With $markup false the whole value is text (a web or email address). * * @return array{0: string, 1: int, 2: int} The new value, replacements made, occurrences left in markup. */ private static function replace_in( $value, $pattern, $find, $replace, $markup ) { $parts = $markup ? preg_split( self::MARKUP, $value, -1, PREG_SPLIT_DELIM_CAPTURE ) : array( $value ); if ( false === $parts ) { throw new Tool_Error( 'This content is too large or tangled to search safely. Nothing was changed. Use wp_update_field on the field instead.' ); } $count = 0; $hidden = 0; foreach ( $parts as $i => $part ) { if ( $i % 2 ) { $hidden += preg_match_all( $pattern, $part ); continue; } $parts[ $i ] = preg_replace_callback( $pattern, static function ( $m ) use ( $find, $replace ) { return $m[0] === $find ? $replace : esc_html( $replace ); }, $part, -1, $n ); $count += $n; } return array( implode( '', $parts ), $count, $hidden ); } /** * A write failed: put the target back from this replacement's restore point (Content already * undid the failing field itself) and say so. If even that doesn't hold, say exactly how much * changed and how to undo it. */ private static function undo_partial( $snapshot, array $changes, $of, $path, Tool_Error $e ) { $done = count( $changes ); if ( Snapshots::roll_back( $snapshot ) ) { if ( ! $done ) { throw $e; } // Not "nothing changed": WordPress ran its save hooks for those fields (and may keep revisions). throw new Tool_Error( esc_html( "$path was refused: " . Tool_Error::text( $e ) . " The $done field" . ( 1 === $done ? '' : 's' ) . ' this replacement had already changed were put back too: the content is as it was before.' ) ); } Log::line( "could not roll back a partial wp_replace_text ($done of $of fields)" ); $paths = $done ? ' (' . implode( ', ', array_column( $changes, 'path' ) ) . ')' : ''; throw new Tool_Error( esc_html( "$done of $of fields were changed$paths before $path was refused: " . Tool_Error::text( $e ) . " Putting them back didn't fully work. wp_restore_snapshot with snapshot_id $snapshot puts it back as it was before this replacement." ) ); } public static function create_draft( array $args ) { $types = Content::post_types(); if ( ! isset( $types[ $args['post_type'] ] ) ) { throw new Tool_Error( esc_html( "\"{$args['post_type']}\" is not a content type ADI can create. Types: " . implode( ', ', array_keys( $types ) ) . '.' ) ); } $type = $types[ $args['post_type'] ]; if ( ! current_user_can( $type->cap->create_posts ) ) { $user = wp_get_current_user(); throw new Tool_Error( esc_html( "The WordPress user {$user->user_login} is not allowed to create " . strtolower( $type->labels->name ) . '.' ) ); } $title = trim( (string) $args['title'] ); if ( preg_match( '/[\r\n]/', $title ) ) { throw new Tool_Error( 'The title is a single line; remove the line breaks. Nothing was created.' ); } $data = array( 'post_type' => $args['post_type'], 'post_status' => 'draft', // always: publishing is a separate, confirmed step 'post_title' => $title, 'post_author' => get_current_user_id(), ); if ( isset( $args['body'] ) ) { $data['post_content'] = (string) $args['body']; } if ( isset( $args['excerpt'] ) ) { $data['post_excerpt'] = (string) $args['excerpt']; } // Refuse markup WordPress would strip from this user rather than create a quietly different // page: titles are filtered like comments (wp_kses_data), body and excerpt like posts. if ( ! current_user_can( 'unfiltered_html' ) ) { $rules = array( 'post_title' => array( 'title', 'wp_kses_data' ), 'post_content' => array( 'body', 'wp_kses_post' ), 'post_excerpt' => array( 'excerpt', 'wp_kses_post' ) ); $lost = array(); foreach ( $rules as $col => $rule ) { if ( isset( $data[ $col ] ) && ! Html::equivalent( call_user_func( $rule[1], $data[ $col ] ), $data[ $col ] ) ) { $lost[] = $rule[0]; } } if ( $lost ) { throw new Tool_Error( esc_html( 'The ' . implode( ' and ', $lost ) . ' ha' . ( 1 === count( $lost ) ? 's' : 've' ) . ' markup (scripts, iframes, forms) this WordPress user isn\'t allowed to save. Nothing was created.' ) ); } } // Nobody creates scripts, embeds or forms through the bridge, whatever their role. foreach ( array( 'post_title' => 'The title', 'post_content' => 'The body', 'post_excerpt' => 'The excerpt' ) as $col => $what ) { if ( isset( $data[ $col ] ) ) { Html::refuse_unsafe_additions( $data[ $col ], '', $what ); } } $id = wp_insert_post( wp_slash( $data ), true ); if ( is_wp_error( $id ) ) { throw new Tool_Error( esc_html( 'WordPress refused to create it: ' . $id->get_error_message() ) ); } do_action( 'adibridge_after_create', $id ); return array( 'id' => $id, 'status' => get_post_status( $id ), 'edit' => get_edit_post_link( $id, 'raw' ), 'preview' => get_preview_post_link( $id ), 'message' => 'Created a draft. It is not on the live site until it is published.', ); } public static function update_status( array $args ) { // Only someone who may write the target can make others wait for it. return Lock::with( Snapshots::authorise( $args['id'] ), static function () use ( $args ) { return self::update_status_locked( $args ); } ); } private static function update_status_locked( array $args ) { $change = Content::set_status( Content::post( $args['id'] ), $args['status'] ); // Say what WordPress did, not what was asked: publishing a post dated ahead schedules it. if ( 'future' === $change['after'] ) { $message = 'Scheduled for ' . get_date_from_gmt( get_post_field( 'post_date_gmt', $change['id'] ), 'Y-m-d H:i' ) . '; it goes live then.'; } else { $labels = array( 'publish' => 'published', 'draft' => 'unpublished (draft)', 'pending' => 'sent for review', 'private' => 'made private', 'trash' => 'moved to the trash' ); $message = 'Now ' . $labels[ $change['after'] ] . '.'; } return self::done( (int) $args['id'], array( $change ), $message ); } }