*/ private static $access_cache = array(); /** * 通知を出力済みかどうか(1ページに1回だけ)。 * * @var bool */ private $notice_rendered = false; /** * フックを登録する。 */ public function __construct() { // 優先度5。do_blocks(9)・wpautop(10)より前に本文を分割する。 add_filter( 'the_content', array( $this, 'filter_the_content' ), 5 ); // 分割の直後に通知を差し込む(購入失敗・リンク期限切れ)。 add_filter( 'the_content', array( $this, 'prepend_notice' ), 6 ); // 抜粋。自動生成なら無料部分から作り直す。 add_filter( 'get_the_excerpt', array( $this, 'filter_excerpt' ), 5, 2 ); add_filter( 'the_excerpt_rss', array( $this, 'filter_excerpt_rss' ), 5 ); add_filter( 'the_excerpt_embed', array( $this, 'filter_excerpt_rss' ), 5 ); } /* * ----------------------------------------------------------------------- * アクセス判定 * ----------------------------------------------------------------------- */ /** * 現在の読者がこのコンテンツの全文を読めるかどうか。 * * @param int $post_id コンテンツID。 * @return bool */ public static function reader_can_read( $post_id ) { $post_id = absint( $post_id ); if ( isset( self::$access_cache[ $post_id ] ) ) { return self::$access_cache[ $post_id ]; } $can = false; if ( $post_id > 0 ) { if ( current_user_can( 'edit_post', $post_id ) ) { // 編集できる人(著者・管理者)は当然そのまま読める。 $can = true; } else { $token = ACSCW_Plugin::instance()->get( 'token' ); if ( $token instanceof ACSCW_Access_Token ) { $can = (bool) $token->current_reader_has_access( $post_id ); } } } /** * 有料本文を読めるかどうか。 * * 会員プラグイン等から解放したい場合に使う。 * * @since 3.0.0 * * @param bool $can 判定結果。 * @param int $post_id コンテンツID。 */ $can = (bool) apply_filters( 'acscw_reader_can_read', $can, $post_id ); self::$access_cache[ $post_id ] = $can; return $can; } /** * 判定キャッシュを捨てる(Cookie 発行直後など)。 * * @return void */ public static function flush_access_cache() { self::$access_cache = array(); } /** * 現在描画中のコンテンツIDを返す。 * * 特定できない場合は 0 を返す。0 は「読めない」に倒れる(fail closed)。 * * @return int */ public static function current_post_id() { if ( isset( $GLOBALS['post'] ) && is_object( $GLOBALS['post'] ) && isset( $GLOBALS['post']->ID ) ) { return absint( $GLOBALS['post']->ID ); } if ( function_exists( 'get_the_ID' ) ) { $post_id = get_the_ID(); if ( $post_id ) { return absint( $post_id ); } } return 0; } /* * ----------------------------------------------------------------------- * 網1: the_content の分割 * ----------------------------------------------------------------------- */ /** * 本文分割の対象になるブロック名を返す。 * * v3 の `acscw/paywall` に加えて、v2 で保存された `acs-wc/paywall` も対象にする。 * ここに旧名を入れないと、旧ブロックで作られた記事の有料本文が * **未購入者のレスポンスに素で載る**(フェーズ6・互換レイヤーの中核)。 * * @return string[] */ public static function get_block_names() { $names = array( self::BLOCK_NAME ); if ( class_exists( 'ACSCW_Legacy_Blocks' ) ) { $names[] = ACSCW_Legacy_Blocks::BLOCK_PAYWALL; } return $names; } /** * 本文に Paywall ブロック(新旧いずれか)が含まれるかどうか。 * * @param string $content 本文。 * @return bool */ public static function content_has_paywall( $content ) { $content = (string) $content; foreach ( self::get_block_names() as $name ) { if ( false !== strpos( $content, 'wp:' . $name ) ) { return true; } } return false; } /** * 未購入者向けに本文を分割する。 * * @param string $content 本文(この時点ではまだブロックマークアップ)。 * @return string */ public function filter_the_content( $content ) { if ( ! is_string( $content ) || '' === $content ) { return $content; } // ブロックが無いなら何もしない(無関係な the_content 適用を素通しする)。 if ( ! self::content_has_paywall( $content ) ) { return $content; } $post_id = self::current_post_id(); if ( self::reader_can_read( $post_id ) ) { return $content; } if ( ! function_exists( 'parse_blocks' ) || ! function_exists( 'serialize_blocks' ) ) { // 分割できない環境では、有料本文を出すより丸ごと落とす方を選ぶ。 return ''; } $split = self::split_blocks( parse_blocks( $content ) ); if ( ! $split['found'] ) { return $content; } return serialize_blocks( $split['blocks'] ); } /** * パース済みブロック列を「無料部分+空の Paywall ブロック」に切り詰める。 * * Paywall がグループ等の中に入れ子で置かれている場合は、 * **その最上位の親ごと落とす**(入れ子の内側だけ残すと、 * 親の装飾に有料本文の一部が引きずられて出る可能性があるため)。 * * @param array $blocks parse_blocks() の結果。 * @return array array{found:bool,blocks:array} */ public static function split_blocks( $blocks ) { if ( ! is_array( $blocks ) ) { return array( 'found' => false, 'blocks' => array(), ); } $kept = array(); $found = null; foreach ( $blocks as $block ) { $paywall = self::find_paywall( $block ); if ( null === $paywall ) { $kept[] = $block; continue; } $found = $paywall; break; } if ( null === $found ) { return array( 'found' => false, 'blocks' => $blocks, ); } // 属性だけを引き継いだ「中身のない Paywall ブロック」を置く。 // これが do_blocks でレンダーコールバックに渡り、購入導線の箱になる。 // ブロック名は見つかったものをそのまま使う。旧ブロックなら旧名のまま残し、 // 互換レイヤーのレンダーコールバック(価格属性の読み替えを含む)へ渡す。 $kept[] = array( 'blockName' => ( isset( $found['blockName'] ) && '' !== $found['blockName'] ) ? $found['blockName'] : self::BLOCK_NAME, 'attrs' => ( isset( $found['attrs'] ) && is_array( $found['attrs'] ) ) ? $found['attrs'] : array(), 'innerBlocks' => array(), 'innerHTML' => '', 'innerContent' => array(), ); return array( 'found' => true, 'blocks' => $kept, ); } /** * ブロック(と入れ子)から最初の Paywall ブロックを探す。 * * @param array $block パース済みブロック。 * @return array|null */ private static function find_paywall( $block ) { if ( ! is_array( $block ) ) { return null; } if ( isset( $block['blockName'] ) && in_array( $block['blockName'], self::get_block_names(), true ) ) { return $block; } if ( empty( $block['innerBlocks'] ) || ! is_array( $block['innerBlocks'] ) ) { return null; } foreach ( $block['innerBlocks'] as $inner ) { $found = self::find_paywall( $inner ); if ( null !== $found ) { return $found; } } return null; } /* * ----------------------------------------------------------------------- * 網2: レンダーコールバック * ----------------------------------------------------------------------- */ /** * Paywall ブロックを描画する。 * * @param array $attributes ブロック属性。 * @param string $content 有料本文(網1を通っていれば空)。 * @param WP_Block|null $block ブロックインスタンス。 * @return string */ public function render( $attributes, $content = '', $block = null ) { unset( $block ); $post_id = self::current_post_id(); if ( self::reader_can_read( $post_id ) ) { // 購入済み読者・編集権限者はそのまま全文。箱は出さない。 return (string) $content; } ACSCW_Blocks::ensure_assets(); return $this->render_box( (array) $attributes, $post_id ); } /** * 購入導線の箱を組み立てる。 * * @param array $attributes ブロック属性。 * @param int $post_id コンテンツID。 * @return string */ private function render_box( $attributes, $post_id ) { $price = ACSCW_Products::get_content_price( $post_id ); $purchase_url = ( $post_id > 0 && $price > 0 ) ? ACSCW_Checkout::get_purchase_url( $post_id ) : ''; $headline = $this->get_attribute( $attributes, 'headline', __( 'The rest of this article is paid', 'acs-content-for-woocommerce' ) ); $description = $this->get_attribute( $attributes, 'description', '' ); $show_price = ! isset( $attributes['showPrice'] ) || (bool) $attributes['showPrice']; $wrapper = $this->get_wrapper_attributes(); $html = '
%s
', esc_html__( 'Paid from here', 'acs-content-for-woocommerce' ) ); $html .= sprintf( '%s
', esc_html( $description ) ); } if ( '' === $purchase_url ) { // 価格が未設定・商品が作れない等。壊れたボタンを出すより、正直に言う。 $html .= sprintf( '%s
', esc_html__( 'This content cannot be purchased right now. Please try again later.', 'acs-content-for-woocommerce' ) ); $html .= '%1$s%2$s
', wp_kses_post( ACSCW_Products::format_price( $price ) ), esc_html__( 'One-time payment', 'acs-content-for-woocommerce' ) ); } $html .= sprintf( '', esc_url( $purchase_url ), esc_html( $this->get_button_text( $attributes, $price ) ) ); // 不安を消す一言。箇条書きにはしない(柱2)。 $html .= sprintf( '', esc_html__( 'No account needed', 'acs-content-for-woocommerce' ), esc_html__( 'Read it right after paying', 'acs-content-for-woocommerce' ) ); $html .= $this->render_restore_link( $post_id ); $html .= ''; return $html; } /** * 「すでに購入済みですか?」の復旧導線。 * * ここだけは押せるものが2つ目になるが、購入ボタンとは * 大きさ・色・位置で明確に差をつけ、区切り線の下に置く。 * * @param int $post_id コンテンツID。 * @return string */ private function render_restore_link( $post_id ) { $html = ''; $html .= sprintf( '%1$s ', esc_html__( 'Already bought this?', 'acs-content-for-woocommerce' ), absint( $post_id ), esc_html__( 'Restore access with your email address', 'acs-content-for-woocommerce' ) ); $html .= '
'; // JavaScript が無い環境向けの案内。押せないボタンだけを残さない。 $html .= sprintf( '', esc_html__( 'The email sent to you at checkout contains an access link for reading on another device.', 'acs-content-for-woocommerce' ) ); return $html; } /** * ボタンの文言を決める。 * * 優先順は ブロック属性 → サイト既定(設定 › デザイン)→ 価格入りの既定文言。 * v2 はデザイン設定の文言を一度も読まない死に設定だった(§2-1③)。 * * @param array $attributes ブロック属性。 * @param float $price 価格。 * @return string */ private function get_button_text( $attributes, $price ) { $custom = $this->get_attribute( $attributes, 'buttonText', '' ); if ( '' !== $custom ) { return $custom; } $site_default = trim( (string) get_option( 'acscw_button_text', '' ) ); if ( '' !== $site_default ) { return $site_default; } return sprintf( /* translators: %s: price with currency symbol */ __( 'Read on (%s)', 'acs-content-for-woocommerce' ), ACSCW_Products::format_price_plain( $price ) ); } /** * ブロック属性を文字列で取り出す。 * * @param array $attributes ブロック属性。 * @param string $key キー。 * @param string $fallback 既定値。 * @return string */ private function get_attribute( $attributes, $key, $fallback = '' ) { if ( ! isset( $attributes[ $key ] ) || ! is_scalar( $attributes[ $key ] ) ) { return $fallback; } $value = trim( (string) $attributes[ $key ] ); return ( '' === $value ) ? $fallback : $value; } /** * ラッパー要素の属性を返す。 * * @return string */ private function get_wrapper_attributes() { if ( function_exists( 'get_block_wrapper_attributes' ) ) { return get_block_wrapper_attributes( array( 'class' => 'acscw-paywall' ) ); } return 'class="acscw-paywall"'; } /* * ----------------------------------------------------------------------- * 抜粋・フィード * ----------------------------------------------------------------------- */ /** * 自動抜粋を無料部分から作り直す。 * * 著者が手で書いた抜粋(post_excerpt)はそのまま尊重する。 * * @param string $excerpt 抜粋。 * @param WP_Post|null $post 対象の投稿。 * @return string */ public function filter_excerpt( $excerpt, $post = null ) { $post = get_post( $post ); if ( ! $post || empty( $post->post_content ) ) { return $excerpt; } if ( ! self::content_has_paywall( $post->post_content ) ) { return $excerpt; } if ( self::reader_can_read( $post->ID ) ) { return $excerpt; } if ( isset( $post->post_excerpt ) && '' !== trim( (string) $post->post_excerpt ) ) { return $excerpt; } return $this->build_free_excerpt( $post ); } /** * フィード・埋め込み用の抜粋。 * * @param string $excerpt 抜粋。 * @return string */ public function filter_excerpt_rss( $excerpt ) { return $this->filter_excerpt( $excerpt, null ); } /** * 無料部分だけから抜粋を作る。 * * @param WP_Post $post 投稿。 * @return string */ private function build_free_excerpt( $post ) { if ( ! function_exists( 'parse_blocks' ) || ! function_exists( 'serialize_blocks' ) ) { return ''; } $split = self::split_blocks( parse_blocks( $post->post_content ) ); $free = array(); foreach ( $split['blocks'] as $block ) { if ( isset( $block['blockName'] ) && in_array( $block['blockName'], self::get_block_names(), true ) ) { continue; } $free[] = $block; } $text = serialize_blocks( $free ); $text = strip_shortcodes( $text ); // serialize_blocks の出力にはブロックコメントが含まれる。タグごと落とす。 $text = wp_strip_all_tags( $text ); $text = str_replace( array( "\r", "\n", "\t" ), ' ', $text ); $text = trim( preg_replace( '/\s+/u', ' ', $text ) ); /** This filter is documented in wp-includes/formatting.php */ // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WordPress core hook, applied on purpose so the free preview honours the site's excerpt settings. $length = (int) apply_filters( 'excerpt_length', 55 ); /** This filter is documented in wp-includes/formatting.php */ // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WordPress core hook, applied on purpose so the free preview honours the site's excerpt settings. $more = apply_filters( 'excerpt_more', ' […]' ); return wp_trim_words( $text, $length, $more ); } /* * ----------------------------------------------------------------------- * フロント通知 * ----------------------------------------------------------------------- */ /** * acscw_notice に応じた通知を本文の前に差し込む。 * * @param string $content 本文。 * @return string */ public function prepend_notice( $content ) { if ( $this->notice_rendered || ! is_string( $content ) ) { return $content; } $code = self::get_notice_code(); if ( '' === $code ) { return $content; } if ( function_exists( 'is_singular' ) && ! is_singular() ) { return $content; } if ( function_exists( 'in_the_loop' ) && ! in_the_loop() ) { return $content; } $this->notice_rendered = true; ACSCW_Blocks::ensure_assets(); return $this->render_notice( $code ) . $content; } /** * リクエストの通知コードを返す。 * * @return string 未知のコードは空文字。 */ public static function get_notice_code() { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- 表示専用。副作用なし。 if ( empty( $_GET[ self::NOTICE_QUERY_VAR ] ) ) { return ''; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended $code = sanitize_key( wp_unslash( $_GET[ self::NOTICE_QUERY_VAR ] ) ); $known = array( 'unavailable', 'cart_failed', 'link_expired', 'expired' ); return in_array( $code, $known, true ) ? $code : ''; } /** * 通知の HTML を組み立てる。 * * @param string $code 通知コード。 * @return string */ private function render_notice( $code ) { $messages = array( 'unavailable' => array( 'type' => 'error', 'text' => __( 'This content cannot be purchased right now. Please try again later.', 'acs-content-for-woocommerce' ), ), 'cart_failed' => array( 'type' => 'error', 'text' => __( 'This could not be added to the cart. Please try again.', 'acs-content-for-woocommerce' ), ), 'link_expired' => array( 'type' => 'warning', 'text' => __( 'This access link has expired or has already been used. Send a new one from "Already bought this?" below.', 'acs-content-for-woocommerce' ), ), 'expired' => array( 'type' => 'warning', 'text' => __( 'That purchase link was no longer valid, so nothing was added to your cart. The button below has been refreshed - please use it to continue.', 'acs-content-for-woocommerce' ), ), ); if ( ! isset( $messages[ $code ] ) ) { return ''; } return sprintf( '