login-button.php
63 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Premium Content Login Button Child Block. |
| 4 | * |
| 5 | * @package automattic/jetpack |
| 6 | */ |
| 7 | |
| 8 | namespace Automattic\Jetpack\Extensions\Premium_Content; |
| 9 | |
| 10 | use Automattic\Jetpack\Blocks; |
| 11 | use Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service\Token_Subscription_Service; |
| 12 | use Automattic\Jetpack\Status\Host; |
| 13 | use Jetpack_Gutenberg; |
| 14 | |
| 15 | require_once dirname( __DIR__ ) . '/_inc/subscription-service/include.php'; |
| 16 | |
| 17 | const LOGIN_BUTTON_NAME = 'premium-content/login-button'; |
| 18 | |
| 19 | /** |
| 20 | * Registers the block for use in Gutenberg |
| 21 | * This is done via an action so that we can disable |
| 22 | * registration if we need to. |
| 23 | */ |
| 24 | function register_login_button_block() { |
| 25 | Blocks::jetpack_register_block( |
| 26 | LOGIN_BUTTON_NAME, |
| 27 | array( |
| 28 | 'render_callback' => __NAMESPACE__ . '\render_login_button_block', |
| 29 | ) |
| 30 | ); |
| 31 | } |
| 32 | add_action( 'init', __NAMESPACE__ . '\register_login_button_block' ); |
| 33 | |
| 34 | /** |
| 35 | * Render callback. |
| 36 | * |
| 37 | * @param array $attributes Array containing the block attributes. |
| 38 | * @param string $content String containing the block content. |
| 39 | * |
| 40 | * @return string |
| 41 | */ |
| 42 | function render_login_button_block( $attributes, $content ) { |
| 43 | if ( ! pre_render_checks() ) { |
| 44 | return ''; |
| 45 | } |
| 46 | |
| 47 | $has_auth_cookie = isset( $_COOKIE[ Token_Subscription_Service::JWT_AUTH_TOKEN_COOKIE_NAME ] ); |
| 48 | // phpcs:ignore WordPress.Security.NonceVerification.Recommended |
| 49 | $has_token_parameter = isset( $_GET['token'] ); |
| 50 | |
| 51 | $is_user_logged_in_on_wpcom = ( new Host() )->is_wpcom_simple() && is_user_logged_in(); |
| 52 | if ( $is_user_logged_in_on_wpcom || $has_auth_cookie || $has_token_parameter ) { |
| 53 | // The viewer is logged it, so they shouldn't see the login button. |
| 54 | return ''; |
| 55 | } |
| 56 | |
| 57 | Jetpack_Gutenberg::load_styles_as_required( LOGIN_BUTTON_NAME ); |
| 58 | |
| 59 | $url = subscription_service()->access_url(); |
| 60 | |
| 61 | return preg_replace( '/(<a\b[^><]*)>/i', '$1 href="' . esc_url( $url ) . '">', $content ); |
| 62 | } |
| 63 |