Skip to content

Commit

Permalink
Refactor subscriptions code so it can be used in Fusion (#11023)
Browse files Browse the repository at this point in the history
Fixes a problem we've seen in developing the subscription block where we sometimes
forget to make the equivalent upstream changes.

#### Changes proposed in this Pull Request:

* Moves the class Jetpack_Subscriptions_Widget into /modules/subscriptions/views.php
* Moves the registration for the subscriptions block into /modules/subscriptions/views.php
* /modules/subscriptions/views.php will be shared with wordpress.com

#### Testing instructions:

- Get this branch running locally or on jurassic.ninja
- Ensure subscription widgets still function as usual
- add a widget to the blog
- add a subscription block to a post
- try subscribing from the front end

#### Proposed changelog entry for your changes:
No changelog needed
  • Loading branch information
roccotripaldi authored and jeherve committed Jan 3, 2019
1 parent f3b4986 commit 1c3ce55
Show file tree
Hide file tree
Showing 3 changed files with 740 additions and 357 deletions.
358 changes: 1 addition & 357 deletions modules/subscriptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,6 @@ function __construct() {
// Add Configuration Page
add_action( 'admin_init', array( $this, 'configure' ) );

// Set up the subscription widget.
add_action( 'widgets_init', array( $this, 'widget_init' ) );

// Catch subscription widget submits
if ( isset( $_REQUEST['jetpack_subscriptions_widget'] ) )
add_action( 'template_redirect', array( $this, 'widget_submit' ) );
Expand Down Expand Up @@ -514,15 +511,6 @@ function subscribe( $email, $post_ids = 0, $async = true, $extra_data = array()
return $r;
}

/**
* Jetpack_Subscriptions::widget_init()
*
* Initialize and register the Jetpack Subscriptions widget.
*/
function widget_init() {
register_widget( 'Jetpack_Subscriptions_Widget' );
}

/**
* Jetpack_Subscriptions::widget_submit()
*
Expand Down Expand Up @@ -787,348 +775,4 @@ function set_cookies( $subscribe_to_post = false, $post_id = null, $subscribe_to

Jetpack_Subscriptions::init();


/***
* Blog Subscription Widget
*/

class Jetpack_Subscriptions_Widget extends WP_Widget {
function __construct() {
$widget_ops = array(
'classname' => 'jetpack_subscription_widget',
'description' => esc_html__( 'Add an email signup form to allow people to subscribe to your blog.', 'jetpack' ),
'customize_selective_refresh' => true,
);

parent::__construct(
'blog_subscription',
/** This filter is documented in modules/widgets/facebook-likebox.php */
apply_filters( 'jetpack_widget_name', __( 'Blog Subscriptions', 'jetpack' ) ),
$widget_ops
);

if ( is_active_widget( false, false, $this->id_base ) || is_active_widget( false, false, 'monster' ) || is_customize_preview() ) {
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_style' ) );
}
}

/**
* Enqueue the form's CSS.
*
* @since 4.5.0
*/
function enqueue_style() {
wp_register_style( 'jetpack-subscriptions', plugins_url( 'subscriptions/subscriptions.css', __FILE__ ) );
wp_enqueue_style( 'jetpack-subscriptions' );
}

function widget( $args, $instance ) {
if (
( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) &&
/** This filter is already documented in modules/contact-form/grunion-contact-form.php */
false === apply_filters( 'jetpack_auto_fill_logged_in_user', false )
) {
$subscribe_email = '';
} else {
$current_user = wp_get_current_user();
if ( ! empty( $current_user->user_email ) ) {
$subscribe_email = esc_attr( $current_user->user_email );
} else {
$subscribe_email = '';
}
}

/** This action is already documented in modules/widgets/gravatar-profile.php */
do_action( 'jetpack_stats_extra', 'widget_view', 'jetpack_subscriptions' );

$source = 'widget';
$instance = wp_parse_args( (array) $instance, $this->defaults() );
$subscribe_text = isset( $instance['subscribe_text'] ) ? stripslashes( $instance['subscribe_text'] ) : '';
$subscribe_placeholder = isset( $instance['subscribe_placeholder'] ) ? stripslashes( $instance['subscribe_placeholder'] ) : '';
$subscribe_button = isset( $instance['subscribe_button'] ) ? stripslashes( $instance['subscribe_button'] ) : '';
$success_message = isset( $instance['success_message'] ) ? stripslashes( $instance['success_message'] ) : '';
$widget_id = esc_attr( !empty( $args['widget_id'] ) ? esc_attr( $args['widget_id'] ) : mt_rand( 450, 550 ) );

$show_subscribers_total = (bool) $instance['show_subscribers_total'];
$subscribers_total = self::fetch_subscriber_count();

if ( isset( $instance['show_only_email_and_button'] ) && $instance['show_only_email_and_button'] ) {
unset( $instance['title'] );
$subscribe_text = false;
}

// Give the input element a unique ID
/**
* Filter the subscription form's ID prefix.
*
* @module subscriptions
*
* @since 2.7.0
*
* @param string subscribe-field Subscription form field prefix.
* @param int $widget_id Widget ID.
*/
$subscribe_field_id = apply_filters( 'subscribe_field_id', 'subscribe-field', $widget_id );

// Display the subscription form
echo $args['before_widget'];

// Only show the title if there actually is a title
if( ! empty( $instance['title'] ) ) {
echo $args['before_title'] . esc_attr( $instance['title'] ) . $args['after_title'] . "\n";
}

$referer = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );

// Display any errors
if ( isset( $_GET['subscribe'] ) ) :
switch ( $_GET['subscribe'] ) :
case 'invalid_email' : ?>
<p class="error"><?php esc_html_e( 'The email you entered was invalid. Please check and try again.', 'jetpack' ); ?></p>
<?php break;
case 'opted_out' : ?>
<p class="error"><?php printf( __( 'The email address has opted out of subscription emails. <br /> You can manage your preferences at <a href="%1$s" title="%2$s" target="_blank">subscribe.wordpress.com</a>', 'jetpack' ),
'https://subscribe.wordpress.com/',
__( 'Manage your email preferences.', 'jetpack' )
); ?></p>
<?php break;
case 'already' : ?>
<p class="error"><?php printf( __( 'You have already subscribed to this site. Please check your inbox. <br /> You can manage your preferences at <a href="%1$s" title="%2$s" target="_blank">subscribe.wordpress.com</a>', 'jetpack' ),
'https://subscribe.wordpress.com/',
__( 'Manage your email preferences.', 'jetpack' )
); ?></p>
<?php break;
case 'success' : ?>
<div class="success"><?php echo wpautop( str_replace( '[total-subscribers]', number_format_i18n( $subscribers_total['value'] ), $success_message ) ); ?></div>
<?php break;
default : ?>
<p class="error"><?php esc_html_e( 'There was an error when subscribing. Please try again.', 'jetpack' ); ?></p>
<?php break;
endswitch;
endif;

// Display a subscribe form
if ( isset( $_GET['subscribe'] ) && 'success' == $_GET['subscribe'] ) { ?>
<?php
} else { ?>
<form action="#" method="post" accept-charset="utf-8" id="subscribe-blog-<?php echo $widget_id; ?>">
<?php
if ( $subscribe_text && ( ! isset ( $_GET['subscribe'] ) || 'success' != $_GET['subscribe'] ) ) {
?><div id="subscribe-text"><?php echo wpautop( str_replace( '[total-subscribers]', number_format_i18n( $subscribers_total['value'] ), $subscribe_text ) ); ?></div><?php
}

if ( $show_subscribers_total && 0 < $subscribers_total['value'] ) {
echo wpautop( sprintf( _n( 'Join %s other subscriber', 'Join %s other subscribers', $subscribers_total['value'], 'jetpack' ), number_format_i18n( $subscribers_total['value'] ) ) );
}
if ( ! isset ( $_GET['subscribe'] ) || 'success' != $_GET['subscribe'] ) { ?>
<p id="subscribe-email">
<label id="jetpack-subscribe-label" for="<?php echo esc_attr( $subscribe_field_id ) . '-' . esc_attr( $widget_id ); ?>">
<?php echo !empty( $subscribe_placeholder ) ? esc_html( $subscribe_placeholder ) : esc_html__( 'Email Address:', 'jetpack' ); ?>
</label>
<input type="email" name="email" required="required" class="required" value="<?php echo esc_attr( $subscribe_email ); ?>" id="<?php echo esc_attr( $subscribe_field_id ) . '-' . esc_attr( $widget_id ); ?>" placeholder="<?php echo esc_attr( $subscribe_placeholder ); ?>" />
</p>

<p id="subscribe-submit">
<input type="hidden" name="action" value="subscribe" />
<input type="hidden" name="source" value="<?php echo esc_url( $referer ); ?>" />
<input type="hidden" name="sub-type" value="<?php echo esc_attr( $source ); ?>" />
<input type="hidden" name="redirect_fragment" value="<?php echo $widget_id; ?>" />
<?php
if ( is_user_logged_in() ) {
wp_nonce_field( 'blogsub_subscribe_'. get_current_blog_id(), '_wpnonce', false );
}
?>
<input type="submit" value="<?php echo esc_attr( $subscribe_button ); ?>" name="jetpack_subscriptions_widget" />
</p>
<?php }?>
</form>

<script>
/*
Custom functionality for safari and IE
*/
(function( d ) {
// In case the placeholder functionality is available we remove labels
if ( ( 'placeholder' in d.createElement( 'input' ) ) ) {
var label = d.querySelector( 'label[for=subscribe-field-<?php echo $widget_id; ?>]' );
label.style.clip = 'rect(1px, 1px, 1px, 1px)';
label.style.position = 'absolute';
label.style.height = '1px';
label.style.width = '1px';
label.style.overflow = 'hidden';
}

// Make sure the email value is filled in before allowing submit
var form = d.getElementById('subscribe-blog-<?php echo $widget_id; ?>'),
input = d.getElementById('<?php echo esc_attr( $subscribe_field_id ) . '-' . esc_attr( $widget_id ); ?>'),
handler = function( event ) {
if ( '' === input.value ) {
input.focus();

if ( event.preventDefault ){
event.preventDefault();
}

return false;
}
};

if ( window.addEventListener ) {
form.addEventListener( 'submit', handler, false );
} else {
form.attachEvent( 'onsubmit', handler );
}
})( document );
</script>
<?php } ?>
<?php

echo "\n" . $args['after_widget'];
}

function increment_subscriber_count( $current_subs_array = array() ) {
$current_subs_array['value']++;

set_transient( 'wpcom_subscribers_total', $current_subs_array, 3600 ); // try to cache the result for at least 1 hour

return $current_subs_array;
}

static function fetch_subscriber_count() {
$subs_count = get_transient( 'wpcom_subscribers_total' );

if ( FALSE === $subs_count || 'failed' == $subs_count['status'] ) {
Jetpack:: load_xml_rpc_client();

$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );

$xml->query( 'jetpack.fetchSubscriberCount' );

if ( $xml->isError() ) { // if we get an error from .com, set the status to failed so that we will try again next time the data is requested
$subs_count = array(
'status' => 'failed',
'code' => $xml->getErrorCode(),
'message' => $xml->getErrorMessage(),
'value' => ( isset( $subs_count['value'] ) ) ? $subs_count['value'] : 0,
);
} else {
$subs_count = array(
'status' => 'success',
'value' => $xml->getResponse(),
);
}

set_transient( 'wpcom_subscribers_total', $subs_count, 3600 ); // try to cache the result for at least 1 hour
}

return $subs_count;
}

function update( $new_instance, $old_instance ) {
$instance = $old_instance;

$instance['title'] = wp_kses( stripslashes( $new_instance['title'] ), array() );
$instance['subscribe_text'] = wp_filter_post_kses( stripslashes( $new_instance['subscribe_text'] ) );
$instance['subscribe_placeholder'] = wp_kses( stripslashes( $new_instance['subscribe_placeholder'] ), array() );
$instance['subscribe_button'] = wp_kses( stripslashes( $new_instance['subscribe_button'] ), array() );
$instance['success_message'] = wp_kses( stripslashes( $new_instance['success_message'] ), array() );
$instance['show_subscribers_total'] = isset( $new_instance['show_subscribers_total'] ) && $new_instance['show_subscribers_total'];

return $instance;
}

public static function defaults() {
return array(
'title' => esc_html__( 'Subscribe to Blog via Email', 'jetpack' ),
'subscribe_text' => esc_html__( 'Enter your email address to subscribe to this blog and receive notifications of new posts by email.', 'jetpack' ),
'subscribe_placeholder' => esc_html__( 'Email Address', 'jetpack' ),
'subscribe_button' => esc_html__( 'Subscribe', 'jetpack' ),
'success_message' => esc_html__( "Success! An email was just sent to confirm your subscription. Please find the email now and click 'Confirm Follow' to start subscribing.", 'jetpack' ),
'show_subscribers_total' => true,
);
}

function form( $instance ) {
$instance = wp_parse_args( (array) $instance, $this->defaults() );

$title = stripslashes( $instance['title'] );
$subscribe_text = stripslashes( $instance['subscribe_text'] );
$subscribe_placeholder = stripslashes( $instance['subscribe_placeholder'] );
$subscribe_button = stripslashes( $instance['subscribe_button'] );
$success_message = stripslashes( $instance['success_message']);
$show_subscribers_total = checked( $instance['show_subscribers_total'], true, false );

$subs_fetch = self::fetch_subscriber_count();

if ( 'failed' == $subs_fetch['status'] ) {
printf( '<div class="error inline"><p>' . __( '%s: %s', 'jetpack' ) . '</p></div>', esc_html( $subs_fetch['code'] ), esc_html( $subs_fetch['message'] ) );
}
$subscribers_total = number_format_i18n( $subs_fetch['value'] );
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>">
<?php _e( 'Widget title:', 'jetpack' ); ?>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id( 'subscribe_text' ); ?>">
<?php _e( 'Optional text to display to your readers:', 'jetpack' ); ?>
<textarea class="widefat" id="<?php echo $this->get_field_id( 'subscribe_text' ); ?>" name="<?php echo $this->get_field_name( 'subscribe_text' ); ?>" rows="3"><?php echo esc_html( $subscribe_text ); ?></textarea>
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id( 'subscribe_placeholder' ); ?>">
<?php esc_html_e( 'Subscribe Placeholder:', 'jetpack' ); ?>
<input class="widefat" id="<?php echo $this->get_field_id( 'subscribe_placeholder' ); ?>" name="<?php echo $this->get_field_name( 'subscribe_placeholder' ); ?>" type="text" value="<?php echo esc_attr( $subscribe_placeholder ); ?>" />
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id( 'subscribe_button' ); ?>">
<?php _e( 'Subscribe Button:', 'jetpack' ); ?>
<input class="widefat" id="<?php echo $this->get_field_id( 'subscribe_button' ); ?>" name="<?php echo $this->get_field_name( 'subscribe_button' ); ?>" type="text" value="<?php echo esc_attr( $subscribe_button ); ?>" />
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id( 'success_message' ); ?>">
<?php _e( 'Success Message Text:', 'jetpack' ); ?>
<textarea class="widefat" id="<?php echo $this->get_field_id( 'success_message' ); ?>" name="<?php echo $this->get_field_name( 'success_message' ); ?>" rows="5"><?php echo esc_html( $success_message ); ?></textarea>
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id( 'show_subscribers_total' ); ?>">
<input type="checkbox" id="<?php echo $this->get_field_id( 'show_subscribers_total' ); ?>" name="<?php echo $this->get_field_name( 'show_subscribers_total' ); ?>" value="1"<?php echo $show_subscribers_total; ?> />
<?php echo esc_html( sprintf( _n( 'Show total number of subscribers? (%s subscriber)', 'Show total number of subscribers? (%s subscribers)', $subscribers_total, 'jetpack' ), $subscribers_total ) ); ?>
</label>
</p>
<?php
}
}

add_shortcode( 'jetpack_subscription_form', 'jetpack_do_subscription_form' );
add_shortcode( 'blog_subscription_form', 'jetpack_do_subscription_form' );

function jetpack_do_subscription_form( $instance ) {
if ( empty( $instance ) || ! is_array( $instance ) ) {
$instance = array();
}
$instance['show_subscribers_total'] = empty( $instance['show_subscribers_total'] ) ? false : true;
$show_only_email_and_button = isset( $instance['show_only_email_and_button'] ) ? $instance['show_only_email_and_button'] : false;

$instance = shortcode_atts(
Jetpack_Subscriptions_Widget::defaults(),
$instance,
'jetpack_subscription_form'
);
$instance['show_only_email_and_button'] = $show_only_email_and_button;

$args = array(
'before_widget' => sprintf( '<div class="%s">', 'jetpack_subscription_widget' ),
);
ob_start();
the_widget( 'Jetpack_Subscriptions_Widget', $instance, $args );
$output = ob_get_clean();
return $output;
}

jetpack_register_block( 'subscriptions' );
include dirname( __FILE__ ) . '/subscriptions/views.php';
12 changes: 12 additions & 0 deletions modules/subscriptions/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
## Assets for Subscriptions

### subscriptions.css

CSS required to render the subscription widget

### views.php

This file handles the registration of various subscriptions
views, i.e. a widget and a block for the post editor.

This file is shared with wordpress.com
Loading

0 comments on commit 1c3ce55

Please sign in to comment.