This commit is contained in:
2026-07-02 15:54:39 -06:00
commit 9883323161
17470 changed files with 4470592 additions and 0 deletions
@@ -0,0 +1,542 @@
<?php
/**
* Jetpack Newsletter Abilities Registration
*
* Registers Jetpack Newsletter (subscriptions) abilities with the WordPress
* Abilities API.
*
* @package automattic/jetpack
*/
namespace Automattic\Jetpack\Plugin\Abilities;
use Automattic\Jetpack\Connection\Client;
use Automattic\Jetpack\Modules\Subscriptions\Settings as Subscriptions_Settings;
use Automattic\Jetpack\WP_Abilities\Registrar;
use Jetpack;
use Jetpack_Options;
// The Subscriptions module doesn't load its Settings helpers eagerly. Pull it
// in here so `Subscriptions_Settings::$default_reply_to` and
// `is_valid_reply_to()` are resolvable when the abilities run.
require_once __DIR__ . '/../class-settings.php';
/**
* Registers Jetpack Newsletter abilities with the WordPress Abilities API.
*
* Exposes a consolidated read of the site's newsletter (subscriptions) settings
* and a partial-update writer so AI agents can configure the Newsletter module
* through the standard `wp-abilities/v1` REST surface.
*/
class Newsletter_Abilities extends Registrar {
// Field type tags used in `settings_map()`. Constants (not strings) so a
// typo in a `case` label fails fast instead of silently falling through.
private const TYPE_BOOL = 'bool';
private const TYPE_ON_OFF = 'on_off';
private const TYPE_ENUM = 'enum';
private const TYPE_STRING = 'string';
/**
* Allowed values for the `reply_to` setting. Mirror of
* `Subscriptions_Settings::is_valid_reply_to()` — kept here so it can be
* referenced from the JSON Schema enum without loading the Settings class
* at file-parse time.
*/
private const REPLY_TO_VALUES = array( 'comment', 'author', 'no-reply' );
/**
* Returns the abilities category, definition, or registered abilities.
*
* @inheritDoc
*/
public static function get_category_slug(): string {
return 'jetpack-newsletter';
}
/**
* Returns the abilities category, definition, or registered abilities.
*
* @inheritDoc
*/
public static function get_category_definition(): array {
return array(
// "Jetpack" and "Newsletter" are product names and should not be translated.
'label' => 'Jetpack Newsletter',
'description' => __( 'Abilities for reading and updating Jetpack Newsletter settings.', 'jetpack' ),
);
}
/**
* Returns the abilities category, definition, or registered abilities.
*
* @inheritDoc
*/
public static function get_abilities(): array {
$settings_object_schema = array(
'type' => 'object',
'additionalProperties' => false,
'properties' => array(
'subscribe_post_end_enabled' => array(
'type' => 'boolean',
'description' => __( 'Show a "subscribe to blog" checkbox at the end of every post. Default true.', 'jetpack' ),
),
'subscribe_comments_enabled' => array(
'type' => 'boolean',
'description' => __( 'Show a "notify me of new comments" checkbox in the comment form. Default true.', 'jetpack' ),
),
'notify_admin_on_subscribe' => array(
'type' => 'boolean',
'description' => __( 'Email the site admin whenever a new subscriber signs up. Default true.', 'jetpack' ),
),
'reply_to' => array(
'type' => 'string',
'enum' => self::REPLY_TO_VALUES,
'description' => __( 'Reply-to address for newsletter emails. "comment" routes to the post comment author, "author" to the post author, "no-reply" disables replies. Default "comment".', 'jetpack' ),
),
'from_name' => array(
'type' => 'string',
'description' => __( 'Sender name shown on newsletter emails. Empty string falls back to the site name.', 'jetpack' ),
'maxLength' => 200,
),
),
);
return array(
'jetpack-newsletter/get-settings' => array(
'label' => __( 'Get Newsletter settings', 'jetpack' ),
'description' => __(
'Return the current Jetpack Newsletter settings as a flat object. Always returns the same five fields: subscribe_post_end_enabled (bool), subscribe_comments_enabled (bool), notify_admin_on_subscribe (bool), reply_to ("comment"|"author"|"no-reply"), and from_name (string). Read-only and idempotent. To change any value, call jetpack-newsletter/update-settings.',
'jetpack'
),
'input_schema' => array(
'type' => 'object',
'default' => array(),
'properties' => array(),
'additionalProperties' => false,
),
'output_schema' => $settings_object_schema,
'execute_callback' => array( __CLASS__, 'get_settings' ),
'permission_callback' => array( __CLASS__, 'can_view_settings' ),
'meta' => array(
'annotations' => array(
'readonly' => true,
'destructive' => false,
'idempotent' => true,
),
'show_in_rest' => true,
'mcp' => array(
'public' => true,
'type' => 'tool', // default is already "tool", but can be explicit.
),
),
),
'jetpack-newsletter/update-settings' => array(
'label' => __( 'Update Newsletter settings', 'jetpack' ),
'description' => __(
'Update one or more Jetpack Newsletter settings. Any subset of the five fields may be supplied; omitted fields are left untouched. Idempotent — fields whose desired value already matches the current value are not rewritten. Returns { settings: <full current state after the update>, changed: <array of field names that actually transitioned> }. An empty input or input matching the current state returns changed = [].',
'jetpack'
),
'input_schema' => $settings_object_schema,
'output_schema' => array(
'type' => 'object',
'properties' => array(
'settings' => $settings_object_schema,
'changed' => array(
'type' => 'array',
'items' => array( 'type' => 'string' ),
'description' => __( 'Names of the fields that actually changed during this call. Empty when the call was a no-op.', 'jetpack' ),
),
),
),
'execute_callback' => array( __CLASS__, 'update_settings' ),
'permission_callback' => array( __CLASS__, 'can_manage_settings' ),
'meta' => array(
'annotations' => array(
'readonly' => false,
'destructive' => false,
'idempotent' => true,
),
'show_in_rest' => true,
'mcp' => array(
'public' => true,
'type' => 'tool', // default is already "tool", but can be explicit.
),
),
),
'jetpack-newsletter/get-subscriber-stats' => array(
'label' => __( 'Get Newsletter subscriber stats', 'jetpack' ),
'description' => __(
'Return aggregate subscriber counts for the site. Always returns { all: int, email: int, paid: int }: all is the total subscriber count (email + WordPress.com followers); email is the subset that receives email; paid is the subset on a paid newsletter plan. Numbers are fetched from WordPress.com and cached locally for one hour, so transient network errors yield a stale-but-non-zero response when one is available. Requires an active Jetpack connection — sites without one return jetpack_newsletter_not_connected.',
'jetpack'
),
'input_schema' => array(
'type' => 'object',
'default' => array(),
'properties' => array(),
'additionalProperties' => false,
),
'output_schema' => array(
'type' => 'object',
'properties' => array(
'all' => array( 'type' => 'integer' ),
'email' => array( 'type' => 'integer' ),
'paid' => array( 'type' => 'integer' ),
),
),
'execute_callback' => array( __CLASS__, 'get_subscriber_stats' ),
'permission_callback' => array( __CLASS__, 'can_view_settings' ),
'meta' => array(
'annotations' => array(
'readonly' => true,
'destructive' => false,
'idempotent' => true,
),
'show_in_rest' => true,
'mcp' => array(
'public' => true,
'type' => 'tool', // default is already "tool", but can be explicit.
),
),
),
);
}
/**
* Permission check for read abilities. Newsletter settings live on the WP
* Newsletter settings screen, which is itself gated on `manage_options`.
*/
public static function can_view_settings(): bool {
return current_user_can( 'manage_options' );
}
/**
* Permission check for write abilities. Mirrors the gating on the
* Newsletter settings screen.
*/
public static function can_manage_settings(): bool {
return current_user_can( 'manage_options' );
}
/**
* Execute: return the current newsletter settings.
*
* @param array|null $input Unused — input schema accepts no parameters.
* @return array
*/
public static function get_settings( $input = null ): array {
unset( $input );
return self::current_settings();
}
/**
* Transient key for the wpcom subscriber-stats response.
*/
private const SUBSCRIBER_STATS_CACHE_KEY = 'jetpack_newsletter_subscriber_stats';
/**
* Transient TTL for subscriber-stats responses, in seconds.
*
* Matches the existing legacy widget pattern of an hour-long cache so
* agents calling this ability repeatedly don't fan out to wpcom.
*/
private const SUBSCRIBER_STATS_CACHE_TTL = HOUR_IN_SECONDS;
/**
* Execute: fetch (and cache) aggregate subscriber counts from WordPress.com.
*
* @param array|null $input Unused — input schema accepts no parameters.
* @return array|\WP_Error
*/
public static function get_subscriber_stats( $input = null ) {
unset( $input );
$cached = get_transient( self::SUBSCRIBER_STATS_CACHE_KEY );
if ( is_array( $cached ) ) {
return $cached;
}
if ( ! class_exists( 'Jetpack' ) || ! Jetpack::is_connection_ready() ) {
return new \WP_Error(
'jetpack_newsletter_not_connected',
__( 'Subscriber stats are only available on Jetpack-connected sites. Connect Jetpack and retry.', 'jetpack' )
);
}
$site_id = (int) Jetpack_Options::get_option( 'id' );
if ( $site_id <= 0 ) {
return new \WP_Error(
'jetpack_newsletter_not_connected',
__( 'No Jetpack site ID is registered. Connect Jetpack and retry.', 'jetpack' )
);
}
$response = Client::wpcom_json_api_request_as_blog(
sprintf( '/sites/%d/subscribers/stats', $site_id ),
'2',
array(),
null,
'wpcom'
);
if ( is_wp_error( $response ) ) {
return new \WP_Error(
'jetpack_newsletter_subscriber_stats_unavailable',
$response->get_error_message()
);
}
if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
return new \WP_Error(
'jetpack_newsletter_subscriber_stats_unavailable',
__( 'WordPress.com did not return subscriber stats. Retry shortly.', 'jetpack' )
);
}
$body = json_decode( wp_remote_retrieve_body( $response ), true );
$counts = is_array( $body ) && isset( $body['counts'] ) && is_array( $body['counts'] )
? $body['counts']
: array();
$stats = array(
'all' => isset( $counts['all_subscribers'] ) ? (int) $counts['all_subscribers'] : 0,
'email' => isset( $counts['email_subscribers'] ) ? (int) $counts['email_subscribers'] : 0,
'paid' => isset( $counts['paid_subscribers'] ) ? (int) $counts['paid_subscribers'] : 0,
);
set_transient( self::SUBSCRIBER_STATS_CACHE_KEY, $stats, self::SUBSCRIBER_STATS_CACHE_TTL );
return $stats;
}
/**
* Execute: idempotent partial update of newsletter settings.
*
* Validates every supplied field before writing anything, so a malformed
* field cannot leave the option set in a partially-updated state.
*
* @param array|null $input Input matching the ability's input_schema.
* @return array|\WP_Error
*/
public static function update_settings( $input = null ) {
$input = is_array( $input ) ? $input : array();
$map = self::settings_map();
// Validate + normalize every supplied field up-front. Any failure
// short-circuits the call with no writes, so a bad field can't leave
// earlier fields in a partially-updated state.
$normalized = array();
foreach ( $map as $field => $config ) {
if ( ! array_key_exists( $field, $input ) ) {
continue;
}
$result = self::normalize_input_value( $field, $config, $input[ $field ] );
if ( $result instanceof \WP_Error ) {
return $result;
}
$normalized[ $field ] = $result;
}
// Read every field's current value once. This pass also feeds the
// post-update response, avoiding a second `get_option` sweep.
$current_storage = array();
foreach ( $map as $field => $config ) {
$current_storage[ $field ] = self::read_option( $config );
}
$changed = array();
foreach ( $normalized as $field => $desired ) {
// String-cast on both sides because every field's storage form is
// scalar (`0`/`1` for BOOL, `'on'`/`'off'` for ON_OFF, plain strings
// for ENUM/STRING). New field types added later must keep that
// invariant or this comparison will misfire.
if ( (string) $desired === (string) $current_storage[ $field ] ) {
continue;
}
update_option( $map[ $field ]['option'], $desired );
$current_storage[ $field ] = $desired;
$changed[] = $field;
}
$settings = array();
foreach ( $map as $field => $config ) {
$settings[ $field ] = self::cast_to_response( $config, $current_storage[ $field ] );
}
return array(
'settings' => $settings,
'changed' => $changed,
);
}
/**
* Map of public ability field name → backing option config.
*
* Storage shape (option key, type tag, default, enum). The agent-facing
* descriptions and JSON Schema live in `get_abilities()`; this map drives
* the storage-side validation, normalization, and casting.
*
* Kept as a method (not a class constant) so the description strings
* referenced from `cast_to_response()` and `normalize_input_value()` can
* resolve through `__()` at call time rather than file load time.
*/
private static function settings_map(): array {
return array(
'subscribe_post_end_enabled' => array(
'option' => 'stb_enabled',
'type' => self::TYPE_BOOL,
'default' => 1,
),
'subscribe_comments_enabled' => array(
'option' => 'stc_enabled',
'type' => self::TYPE_BOOL,
'default' => 1,
),
'notify_admin_on_subscribe' => array(
'option' => 'social_notifications_subscribe',
'type' => self::TYPE_ON_OFF,
'default' => 'on',
),
'reply_to' => array(
'option' => 'jetpack_subscriptions_reply_to',
'type' => self::TYPE_ENUM,
'default' => Subscriptions_Settings::$default_reply_to,
'enum' => self::REPLY_TO_VALUES,
),
'from_name' => array(
'option' => 'jetpack_subscriptions_from_name',
'type' => self::TYPE_STRING,
'default' => '',
'max_length' => 200,
),
);
}
/**
* Read all settings as the public response shape.
*/
private static function current_settings(): array {
$out = array();
foreach ( self::settings_map() as $field => $config ) {
$out[ $field ] = self::cast_to_response( $config, self::read_option( $config ) );
}
return $out;
}
/**
* Read the raw option for a field config, falling back to its default.
*
* @param array $config Field config from `settings_map()`.
* @return mixed
*/
private static function read_option( array $config ) {
return get_option( $config['option'], $config['default'] );
}
/**
* Validate + normalize a single input value to the storage form.
*
* @param string $field Public field name (used in error messages).
* @param array $config Field config from `settings_map()`.
* @param mixed $value Raw input value.
* @return mixed|\WP_Error Storage-form value, or WP_Error when invalid.
*/
private static function normalize_input_value( string $field, array $config, $value ) {
switch ( $config['type'] ) {
case self::TYPE_BOOL:
if ( ! is_bool( $value ) ) {
return self::invalid_field( $field, __( 'expected a boolean (true or false).', 'jetpack' ) );
}
return $value ? 1 : 0;
case self::TYPE_ON_OFF:
if ( ! is_bool( $value ) ) {
return self::invalid_field( $field, __( 'expected a boolean (true or false).', 'jetpack' ) );
}
return $value ? 'on' : 'off';
case self::TYPE_ENUM:
// reply_to is the only enum today and shares its allowed-values
// list with `Subscriptions_Settings::is_valid_reply_to()`. Defer
// to that validator so the two surfaces can't drift.
$valid = 'reply_to' === $field
? Subscriptions_Settings::is_valid_reply_to( $value )
: ( is_string( $value ) && in_array( $value, $config['enum'], true ) );
if ( ! $valid ) {
return self::invalid_field(
$field,
sprintf(
/* translators: %s: comma-separated list of allowed values. */
__( 'allowed values are %s.', 'jetpack' ),
implode( ', ', $config['enum'] )
)
);
}
return $value;
case self::TYPE_STRING:
if ( ! is_string( $value ) ) {
return self::invalid_field( $field, __( 'expected a string.', 'jetpack' ) );
}
$sanitized = sanitize_text_field( $value );
if ( isset( $config['max_length'] ) && mb_strlen( $sanitized ) > (int) $config['max_length'] ) {
return self::invalid_field(
$field,
sprintf(
/* translators: %d: maximum number of characters. */
__( 'must be %d characters or fewer.', 'jetpack' ),
(int) $config['max_length']
)
);
}
return $sanitized;
}
return self::invalid_field( $field, __( 'unsupported field type.', 'jetpack' ) );
}
/**
* Cast a stored option value to the public response shape.
*
* @param array $config Field config from `settings_map()`.
* @param mixed $value Raw stored value.
* @return mixed
*/
private static function cast_to_response( array $config, $value ) {
switch ( $config['type'] ) {
case self::TYPE_BOOL:
return 1 === (int) $value;
case self::TYPE_ON_OFF:
return 'on' === (string) $value;
case self::TYPE_ENUM:
$value = (string) $value;
return in_array( $value, $config['enum'], true ) ? $value : (string) $config['default'];
case self::TYPE_STRING:
return (string) $value;
}
return $value;
}
/**
* Build a `jetpack_newsletter_invalid_<field>` WP_Error with a message
* that names the field and tells the agent how to fix the input.
*
* @param string $field Public field name; appears in the error code and message.
* @param string $reason Translated explanation of the expected value.
* @return \WP_Error
*/
private static function invalid_field( string $field, string $reason ): \WP_Error {
return new \WP_Error(
'jetpack_newsletter_invalid_' . $field,
sprintf(
/* translators: 1: field name, 2: explanation of the expected value. */
__( 'Invalid value for "%1$s": %2$s', 'jetpack' ),
$field,
$reason
)
);
}
}
@@ -0,0 +1,36 @@
<?php
/**
* The Subscriptions settings.
*
* This is a class that contains helper functions for the Subscriptions settings module.
*
* @package automattic/jetpack-subscriptions
*/
namespace Automattic\Jetpack\Modules\Subscriptions;
/**
* Class Settings
*/
class Settings {
/**
* The default reply-to option.
*
* @var string
*/
public static $default_reply_to = 'comment';
/**
* Validate the reply-to option.
*
* @param string $reply_to The reply-to option to validate.
* @return bool Whether the reply-to option is valid or not.
*/
public static function is_valid_reply_to( $reply_to ) {
$valid_values = array( 'author', 'no-reply', 'comment' );
if ( in_array( $reply_to, $valid_values, true ) ) {
return true;
}
return false;
}
}
@@ -0,0 +1,77 @@
<?php
/**
* User Content Link Redirection
*
* The purpose of this file is to track and redirect user content links in emails.
* This renders an iframe pointing to subscribe.wordpress.com which will track and
* return the destination url for the iframe parent to redirect to.
*
* @package automattic/jetpack
*/
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
/**
* Render a page with an iframe to track and redirect user content links in emails.
*
* Hooked to the `init` action, this function renders a page with an iframe pointing to
* subscribe.wordpress.com to track and return the destination URL for redirection.
*
* Redirects to the site's home page if required parameters are missing.
* Returns a 400 error if the request's `blog_id` doesn't match the actual `blog_id`.
*
* @return never
*/
function jetpack_user_content_link_redirection() {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( empty( $_SERVER['QUERY_STRING'] ) || empty( $_SERVER['HTTP_HOST'] ) || empty( $_GET['blog_id'] ) ) {
wp_safe_redirect( get_home_url() );
exit( 0 );
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$request_blog_id = intval( sanitize_text_field( wp_unslash( $_GET['blog_id'] ) ) );
$actual_blog_id = Connection_Manager::get_site_id( true );
if ( $actual_blog_id !== $request_blog_id ) {
wp_die( esc_html__( 'Invalid link.', 'jetpack' ), 400 );
exit( 0 );
}
$query_params = sanitize_text_field( wp_unslash( $_SERVER['QUERY_STRING'] ) );
$iframe_url = "https://subscribe.wordpress.com/?$query_params";
echo <<<'EOF'
<!DOCTYPE html>
<html>
<head>
<script>
let messageReceived = false;
window.addEventListener( 'message', function(event) {
if ( event.origin !== 'https://subscribe.wordpress.com' || messageReceived ) {
return;
}
if ( event.data.redirectUrl ) {
messageReceived = true;
window.location.href = event.data.redirectUrl;
}
} );
</script>
</head>
<body>
EOF;
echo '<iframe id="user-content-link-redirection" hidden aria-hidden="true" tabindex="-1" width="0" height="0" style="display: none" src="' . esc_url( $iframe_url ) . '"></iframe>';
echo <<<'EOF'
</body>
</html>
EOF;
exit( 0 );
}
// The WPCOM_USER_CONTENT_LINK_REDIRECTION flag prevents this redirection logic from running
// on Atomic in case we'd like to override the redirection logic on the Atomic end.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( ! defined( 'WPCOM_USER_CONTENT_LINK_REDIRECTION' ) && isset( $_GET['action'] ) && $_GET['action'] === 'user_content_redirect' ) {
add_action( 'init', 'jetpack_user_content_link_redirection' );
}
@@ -0,0 +1,239 @@
<?php
/**
* Jetpack Newsletter Dashboard Widget.
*
* @package jetpack
*/
use Automattic\Jetpack\Connection\Client;
use Automattic\Jetpack\Modules;
/**
* Class that adds the Jetpack Newsletter Dashboard Widget to the WordPress admin dashboard.
*/
class Jetpack_Newsletter_Dashboard_Widget {
/**
* Indicates whether the class initialized or not.
*
* @var bool
*/
private static $initialized = false;
/**
* The Widget ID.
*
* @var string
*/
private static $widget_id = 'jetpack_newsletter_dashboard_widget';
/**
* Initialize the class by calling the setup static function.
*
* @return void
*/
public static function init() {
if ( ! self::$initialized ) {
self::$initialized = true;
self::wp_dashboard_setup();
}
}
/**
* Get the config data for the Jetpack Newsletter widget.
*
* @return array
*/
public static function get_config_data() {
$config_data = array(
'emailSubscribers' => 0,
'paidSubscribers' => 0,
'allSubscribers' => 0,
'subscriberTotalsByDate' => array(),
'isStatsModuleActive' => false,
'showHeader' => false,
'showChart' => false,
'isWidgetVisible' => false,
'newsletterSettingsUrl' => \Automattic\Jetpack\Newsletter\Urls::get_newsletter_settings_url(),
);
if ( Jetpack::is_connection_ready() ) {
$site_id = Jetpack_Options::get_option( 'id' );
$api_path = sprintf( '/sites/%d/subscribers/stats', $site_id );
$response = Client::wpcom_json_api_request_as_blog(
$api_path,
'2',
array(),
null,
'wpcom'
);
if ( 200 === wp_remote_retrieve_response_code( $response ) ) {
$subscriber_counts = json_decode( wp_remote_retrieve_body( $response ), true );
if ( isset( $subscriber_counts['counts']['email_subscribers'] ) ) {
$config_data['emailSubscribers'] = (int) $subscriber_counts['counts']['email_subscribers'];
}
if ( isset( $subscriber_counts['counts']['paid_subscribers'] ) ) {
$config_data['paidSubscribers'] = (int) $subscriber_counts['counts']['paid_subscribers'];
}
if ( isset( $subscriber_counts['counts']['all_subscribers'] ) ) {
$config_data['allSubscribers'] = (int) $subscriber_counts['counts']['all_subscribers'];
}
if ( isset( $subscriber_counts['aggregate'] ) ) {
$config_data['subscriberTotalsByDate'] = $subscriber_counts['aggregate'];
}
}
$config_data['isStatsModuleActive'] = ( new Modules() )->is_active( 'stats' );
$config_data['showHeader'] = $config_data['isStatsModuleActive'] && ( $config_data['allSubscribers'] > 0 || $config_data['paidSubscribers'] > 0 );
foreach ( $config_data['subscriberTotalsByDate'] as $day ) {
if ( $day && ( $day['all'] >= 5 || $day['paid'] > 0 ) ) {
$config_data['showChart'] = true;
break;
}
}
$config_data['isWidgetVisible'] = $config_data['showHeader'] || $config_data['showChart'];
}
return $config_data;
}
/**
* Sets up the Jetpack Newsletter widget in the WordPress admin dashboard.
*/
public static function wp_dashboard_setup() {
// Do not show the widget to non-admins.
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
if ( Jetpack::is_connection_ready() ) {
$config_data = static::get_config_data();
if ( ! $config_data['isWidgetVisible'] ) {
return;
}
static::load_admin_scripts(
'jp-newsletter-widget',
'newsletter-widget',
array(
'config_variable_name' => 'jetpackNewsletterWidgetConfigData',
'config_data' => $config_data,
'load_minified_js' => false,
)
);
wp_add_dashboard_widget(
self::$widget_id,
/** "Newsletter" is a product name, do not translate. */
'Jetpack Newsletter',
array( static::class, 'render' ),
// @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- Core should ideally document null for no-callback arg. https://core.trac.wordpress.org/ticket/52539.
null,
array(),
'side',
'high'
);
}
}
/**
* Render the Jetpack Newsletter widget.
*
* @return void
*/
public static function render() {
?>
<div id="wpcom">
<div id="newsletter-widget-app"></div>
</div>
<?php
}
/**
* Load the admin scripts for the Jetpack Newsletter widget.
*
* @param string $asset_handle The handle of the asset.
* @param string $asset_name The name of the asset.
* @param array $options The options for the asset.
* @return void
*/
public static function load_admin_scripts( $asset_handle, $asset_name, $options = array() ) {
$default_options = array(
'config_data' => array(),
'config_variable_name' => 'configData',
'enqueue_css' => true,
'load_minified_js' => true,
);
$options = wp_parse_args( $options, $default_options );
// Get the asset file path
$asset_path = JETPACK__PLUGIN_DIR . '_inc/build/' . $asset_name . '.min.asset.php';
// Get dependencies and version from asset file
$dependencies = array();
$version = JETPACK__VERSION;
if ( file_exists( $asset_path ) ) {
$asset = require $asset_path;
$dependencies = $asset['dependencies'];
$version = $asset['version'];
}
$file_extension = '.min.js';
if ( ! $options['load_minified_js'] ) {
$file_extension = '.js';
}
// Register and enqueue the script
wp_register_script(
$asset_handle,
plugins_url( '_inc/build/' . $asset_name . $file_extension, JETPACK__PLUGIN_FILE ),
$dependencies,
$version,
true
);
wp_enqueue_script( $asset_handle );
if ( in_array( 'wp-i18n', $dependencies, true ) ) {
wp_set_script_translations( $asset_handle, 'jetpack' );
}
// Enqueue the CSS if enabled
if ( $options['enqueue_css'] ) {
wp_enqueue_style(
$asset_handle,
plugins_url( '_inc/build/' . $asset_name . '.css', JETPACK__PLUGIN_FILE ),
array(),
$version
);
// Enqueue RTL stylesheet if needed
if ( is_rtl() ) {
wp_enqueue_style(
$asset_handle . '-rtl',
plugins_url( '_inc/build/' . $asset_name . '.rtl.css', JETPACK__PLUGIN_FILE ),
array( $asset_handle ),
$version
);
}
}
// Add any configuration data if needed
if ( ! empty( $options['config_data'] ) ) {
wp_add_inline_script(
$asset_handle,
"window.{$options['config_variable_name']} = " . wp_json_encode( $options['config_data'], JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) . ';',
'before'
);
}
}
}
add_action(
'wp_dashboard_setup',
array( 'Jetpack_Newsletter_Dashboard_Widget', 'init' )
);
@@ -0,0 +1,205 @@
<?php
/**
* Adds support for Jetpack floating Subscribe button feature
*
* @package automattic/jetpack-subscriptions
* @since 14.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit( 0 );
}
/**
* Jetpack_Subscribe_Floating_Button class.
*/
class Jetpack_Subscribe_Floating_Button {
/**
* Jetpack_Subscribe_Floating_Button singleton instance.
*
* @var Jetpack_Subscribe_Floating_Button|null
*/
private static $instance;
/**
* Jetpack_Subscribe_Floating_Button instance init.
*/
public static function init() {
if ( self::$instance === null ) {
self::$instance = new Jetpack_Subscribe_Floating_Button();
}
return self::$instance;
}
const BLOCK_TEMPLATE_PART_SLUG = 'jetpack-subscribe-floating-button';
/**
* Jetpack_Subscribe_Floating_Button class constructor.
*/
public function __construct() {
if ( get_option( 'jetpack_subscribe_floating_button_enabled', false ) ) {
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
add_action( 'wp_footer', array( $this, 'add_subscribe_floating_button_to_frontend' ) );
}
add_filter( 'get_block_template', array( $this, 'get_block_template_filter' ), 10, 3 );
add_filter(
'jetpack_options_whitelist',
function ( $options ) {
$options[] = 'jetpack_subscribe_floating_button_enabled';
return $options;
}
);
}
/**
* Returns the block template part ID.
*
* @return string
*/
public static function get_block_template_part_id() {
return get_stylesheet() . '//' . self::BLOCK_TEMPLATE_PART_SLUG;
}
/**
* Makes get_block_template return the WP_Block_Template for the floating Subscribe button.
*
* @param WP_Block_Template $block_template The block template to be returned.
* @param string $id Template unique identifier (example: theme_slug//template_slug).
* @param string $template_type Template type: `'wp_template'` or '`wp_template_part'`.
*
* @return WP_Block_Template|null
*/
public function get_block_template_filter( $block_template, $id, $template_type ) {
if ( empty( $block_template ) && $template_type === 'wp_template_part' ) {
if ( $id === self::get_block_template_part_id() ) {
return $this->get_template();
}
}
return $block_template;
}
/**
* Returns a custom template for the floating Subscribe button.
*
* @return WP_Block_Template
*/
public function get_template() {
$template = new WP_Block_Template();
$template->theme = get_stylesheet();
$template->slug = self::BLOCK_TEMPLATE_PART_SLUG;
$template->id = self::get_block_template_part_id();
$template->area = 'uncategorized';
$template->content = $this->get_floating_subscribe_button_template_content();
$template->source = 'plugin';
$template->type = 'wp_template_part';
$template->title = __( 'Jetpack Subscribe floating button', 'jetpack' );
$template->status = 'publish';
$template->has_theme_file = false;
$template->is_custom = true;
$template->description = __( 'A floating subscribe button that shows up when someone visits your site.', 'jetpack' );
return $template;
}
/**
* Returns the initial content of the floating Subscribe button template.
* This can then be edited by the user.
*
* @return string
*/
public function get_floating_subscribe_button_template_content() {
$block_name = esc_attr__( 'Floating subscribe button', 'jetpack' );
return '<!-- wp:jetpack/subscriptions {"className":"is-style-button","appSource":"subscribe-floating-button","lock":{"move":false,"remove":true},"style":{"spacing":{"margin":{"right":"20px","left":"20px","top":"20px","bottom":"20px"}}},"metadata":{"name":"' . $block_name . '"}} /-->';
}
/**
* Enqueues styles.
*
* @return void
*/
public function enqueue_assets() {
if ( $this->should_user_see_floating_button() ) {
wp_enqueue_style( 'subscribe-floating-button-css', plugins_url( 'subscribe-floating-button.css', __FILE__ ), array(), JETPACK__VERSION );
// Disables WP.com action bar as the features collide/overlap
add_filter( 'wpcom_disable_logged_out_follow', '__return_true', 10, 1 );
}
}
/**
* Adds floating Subscribe button HTML wrapper
*
* @return void
*/
public function add_subscribe_floating_button_to_frontend() {
if ( $this->should_user_see_floating_button() ) { ?>
<div class="jetpack-subscribe-floating-button">
<?php block_template_part( self::BLOCK_TEMPLATE_PART_SLUG ); ?>
</div>
<?php
}
}
/**
* Returns true if a site visitor should see
* the floating Subscribe button.
*
* @return bool
*/
public function should_user_see_floating_button() {
// Only show when viewing frontend.
if ( is_admin() ) {
return false;
}
// No content to subscribe to on 404 pages.
if ( is_404() ) {
return false;
}
// Needed because Elementor editor makes is_admin() return false
// See https://coreysalzano.com/wordpress/why-elementor-disobeys-is_admin/
// Ignore nonce warning as just checking if is set
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['elementor-preview'] ) ) {
return false;
}
// Don't show when previewing blog posts or site's theme
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['preview'] ) || isset( $_GET['theme_preview'] ) || isset( $_GET['customize_preview'] ) || isset( $_GET['hide_banners'] ) ) {
return false;
}
// Don't show if one of subscribe query params is set.
// They are set when user submits the subscribe form.
// The nonce is checked elsewhere before redirect back to this page with query params.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['subscribe'] ) || isset( $_GET['blogsub'] ) ) {
return false;
}
// Don't show if user is subscribed to blog.
require_once __DIR__ . '/../views.php';
if ( ! class_exists( 'Jetpack_Memberships' ) || Jetpack_Memberships::is_current_user_subscribed() ) {
return false;
}
return true;
}
}
Jetpack_Subscribe_Floating_Button::init();
add_action(
'rest_api_switched_to_blog',
function () {
Jetpack_Subscribe_Floating_Button::init();
}
);
@@ -0,0 +1,6 @@
.jetpack-subscribe-floating-button {
position: fixed;
z-index: 50000; /* Same as WP.com Action bar */
bottom: 0;
right: 0;
}
@@ -0,0 +1,268 @@
<?php
/**
* Adds support for Jetpack Subscribe Modal feature
*
* @package automattic/jetpack-mu-wpcom
* @since 12.4
*/
use Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service\Abstract_Token_Subscription_Service;
use const Automattic\Jetpack\Extensions\Subscriptions\META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS;
/**
* Jetpack_Subscribe_Modal class.
*/
class Jetpack_Subscribe_Modal {
/**
* Jetpack_Subscribe_Modal singleton instance.
*
* @var Jetpack_Subscribe_Modal|null
*/
private static $instance;
/**
* Jetpack_Subscribe_Modal instance init.
*/
public static function init() {
if ( self::$instance === null ) {
self::$instance = new Jetpack_Subscribe_Modal();
}
return self::$instance;
}
const BLOCK_TEMPLATE_PART_SLUG = 'jetpack-subscribe-modal';
/**
* Returns the block template part ID.
*
* @return string
*/
public static function get_block_template_part_id() {
return get_stylesheet() . '//' . self::BLOCK_TEMPLATE_PART_SLUG;
}
/**
* Jetpack_Subscribe_Modal class constructor.
*/
public function __construct() {
if ( get_option( 'sm_enabled', false ) ) {
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
add_action( 'wp_footer', array( $this, 'add_subscribe_modal_to_frontend' ) );
}
add_filter( 'get_block_template', array( $this, 'get_block_template_filter' ), 10, 3 );
}
/**
* Enqueues JS to load modal.
*
* @return void
*/
public function enqueue_assets() {
if ( $this->should_user_see_modal() ) {
wp_enqueue_style( 'subscribe-modal-css', plugins_url( 'subscribe-modal.css', __FILE__ ), array(), JETPACK__VERSION );
wp_enqueue_script( 'subscribe-modal-js', plugins_url( 'subscribe-modal.js', __FILE__ ), array( 'wp-dom-ready' ), JETPACK__VERSION, true );
/**
* Filter how many milliseconds until the Subscribe Modal appears.
*
* @module subscriptions
*
* @since 13.4
*
* @param int 60000 Time in milliseconds for the Subscribe Modal to appear.
*/
$load_time = absint( apply_filters( 'jetpack_subscribe_modal_load_time', 60000 ) );
/**
* Filter how many percentage of the page should be scrolled before the Subscribe Modal appears.
*
* @module subscriptions
*
* @since 13.6
*
* @param int Percentage of the page scrolled before the Subscribe Modal appears.
*/
$scroll_threshold = absint( apply_filters( 'jetpack_subscribe_modal_scroll_threshold', 50 ) );
/**
* Filter to control the interval at which the subscribe modal is shown to the same user. The default interval is 24 hours.
*
* @since 13.7
*
* @param int 24 Hours before we show the same user the Subscribe Modal to again.
*/
$modal_interval = absint( apply_filters( 'jetpack_subscribe_modal_interval', 24 ) );
wp_localize_script(
'subscribe-modal-js',
'Jetpack_Subscriptions',
array(
'modalLoadTime' => $load_time,
'modalScrollThreshold' => $scroll_threshold,
'modalInterval' => ( $modal_interval * HOUR_IN_SECONDS * 1000 ),
)
);
}
}
/**
* Adds modal with Subscribe Modal content.
*
* @return void
*/
public function add_subscribe_modal_to_frontend() {
if ( $this->should_user_see_modal() ) { ?>
<div class="jetpack-subscribe-modal">
<div class="jetpack-subscribe-modal__modal-content">
<?php block_template_part( self::BLOCK_TEMPLATE_PART_SLUG ); ?>
</div>
</div>
<?php
}
}
/**
* Makes get_block_template return the WP_Block_Template for the Subscribe Modal.
*
* @param WP_Block_Template $block_template The block template to be returned.
* @param string $id Template unique identifier (example: theme_slug//template_slug).
* @param string $template_type Template type: `'wp_template'` or '`wp_template_part'`.
*
* @return WP_Block_Template
*/
public function get_block_template_filter( $block_template, $id, $template_type ) {
if ( empty( $block_template ) && $template_type === 'wp_template_part' ) {
if ( $id === self::get_block_template_part_id() ) {
return $this->get_template();
}
}
return $block_template;
}
/**
* Returns a custom template for the Subscribe Modal.
*
* @return WP_Block_Template
*/
public function get_template() {
$template = new WP_Block_Template();
$template->theme = get_stylesheet();
$template->slug = self::BLOCK_TEMPLATE_PART_SLUG;
$template->id = self::get_block_template_part_id();
$template->area = 'uncategorized';
$template->content = $this->get_subscribe_template_content();
$template->source = 'plugin';
$template->type = 'wp_template_part';
$template->title = __( 'Jetpack Subscribe modal', 'jetpack' );
$template->status = 'publish';
$template->has_theme_file = false;
$template->is_custom = true;
$template->description = __( 'A subscribe form that pops up when someone visits your site.', 'jetpack' );
return $template;
}
/**
* Returns the initial content of the Subscribe Modal template.
* This can then be edited by the user.
*
* @return string
*/
public function get_subscribe_template_content() {
// translators: %s is the name of the site.
$discover_more_from = sprintf( __( 'Discover more from %s', 'jetpack' ), get_bloginfo( 'name' ) );
$continue_reading = __( 'Continue reading', 'jetpack' );
$subscribe_text = __( 'Subscribe now to keep reading and get access to the full archive.', 'jetpack' );
$group_block_name = esc_attr__( 'Subscription pop-up container', 'jetpack' );
return <<<HTML
<!-- wp:group {"metadata":{"name":"$group_block_name"},"style":{"spacing":{"padding":{"top":"32px","bottom":"32px","left":"32px","right":"32px"},"margin":{"top":"0","bottom":"0"}},"border":{"color":"#dddddd","width":"1px"}},"layout":{"type":"constrained","contentSize":"450px"}} -->
<div class="wp-block-group has-border-color" style="border-color:#dddddd;border-width:1px;margin-top:0;margin-bottom:0;padding-top:32px;padding-right:32px;padding-bottom:32px;padding-left:32px">
<!-- wp:heading {"textAlign":"center","style":{"typography":{"fontStyle":"normal","fontWeight":"600","fontSize":"26px"},"layout":{"selfStretch":"fit","flexSize":null},"spacing":{"margin":{"top":"4px","bottom":"10px"}}}} -->
<h2 class="wp-block-heading has-text-align-center" style="margin-top:4px;margin-bottom:10px;font-size:26px;font-style:normal;font-weight:600">$discover_more_from</h2>
<!-- /wp:heading -->
<!-- wp:paragraph {"align":"center","style":{"typography":{"fontSize":"15px"},"spacing":{"margin":{"top":"4px","bottom":"0px"}}}} -->
<p class='has-text-align-center' style='margin-top:4px;margin-bottom:1em;font-size:15px'>$subscribe_text</p>
<!-- /wp:paragraph -->
<!-- wp:jetpack/subscriptions {"borderRadius":50,"className":"is-style-compact","appSource":"subscribe-modal"} /-->
<!-- wp:paragraph {"align":"center","style":{"spacing":{"margin":{"top":"20px"}},"typography":{"fontSize":"14px"}},"className":"jetpack-subscribe-modal__close"} -->
<p class="has-text-align-center jetpack-subscribe-modal__close" style="margin-top:20px;margin-bottom:0;font-size:14px"><a href="#">$continue_reading</a></p>
<!-- /wp:paragraph -->
</div>
<!-- /wp:group -->
HTML;
}
/**
* Returns true if a site visitor should see
* the Subscribe Modal.
*
* @return bool
*/
public function should_user_see_modal() {
// Only show when viewing frontend single post.
if ( is_admin() || ! is_singular( 'post' ) ) {
return false;
}
// Needed because Elementor editor makes is_admin() return false
// See https://coreysalzano.com/wordpress/why-elementor-disobeys-is_admin/
// Ignore nonce warning as just checking if is set
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['elementor-preview'] ) ) {
return false;
}
// Don't show when previewing blog posts or site's theme
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['preview'] ) || isset( $_GET['theme_preview'] ) || isset( $_GET['customize_preview'] ) || isset( $_GET['hide_banners'] ) ) {
return false;
}
// Don't show if one of subscribe query params is set.
// They are set when user submits the subscribe form.
// The nonce is checked elsewhere before redirect back to this page with query params.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['subscribe'] ) || isset( $_GET['blogsub'] ) ) {
return false;
}
// Don't show if post is not a post, is for subscribers only, or has paywall block
global $post;
if ( ! $post instanceof WP_Post ) {
return false;
}
if ( defined( 'Automattic\\Jetpack\\Extensions\\Subscriptions\\META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS' ) ) {
$access_level = get_post_meta( $post->ID, META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS, true );
} else {
$access_level = get_post_meta( $post->ID, '_jetpack_newsletter_access', true );
}
require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/premium-content/_inc/subscription-service/include.php';
$is_accessible_by_everyone = Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_EVERYBODY === $access_level || empty( $access_level );
if ( ! $is_accessible_by_everyone ) {
return false;
}
// Don't show if user is subscribed to blog.
require_once __DIR__ . '/../views.php';
if ( ! class_exists( 'Jetpack_Memberships' ) || Jetpack_Memberships::is_current_user_subscribed() ) {
return false;
}
return true;
}
}
Jetpack_Subscribe_Modal::init();
add_action(
'rest_api_switched_to_blog',
function () {
Jetpack_Subscribe_Modal::init();
}
);
@@ -0,0 +1,58 @@
body.jetpack-subscribe-modal-open {
overflow: hidden;
}
.jetpack-subscribe-modal {
visibility: hidden;
position: fixed;
z-index: 50000; /* Same as WP.com Action bar */
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: transparent;
transition: all 0.4s;
}
.jetpack-subscribe-modal.open {
background-color: rgba(0, 0, 0, 0.3);
visibility: visible;
}
.jetpack-subscribe-modal__modal-content {
position: relative;
visibility: hidden;
overflow: hidden;
top: 100%;
background-color: #fefefe;
margin: 15% auto;
width: 100%;
max-width: 600px;
border-radius: 10px;
box-sizing: border-box;
transition: all 0.4s;
text-wrap: balance;
}
.jetpack-subscribe-modal.open .jetpack-subscribe-modal__modal-content {
top: 0;
visibility: visible;
}
/*
* These text-wrap properties still have limited browser
* support, but based on feedback still adding them for when
* they are supported.
*/
.jetpack-subscribe-modal__modal-content p {
text-wrap: balance;
text-wrap: pretty;
}
@media screen and (max-width: 640px) {
.jetpack-subscribe-modal__modal-content {
width: 94%;
}
}
@@ -0,0 +1,123 @@
/* global Jetpack_Subscriptions */
const { domReady } = wp;
domReady( () => {
const modal = document.querySelector( '.jetpack-subscribe-modal' );
const modalDismissedCookie = 'jetpack_post_subscribe_modal_dismissed';
const skipUrlParam = 'jetpack_skip_subscription_popup';
function hasEnoughTimePassed() {
const lastDismissed = localStorage.getItem( modalDismissedCookie );
return lastDismissed ? Date.now() - lastDismissed > Jetpack_Subscriptions.modalInterval : true;
}
// Subscriber ended up here e.g. from emails:
// we won't show the modal to them in future since they most likely are already a subscriber.
function skipModal() {
const url = new URL( window.location.href );
if ( url.searchParams.has( skipUrlParam ) ) {
url.searchParams.delete( skipUrlParam );
window.history.replaceState( {}, '', url );
storeCloseTimestamp();
return true;
}
return false;
}
if ( ! modal || ! hasEnoughTimePassed() || skipModal() ) {
return;
}
const modalLoadTimeout = setTimeout( openModal, Jetpack_Subscriptions.modalLoadTime );
const targetElement = (
document.querySelector( '.entry-content' ) || document.documentElement
).getBoundingClientRect();
function hasPassedScrollThreshold() {
const scrollPosition = window.scrollY + window.innerHeight / 2;
const scrollPositionThreshold =
targetElement.top +
( targetElement.height * Jetpack_Subscriptions.modalScrollThreshold ) / 100;
return scrollPosition > scrollPositionThreshold;
}
function onScroll() {
requestAnimationFrame( () => {
if ( hasPassedScrollThreshold() ) {
openModal();
}
} );
}
window.addEventListener( 'scroll', onScroll, { passive: true } );
// This take care of the case where the user has multiple tabs open.
function onLocalStorage( event ) {
if ( event.key === modalDismissedCookie ) {
closeModal();
removeEventListeners();
}
}
window.addEventListener( 'storage', onLocalStorage );
// When the form is submitted, and next modal loads, it'll fire "subscription-modal-loaded" signalling that this form can be hidden.
const form = modal.querySelector( 'form' );
if ( form ) {
form.addEventListener( 'subscription-modal-loaded', closeModal );
}
// User can edit modal, and could remove close link.
function onCloseButtonClick( event ) {
event.preventDefault();
closeModal();
}
const close = document.getElementsByClassName( 'jetpack-subscribe-modal__close' )[ 0 ];
if ( close ) {
close.addEventListener( 'click', onCloseButtonClick );
}
function closeOnWindowClick( event ) {
if ( event.target === modal ) {
closeModal();
}
}
function closeModalOnEscapeKeydown( event ) {
if ( event.key === 'Escape' ) {
closeModal();
}
}
function openModal() {
// If the user is typing in a form, don't open the modal or has anything else focused.
if ( document.activeElement && document.activeElement.tagName !== 'BODY' ) {
return;
}
modal.classList.add( 'open' );
document.body.classList.add( 'jetpack-subscribe-modal-open' );
window.addEventListener( 'keydown', closeModalOnEscapeKeydown );
window.addEventListener( 'click', closeOnWindowClick );
removeEventListeners();
}
function closeModal() {
modal.classList.remove( 'open' );
document.body.classList.remove( 'jetpack-subscribe-modal-open' );
window.removeEventListener( 'keydown', closeModalOnEscapeKeydown );
window.removeEventListener( 'storage', onLocalStorage );
window.removeEventListener( 'click', closeOnWindowClick );
storeCloseTimestamp();
}
// Remove all event listeners. That would add the modal again.
function removeEventListeners() {
window.removeEventListener( 'scroll', onScroll );
clearTimeout( modalLoadTimeout );
}
function storeCloseTimestamp() {
localStorage.setItem( modalDismissedCookie, Date.now() );
}
} );
@@ -0,0 +1,233 @@
<?php
/**
* Adds support for Jetpack Subscribe Overlay feature
*
* @package automattic/jetpack-subscriptions
* @since 13.5
*/
if ( ! defined( 'ABSPATH' ) ) {
exit( 0 );
}
/**
* Jetpack_Subscribe_Overlay class.
*/
class Jetpack_Subscribe_Overlay {
/**
* Jetpack_Subscribe_Overlay singleton instance.
*
* @var Jetpack_Subscribe_Overlay|null
*/
private static $instance;
/**
* Jetpack_Subscribe_Overlay instance init.
*/
public static function init() {
if ( self::$instance === null ) {
self::$instance = new Jetpack_Subscribe_Overlay();
}
return self::$instance;
}
const BLOCK_TEMPLATE_PART_SLUG = 'jetpack-subscribe-overlay';
/**
* Jetpack_Subscribe_Overlay class constructor.
*/
public function __construct() {
if ( get_option( 'jetpack_subscribe_overlay_enabled', false ) ) {
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
add_action( 'wp_footer', array( $this, 'add_subscribe_overlay_to_frontend' ) );
}
add_filter( 'get_block_template', array( $this, 'get_block_template_filter' ), 10, 3 );
add_filter(
'jetpack_options_whitelist',
function ( $options ) {
$options[] = 'jetpack_subscribe_overlay_enabled';
return $options;
}
);
}
/**
* Returns the block template part ID.
*
* @return string
*/
public static function get_block_template_part_id() {
return get_stylesheet() . '//' . self::BLOCK_TEMPLATE_PART_SLUG;
}
/**
* Makes get_block_template return the WP_Block_Template for the Subscribe Overlay.
*
* @param WP_Block_Template $block_template The block template to be returned.
* @param string $id Template unique identifier (example: theme_slug//template_slug).
* @param string $template_type Template type: `'wp_template'` or '`wp_template_part'`.
*
* @return WP_Block_Template|null
*/
public function get_block_template_filter( $block_template, $id, $template_type ) {
if ( empty( $block_template ) && $template_type === 'wp_template_part' ) {
if ( $id === self::get_block_template_part_id() ) {
return $this->get_template();
}
}
return $block_template;
}
/**
* Returns a custom template for the Subscribe Overlay.
*
* @return WP_Block_Template
*/
public function get_template() {
$template = new WP_Block_Template();
$template->theme = get_stylesheet();
$template->slug = self::BLOCK_TEMPLATE_PART_SLUG;
$template->id = self::get_block_template_part_id();
$template->area = 'uncategorized';
$template->content = $this->get_subscribe_overlay_template_content();
$template->source = 'plugin';
$template->type = 'wp_template_part';
$template->title = __( 'Jetpack Subscribe overlay', 'jetpack' );
$template->status = 'publish';
$template->has_theme_file = false;
$template->is_custom = true;
$template->description = __( 'An overlay that shows up when someone visits your site.', 'jetpack' );
return $template;
}
/**
* Returns the initial content of the Subscribe Overlay template.
* This can then be edited by the user.
*
* @return string
*/
public function get_subscribe_overlay_template_content() {
$home_url = get_home_url();
$site_tagline = get_bloginfo( 'description' );
$default_tagline = __( 'Stay informed with curated content and the latest headlines, all delivered straight to your inbox. Subscribe now to stay ahead and never miss a beat!', 'jetpack' );
$tagline_block = empty( $site_tagline )
? '<!-- wp:paragraph {"align":"center","fontSize":"medium"} --><p class="has-text-align-center has-medium-font-size">' . $default_tagline . '</p><!-- /wp:paragraph -->'
: '<!-- wp:site-tagline {"textAlign":"center","fontSize":"medium"} /-->';
$skip_to_content = __( 'Skip to content', 'jetpack' );
$group_block_name = esc_attr__( 'Subscribe overlay container', 'jetpack' );
return <<<HTML
<!-- wp:group {"metadata":{"name":"$group_block_name"},"style":{"spacing":{"padding":{"top":"0","bottom":"0","left":"0","right":"0"}}},"layout":{"type":"constrained","contentSize":"400px"}} -->
<div class="wp-block-group" style="padding-top:0;padding-right:0;padding-bottom:0;padding-left:0">
<!-- wp:site-logo {"width":90,"isLink":false,"shouldSyncIcon":true,"align":"center","className":"is-style-rounded"} /-->
<!-- wp:site-title {"textAlign":"center","isLink":false,"fontSize":"x-large"} /-->
$tagline_block
<!-- wp:jetpack/subscriptions {"appSource":"subscribe-overlay"} /-->
<!-- wp:paragraph {"align":"center","className":"jetpack-subscribe-overlay__to-content"} -->
<p class="has-text-align-center jetpack-subscribe-overlay__to-content"><a href="$home_url">$skip_to_content ↓</a></p>
<!-- /wp:paragraph -->
</div>
<!-- /wp:group -->
HTML;
}
/**
* Enqueues JS to load overlay.
*
* @return void
*/
public function enqueue_assets() {
if ( $this->should_user_see_overlay() ) {
wp_enqueue_style( 'subscribe-overlay-css', plugins_url( 'subscribe-overlay.css', __FILE__ ), array(), JETPACK__VERSION );
wp_enqueue_script( 'subscribe-overlay-js', plugins_url( 'subscribe-overlay.js', __FILE__ ), array( 'wp-dom-ready' ), JETPACK__VERSION, true );
}
}
/**
* Adds overlay with Subscribe Overlay content.
*
* @return void
*/
public function add_subscribe_overlay_to_frontend() {
if ( $this->should_user_see_overlay() ) { ?>
<div class="jetpack-subscribe-overlay">
<div class="jetpack-subscribe-overlay__close">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<path d="M5.40456 5L19 19M5 19L18.5954 5" stroke="currentColor" stroke-width="1.5"/>
</svg>
</div>
<div class="jetpack-subscribe-overlay__content">
<?php block_template_part( self::BLOCK_TEMPLATE_PART_SLUG ); ?>
</div>
</div>
<?php
}
}
/**
* Returns true if a site visitor should see
* the Subscribe Overlay.
*
* @return bool
*/
public function should_user_see_overlay() {
// Only show when viewing frontend.
if ( is_admin() ) {
return false;
}
// The overlay only appears on the blog home and front page.
if ( ! is_home() && ! is_front_page() ) {
return false;
}
// Needed because Elementor editor makes is_admin() return false
// See https://coreysalzano.com/wordpress/why-elementor-disobeys-is_admin/
// Ignore nonce warning as just checking if is set
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['elementor-preview'] ) ) {
return false;
}
// Don't show when previewing blog posts or site's theme
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['preview'] ) || isset( $_GET['theme_preview'] ) || isset( $_GET['customize_preview'] ) || isset( $_GET['hide_banners'] ) ) {
return false;
}
// Don't show if one of subscribe query params is set.
// They are set when user submits the subscribe form.
// The nonce is checked elsewhere before redirect back to this page with query params.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['subscribe'] ) || isset( $_GET['blogsub'] ) ) {
return false;
}
// Don't show if user is subscribed to blog.
require_once __DIR__ . '/../views.php';
if ( ! class_exists( 'Jetpack_Memberships' ) || Jetpack_Memberships::is_current_user_subscribed() ) {
return false;
}
return true;
}
}
Jetpack_Subscribe_Overlay::init();
add_action(
'rest_api_switched_to_blog',
function () {
Jetpack_Subscribe_Overlay::init();
}
);
@@ -0,0 +1,86 @@
body.jetpack-subscribe-overlay-open {
overflow: hidden;
}
.jetpack-subscribe-overlay {
--jetpack-subscribe-overlay--background-color: var(--wp--preset--color--background, var(--wp--preset--color--base, var(--wp--preset--color--contrast, #f9f9f9)));
visibility: hidden;
position: fixed;
z-index: 50001; /* WP.com Action bar and floating subscribe button are 5000 */
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: transparent;
transition: background-color 0.4s, visibility 0.4s;
}
.jetpack-subscribe-overlay__content {
position: relative;
visibility: hidden;
overflow: hidden;
top: 100%;
margin: 15% auto;
width: 100%;
max-width: 400px;
transition: top 0.4s, visibility 0.4s;
text-wrap: pretty;
}
.jetpack-subscribe-overlay__close {
display: none;
cursor: pointer;
position: absolute;
top: 32px;
right: 32px;
width: 24px;
height: 24px;
}
body.admin-bar .jetpack-subscribe-overlay__close {
top: 64px;
}
body.has-marketing-bar .jetpack-subscribe-overlay__close {
top: 81px;
}
body.admin-bar.has-marketing-bar .jetpack-subscribe-overlay__close {
top: 114px;
}
.jetpack-subscribe-overlay__to-content {
display: none;
position: fixed;
bottom: 64px;
left: 0;
right: 0;
margin: 0 auto;
}
.jetpack-subscribe-overlay.open {
background-color: var(--jetpack-subscribe-overlay--background-color);
visibility: visible;
.jetpack-subscribe-overlay__content {
top: 0;
visibility: visible;
}
.jetpack-subscribe-overlay__close {
display: block;
}
.jetpack-subscribe-overlay__to-content {
display: block;
}
}
@media screen and (max-width: 640px) {
.jetpack-subscribe-overlay__content {
width: 94%;
}
}
@@ -0,0 +1,73 @@
const { domReady } = wp;
domReady( function () {
const overlay = document.querySelector( '.jetpack-subscribe-overlay' );
const overlayDismissedCookie = 'jetpack_post_subscribe_overlay_dismissed';
const skipUrlParam = 'jetpack_skip_subscription_popup';
const hasOverlayDismissedCookie =
document.cookie && document.cookie.indexOf( overlayDismissedCookie ) > -1;
// Subscriber ended up here e.g. from emails:
// we won't show the overlay to them in future since they most likely are already a subscriber.
function skipOverlay() {
const url = new URL( window.location.href );
if ( url.searchParams.has( skipUrlParam ) ) {
url.searchParams.delete( skipUrlParam );
window.history.replaceState( {}, '', url );
setOverlayDismissedCookie();
return true;
}
return false;
}
if ( ! overlay || hasOverlayDismissedCookie || skipOverlay() ) {
return;
}
const close = overlay.querySelector( '.jetpack-subscribe-overlay__close' );
close.onclick = function ( event ) {
event.preventDefault();
closeOverlay();
};
const toContent = overlay.querySelector( '.jetpack-subscribe-overlay__to-content' );
// User can edit overlay, and could remove to content link.
if ( toContent ) {
toContent.onclick = function ( event ) {
event.preventDefault();
closeOverlay();
};
}
// When the form is submitted, and next modal loads, it'll fire "subscription-modal-loaded" signalling that this form can be hidden.
const form = overlay.querySelector( 'form' );
if ( form ) {
form.addEventListener( 'subscription-modal-loaded', closeOverlay );
}
function closeOverlayOnEscapeKeydown( event ) {
if ( event.key === 'Escape' ) {
closeOverlay();
}
}
function openOverlay() {
overlay.classList.add( 'open' );
document.body.classList.add( 'jetpack-subscribe-overlay-open' );
setOverlayDismissedCookie();
window.addEventListener( 'keydown', closeOverlayOnEscapeKeydown );
}
function closeOverlay() {
overlay.classList.remove( 'open' );
document.body.classList.remove( 'jetpack-subscribe-overlay-open' );
window.removeEventListener( 'keydown', closeOverlayOnEscapeKeydown );
}
function setOverlayDismissedCookie() {
document.cookie = `${ overlayDismissedCookie }=true; path=/;`;
}
openOverlay();
} );
@@ -0,0 +1,28 @@
#subscribe-email input {
width: 95%;
}
.comment-subscription-form {
margin-bottom: 1em;
}
.comment-subscription-form .subscribe-label {
display: inline !important;
}
/*
Text meant only for screen readers.
Provides support for themes that do not bundle this CSS yet.
@see https://make.wordpress.org/accessibility/2015/02/09/hiding-text-for-screen-readers-with-wordpress-core/
***********************************/
.screen-reader-text {
border: 0;
clip-path: inset(50%);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute !important;
width: 1px;
overflow-wrap: normal !important;
}
File diff suppressed because it is too large Load Diff