` が * そのまま残っている。旧プラグインを無効化すると、このブロックは * 「未登録ブロック」になり、フロントでは中身(=有料本文)が**素で全部出る**。 * これは有料記事が無料で読める状態であり、移行の最大の事故になる。 * * したがって旧ブロック名を**サーバー側で** register_block_type し、 * render_callback を新実装へ委譲する。エディタ用 JS は同梱しない * (registerBlockType を新たに増やさない)。理由は3つ。 * - 旧ブロックの編集 UI を維持することは目的ではない。目的は「表示が壊れないこと」 * - エディタ用 JS を足すと、廃止予定のブロックが今後もインサータに残る * - 置換は JS ではなくサーバー側の1操作(下の convert_post)で足りる * * 代わりに、旧ブロックを含む記事を編集画面で開いたときは * 管理画面通知で警告し、そこから1クリックで acscw/ ブロックへ置換できるようにする。 * * --------------------------------------------------------------------------- * 価格の読み替え * --------------------------------------------------------------------------- * v2 は価格を「ブロック属性 price」と「投稿メタ `_acs_article_price`」の * 2か所に持っていた(描画のたびにメタを上書きしていた)。 * v3 の正本は `_acscw_price` 1か所だけなので、 * 1. `_acscw_price` があればそれ(v3 の正本が最優先) * 2. 旧ブロックを描画中なら、その属性 price * 3. 旧メタ `_acs_article_price` * の順で読み替える。置換を実行した時点で 1 に一本化される。 */ class ACSCW_Legacy_Blocks { /** 旧 Paywall ブロック名。 */ const BLOCK_PAYWALL = 'acs-wc/paywall'; /** 旧投げ銭ブロック名。 */ const BLOCK_TIPPING = 'acs-wc/tipping'; /** 旧価格メタ。 */ const META_LEGACY_PRICE = '_acs_article_price'; /** 旧商品メタ(対応コンテンツID)。移行時の実額復元で使う。 */ const META_LINKED_POST_ID = '_acs_linked_post_id'; /** 置換の admin-post アクション。 */ const ACTION_CONVERT = 'acscw_convert_blocks'; /** 旧 → 新のブロック名対応。 */ const BLOCK_MAP = array( self::BLOCK_PAYWALL => 'acscw/paywall', self::BLOCK_TIPPING => 'acscw/tipping', ); /** * 描画中の旧 Paywall ブロックの価格属性。描画外は 0。 * * @var float */ private $rendering_price = 0.0; /** * フックを登録する。 */ public function __construct() { // 21 = ACSCW_Blocks::register_blocks(20)の直後。新ブロックを先に登録させる。 add_action( 'init', array( $this, 'register_blocks' ), 21 ); add_filter( 'acscw_content_price', array( $this, 'filter_content_price' ), 10, 2 ); add_action( 'admin_notices', array( $this, 'render_editor_notice' ) ); add_action( 'admin_post_' . self::ACTION_CONVERT, array( $this, 'handle_convert' ) ); } /* * ----------------------------------------------------------------------- * 登録 * ----------------------------------------------------------------------- */ /** * 旧ブロック名を返す。 * * @return string[] */ public static function get_block_names() { return array_keys( self::BLOCK_MAP ); } /** * 旧ブロックをサーバー側で登録する。 * * 旧プラグインが有効で既に登録済みなら**何もしない**。 * 同じブロック名を二重登録すると WordPress が _doing_it_wrong を出すうえ、 * どちらのコールバックが勝つかが読み込み順に依存してしまう。 * * @return void */ public function register_blocks() { if ( ! function_exists( 'register_block_type' ) || ! class_exists( 'WP_Block_Type_Registry' ) ) { return; } $registry = WP_Block_Type_Registry::get_instance(); if ( ! $registry->is_registered( self::BLOCK_PAYWALL ) ) { register_block_type( self::BLOCK_PAYWALL, array( 'api_version' => 3, 'title' => __( 'Paid Area (previous version)', 'acs-content-for-woocommerce' ), 'description' => __( 'A paid area created by the previous version. It is rendered by the new implementation.', 'acs-content-for-woocommerce' ), 'category' => 'widgets', 'icon' => 'lock', 'supports' => array( 'html' => false, 'inserter' => false, ), 'attributes' => array( 'price' => array( 'type' => 'number', 'default' => 0, ), 'buttonText' => array( 'type' => 'string', 'default' => '', ), 'buttonColor' => array( 'type' => 'string', 'default' => '', ), 'showPrice' => array( 'type' => 'boolean', 'default' => true, ), ), 'render_callback' => array( $this, 'render_paywall' ), ) ); } if ( ! $registry->is_registered( self::BLOCK_TIPPING ) ) { register_block_type( self::BLOCK_TIPPING, array( 'api_version' => 3, 'title' => __( 'Tip Jar (previous version)', 'acs-content-for-woocommerce' ), 'description' => __( 'A tip jar block created by the previous version. It is rendered by the new implementation.', 'acs-content-for-woocommerce' ), 'category' => 'widgets', 'icon' => 'heart', 'supports' => array( 'html' => false, 'inserter' => false, ), 'attributes' => array( 'title' => array( 'type' => 'string', 'default' => '', ), 'amounts' => array( 'type' => 'array', 'default' => array(), ), 'showStats' => array( 'type' => 'boolean', 'default' => true, ), ), 'render_callback' => array( $this, 'render_tipping' ), ) ); } } /* * ----------------------------------------------------------------------- * レンダリング(新実装へ委譲する) * ----------------------------------------------------------------------- */ /** * 旧 Paywall ブロックを描画する。 * * 旧属性を新属性へ読み替えたうえで ACSCW_Paywall::render() を呼ぶ。 * 独自の描画は一切しない(箱が2種類あると、片方だけ直す事故が起きる)。 * * @param array $attributes 旧ブロック属性。 * @param string $content 有料本文(未購入者には空で渡る)。 * @param WP_Block|null $block ブロックインスタンス。 * @return string */ public function render_paywall( $attributes, $content = '', $block = null ) { $paywall = ACSCW_Plugin::instance()->get( 'paywall' ); if ( ! $paywall instanceof ACSCW_Paywall ) { // 新実装が居ない状況で有料本文をそのまま返すことは絶対にしない。 return ''; } $attributes = (array) $attributes; $this->rendering_price = self::read_price_attribute( $attributes ); $html = $paywall->render( self::map_paywall_attributes( $attributes ), (string) $content, $block ); $this->rendering_price = 0.0; return $html; } /** * 旧投げ銭ブロックを描画する。 * * 金額セットは属性ではなく「設定 › 全般」の金額セットを使う。 * v2 は記事ごとの任意金額から商品を都度生成していて、 * 未認証で商品を作れる口(🟠F)と孤児商品の温床になっていた。 * * @param array $attributes 旧ブロック属性。 * @param string $content 内容(未使用)。 * @param WP_Block|null $block ブロックインスタンス。 * @return string */ public function render_tipping( $attributes, $content = '', $block = null ) { $tipping = ACSCW_Plugin::instance()->get( 'tipping' ); if ( ! $tipping instanceof ACSCW_Tipping ) { return ''; } return $tipping->render( self::map_tipping_attributes( (array) $attributes ), (string) $content, $block ); } /** * 旧 Paywall 属性を新 Paywall 属性へ読み替える。 * * price は新属性に持たせない(正本は `_acscw_price`)。 * buttonColor は捨てる。色はテーマ変数を継承する方針のため(再設計案 §3-4)。 * * @param array $attributes 旧属性。 * @return array 新属性。 */ public static function map_paywall_attributes( $attributes ) { $mapped = array( 'showPrice' => ! isset( $attributes['showPrice'] ) || (bool) $attributes['showPrice'], ); if ( isset( $attributes['buttonText'] ) && is_scalar( $attributes['buttonText'] ) ) { $mapped['buttonText'] = (string) $attributes['buttonText']; } return $mapped; } /** * 旧投げ銭属性を新投げ銭属性へ読み替える。 * * @param array $attributes 旧属性。 * @return array 新属性。 */ public static function map_tipping_attributes( $attributes ) { $mapped = array(); if ( isset( $attributes['title'] ) && is_scalar( $attributes['title'] ) ) { $mapped['title'] = (string) $attributes['title']; } return $mapped; } /** * 旧属性から価格を読む。 * * @param array $attributes 旧属性。 * @return float */ public static function read_price_attribute( $attributes ) { if ( ! isset( $attributes['price'] ) || ! is_scalar( $attributes['price'] ) ) { return 0.0; } return ACSCW_Products::normalize_amount( $attributes['price'] ); } /* * ----------------------------------------------------------------------- * 価格の読み替え * ----------------------------------------------------------------------- */ /** * `_acscw_price` が無いコンテンツで、旧価格を代替として返す。 * * @param float $price 既定の判定結果。 * @param int $post_id コンテンツID。 * @return float */ public function filter_content_price( $price, $post_id ) { $post_id = absint( $post_id ); if ( 0 === $post_id ) { return $price; } // v3 の正本が入っていれば、旧値は一切見ない。 $own = get_post_meta( $post_id, ACSCW_Products::POST_META_PRICE, true ); if ( '' !== $own && null !== $own && ACSCW_Products::normalize_amount( $own ) > 0 ) { return $price; } if ( $this->rendering_price > 0 ) { return $this->rendering_price; } $legacy = ACSCW_Products::normalize_amount( get_post_meta( $post_id, self::META_LEGACY_PRICE, true ) ); return ( $legacy > 0 ) ? $legacy : $price; } /* * ----------------------------------------------------------------------- * 検出と置換 * ----------------------------------------------------------------------- */ /** * 本文に旧ブロックが含まれるかどうか。 * * @param string $content 本文。 * @return bool */ public static function content_has_legacy_blocks( $content ) { $content = (string) $content; foreach ( self::get_block_names() as $name ) { if ( false !== strpos( $content, 'wp:' . $name ) ) { return true; } } return false; } /** * コンテンツが旧ブロックを含むかどうか。 * * @param int $post_id コンテンツID。 * @return bool */ public static function post_has_legacy_blocks( $post_id ) { $post = get_post( absint( $post_id ) ); if ( ! $post || ! isset( $post->post_content ) ) { return false; } return self::content_has_legacy_blocks( $post->post_content ); } /** * 旧ブロックを含むコンテンツIDを返す。 * * @param int $limit 取得上限。 * @return int[] */ public static function get_legacy_post_ids( $limit = 200 ) { global $wpdb; $limit = max( 1, absint( $limit ) ); $like = '%' . $wpdb->esc_like( 'wp:acs-wc/' ) . '%'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE %s AND post_status != 'trash' ORDER BY ID ASC LIMIT %d", $like, $limit ) ); return array_map( 'absint', (array) $ids ); } /** * 1コンテンツの旧ブロックを新ブロックへ置換する。 * * ブロック名の文字列置換ではなく parse → 変換 → serialize で行う。 * 文字列置換だと、本文中に同じ文字列があるだけの箇所まで書き換わる。 * * 価格属性は `_acscw_price` へ移し、置換後は v3 の正本1か所だけになる。 * * @param int $post_id コンテンツID。 * @return bool 置換したら true。対象外・失敗なら false。 */ public static function convert_post( $post_id ) { $post_id = absint( $post_id ); $post = get_post( $post_id ); if ( ! $post || ! isset( $post->post_content ) ) { return false; } if ( ! self::content_has_legacy_blocks( $post->post_content ) ) { return false; } if ( ! function_exists( 'parse_blocks' ) || ! function_exists( 'serialize_blocks' ) ) { return false; } $price = 0.0; $blocks = self::convert_blocks( parse_blocks( $post->post_content ), $price ); $content = serialize_blocks( $blocks ); if ( $content === $post->post_content ) { return false; } // 価格の引っ越しは本文の書き換えより先に行う。 // 本文だけ新ブロックになって価格が消える中間状態を作らないため。 if ( $price > 0 ) { $own = get_post_meta( $post_id, ACSCW_Products::POST_META_PRICE, true ); if ( '' === $own || null === $own || ACSCW_Products::normalize_amount( $own ) <= 0 ) { update_post_meta( $post_id, ACSCW_Products::POST_META_PRICE, $price ); } } $updated = wp_update_post( array( 'ID' => $post_id, 'post_content' => $content, ), true ); return ! is_wp_error( $updated ) && $updated > 0; } /** * パース済みブロック列の旧ブロック名を新ブロック名へ差し替える。 * * @param array $blocks parse_blocks() の結果。 * @param float $price 見つかった旧価格属性(参照渡し・最初の1つ)。 * @return array */ public static function convert_blocks( $blocks, &$price ) { $out = array(); foreach ( (array) $blocks as $block ) { if ( ! is_array( $block ) ) { $out[] = $block; continue; } $name = isset( $block['blockName'] ) ? (string) $block['blockName'] : ''; if ( self::BLOCK_PAYWALL === $name ) { $attrs = isset( $block['attrs'] ) ? (array) $block['attrs'] : array(); $found = self::read_price_attribute( $attrs ); if ( $found > 0 && $price <= 0 ) { $price = $found; } $block['blockName'] = self::BLOCK_MAP[ self::BLOCK_PAYWALL ]; $block['attrs'] = self::map_paywall_attributes( $attrs ); } elseif ( self::BLOCK_TIPPING === $name ) { $block['blockName'] = self::BLOCK_MAP[ self::BLOCK_TIPPING ]; $block['attrs'] = self::map_tipping_attributes( isset( $block['attrs'] ) ? (array) $block['attrs'] : array() ); } if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) ) { $block['innerBlocks'] = self::convert_blocks( $block['innerBlocks'], $price ); } $out[] = $block; } return $out; } /* * ----------------------------------------------------------------------- * 編集画面の警告と置換ボタン * ----------------------------------------------------------------------- */ /** * 編集中のコンテンツに旧ブロックがあれば警告と置換ボタンを出す。 * * @return void */ public function render_editor_notice() { $post_id = self::get_edited_post_id(); if ( 0 === $post_id || ! current_user_can( 'edit_post', $post_id ) ) { return; } if ( ! self::post_has_legacy_blocks( $post_id ) ) { return; } echo '
'; printf( '

%s

', esc_html__( 'This post uses blocks from the previous version. Readers are unaffected, because rendering is handled by the new implementation, but the editor shows them as unsupported blocks. Replace them with the new blocks.', 'acs-content-for-woocommerce' ) ); echo '
'; wp_nonce_field( self::ACTION_CONVERT ); printf( '', esc_attr( self::ACTION_CONVERT ) ); printf( '', absint( $post_id ) ); printf( '

', esc_html__( 'Replace with the new blocks', 'acs-content-for-woocommerce' ) ); echo '
'; echo '
'; } /** * 編集画面で開いているコンテンツIDを返す。 * * @return int 編集画面でなければ 0。 */ private static function get_edited_post_id() { if ( ! is_admin() || ! function_exists( 'get_current_screen' ) ) { return 0; } $screen = get_current_screen(); if ( ! $screen || ! isset( $screen->base ) || 'post' !== $screen->base ) { return 0; } // 編集画面の post= は読み取りにしか使わない。権限は呼び出し側で必ず確認する。 // phpcs:ignore WordPress.Security.NonceVerification.Recommended return isset( $_GET['post'] ) ? absint( wp_unslash( $_GET['post'] ) ) : 0; } /** * 置換要求を処理する。 * * post_id を渡せば1件、渡さなければ検出できた全件を置換する。 * * @return void */ public function handle_convert() { check_admin_referer( self::ACTION_CONVERT ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- 直前で検証済み。 $post_id = isset( $_POST['post_id'] ) ? absint( wp_unslash( $_POST['post_id'] ) ) : 0; if ( $post_id > 0 ) { if ( ! current_user_can( 'edit_post', $post_id ) ) { wp_die( esc_html__( 'You do not have permission to perform this action.', 'acs-content-for-woocommerce' ), esc_html__( 'Permission denied', 'acs-content-for-woocommerce' ), array( 'response' => 403 ) ); } $converted = self::convert_post( $post_id ) ? 1 : 0; wp_safe_redirect( add_query_arg( 'acscw_converted', $converted, get_edit_post_link( $post_id, 'url' ) ) ); exit; } ACSCW_Admin::require_capability(); $converted = 0; foreach ( self::get_legacy_post_ids() as $id ) { if ( ! current_user_can( 'edit_post', $id ) ) { continue; } if ( self::convert_post( $id ) ) { ++$converted; } } wp_safe_redirect( ACSCW_Admin::page_url( ACSCW_Settings::PAGE_SLUG, array( 'tab' => 'data', 'acscw_message' => 'converted', 'acscw_count' => absint( $converted ), ) ) ); exit; } }