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