wordpress-email-center-plugin/interweb-ao-email-center/includes/class-subscribe.php
2026-12-01 13:26:00 +02:00

434 lines
20 KiB
PHP

<?php
if (!defined('ABSPATH')) {
exit;
}
/**
* Newsletter sign-up forms (shortcode [interweb_ao_email_subscribe] and the "Newsletter sign-up" block).
* Contacts go to E-mail Center (POST /v1/email/contacts).
*
* The API adds contacts straight away and leaves the consent with the site, so the double confirmation
* is done here: the sign-up waits in a table of this site until the person opens the link sent by email.
* Only then does the contact go to the API. The proof of consent (date, IP and the exact text accepted)
* stays in that table.
*/
class INTERWEB_AO_EMAIL_CENTER_Subscribe
{
const DB_VERSION = '1';
const PENDING_DAYS = 7;
public static function init()
{
add_shortcode('interweb_ao_email_subscribe', array(__CLASS__, 'shortcode'));
add_action('init', array(__CLASS__, 'register_block'));
add_action('rest_api_init', array(__CLASS__, 'routes'));
add_action('template_redirect', array(__CLASS__, 'maybe_confirm_link'));
add_action('interweb_ao_email_center_daily_cleanup', array(__CLASS__, 'cleanup'));
add_action('plugins_loaded', array(__CLASS__, 'maybe_upgrade'));
}
public static function table()
{
global $wpdb;
return $wpdb->prefix . 'interweb_ao_email_center_signups';
}
public static function install()
{
global $wpdb;
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$charset = $wpdb->get_charset_collate();
$t = self::table();
dbDelta("CREATE TABLE $t (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
token_hash char(64) NOT NULL,
channel varchar(10) NOT NULL,
email varchar(190) DEFAULT NULL,
name varchar(190) DEFAULT NULL,
email_groups varchar(255) DEFAULT NULL,
lang varchar(5) NOT NULL DEFAULT 'en',
consent_text text,
ip varchar(45) DEFAULT NULL,
status varchar(12) NOT NULL DEFAULT 'pending',
result text,
created_at datetime NOT NULL,
confirmed_at datetime DEFAULT NULL,
confirmation_ip varchar(45) DEFAULT NULL,
PRIMARY KEY (id),
KEY token_hash (token_hash),
KEY status (status),
KEY email (email)
) $charset;");
update_option('interweb_ao_email_center_db_version', self::DB_VERSION, false);
if (!wp_next_scheduled('interweb_ao_email_center_daily_cleanup')) {
wp_schedule_event(time() + 3600, 'daily', 'interweb_ao_email_center_daily_cleanup');
}
}
public static function maybe_upgrade()
{
if (get_option('interweb_ao_email_center_db_version') !== self::DB_VERSION) {
self::install();
}
}
public static function deactivate()
{
wp_clear_scheduled_hook('interweb_ao_email_center_daily_cleanup');
}
/** Sign-ups not confirmed in 7 days expire and their data is deleted. */
public static function cleanup()
{
global $wpdb;
$t = self::table();
$limit = gmdate('Y-m-d H:i:s', time() - self::PENDING_DAYS * DAY_IN_SECONDS);
$wpdb->query($wpdb->prepare("DELETE FROM $t WHERE status = 'pending' AND created_at < %s", $limit));
}
/* ------------------------------------------------------------------ */
/* Form */
/* ------------------------------------------------------------------ */
public static function register_block()
{
wp_register_script('interweb-ao-email-center-block-subscribe', INTERWEB_AO_EMAIL_CENTER_URL . 'assets/block-subscribe.js', array('wp-blocks', 'wp-element', 'wp-components', 'wp-block-editor', 'wp-server-side-render', 'wp-i18n'), INTERWEB_AO_EMAIL_CENTER_VERSION, true);
wp_localize_script('interweb-ao-email-center-block-subscribe', 'interwebAoEmailCenterBlockI18n', array(
'title' => __('Newsletter sign-up', 'interweb-ao-email-center'),
'description' => __('Collects email contacts for E-mail Center, with consent and double confirmation.', 'interweb-ao-email-center'),
'groups' => __('E-mail Center groups (ids, comma separated)', 'interweb-ao-email-center'),
'formTitle' => __('Title', 'interweb-ao-email-center'),
'button' => __('Button text', 'interweb-ao-email-center'),
'askName' => __('Ask for the name', 'interweb-ao-email-center'),
'settings' => __('Form settings', 'interweb-ao-email-center'),
));
register_block_type(INTERWEB_AO_EMAIL_CENTER_DIR . 'blocks/subscribe', array(
'render_callback' => array(__CLASS__, 'render_block'),
'editor_script' => 'interweb-ao-email-center-block-subscribe',
));
}
public static function render_block($attrs)
{
$a = array(
'groups' => isset($attrs['groups']) ? $attrs['groups'] : '',
'title' => isset($attrs['title']) ? $attrs['title'] : '',
'button' => isset($attrs['button']) ? $attrs['button'] : '',
'name' => !empty($attrs['askName']) ? '1' : '0',
);
return self::shortcode($a);
}
private static function ids($csv)
{
$out = array();
foreach (preg_split('/[\s,]+/', (string) $csv) as $p) {
if (ctype_digit($p) && (int) $p > 0) {
$out[] = (int) $p;
}
}
return array_values(array_unique($out));
}
/** The form settings travel signed, so a visitor cannot change the groups. */
private static function sign(array $cfg)
{
$json = wp_json_encode($cfg);
return base64_encode($json) . '.' . hash_hmac('sha256', $json, wp_salt('nonce') . 'interweb-ao-email-center-sub');
}
private static function unsign($token)
{
$parts = explode('.', (string) $token, 2);
if (count($parts) !== 2) {
return null;
}
$json = base64_decode($parts[0], true);
if ($json === false || !hash_equals(hash_hmac('sha256', $json, wp_salt('nonce') . 'interweb-ao-email-center-sub'), $parts[1])) {
return null;
}
$cfg = json_decode($json, true);
return is_array($cfg) ? $cfg : null;
}
public static function consent_text($lang)
{
$custom = trim((string) INTERWEB_AO_EMAIL_CENTER_Settings::get('sub_consent_' . $lang));
if ($custom !== '') {
return $custom;
}
$site = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
return sprintf(INTERWEB_AO_EMAIL_CENTER_I18n::in($lang, 'I agree to receive news and offers from %s. I can cancel at any time.'), $site);
}
public static function shortcode($atts)
{
$a = shortcode_atts(array(
'groups' => '',
'title' => '',
'button' => '',
'name' => '1',
), $atts, 'interweb_ao_email_subscribe');
$email_groups = $a['groups'] !== '' ? self::ids($a['groups']) : array_map('intval', (array) INTERWEB_AO_EMAIL_CENTER_Settings::get('sub_email_groups'));
$lang = INTERWEB_AO_EMAIL_CENTER_I18n::lang();
$cfg = array('l' => 'email', 'eg' => $email_groups, 'n' => $a['name'] === '1' ? 1 : 0);
wp_enqueue_style('interweb-ao-email-center-subscribe', INTERWEB_AO_EMAIL_CENTER_URL . 'assets/subscribe.css', array(), INTERWEB_AO_EMAIL_CENTER_VERSION);
wp_enqueue_script('interweb-ao-email-center-subscribe', INTERWEB_AO_EMAIL_CENTER_URL . 'assets/subscribe.js', array(), INTERWEB_AO_EMAIL_CENTER_VERSION, true);
wp_localize_script('interweb-ao-email-center-subscribe', 'interwebAoEmailCenterSubscribe', array(
'url' => esc_url_raw(rest_url('interweb-ao-email-center/v1/subscribe')),
'sending' => __('Sending...', 'interweb-ao-email-center'),
'error' => __('Something went wrong. Please try again in a moment.', 'interweb-ao-email-center'),
));
$uid = 'interweb-ao-email-center-sub-' . wp_rand(1000, 999999);
$title = $a['title'] !== '' ? $a['title'] : __('Subscribe to our news', 'interweb-ao-email-center');
$button = $a['button'] !== '' ? $a['button'] : __('Subscribe', 'interweb-ao-email-center');
ob_start();
?>
<form class="interweb-ao-email-center-subscribe" id="<?php echo esc_attr($uid); ?>" novalidate>
<?php if ($title !== '-') : ?><p class="interweb-ao-email-center-subscribe__title"><?php echo esc_html($title); ?></p><?php endif; ?>
<input type="hidden" name="cfg" value="<?php echo esc_attr(self::sign($cfg)); ?>">
<input type="hidden" name="lang" value="<?php echo esc_attr($lang); ?>">
<div class="interweb-ao-email-center-subscribe__hp" aria-hidden="true">
<label><?php esc_html_e('Leave this field empty', 'interweb-ao-email-center'); ?> <input type="text" name="website" tabindex="-1" autocomplete="off"></label>
</div>
<?php if ($cfg['n']) : ?>
<label class="interweb-ao-email-center-subscribe__field"><span><?php esc_html_e('Name', 'interweb-ao-email-center'); ?></span>
<input type="text" name="name" autocomplete="name" maxlength="120"></label>
<?php endif; ?>
<label class="interweb-ao-email-center-subscribe__field"><span><?php esc_html_e('Email', 'interweb-ao-email-center'); ?></span>
<input type="email" name="email" autocomplete="email" maxlength="190" required></label>
<label class="interweb-ao-email-center-subscribe__consent"><input type="checkbox" name="consent" value="1" required>
<span><?php echo esc_html(self::consent_text($lang)); ?></span></label>
<button type="submit" class="interweb-ao-email-center-subscribe__button"><?php echo esc_html($button); ?></button>
<p class="interweb-ao-email-center-subscribe__msg" role="status" aria-live="polite"></p>
</form>
<?php
return ob_get_clean();
}
/* ------------------------------------------------------------------ */
/* REST */
/* ------------------------------------------------------------------ */
public static function routes()
{
register_rest_route('interweb-ao-email-center/v1', '/subscribe', array(
'methods' => 'POST',
'callback' => array(__CLASS__, 'rest_subscribe'),
'permission_callback' => '__return_true',
));
}
public static function client_ip()
{
$ip = isset($_SERVER['REMOTE_ADDR']) ? (string) $_SERVER['REMOTE_ADDR'] : '';
$ip = apply_filters('interweb_ao_email_center_client_ip', $ip);
return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '0.0.0.0';
}
/** Counts actions per key in a time window; false when the limit has been reached. */
public static function rate_ok($bucket, $limit, $window)
{
if ($limit <= 0) {
return true;
}
$key = 'interweb_ao_email_center_rl_' . md5($bucket);
$n = (int) get_transient($key);
if ($n >= $limit) {
return false;
}
set_transient($key, $n + 1, $window);
return true;
}
private static function reply($ok, $message, $extra = array(), $status = 200)
{
return new WP_REST_Response(array_merge(array('ok' => $ok, 'message' => $message), $extra), $status);
}
public static function rest_subscribe(WP_REST_Request $req)
{
$lang = $req->get_param('lang') === 'pt' ? 'pt' : 'en';
$t = function ($s) use ($lang) {
return INTERWEB_AO_EMAIL_CENTER_I18n::in($lang, $s);
};
if (trim((string) $req->get_param('website')) !== '') {
// Robots fill the hidden field: answer as if all went well and do nothing.
return self::reply(true, $t('Thank you. Check your email to confirm.'));
}
$cfg = self::unsign($req->get_param('cfg'));
if (!$cfg) {
return self::reply(false, $t('This form is out of date. Reload the page and try again.'), array(), 400);
}
if (!$req->get_param('consent')) {
return self::reply(false, $t('Please tick the box to give your consent.'), array(), 422);
}
$name = sanitize_text_field((string) $req->get_param('name'));
$name = function_exists('mb_substr') ? mb_substr($name, 0, 120) : substr($name, 0, 120);
$email = sanitize_email((string) $req->get_param('email'));
if (!is_email($email)) {
return self::reply(false, $t('Please write a valid email address.'), array(), 422);
}
$ip = self::client_ip();
if (!self::rate_ok('sub_ip_' . $ip, max(1, (int) INTERWEB_AO_EMAIL_CENTER_Settings::get('sub_per_hour')), HOUR_IN_SECONDS)
|| !self::rate_ok('sub_id_' . strtolower($email), 3, DAY_IN_SECONDS)) {
return self::reply(false, $t('Too many attempts. Please try again later.'), array(), 429);
}
global $wpdb;
$token = wp_generate_password(40, false, false);
$row = array(
'token_hash' => hash('sha256', $token),
'channel' => 'email',
'email' => $email,
'name' => $name ?: null,
'email_groups' => implode(',', array_map('intval', (array) $cfg['eg'])),
'lang' => $lang,
'consent_text' => self::consent_text($lang),
'ip' => $ip,
'status' => 'pending',
'created_at' => current_time('mysql', true),
);
if ((int) INTERWEB_AO_EMAIL_CENTER_Settings::get('sub_double_optin') !== 1) {
$row['status'] = 'confirmed';
$row['confirmed_at'] = $row['created_at'];
$row['confirmation_ip'] = $ip;
$wpdb->insert(self::table(), $row);
$id = (int) $wpdb->insert_id;
$res = self::push_to_api($id);
if (is_wp_error($res)) {
return self::reply(false, $t('We could not save your subscription right now. Please try again later.'), array(), 502);
}
return self::reply(true, $t('Thank you. Your subscription is saved.'));
}
$wpdb->insert(self::table(), $row);
$sent = self::send_confirmation_email((int) $wpdb->insert_id, $token, $lang);
if (!$sent) {
return self::reply(false, $t('We could not send the confirmation email. Please try again later.'), array(), 502);
}
return self::reply(true, $t('Thank you. We sent you an email: open the link in it to confirm your subscription.'));
}
private static function send_confirmation_email($id, $token, $lang)
{
$site = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
$link = add_query_arg('interweb_ao_email_center_confirm', rawurlencode($token), home_url('/'));
global $wpdb;
$t_name = self::table();
$row = $wpdb->get_row($wpdb->prepare("SELECT * FROM $t_name WHERE id = %d", $id));
if (!$row) {
return false;
}
$hello = $row->name ? sprintf(INTERWEB_AO_EMAIL_CENTER_I18n::in($lang, 'Hello %s,'), $row->name) : INTERWEB_AO_EMAIL_CENTER_I18n::in($lang, 'Hello,');
$subject = sprintf(INTERWEB_AO_EMAIL_CENTER_I18n::in($lang, 'Confirm your subscription to %s'), $site);
$body = '<p>' . esc_html($hello) . '</p>'
. '<p>' . esc_html(sprintf(INTERWEB_AO_EMAIL_CENTER_I18n::in($lang, 'Someone (we hope it was you) asked to receive news from %s at this address. To confirm, open this link:'), $site)) . '</p>'
. '<p><a href="' . esc_url($link) . '">' . esc_html(INTERWEB_AO_EMAIL_CENTER_I18n::in($lang, 'Confirm my subscription')) . '</a></p>'
. '<p>' . esc_html(INTERWEB_AO_EMAIL_CENTER_I18n::in($lang, 'If it was not you, ignore this email: without confirmation nothing is saved, and the request is deleted in 7 days.')) . '</p>';
return wp_mail($row->email, $subject, $body, array('Content-Type: text/html; charset=UTF-8'));
}
public static function maybe_confirm_link()
{
if (empty($_GET['interweb_ao_email_center_confirm'])) {
return;
}
$token = sanitize_text_field(wp_unslash($_GET['interweb_ao_email_center_confirm']));
global $wpdb;
$t_name = self::table();
$row = $wpdb->get_row($wpdb->prepare("SELECT * FROM $t_name WHERE token_hash = %s LIMIT 1", hash('sha256', $token)));
$lang = $row ? $row->lang : INTERWEB_AO_EMAIL_CENTER_I18n::lang();
$site = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
if (!$row || ($row->status === 'pending' && strtotime($row->created_at . ' UTC') < time() - self::PENDING_DAYS * DAY_IN_SECONDS)) {
$msg = INTERWEB_AO_EMAIL_CENTER_I18n::in($lang, 'This confirmation link is no longer valid. You can subscribe again on the site.');
$ok = false;
$code = 410;
} elseif ($row->status === 'confirmed') {
$msg = INTERWEB_AO_EMAIL_CENTER_I18n::in($lang, 'Your subscription was already confirmed. Thank you.');
$ok = true;
$code = 200;
} else {
$res = self::confirm_row((int) $row->id);
$ok = !is_wp_error($res);
$code = $ok ? 200 : 503;
$msg = $ok ? INTERWEB_AO_EMAIL_CENTER_I18n::in($lang, 'Done. Your subscription is confirmed. Thank you.')
: INTERWEB_AO_EMAIL_CENTER_I18n::in($lang, 'We could not save your subscription right now. Open the link again later.');
}
$thanks = (string) INTERWEB_AO_EMAIL_CENTER_Settings::get('sub_thanks_url');
if ($ok && $thanks !== '' && wp_http_validate_url($thanks)) {
wp_safe_redirect($thanks);
exit;
}
$html = '<p>' . esc_html($msg) . '</p><p><a href="' . esc_url(home_url('/')) . '">' . esc_html(sprintf(INTERWEB_AO_EMAIL_CENTER_I18n::in($lang, 'Back to %s'), $site)) . '</a></p>';
wp_die($html, esc_html($site), array('response' => $code, 'back_link' => false));
}
/** @return true|WP_Error */
private static function confirm_row($id)
{
global $wpdb;
$wpdb->update(self::table(), array(
'status' => 'confirmed',
'confirmed_at' => current_time('mysql', true),
'confirmation_ip' => self::client_ip(),
), array('id' => $id));
return self::push_to_api($id);
}
/** Sends a confirmed sign-up to the API. Idempotent: the key is the sign-up id. */
public static function push_to_api($id)
{
global $wpdb;
$t_name = self::table();
$row = $wpdb->get_row($wpdb->prepare("SELECT * FROM $t_name WHERE id = %d", $id));
if (!$row) {
return new WP_Error('interweb_ao_email_center_not_found', 'not found');
}
$results = array();
$error = null;
$site_key = substr(md5(home_url()), 0, 8);
if ($row->email) {
$body = array('email' => $row->email, 'subscription' => 'subscribed');
if ($row->name) {
$body['name'] = $row->name;
}
$groups = self::ids($row->email_groups);
if ($groups) {
$body['groups'] = $groups;
}
$r = INTERWEB_AO_EMAIL_CENTER_Api::request('POST', '/v1/email/contacts', $body, array('idempotency_key' => 'interweb-ao-email-center-sub-e-' . $site_key . '-' . $id));
$results['email'] = is_wp_error($r) ? $r->get_error_code() : 'ok';
if (is_wp_error($r)) {
$error = $r;
}
}
$wpdb->update($t_name, array('result' => wp_json_encode($results), 'status' => $error ? 'failed' : 'confirmed'), array('id' => $id));
INTERWEB_AO_EMAIL_CENTER_Log::add('subscribe', !$error, $error ? $error->get_error_message() : __('Contact added through the API.', 'interweb-ao-email-center'), array(
'to' => INTERWEB_AO_EMAIL_CENTER_Log::mask_email($row->email),
));
return $error ? $error : true;
}
/** Last sign-ups, for the settings page (masked). */
public static function recent($n = 15)
{
global $wpdb;
$t_name = self::table();
if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $t_name)) !== $t_name) {
return array();
}
return $wpdb->get_results($wpdb->prepare("SELECT id, email, status, created_at, confirmed_at FROM $t_name ORDER BY id DESC LIMIT %d", $n));
}
}