` を吐いていた(問題③)。 * - **未認証で叩ける口は「復旧リンクの送信」だけ。** v2 の * wp_ajax_nopriv_acs_wc_create_tip_product のような**生成系の未認証エンドポイントは持たない**(🟠F)。 * - 復旧エンドポイントは購入の有無で応答を変えない(メールアドレス存在確認器にしない)。 * 分岐はフェーズ2の ACSCW_Access_Token::request_access_link() の中に閉じている。 */ class ACSCW_Blocks { /** REST 名前空間。 */ const REST_NAMESPACE = 'acscw/v1'; /** アクセス復旧エンドポイントのルート。 */ const REST_ROUTE = '/access-link'; /** 復旧リクエストの nonce アクション名。 */ const NONCE_ACTION = 'acscw_access_link'; /** フロント CSS のハンドル。 */ const STYLE_HANDLE = 'acscw-frontend'; /** フロント JS のハンドル。 */ const SCRIPT_HANDLE = 'acscw-frontend'; /** 登録するブロック名とディレクトリ名の対応。 */ const BLOCKS = array( 'acscw/paywall' => 'paywall', 'acscw/tipping' => 'tipping', ); /** * フロント資産を登録済みかどうか。 * * @var bool */ private $assets_registered = false; /** * フロント資産をエンキュー済みかどうか。 * * @var bool */ private $assets_enqueued = false; /** * フックを登録する。 */ public function __construct() { /* * どちらも init。優先度に意味がある。 * 10 = ACSCW_Plugin::load_textdomain(翻訳の読み込み) * 11 = 価格メタ(説明文が翻訳済みになるよう、翻訳の後に登録する) * 20 = ブロック(エディタスクリプトへ設定値を渡すため、メタの後) */ add_action( 'init', array( $this, 'register_meta' ), 11 ); add_action( 'init', array( $this, 'register_blocks' ), 20 ); add_action( 'wp_enqueue_scripts', array( $this, 'register_frontend_assets' ), 5 ); add_action( 'wp_enqueue_scripts', array( $this, 'maybe_enqueue_frontend_assets' ), 20 ); add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) ); } /* * ----------------------------------------------------------------------- * 価格メタ * ----------------------------------------------------------------------- */ /** * 販売価格のメタを REST 経由で編集できるようにする。 * * `_acscw_price` は先頭アンダースコアの保護メタなので、 * show_in_rest と auth_callback をそろえないとエディタから書けない。 * * @return void */ public function register_meta() { if ( ! function_exists( 'register_post_meta' ) ) { return; } foreach ( ACSCW_Products::get_supported_post_types() as $post_type ) { register_post_meta( $post_type, ACSCW_Products::POST_META_PRICE, array( 'type' => 'number', 'description' => __( 'The price this article sells for. 0 means it is not for sale.', 'acs-content-for-woocommerce' ), 'single' => true, 'default' => 0, 'show_in_rest' => true, 'sanitize_callback' => array( 'ACSCW_Products', 'normalize_amount' ), 'auth_callback' => array( $this, 'can_edit_price' ), ) ); } } /** * 価格メタを書き換えてよいかどうか。 * * @param bool $allowed 既定の判定。 * @param string $meta_key メタキー。 * @param int $object_id 対象の投稿ID。 * @return bool */ public function can_edit_price( $allowed, $meta_key, $object_id = 0 ) { unset( $allowed, $meta_key ); return current_user_can( 'edit_post', absint( $object_id ) ); } /* * ----------------------------------------------------------------------- * ブロック登録 * ----------------------------------------------------------------------- */ /** * block.json からブロックを登録する。 * * @return void */ public function register_blocks() { if ( ! function_exists( 'register_block_type' ) ) { return; } foreach ( self::BLOCKS as $block_name => $dir_name ) { $dir = ACSCW_PLUGIN_DIR . 'blocks/' . $dir_name; if ( ! is_readable( $dir . '/block.json' ) ) { continue; } $registered = register_block_type( $dir, array( 'render_callback' => ( 'acscw/paywall' === $block_name ) ? array( $this, 'render_paywall' ) : array( $this, 'render_tipping' ), ) ); $this->setup_editor_script( $registered ); } } /** * エディタスクリプトに翻訳と設定値を渡す。 * * ハンドル名は block.json 登録時に WordPress が決めるため、 * 生成規則を推測せず、登録結果のオブジェクトから受け取る。 * * @param WP_Block_Type|false $block_type 登録結果。 * @return void */ private function setup_editor_script( $block_type ) { if ( ! $block_type || ! is_object( $block_type ) ) { return; } $handles = isset( $block_type->editor_script_handles ) ? (array) $block_type->editor_script_handles : array(); foreach ( $handles as $handle ) { if ( '' === (string) $handle ) { continue; } if ( function_exists( 'wp_set_script_translations' ) ) { wp_set_script_translations( $handle, 'acs-content-for-woocommerce', ACSCW_PLUGIN_DIR . 'languages' ); } wp_localize_script( $handle, 'acscwEditor', $this->get_editor_data() ); } } /** * エディタへ渡す設定値。 * * @return array */ private function get_editor_data() { $default_price = ACSCW_Products::normalize_amount( get_option( 'acscw_default_price', 0 ) ); $stats = $this->get_current_post_stats(); return array( 'priceMetaKey' => ACSCW_Products::POST_META_PRICE, 'defaultPrice' => $default_price, 'defaultPriceLabel' => ACSCW_Products::format_price_plain( $default_price ), 'tipAmountLabels' => $this->get_tip_amount_labels(), 'supportedPostTypes' => array_values( ACSCW_Products::get_supported_post_types() ), // 「この記事の実績」パネル。集計はフェーズ5の ACSCW_Stats が持つ。 'statsAvailable' => ! empty( $stats ), 'stats' => $stats, 'statsPlaceholder' => __( 'Sales and revenue appear once purchases start coming in.', 'acs-content-for-woocommerce' ), // 実績が無いときは購入者画面へのリンクも出さない(空の画面へ送らない)。 'buyersUrl' => ( $stats && class_exists( 'ACSCW_Admin' ) ) ? ACSCW_Admin::page_url( 'acscw-buyers' ) : '', 'buyersLabel' => __( 'View buyers', 'acs-content-for-woocommerce' ), ); } /** * 編集中コンテンツの実績を返す。 * * @return array|null 実績が無い、または権限が無い場合は null。 */ private function get_current_post_stats() { if ( ! is_admin() || ! class_exists( 'ACSCW_Stats' ) ) { return null; } // 編集画面の post= は読み取りにしか使わない。権限は必ず別途確認する。 // phpcs:ignore WordPress.Security.NonceVerification.Recommended $post_id = isset( $_GET['post'] ) ? absint( wp_unslash( $_GET['post'] ) ) : 0; if ( 0 === $post_id || ! current_user_can( 'edit_post', $post_id ) ) { return null; } $stats = ACSCW_Stats::get_post_stats( $post_id ); if ( $stats['sales'] <= 0 && $stats['tip'] <= 0 ) { return null; } return array( 'salesLabel' => sprintf( /* translators: %s: count. */ _n( '%s item', '%s items', (int) $stats['sales'], 'acs-content-for-woocommerce' ), number_format_i18n( $stats['sales'] ) ), 'revenueLabel' => ACSCW_Products::format_price_plain( $stats['revenue'] ), 'tipLabel' => ACSCW_Products::format_price_plain( $stats['tip'] ), 'tipCountLabel' => sprintf( /* translators: %s: count. */ _n( '%s item', '%s items', (int) $stats['tip_count'], 'acs-content-for-woocommerce' ), number_format_i18n( $stats['tip_count'] ) ), ); } /** * 投げ銭の金額を表示用文字列にした配列。 * * @return string[] */ private function get_tip_amount_labels() { $labels = array(); foreach ( ACSCW_Products::get_tip_amounts() as $amount ) { $labels[] = ACSCW_Products::format_price_plain( $amount ); } return $labels; } /* * ----------------------------------------------------------------------- * レンダーコールバック(実処理は各コンポーネントへ委譲する) * ----------------------------------------------------------------------- */ /** * Paywall ブロックを描画する。 * * @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 ''; } return $paywall->render( (array) $attributes, (string) $content, $block ); } /** * 投げ銭ブロックを描画する。 * * @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( (array) $attributes, (string) $content, $block ); } /* * ----------------------------------------------------------------------- * フロント資産 * ----------------------------------------------------------------------- */ /** * フロント資産を登録する(エンキューはしない)。 * * @return void */ public function register_frontend_assets() { if ( $this->assets_registered ) { return; } $this->assets_registered = true; wp_register_style( self::STYLE_HANDLE, ACSCW_PLUGIN_URL . 'assets/css/frontend.css', array(), ACSCW_VERSION ); wp_register_script( self::SCRIPT_HANDLE, ACSCW_PLUGIN_URL . 'assets/js/frontend.js', array(), ACSCW_VERSION, true ); } /** * ブロックのあるページでだけフロント資産をエンキューする。 * * v2 は is_singular('post') というだけで Paywall の無い記事にも CSS を出していた。 * v3 は has_block() を通ったページにしか出さない。 * * @return void */ public function maybe_enqueue_frontend_assets() { if ( ! self::current_page_has_blocks() ) { return; } $this->enqueue_frontend_assets(); } /** * 表示中のコンテンツにこのプラグインのブロックがあるかどうか。 * * @return bool */ public static function current_page_has_blocks() { if ( is_admin() || ! function_exists( 'has_block' ) ) { return false; } $post = get_post(); if ( ! $post || ! isset( $post->ID ) ) { return false; } foreach ( self::get_all_block_names() as $block_name ) { if ( has_block( $block_name, $post ) ) { return true; } } return false; } /** * 資産の要否を判定する対象ブロック名(新+旧)。 * * 旧ブロックしか置かれていない記事でもフロント CSS/JS が要る。 * ここに旧名が無いと、互換描画した箱が無スタイルで出る。 * * @return string[] */ public static function get_all_block_names() { $names = array_keys( self::BLOCKS ); if ( class_exists( 'ACSCW_Legacy_Blocks' ) ) { $names = array_merge( $names, ACSCW_Legacy_Blocks::get_block_names() ); } return $names; } /** * フロント資産をエンキューする。 * * レンダーコールバックからも呼ばれる(テンプレート・ウィジェット経由で * ブロックが描画され、has_block 判定に乗らなかった場合の保険)。 * 何度呼ばれても実処理は1回だけ。 * * @return void */ public function enqueue_frontend_assets() { if ( $this->assets_enqueued || is_admin() ) { return; } if ( ! $this->assets_registered ) { $this->register_frontend_assets(); } $this->assets_enqueued = true; wp_enqueue_style( self::STYLE_HANDLE ); wp_enqueue_script( self::SCRIPT_HANDLE ); /* * 文言は PHP 側で翻訳済みの状態で渡す。 * フロント JS に wp-i18n を積むと、記事1本のために JS が増える。 * (翻訳の必要な JS は block.json の editorScript 側で、 * wp_set_script_translations() を適用してある。) */ wp_localize_script( self::SCRIPT_HANDLE, 'acscwFront', $this->get_frontend_data() ); } /** * フロント資産をエンキューする(静的ショートカット)。 * * @return void */ public static function ensure_assets() { $blocks = ACSCW_Plugin::instance()->get( 'blocks' ); if ( $blocks instanceof self ) { $blocks->enqueue_frontend_assets(); } } /** * フロント JS へ渡すデータ。 * * @return array */ private function get_frontend_data() { $post_id = 0; $post = get_post(); if ( $post && isset( $post->ID ) ) { $post_id = absint( $post->ID ); } return array( 'endpoint' => esc_url_raw( rest_url( self::REST_NAMESPACE . self::REST_ROUTE ) ), 'nonce' => wp_create_nonce( self::NONCE_ACTION ), 'postId' => $post_id, 'i18n' => array( 'modalTitle' => __( 'Restore access', 'acs-content-for-woocommerce' ), 'modalLede' => __( 'Enter the email address you used at checkout and we will send you a link to read with.', 'acs-content-for-woocommerce' ), 'emailLabel' => __( 'Email address', 'acs-content-for-woocommerce' ), 'submit' => __( 'Send the link', 'acs-content-for-woocommerce' ), 'sending' => __( 'Sending…', 'acs-content-for-woocommerce' ), 'close' => __( 'Close', 'acs-content-for-woocommerce' ), 'invalidEmail' => __( 'That email address is not valid.', 'acs-content-for-woocommerce' ), 'staleNonce' => __( 'This page has been open for a while. Reload it and try again.', 'acs-content-for-woocommerce' ), 'networkError' => __( 'The request failed. Please try again later.', 'acs-content-for-woocommerce' ), ), ); } /* * ----------------------------------------------------------------------- * アクセス復旧エンドポイント * ----------------------------------------------------------------------- */ /** * REST ルートを登録する。 * * 未認証で叩ける口はこれ1本だけ。**できるのは「メールを送る」ことだけ**で、 * 商品・注文・アクセス権を作る経路は一切持たない(v2 の🟠F の再発防止)。 * * @return void */ public function register_rest_routes() { register_rest_route( self::REST_NAMESPACE, self::REST_ROUTE, array( 'methods' => 'POST', 'callback' => array( $this, 'handle_access_link_request' ), 'permission_callback' => array( $this, 'check_access_link_permission' ), 'args' => array( 'email' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'post_id' => array( 'type' => 'integer', 'default' => 0, 'sanitize_callback' => 'absint', ), 'nonce' => array( 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ), ), ) ); } /** * 復旧リンク要求の permission_callback。 * * 未認証の読者が使う口なので capability は要求できない。 * その代わり、フロントで発行した nonce をここで検証する * (本処理へ進む前に必ず通る、リクエスト妥当性の関門)。 * * @param WP_REST_Request $request リクエスト。 * @return true|WP_Error */ public function check_access_link_permission( $request ) { $nonce = (string) $request->get_param( 'nonce' ); if ( ! wp_verify_nonce( $nonce, self::NONCE_ACTION ) ) { return new WP_Error( 'acscw_bad_nonce', __( 'This page has been open for a while. Reload it and try again.', 'acs-content-for-woocommerce' ), array( 'status' => 403 ) ); } return true; } /** * 復旧リンクの送信要求を処理する。 * * **購入があってもなくても同じ応答を返す。** * 差が出るのは「形式不正」と「レート超過」だけで、これは * メールアドレスの存在ではなくリクエストの妥当性に由来する情報しか漏らさない。 * * @param WP_REST_Request $request リクエスト。 * @return WP_REST_Response|WP_Error */ public function handle_access_link_request( $request ) { $token = ACSCW_Plugin::instance()->get( 'token' ); if ( ! $token instanceof ACSCW_Access_Token ) { return new WP_Error( 'acscw_not_ready', __( 'This action cannot be accepted right now.', 'acs-content-for-woocommerce' ), array( 'status' => 503 ) ); } $result = $token->request_access_link( (string) $request->get_param( 'email' ), absint( $request->get_param( 'post_id' ) ) ); if ( is_wp_error( $result ) ) { $code = $result->get_error_code(); if ( 'acscw_invalid_email' === $code ) { $status = 400; } elseif ( 'acscw_rate_limited' === $code ) { $status = 429; } else { $status = 500; } return new WP_Error( $code, $result->get_error_message(), array( 'status' => $status ) ); } return new WP_REST_Response( array( 'sent' => true, 'message' => self::get_uniform_message(), ), 200 ); } /** * 成功・未購入どちらでも返す共通メッセージ。 * * @return string */ public static function get_uniform_message() { return __( 'If a purchase was found, an access link has been emailed to you. If it has not arrived within a few minutes, please check your spam folder.', 'acs-content-for-woocommerce' ); } }