Source: front/actions.php
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Cheatin’ uh?' );
}
/**
* Front AJAX for Email To a Friend action.
*
* @since 2.0.0
* @author Geoffrey Crofte
*/
add_action( 'wp_ajax_jsps-email-friend', 'jsps_ajax_email_friend' );
add_action( 'wp_ajax_nopriv_jsps-email-friend', 'jsps_ajax_email_friend' );
/**
* Read a scalar query string parameter, unslashed. Arrays (`?x[]=`) are
* rejected so sanitizers never receive one (fatal error on PHP 8).
*
* @param string $key The $_GET key.
* @return string The raw, unslashed value, or ''.
*
* @since 2.3.8
*/
function jsps_get_query_string( $key ) {
return isset( $_GET[ $key ] ) && is_scalar( $_GET[ $key ] ) ? (string) wp_unslash( $_GET[ $key ] ) : '';
}
/**
* Same as {@see jsps_get_query_string()}, but reads POST first, then GET.
*
* @param string $key The request key.
* @return string The raw, unslashed value, or ''.
*
* @since 2.4.0
*/
function jsps_get_request_string( $key ) {
if ( isset( $_POST[ $key ] ) ) {
return is_scalar( $_POST[ $key ] ) ? (string) wp_unslash( $_POST[ $key ] ) : '';
}
return jsps_get_query_string( $key );
}
/**
* Whether a post can be shared or counted: published, publicly viewable,
* and not password protected. Prevents leaking private/draft titles and links.
*
* @param WP_Post|null $post The post.
* @return bool
*
* @since 2.3.8
*/
function jsps_is_shareable_post( $post ) {
return $post instanceof WP_Post
&& 'publish' === $post->post_status
&& empty( $post->post_password )
&& is_post_type_viewable( $post->post_type );
}
/**
* Clean the sender's display name so it can never alter a mail header:
* no control characters, no header/address delimiters, bounded length.
*
* @param string $name Raw (unslashed) name.
* @return string
*
* @since 2.3.8
*/
function jsps_email_sanitize_name( $name ) {
$name = sanitize_text_field( (string) $name );
$name = preg_replace( '/[\x00-\x1F\x7F:<>"\\\\(),;@]/u', '', $name );
return trim( mb_substr( $name, 0, 80 ) );
}
/**
* Parse the recipient list. Every entry must be a valid email address,
* duplicates are removed and the count is capped.
*
* @param string|array $raw Raw (unslashed) recipients.
* @return array|WP_Error List of addresses, or an error.
*
* @since 2.3.8
*/
function jsps_email_parse_recipients( $raw ) {
if ( is_array( $raw ) ) {
$raw = implode( ',', array_filter( $raw, 'is_scalar' ) );
}
$items = preg_split( '/[\s,;]+/', (string) $raw, -1, PREG_SPLIT_NO_EMPTY );
$recipients = array();
foreach ( $items as $item ) {
if ( ! is_email( $item ) ) {
return new WP_Error( 4, esc_html__( 'The recipient email address is invalid.', 'juiz-social-post-sharer' ) );
}
$recipients[ strtolower( $item ) ] = $item;
}
if ( empty( $recipients ) ) {
return new WP_Error( 6, esc_html__( 'No recipient email address.', 'juiz-social-post-sharer' ) );
}
/**
* Maximum number of recipients for one "email to a friend" request.
*
* @hook jsps_email_max_recipients
*
* @since 2.3.8 First version
* @param {int} $max=5 Maximum number of recipients.
* @return {int} The maximum number of recipients.
*/
$max = max( 1, (int) apply_filters( 'jsps_email_max_recipients', 5 ) );
if ( count( $recipients ) > $max ) {
return new WP_Error(
7,
esc_html( sprintf(
/* translators: %d: maximum number of recipients */
_n( 'You can send this article to %d recipient at most.', 'You can send this article to %d recipients at most.', $max, 'juiz-social-post-sharer' ),
$max
) )
);
}
return array_values( $recipients );
}
/**
* Per-IP rate limit on the number of emails sent, counted per recipient.
* Reserves the quota when allowed.
*
* @param int $nb_emails Number of emails this request would send.
* @return bool True if the request must be refused.
*
* @since 2.3.8
*/
function jsps_email_is_rate_limited( $nb_emails ) {
/**
* Maximum number of emails one visitor (IP address) can send per window.
*
* @hook jsps_email_rate_limit
*
* @since 2.3.8 First version
* @param {int} $limit=10 Number of emails (recipients) allowed per window. 0 disables the limit.
* @return {int} The limit.
*/
$limit = (int) apply_filters( 'jsps_email_rate_limit', 10 );
if ( $limit <= 0 ) {
return false;
}
/**
* Duration of the rate limit window, in seconds.
*
* @hook jsps_email_rate_limit_window
*
* @since 2.3.8 First version
* @param {int} $window=HOUR_IN_SECONDS Window duration in seconds.
* @return {int} The window duration.
*/
$window = max( 60, (int) apply_filters( 'jsps_email_rate_limit_window', HOUR_IN_SECONDS ) );
// REMOTE_ADDR only: forwarded headers are client controlled.
$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? (string) $_SERVER['REMOTE_ADDR'] : '';
$key = 'jsps_mail_rl_' . md5( $ip . wp_salt( 'nonce' ) );
$sent = (int) get_transient( $key );
if ( $sent + $nb_emails > $limit ) {
return true;
}
set_transient( $key, $sent + $nb_emails, $window );
return false;
}
function jsps_ajax_email_friend() {
if ( ! wp_verify_nonce( jsps_get_query_string( 'jsps-email-friend-nonce' ), 'jsps-email-friend' ) ) {
wp_send_json_error( array( 1, esc_html__( 'Your session is expired. Sorry. Retry after reloading the page.', 'juiz-social-post-sharer' ) ) );
}
$post = get_post( absint( jsps_get_query_string( 'id' ) ) );
if ( ! jsps_is_shareable_post( $post ) ) {
wp_send_json_error( array( 2, esc_html__( 'Seems like the post ID you tried to share is not good.', 'juiz-social-post-sharer' ) ) );
}
$sender_email = sanitize_email( jsps_get_query_string( 'email' ) );
if ( ! is_email( $sender_email ) ) {
wp_send_json_error( array( 3, esc_html__( 'Your email address is invalid.', 'juiz-social-post-sharer' ) ) );
}
if ( ! isset( $_GET['friend'] ) ) {
wp_send_json_error( array( 6, esc_html__( 'No recipient email address.', 'juiz-social-post-sharer' ) ) );
}
$recipients = jsps_email_parse_recipients( wp_unslash( $_GET['friend'] ) );
if ( is_wp_error( $recipients ) ) {
wp_send_json_error( array( $recipients->get_error_code(), $recipients->get_error_message() ) );
}
if ( jsps_email_is_rate_limited( count( $recipients ) ) ) {
wp_send_json_error( array( 8, esc_html__( 'Too many emails sent. Please try again later.', 'juiz-social-post-sharer' ) ) );
}
$sender_name = jsps_email_sanitize_name( jsps_get_query_string( 'name' ) );
$user_msg = sanitize_textarea_field( jsps_get_query_string( 'message' ) );
$user_msg = mb_substr( $user_msg, 0, 1000 );
// Prepare the message and title.
$opts = jsps_get_option();
$title = wp_strip_all_tags( jsps_render_mail_content( $opts['juiz_sps_mail_subject'], $post ) );
$permalink = get_permalink( $post->ID );
$message = '' !== $user_msg ? $user_msg . "\n\n" . $permalink : jsps_render_mail_content( $opts['juiz_sps_mail_body'], $post );
// Tell the recipients who shared it, since the mail comes from the site.
$sender_label = '' !== $sender_name ? $sender_name . ' (' . $sender_email . ')' : $sender_email;
$message = sprintf(
/* translators: %s: name and email address of the person sharing the article */
__( '%s shared this article with you:', 'juiz-social-post-sharer' ),
$sender_label
) . "\n\n" . $message;
/*
* Headers are complete "Name: value" strings with fixed names. User input
* only ever lands in a value, already stripped of delimiters. The From
* address stays the site's own (no spoofing); the visitor goes in Reply-To.
*/
$headers = array(
'Reply-To: ' . ( '' !== $sender_name ? $sender_name . ' <' . $sender_email . '>' : $sender_email ),
);
// First recipient in To, the others in Bcc so they don't see each other.
// Addresses passed is_email(): no colon, comma, space or line break possible.
$to = array_shift( $recipients );
if ( ! empty( $recipients ) ) {
$headers[] = 'Bcc: ' . implode( ', ', $recipients );
}
$from_name_cb = function () use ( $sender_name ) {
return '' !== $sender_name
/* translators: 1: sender name, 2: site name */
? sprintf( __( '%1$s via %2$s', 'juiz-social-post-sharer' ), $sender_name, wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ) )
: wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
};
add_filter( 'wp_mail_from_name', $from_name_cb, 99 );
$email_sent = wp_mail( $to, $title, $message, $headers );
remove_filter( 'wp_mail_from_name', $from_name_cb, 99 );
if ( ! $email_sent ) {
wp_send_json_error( array( 5, esc_html__( 'Error trying to send your message. Sorry for that.', 'juiz-social-post-sharer' ) ) );
}
$nb = (int) get_post_meta( $post->ID, '_jsps_email_shares', true );
update_post_meta( $post->ID, '_jsps_email_shares', ++$nb );
wp_send_json_success( esc_html__( 'Post successfully sent!', 'juiz-social-post-sharer' ) );
}
/**
* Front AJAX for Live click counting
*
* @since 2.0.0
* @author Geoffrey Crofte
*/
add_action( 'wp_ajax_jsps-click-count', 'jsps_ajax_click_count' );
add_action( 'wp_ajax_nopriv_jsps-click-count', 'jsps_ajax_click_count' );
/**
* Read the stored counters of a post, keeping only registered networks.
* Unknown keys (removed networks, junk) are ignored, never returned.
*
* @param int $post_id The post ID.
* @return array network slug => count.
*
* @since 2.3.8
*/
function jsps_get_post_counters( $post_id, $networks = null ) {
$counters = get_post_meta( $post_id, JSPS_COUNTERS_META, true );
$counters = is_array( $counters ) ? $counters : array();
$networks = null === $networks ? jsps_get_all_registered_networks() : $networks;
return array_map( 'intval', array_intersect_key( $counters, $networks ) );
}
/**
* Counts a click on a button. Accepts POST (sendBeacon / fetch, since 2.4.0) and GET (older cached JS).
*
* @since 2.4.0 Reads POST too.
* @since 2.0.0
*/
function jsps_ajax_click_count() {
if ( ! wp_verify_nonce( jsps_get_request_string( 'jsps-click-count-nonce' ), 'jsps-click-count' ) ) {
wp_send_json_error( array( 1, 'Your session is expired. Sorry. Retry after reloading the page.' ) );
}
$post = get_post( absint( jsps_get_request_string( 'id' ) ) );
$network = sanitize_key( jsps_get_request_string( 'network' ) );
if ( ! jsps_is_shareable_post( $post ) ) {
wp_send_json_error( array( 2, 'Seems like the post ID you tried to share is not good.' ) );
}
// Only registered networks can be counted: prevents unbounded post meta growth.
if ( '' === $network || ! array_key_exists( $network, jsps_get_all_registered_networks() ) ) {
wp_send_json_error( array( 3, 'Unknown network.' ) );
}
$counters = get_post_meta( $post->ID, JSPS_COUNTERS_META, true );
$counters = is_array( $counters ) ? $counters : array();
$nb = ( isset( $counters[ $network ] ) ? (int) $counters[ $network ] : 0 ) + 1;
$counters[ $network ] = $nb;
// Counters and their total (since 2.6.0, to sort posts by shares).
jsps_save_post_counters( $post->ID, $counters );
wp_send_json_success( array( 'Count increment successful', $network, $nb, jsps_get_post_counters( $post->ID ) ) );
}
/**
* Counters of several posts at once: one posts query, one meta query (meta cache primed).
* Only shareable posts are returned.
*
* @param string $raw_ids Comma separated post IDs.
* @return array post ID => object of network => count.
*
* @since 2.4.0
*/
function jsps_get_posts_counters( $raw_ids ) {
/**
* Maximum number of posts whose counters can be asked in one request.
*
* @hook jsps_counters_batch_max_ids
*
* @since 2.4.0 First version
* @param {int} $max=50 Maximum number of post IDs.
* @return {int} The maximum number of post IDs.
*/
$max = max( 1, (int) apply_filters( 'jsps_counters_batch_max_ids', 50 ) );
$ids = array_slice( array_values( array_unique( array_filter( array_map( 'absint', explode( ',', $raw_ids ) ) ) ) ), 0, $max );
if ( empty( $ids ) ) {
return array();
}
$posts = get_posts( array(
'post__in' => $ids,
'post_type' => array_values( get_post_types( array( 'public' => true ) ) ),
'post_status' => 'publish',
'has_password' => false,
'posts_per_page' => count( $ids ),
'orderby' => 'post__in',
'ignore_sticky_posts' => true,
'no_found_rows' => true,
) );
$networks = jsps_get_all_registered_networks();
$map = array();
foreach ( $posts as $post ) {
if ( jsps_is_shareable_post( $post ) ) {
// Object: always a JSON object, even when empty.
$map[ $post->ID ] = (object) jsps_get_post_counters( $post->ID, $networks );
}
}
return $map;
}
/**
* Front AJAX for getting the share counts
*
* @since 2.0.0
* @author Geoffrey Crofte
*/
add_action( 'wp_ajax_jsps-get-counters', 'jsps_ajax_get_counter' );
add_action( 'wp_ajax_nopriv_jsps-get-counters', 'jsps_ajax_get_counter' );
function jsps_ajax_get_counter() {
if ( ! wp_verify_nonce( jsps_get_query_string( 'jsps-get-counters-nonce' ), 'jsps-get-counters' ) ) {
wp_send_json_error( array( 1, esc_html__( 'Your session is expired. Sorry. Retry after reloading the page.', 'juiz-social-post-sharer' ) ) );
}
// Batch mode (2.4.0+): `ids=1,2,3` returns { "1": {…}, "2": {…} } in one request.
if ( '' !== jsps_get_query_string( 'ids' ) ) {
wp_send_json_success( array( 'Got Counters', jsps_get_posts_counters( jsps_get_query_string( 'ids' ) ) ) );
}
$post = get_post( absint( jsps_get_query_string( 'id' ) ) );
if ( ! jsps_is_shareable_post( $post ) ) {
wp_send_json_error( array( 2, esc_html__( 'Seems like the post ID you tried to share is not good.', 'juiz-social-post-sharer' ) ) );
}
// Empty array is sent as [] and the JS handles both {} and [].
wp_send_json_success( array( 'Got Counters', jsps_get_post_counters( $post->ID ) ) );
}
Plugin and documentation by Geoffrey Crofte - All Right Reserved