self::consent_preticked() ? 1 : 0, 'version' => self::CONSENT_VERSION); $pre = null === $proof['preticked'] ? (self::consent_preticked() ? 1 : 0) : (int) $proof['preticked']; $version = '' !== $proof['version'] ? $proof['version'] : self::CONSENT_VERSION; $id = 'aieo-comp-consent-' . $form_id; return '' . $button; } private static function is_resubmission($form_id) { return isset($_POST['aieo_comp_consent_shown'], $_POST['gform_submit']) && (int) $_POST['gform_submit'] === (int) $form_id; } public static function consent_from_request() { if (!isset($_POST['aieo_comp_consent_shown'])) { return null; } return !empty($_POST['aieo_comp_newsletter_consent']) ? 1 : 0; } public static function consent_proof_from_request() { $pre = isset($_POST['aieo_comp_consent_pre']) ? (string) wp_unslash($_POST['aieo_comp_consent_pre']) : ''; $ver = isset($_POST['aieo_comp_consent_v']) ? sanitize_key(wp_unslash($_POST['aieo_comp_consent_v'])) : ''; return array( 'preticked' => in_array($pre, array('0', '1'), true) ? (int) $pre : null, 'version' => substr($ver, 0, 20), ); } public static function table() { global $wpdb; return $wpdb->prefix . 'aieo_competition_participants'; } public static function maybe_install() { if (get_option(self::SCHEMA_OPTION) === self::SCHEMA_VERSION) { return; } if (!defined('AIEO_DIR')) { return; } $schema = AIEO_DIR . 'includes/dmm/competitions/sql/competitions-schema.php'; if (!file_exists($schema)) { return; } require_once $schema; if (!AIEO_Schema_Lock::acquire(self::SCHEMA_OPTION)) { return; } if (function_exists('aieo_competitions_install_schema')) { $from = (string) get_option(self::SCHEMA_OPTION, ''); aieo_competitions_install_schema(); update_option(self::SCHEMA_OPTION, self::SCHEMA_VERSION, false); if ('' !== $from && version_compare($from, '3', '<') && self::has_competitions() && class_exists('AIEO_Outbound_Notice')) { AIEO_Outbound_Notice::record('competition_consent', AIEO_Outbound_Notice::NOTE); } } } private static function has_competitions() { if (!class_exists('AIEO_Competition_CPT')) { return false; } $counts = (array) wp_count_posts(AIEO_Competition_CPT::POST_TYPE); foreach ($counts as $status => $n) { if ('trash' !== $status && 'auto-draft' !== $status && (int) $n > 0) { return true; } } return false; } public static function on_gform_submission($entry, $form) { if (!is_array($entry) || !is_array($form)) { return; } $form_id = (int) ($form['id'] ?? 0); if ($form_id <= 0) { return; } $competition_id = self::competition_for_form($form_id); if ($competition_id <= 0) { return; } if (class_exists('AIEO_Competition_CPT') && AIEO_Competition_CPT::schedule_state($competition_id) !== 'live') { return; } self::maybe_install(); self::capture_participant($competition_id, $entry, $form); } private static function competition_for_form($form_id) { static $seen = array(); $form_id = (int) $form_id; if (isset($seen[$form_id])) { return $seen[$form_id]; } if (!class_exists('AIEO_Competition_CPT')) { return 0; } $ids = get_posts(array( 'post_type' => AIEO_Competition_CPT::POST_TYPE, 'post_status' => 'publish', 'numberposts' => 1, 'fields' => 'ids', 'no_found_rows' => true, 'meta_key' => AIEO_Competition_CPT::META_GF, 'meta_value' => (int) $form_id, )); return $seen[$form_id] = ($ids ? (int) $ids[0] : 0); } private static function capture_participant($competition_id, $entry, $form) { list($email, $first, $last) = self::extract_email_name($entry, $form); if ($email === '' || !is_email($email)) { return; } self::record_entry((int) $competition_id, (int) ($entry['id'] ?? 0), $email, $first, $last); } public static function record_entry($competition_id, $entry_id, $email, $first, $last) { $resolved = self::resolve_eponymous_for_email($email); $verified = self::is_verified_email($email, (int) $resolved['eponymous_id']); $consent = self::consent_from_request(); $proof = self::consent_proof_from_request(); $pre = null === $consent ? null : self::server_preticked($proof['preticked']); $version = null === $consent ? '' : self::server_version($proof['version']); $own = $verified && self::is_own_address($email); $settled = false; if ($own && 1 === $consent) { self::subscribe_to_competition_list((int) $competition_id, $email, $first, $last, 'confirmed'); $settled = true; } if ($own) { self::record_active_consent((int) $competition_id, $email, $consent, $pre, $version); } $pending = !$verified; $row = array( 'competition_id' => (int) $competition_id, 'gf_entry_id' => (int) $entry_id, 'email' => $email, 'first_name' => $first, 'last_name' => $last, 'status' => $pending ? 'pending' : 'confirmed', 'source' => $verified ? 'customer' : (1 === $consent ? 'optin' : 'entered'), 'eponymous_id' => (int) $resolved['eponymous_id'], 'wp_user_id' => (int) $resolved['wp_user_id'], 'created_at' => current_time('mysql', true), ); if (null !== $consent) { $row['newsletter_consent'] = $consent; $row['newsletter_consent_at'] = current_time('mysql', true); $row['newsletter_consent_preticked'] = $pre; if ('' !== $version) { $row['newsletter_consent_version'] = $version; } if ($settled && self::SCHEMA_VERSION === (string) get_option(self::SCHEMA_OPTION)) { $row['newsletter_settled_at'] = current_time('mysql', true); } } if (!$pending) { $row['confirmed_at'] = current_time('mysql', true); } self::upsert_participant($row); if ($pending) { self::send_confirmation((int) $competition_id, (int) $row['gf_entry_id'], $email, $first, 1 === $consent); } elseif (1 === $consent && !$own) { self::send_confirmation((int) $competition_id, (int) $row['gf_entry_id'], $email, $first, true, true); } if (class_exists('AIEO_Competition_Analytics') && class_exists('AIEO_DMM_Competitions') && 'off' !== AIEO_DMM_Competitions::get_stats_cadence()) { $once = AIEO_Competition_Analytics::STATS_REFRESH_HOOK . '_once'; if (!wp_next_scheduled($once)) { wp_schedule_single_event(time() + 180, $once); } } global $wpdb; $tbl = self::table(); $pid = (int) $wpdb->get_var($wpdb->prepare("SELECT participant_id FROM {$tbl} WHERE competition_id = %d AND gf_entry_id = %d", (int) $competition_id, (int) $entry_id)); if ($pid > 0) { self::announce($pid, (int) $competition_id, (string) $email, $pending ? 'pending' : 'confirmed', 'entry'); } return array('participant_id' => $pid, 'status' => $pending ? 'pending' : 'confirmed'); } private static function record_active_consent($competition_id, $email, $consent, $preticked, $version) { if (1 !== $consent || 0 !== $preticked || !class_exists('AIEO_Contact_Consent') || self::has_opted_out($email)) { return false; } if (AIEO_Contact_Consent::has_record((string) $email)) { return false; } $source = 'comp-' . (int) $competition_id . ('' !== (string) $version ? '-v' . sanitize_key((string) $version) : ''); return (bool) AIEO_Contact_Consent::record_consent((string) $email, substr($source, 0, 20), true); } private static function server_preticked($posted) { return (self::consent_preticked() || 1 === $posted) ? 1 : 0; } private static function server_version($posted) { $posted = (string) $posted; return (ctype_digit($posted) && (int) $posted >= 1 && (int) $posted <= (int) self::CONSENT_VERSION) ? (string) (int) $posted : self::CONSENT_VERSION; } private static function is_own_address($email) { if (!function_exists('is_user_logged_in') || !is_user_logged_in()) { return false; } $mine = strtolower(trim((string) wp_get_current_user()->user_email)); return '' !== $mine && $mine === strtolower(trim((string) $email)); } private static function announce($participant_id, $competition_id, $email, $status, $via) { do_action('aieo_competition_entry_recorded', (int) $participant_id, (int) $competition_id, (string) $email, (string) $status, (string) $via); } public static function find_entry($competition_id, $entry_id) { global $wpdb; $tbl = self::table(); $row = $wpdb->get_row($wpdb->prepare("SELECT participant_id, status FROM {$tbl} WHERE competition_id = %d AND gf_entry_id = %d", (int) $competition_id, (int) $entry_id)); return $row ? array('participant_id' => (int) $row->participant_id, 'status' => (string) $row->status) : null; } private static function confirm_key($competition_id, $entry_id, $email) { return substr(hash_hmac('sha256', 'aieo-comp-confirm|' . (int) $competition_id . '|' . (int) $entry_id . '|' . strtolower(trim((string) $email)), wp_salt('nonce')), 0, 32); } public static function confirm_url($competition_id, $entry_id, $email) { $page = get_permalink((int) $competition_id); return add_query_arg( array( self::CONFIRM_ARG => (int) $competition_id . '-' . (int) $entry_id, 'k' => self::confirm_key($competition_id, $entry_id, $email), ), $page ? $page : home_url('/') ); } private static function send_confirmation($competition_id, $entry_id, $email, $first, $consent, $entered = false) { $title = wp_strip_all_tags((string) get_the_title((int) $competition_id)); if ($entered) { return self::send_subscription_confirmation($competition_id, $entry_id, $email, $first, $title); } $subject = sprintf(__('Confirm your entry: %s', 'ai-eshop-optimizer'), $title); $hello = '' !== trim((string) $first) ? sprintf(__('Hello %s,', 'ai-eshop-optimizer'), trim((string) $first)) : __('Hello,', 'ai-eshop-optimizer'); $body = '

' . esc_html($hello) . '

' . '

' . esc_html(sprintf(__('Thank you for entering “%s”. Confirm your e-mail address with the link below: only confirmed entries take part in the draw.', 'ai-eshop-optimizer'), $title)) . '

' . AIEO_Email_Frame::button(self::confirm_url($competition_id, $entry_id, $email), __('Confirm my entry', 'ai-eshop-optimizer')); if ($consent) { $body .= '

' . esc_html__('You also asked to receive our news and offers by e-mail: confirming your entry subscribes you as well. You can unsubscribe at any time.', 'ai-eshop-optimizer') . '

'; } $body .= '

' . esc_html__('If you did not enter, you can ignore this e-mail.', 'ai-eshop-optimizer') . '

'; return AIEO_Email_Frame::send($email, $subject, $body, array('id' => 'aieo_competition_entry', 'heading' => $subject)); } private static function send_subscription_confirmation($competition_id, $entry_id, $email, $first, $title) { $subject = sprintf(__('Confirm your subscription: %s', 'ai-eshop-optimizer'), $title); $hello = '' !== trim((string) $first) ? sprintf(__('Hello %s,', 'ai-eshop-optimizer'), trim((string) $first)) : __('Hello,', 'ai-eshop-optimizer'); $body = '

' . esc_html($hello) . '

' . '

' . esc_html(sprintf(__('Thank you for entering “%s”: your entry takes part in the draw. You also asked to receive our news and offers by e-mail: confirm with the link below to subscribe. You can unsubscribe at any time.', 'ai-eshop-optimizer'), $title)) . '

' . AIEO_Email_Frame::button(self::confirm_url($competition_id, $entry_id, $email), __('Confirm my subscription', 'ai-eshop-optimizer')) . '

' . esc_html__('If you did not ask for this, you can ignore this e-mail: nothing is subscribed without your click.', 'ai-eshop-optimizer') . '

'; return AIEO_Email_Frame::send($email, $subject, $body, array('id' => 'aieo_competition_entry', 'heading' => $subject)); } public static function confirm_entry($competition_id, $entry_id, $key) { global $wpdb; $tbl = self::table(); $row = $wpdb->get_row($wpdb->prepare("SELECT participant_id, email, first_name, last_name, status, newsletter_consent, newsletter_consent_preticked, newsletter_consent_version FROM {$tbl} WHERE competition_id = %d AND gf_entry_id = %d", (int) $competition_id, (int) $entry_id)); if (!$row || !hash_equals(self::confirm_key($competition_id, $entry_id, (string) $row->email), (string) $key)) { return false; } $done = 0; if ('pending' === (string) $row->status) { $done = (int) $wpdb->query($wpdb->prepare("UPDATE {$tbl} SET status = 'confirmed', confirmed_at = %s WHERE participant_id = %d AND status = 'pending'", current_time('mysql', true), (int) $row->participant_id)); } $claimed = 0; if (1 === (int) $row->newsletter_consent && ($done || 'confirmed' === (string) $row->status)) { $claimed = $wpdb->query($wpdb->prepare("UPDATE {$tbl} SET newsletter_settled_at = %s WHERE participant_id = %d AND newsletter_settled_at IS NULL", current_time('mysql', true), (int) $row->participant_id)); } if (false === $claimed || $claimed > 0) { self::subscribe_to_competition_list((int) $competition_id, (string) $row->email, (string) $row->first_name, (string) $row->last_name, 'confirmed'); self::record_active_consent( (int) $competition_id, (string) $row->email, 1, null === $row->newsletter_consent_preticked ? null : (int) $row->newsletter_consent_preticked, (string) $row->newsletter_consent_version ); } if ($done) { self::announce((int) $row->participant_id, (int) $competition_id, (string) $row->email, 'confirmed', 'confirm'); } return true; } public static function maybe_confirm_from_link() { if (!isset($_GET[self::CONFIRM_ARG], $_GET['k']) || is_admin()) { return; } $ids = explode('-', sanitize_text_field(wp_unslash($_GET[self::CONFIRM_ARG]))); $key = sanitize_text_field(wp_unslash($_GET['k'])); $competition_id = (int) ($ids[0] ?? 0); $entry_id = (int) ($ids[1] ?? 0); $ok = $competition_id > 0 && self::confirm_entry($competition_id, $entry_id, $key); $page = $competition_id > 0 ? get_permalink($competition_id) : ''; wp_safe_redirect(add_query_arg(self::RESULT_ARG, $ok ? 'confirmed' : 'invalid', $page ? $page : home_url('/'))); exit; } public static function confirmation_notice() { $result = isset($_GET[self::RESULT_ARG]) ? sanitize_key(wp_unslash($_GET[self::RESULT_ARG])) : ''; if ('confirmed' === $result) { return array('tone' => 'confirmed', 'text' => __('Thank you: your entry is confirmed and takes part in the draw.', 'ai-eshop-optimizer')); } if ('invalid' === $result) { return array('tone' => 'invalid', 'text' => __('This confirmation link is not valid. Open the whole link from the e-mail, or enter again.', 'ai-eshop-optimizer')); } return null; } private static function extract_email_name($entry, $form) { $email = ''; $first = ''; $last = ''; $fields = (is_array($form) && isset($form['fields']) && is_array($form['fields'])) ? $form['fields'] : array(); foreach ($fields as $f) { $type = is_object($f) ? (string) ($f->type ?? '') : (string) ($f['type'] ?? ''); $fid = is_object($f) ? (string) ($f->id ?? '') : (string) ($f['id'] ?? ''); if ($fid === '') { continue; } if ($type === 'email' && $email === '') { $email = strtolower(trim((string) self::rgar($entry, $fid))); } elseif ($type === 'name') { $f3 = trim((string) self::rgar($entry, $fid . '.3')); $f6 = trim((string) self::rgar($entry, $fid . '.6')); if ($first === '' && $f3 !== '') { $first = $f3; } if ($last === '' && $f6 !== '') { $last = $f6; } if ($first === '') { $whole = trim((string) self::rgar($entry, $fid)); if ($whole !== '') { $first = $whole; } } } } if ($email === '') { foreach ((array) $entry as $v) { if (is_string($v) && is_email(trim($v))) { $email = strtolower(trim($v)); break; } } } return array($email, $first, $last); } private static function rgar($arr, $key) { return (is_array($arr) && isset($arr[$key])) ? $arr[$key] : ''; } private static function is_verified_email($email, $eponymous_id) { return (email_exists($email) !== false) || ((int) $eponymous_id > 0); } private static function resolve_eponymous_for_email($email) { global $wpdb; $out = array('eponymous_id' => 0, 'wp_user_id' => 0); $email = strtolower(trim((string) $email)); if ($email === '') { return $out; } static $has_ci = null; $ci = $wpdb->prefix . 'aieo_customer_intelligence'; if ($has_ci === null) { $has_ci = ((string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $ci)) === $ci); } if (!$has_ci) { return $out; } $row = $wpdb->get_row($wpdb->prepare( "SELECT eponymous_id, wp_user_id FROM {$ci} WHERE LOWER(TRIM(email)) COLLATE utf8mb4_unicode_ci = %s COLLATE utf8mb4_unicode_ci LIMIT 1", $email )); if ($row) { $out['eponymous_id'] = (int) $row->eponymous_id; $out['wp_user_id'] = (int) $row->wp_user_id; } return $out; } private static function subscribe_to_competition_list($competition_id, $email, $first, $last, $tnp_status) { if (self::has_opted_out($email)) { return array('ok' => false, 'status' => '', 'list_id' => 0, 'error' => 'opted_out'); } do_action('aieo_competition_newsletter_subscribe', (int) $competition_id, (string) $email, (string) $tnp_status); if (!class_exists('AIEO_Newsletter_Registry') && defined('AIEO_DIR')) { $reg = AIEO_DIR . 'includes/dmm/push/class-aieo-newsletter-registry.php'; if (file_exists($reg)) { require_once $reg; } } if (!class_exists('AIEO_Newsletter_Registry')) { return array(); } $adapter = AIEO_Newsletter_Registry::instance()->adapter(); if (!$adapter || !method_exists($adapter, 'subscribe_one')) { return array(); } $opts = array( 'status' => $tnp_status, 'first_name' => $first, 'last_name' => $last, 'cohort' => self::LIST_COHORT, ); $res = $adapter->subscribe_one($email, $opts); if (is_array($res) && !empty($res['list_id']) && (int) get_option(self::LIST_OPTION, 0) <= 0) { update_option(self::LIST_OPTION, (int) $res['list_id'], false); } return is_array($res) ? $res : array(); } public static function has_opted_out($email) { global $wpdb; $email = strtolower(trim((string) $email)); if ($email === '' || !is_email($email)) { return false; } if (class_exists('AIEO_AW_Decommission') && method_exists('AIEO_AW_Decommission', 'is_suppressed') && AIEO_AW_Decommission::is_suppressed($email)) { return true; } $refused = array('U', 'B', 'P'); $tnp = $wpdb->prefix . 'newsletter'; if ((string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($tnp))) === $tnp) { $status = $wpdb->get_var($wpdb->prepare("SELECT status FROM `{$tnp}` WHERE email = %s LIMIT 1", $email)); if (null !== $status) { return in_array(strtoupper((string) $status), $refused, true); } } $ci = $wpdb->prefix . 'aieo_customer_intelligence'; if ((string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($ci))) === $ci) { $status = $wpdb->get_var($wpdb->prepare( "SELECT tnp_status FROM `{$ci}` WHERE LOWER(TRIM(email)) COLLATE utf8mb4_unicode_ci = %s COLLATE utf8mb4_unicode_ci LIMIT 1", $email )); return null !== $status && in_array(strtoupper((string) $status), $refused, true); } return false; } public static function on_tnp_confirmed($user) { global $wpdb; if (!is_object($user) || empty($user->email)) { return; } $email = strtolower(trim((string) $user->email)); if ($email === '') { return; } $list_id = (int) get_option(self::LIST_OPTION, 0); if ($list_id > 0) { $col = 'list_' . $list_id; if (empty($user->$col)) { return; } } $tbl = self::table(); $now = current_time('mysql', true); $rows = (array) $wpdb->get_results($wpdb->prepare( "SELECT participant_id, competition_id, email FROM {$tbl} WHERE LOWER(TRIM(email)) = %s AND status = 'pending' ORDER BY participant_id ASC", $email )); foreach ($rows as $row) { $done = $wpdb->query($wpdb->prepare( "UPDATE {$tbl} SET status = 'confirmed', confirmed_at = %s WHERE participant_id = %d AND status = 'pending'", $now, (int) $row->participant_id )); if ($done) { self::announce((int) $row->participant_id, (int) $row->competition_id, (string) $row->email, 'confirmed', 'confirm'); } } } private static function upsert_participant(array $row) { global $wpdb; $tbl = self::table(); $cols = array_keys($row); $place = implode(', ', array_fill(0, count($cols), '%s')); $assigns = array(); foreach ($cols as $c) { if ($c === 'competition_id' || $c === 'gf_entry_id') { continue; } $assigns[] = $c . ' = VALUES(' . $c . ')'; } $sql = "INSERT INTO {$tbl} (" . implode(', ', $cols) . ") VALUES ({$place}) ON DUPLICATE KEY UPDATE " . implode(', ', $assigns) . ", updated_at = UTC_TIMESTAMP()"; $wpdb->query($wpdb->prepare($sql, ...array_values($row))); } const PRIVACY_KEY = 'aieo-competition-entries'; const PRIVACY_PAGE = 50; const ERASE_PAGE = 100; const ERASED_KEY_BASE = 2305843009213693952; private static $privacy_registered = false; public static function register_privacy() { if (self::$privacy_registered) { return; } self::$privacy_registered = true; add_filter('wp_privacy_personal_data_exporters', array(__CLASS__, 'register_exporter')); add_filter('wp_privacy_personal_data_erasers', array(__CLASS__, 'register_eraser')); } public static function register_exporter($exporters) { $exporters = is_array($exporters) ? $exporters : array(); $exporters[self::PRIVACY_KEY] = array( 'exporter_friendly_name' => __('Rooster One competition entries', 'ai-eshop-optimizer'), 'callback' => array(__CLASS__, 'privacy_export'), ); return $exporters; } public static function register_eraser($erasers) { $erasers = is_array($erasers) ? $erasers : array(); $erasers[self::PRIVACY_KEY] = array( 'eraser_friendly_name' => __('Rooster One competition entries', 'ai-eshop-optimizer'), 'callback' => array(__CLASS__, 'privacy_erase'), ); return $erasers; } private static function privacy_email($email) { $email = strtolower(trim((string) $email)); return ('' !== $email && is_email($email)) ? $email : ''; } private static function privacy_where($email) { $user = get_user_by('email', $email); if ($user) { return array('( LOWER(TRIM(email)) = %s OR wp_user_id = %d )', array($email, (int) $user->ID)); } return array('LOWER(TRIM(email)) = %s', array($email)); } private static function privacy_table_ready() { global $wpdb; $tbl = self::table(); return (string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($tbl))) === $tbl; } private static function native_key_base() { if (!class_exists('AIEO_Competition_Entry_Form') && is_readable(__DIR__ . '/class-aieo-competition-entry-form.php')) { require_once __DIR__ . '/class-aieo-competition-entry-form.php'; } return class_exists('AIEO_Competition_Entry_Form') ? (int) AIEO_Competition_Entry_Form::NATIVE_BASE : 2 * self::ERASED_KEY_BASE; } public static function addressed_sql($column = 'email') { return "LOCATE('@', {$column}) > 0"; } public static function privacy_export($email, $page = 1) { global $wpdb; $email = self::privacy_email($email); if ('' === $email || !self::privacy_table_ready()) { return array('data' => array(), 'done' => true); } $per = self::PRIVACY_PAGE; $page = max(1, (int) $page); $tbl = self::table(); list($where, $args) = self::privacy_where($email); $rows = (array) $wpdb->get_results($wpdb->prepare( "SELECT * FROM {$tbl} WHERE {$where} ORDER BY participant_id ASC LIMIT %d OFFSET %d", array_merge($args, array($per, ($page - 1) * $per)) )); $yes = __('Yes', 'ai-eshop-optimizer'); $no = __('No', 'ai-eshop-optimizer'); $flag = static function ($v) use ($yes, $no) { return null === $v ? '' : (1 === (int) $v ? $yes : $no); }; $at = static function ($v) { return null === $v || '' === (string) $v ? '' : (string) $v . ' UTC'; }; $states = array( 'confirmed' => __('Confirmed', 'ai-eshop-optimizer'), 'pending' => __('Pending', 'ai-eshop-optimizer'), ); $data = array(); foreach ($rows as $r) { $title = (string) get_the_title((int) $r->competition_id); $status = (string) $r->status; $fields = array( __('Competition', 'ai-eshop-optimizer') => '' !== $title ? $title : '#' . (int) $r->competition_id, __('Date', 'ai-eshop-optimizer') => $at($r->created_at), __('Status', 'ai-eshop-optimizer') => isset($states[$status]) ? $states[$status] : $status, __('Email', 'ai-eshop-optimizer') => (string) $r->email, __('First name', 'ai-eshop-optimizer') => (string) $r->first_name, __('Last name', 'ai-eshop-optimizer') => (string) $r->last_name, __('Confirmed at', 'ai-eshop-optimizer') => $at($r->confirmed_at), __('Newsletter consent', 'ai-eshop-optimizer') => $flag($r->newsletter_consent ?? null), __('Newsletter consent date', 'ai-eshop-optimizer') => $at($r->newsletter_consent_at ?? null), __('Consent box started ticked', 'ai-eshop-optimizer') => $flag($r->newsletter_consent_preticked ?? null), __('Consent wording version', 'ai-eshop-optimizer') => (string) ($r->newsletter_consent_version ?? ''), __('Winner', 'ai-eshop-optimizer') => 1 === (int) $r->is_winner ? $yes : $no, __('Won at', 'ai-eshop-optimizer') => $at($r->won_at), ); $items = array(); foreach ($fields as $label => $value) { if ('' !== trim((string) $value)) { $items[] = array('name' => $label, 'value' => (string) $value); } } $data[] = array( 'group_id' => self::PRIVACY_KEY, 'group_label' => __('Competition entries', 'ai-eshop-optimizer'), 'item_id' => 'aieo-competition-entry-' . (int) $r->participant_id, 'data' => $items, ); } return array('data' => $data, 'done' => count($rows) < $per); } public static function privacy_erase($email, $page = 1) { global $wpdb; $email = self::privacy_email($email); if ('' === $email || !self::privacy_table_ready()) { return array('items_removed' => false, 'items_retained' => false, 'messages' => array(), 'done' => true); } $tbl = self::table(); $native = self::native_key_base(); list($where, $args) = self::privacy_where($email); $rows = (array) $wpdb->get_results($wpdb->prepare( "SELECT participant_id, gf_entry_id, eponymous_id FROM {$tbl} WHERE {$where} ORDER BY participant_id ASC LIMIT %d", array_merge($args, array(self::ERASE_PAGE)) )); $n = 0; $people = array(); foreach ($rows as $r) { $id = (int) $r->participant_id; $key = (int) $r->gf_entry_id; if ($key >= $native) { $key = self::ERASED_KEY_BASE + $id; } $ok = $wpdb->query($wpdb->prepare( "UPDATE {$tbl} SET email = %s, gf_entry_id = %d, first_name = '', last_name = '', wp_user_id = 0, eponymous_id = 0, updated_at = UTC_TIMESTAMP() WHERE participant_id = %d", 'erased-' . $id, $key, $id )); if (false !== $ok) { $n++; if ((int) $r->eponymous_id > 0) { $people[(int) $r->eponymous_id] = true; } } } if ($n > 0) { self::forget_in_stats($email, $people); } $done = count($rows) < self::ERASE_PAGE || $n < count($rows); $forgot = 0; if ($done && class_exists('AIEO_DMM_Offer_Audiences') && method_exists('AIEO_DMM_Offer_Audiences', 'forget_email')) { $forgot = max(0, (int) AIEO_DMM_Offer_Audiences::forget_email($email)); } $withdrew = false; if ($done && class_exists('AIEO_Contact_Consent') && method_exists('AIEO_Contact_Consent', 'record_source') && 0 === strpos((string) AIEO_Contact_Consent::record_source($email), 'comp-')) { $withdrew = AIEO_Contact_Consent::withdraw_consent($email); } return array( 'items_removed' => $n > 0 || $forgot > 0 || $withdrew, 'items_retained' => $n > 0, 'messages' => $n > 0 ? array(__('Competition entries were anonymised: each entry, its status, its newsletter choice and whether it won are kept for the competition\'s counts and draws; the address, the names and the account link are removed.', 'ai-eshop-optimizer')) : array(), 'done' => $done, ); } private static function forget_in_stats($email, array $people) { $option = class_exists('AIEO_Competition_Analytics') ? AIEO_Competition_Analytics::STATS_CACHE_OPTION : 'aieo_competitions_stats_cache'; $cache = get_option($option); if (!is_array($cache) || empty($cache['aggregate']['top_participants']) || !is_array($cache['aggregate']['top_participants'])) { return; } $top = $cache['aggregate']['top_participants']; $kept = array_values(array_filter($top, static function ($row) use ($email, $people) { $row = (array) $row; return strtolower(trim((string) ($row['email'] ?? ''))) !== $email && !isset($people[(int) ($row['eponymous_id'] ?? 0)]); })); if (count($kept) !== count($top)) { $cache['aggregate']['top_participants'] = $kept; update_option($option, $cache, false); } } public static function metrics($competition_id) { global $wpdb; $tbl = self::table(); $out = array('entries' => 0, 'confirmed' => 0, 'pending' => 0, 'winners' => 0); $rows = $wpdb->get_results($wpdb->prepare( "SELECT status, COUNT(*) AS n FROM {$tbl} WHERE competition_id = %d GROUP BY status", (int) $competition_id )); if ($rows) { foreach ($rows as $r) { $out['entries'] += (int) $r->n; if ($r->status === 'confirmed') { $out['confirmed'] += (int) $r->n; } elseif ($r->status === 'pending') { $out['pending'] += (int) $r->n; } } } $out['winners'] = (int) $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM {$tbl} WHERE competition_id = %d AND is_winner = 1", (int) $competition_id )); return $out; } public static function draw_winners($competition_id, $count) { global $wpdb; $tbl = self::table(); $cid = (int) $competition_id; $count = max(1, (int) $count); if (!self::has_ended($cid)) { return new WP_Error('aieo_competition_not_ended', self::not_ended_message()); } $replaced = array_map('intval', (array) $wpdb->get_col($wpdb->prepare( "SELECT participant_id FROM {$tbl} WHERE competition_id = %d AND is_winner = 1 ORDER BY participant_id ASC", $cid ))); $addressed = self::addressed_sql('cp.email'); $ids = array_map('intval', (array) $wpdb->get_col($wpdb->prepare( "SELECT pid FROM ( SELECT MIN(cp.participant_id) AS pid, COUNT(DISTINCT cp2.competition_id) AS weight FROM {$tbl} cp JOIN {$tbl} cp2 ON cp2.email = cp.email AND cp2.status = 'confirmed' WHERE cp.competition_id = %d AND cp.status = 'confirmed' AND {$addressed} AND NOT EXISTS ( SELECT 1 FROM {$tbl} w WHERE w.email = cp.email AND w.is_winner = 1 AND w.competition_id <> %d ) GROUP BY cp.email ) cand ORDER BY POW(RAND(), 1.0 / GREATEST(weight, 1)) DESC LIMIT %d", $cid, $cid, $count ))); self::record_draw($cid, 'draw', $ids, array('asked' => $count, 'replaced' => $replaced)); self::clear_winners($cid); if ($ids) { $in = implode(',', $ids); $wpdb->query($wpdb->prepare( "UPDATE {$tbl} SET is_winner = 1, won_at = %s WHERE participant_id IN ({$in})", current_time('mysql', true) )); } return self::get_winners($cid); } public static function has_ended($competition_id) { return class_exists('AIEO_Competition_CPT') && 'ended' === AIEO_Competition_CPT::schedule_state((int) $competition_id); } public static function not_ended_message() { return __('Winners are chosen after the competition has ended. Set its end date, or wait until it has passed.', 'ai-eshop-optimizer'); } private static function record_draw($competition_id, $kind, array $winners, array $more = array()) { $row = array( 'v' => 1, 'kind' => (string) $kind, 'by' => (int) get_current_user_id(), 'at_gmt' => gmdate('Y-m-d H:i:s'), 'winners' => array_values(array_map('intval', $winners)), ); if (isset($more['asked'])) { $row['asked'] = (int) $more['asked']; } if (isset($more['replaced'])) { $row['replaced'] = array_values(array_map('intval', (array) $more['replaced'])); } add_post_meta((int) $competition_id, self::DRAWS_META, $row, false); } public static function draws($competition_id) { $rows = get_post_meta((int) $competition_id, self::DRAWS_META, false); return is_array($rows) ? array_values(array_filter($rows, 'is_array')) : array(); } public static function eligible_count($competition_id) { global $wpdb; $tbl = self::table(); $addressed = self::addressed_sql('cp.email'); return (int) $wpdb->get_var($wpdb->prepare( "SELECT COUNT(DISTINCT cp.email) FROM {$tbl} cp WHERE cp.competition_id = %d AND cp.status = 'confirmed' AND {$addressed} AND NOT EXISTS (SELECT 1 FROM {$tbl} w WHERE w.email = cp.email AND w.is_winner = 1)", (int) $competition_id )); } public static function clear_winners($competition_id) { global $wpdb; $tbl = self::table(); $wpdb->query($wpdb->prepare( "UPDATE {$tbl} SET is_winner = 0, won_at = NULL WHERE competition_id = %d AND is_winner = 1", (int) $competition_id )); } public static function set_winner($participant_id, $on) { global $wpdb; $tbl = self::table(); $pid = (int) $participant_id; $row = $wpdb->get_row($wpdb->prepare("SELECT competition_id, is_winner FROM {$tbl} WHERE participant_id = %d", $pid)); if (!$row) { return new WP_Error('aieo_competition_no_entry', __('Missing participant.', 'ai-eshop-optimizer')); } $cid = (int) $row->competition_id; if ($on && !self::has_ended($cid)) { return new WP_Error('aieo_competition_not_ended', self::not_ended_message()); } if ((bool) $on === (bool) (int) $row->is_winner) { return true; } self::record_draw($cid, $on ? 'add' : 'remove', array($pid)); if ($on) { $wpdb->query($wpdb->prepare("UPDATE {$tbl} SET is_winner = 1, won_at = %s WHERE participant_id = %d", current_time('mysql', true), $pid)); } else { $wpdb->query($wpdb->prepare("UPDATE {$tbl} SET is_winner = 0, won_at = NULL WHERE participant_id = %d", $pid)); } return true; } public static function get_winners($competition_id) { global $wpdb; $tbl = self::table(); return (array) $wpdb->get_results($wpdb->prepare( "SELECT participant_id, email, first_name, last_name, won_at, status FROM {$tbl} WHERE competition_id = %d AND is_winner = 1 ORDER BY won_at DESC, participant_id ASC", (int) $competition_id )); } public static function import_giveaways(array $args = array()) { if (function_exists('set_time_limit')) { @set_time_limit(0); } $dry = !empty($args['dry_run']); $match = array_key_exists('title_match', $args) ? (string) $args['title_match'] : 'giveaway'; $only = (isset($args['form_ids']) && is_array($args['form_ids'])) ? array_map('intval', $args['form_ids']) : array(); $do_subscribe = !array_key_exists('subscribe', $args) || !empty($args['subscribe']); if (!class_exists('GFAPI') || !class_exists('AIEO_Competition_CPT')) { return array('ok' => false, 'error' => 'Gravity Forms or Competition CPT unavailable'); } self::maybe_install(); $forms = array_merge((array) GFAPI::get_forms(true, false), (array) GFAPI::get_forms(false, false)); $report = array( 'ok' => true, 'dry_run' => $dry, 'totals' => array('forms' => 0, 'entries' => 0, 'participants' => 0, 'verified' => 0, 'unique_emails' => 0, 'subscribed' => 0, 'sub_failed' => 0), 'competitions' => array(), 'errors' => array(), ); $global = array(); foreach ($forms as $f) { $form_id = (int) ($f['id'] ?? 0); $title = trim((string) ($f['title'] ?? '')); if ($form_id <= 0) { continue; } if ($only) { if (!in_array($form_id, $only, true)) { continue; } } elseif ($match !== '' && stripos($title, $match) === false) { continue; } list($start, $end, $count) = self::entry_date_range($form_id); $desc = trim((string) ($f['description'] ?? '')); $post_id = self::find_competition_post($form_id); if (!$dry) { if ($post_id <= 0) { $ins = wp_insert_post(array( 'post_type' => AIEO_Competition_CPT::POST_TYPE, 'post_status' => 'publish', 'post_title' => $title !== '' ? $title : ('Competition #' . $form_id), ), true); if (is_wp_error($ins)) { $report['errors'][] = "form $form_id: " . $ins->get_error_message(); continue; } $post_id = (int) $ins; } else { wp_update_post(array('ID' => $post_id, 'post_title' => $title !== '' ? $title : ('Competition #' . $form_id))); } $ex_b = (array) get_post_meta($post_id, AIEO_Competition_CPT::META_BRANDS, true); $ex_c = (array) get_post_meta($post_id, AIEO_Competition_CPT::META_CATEGORIES, true); $ex_p = (array) get_post_meta($post_id, AIEO_Competition_CPT::META_PRODUCTS, true); $ex_w = (int) get_post_meta($post_id, AIEO_Competition_CPT::META_WINNERS_COUNT, true); $ex_pv = (float) get_post_meta($post_id, AIEO_Competition_CPT::META_PRIZE_VALUE, true); AIEO_Competition_CPT::persist_fields($post_id, $form_id, $desc, 0, 0, $start, $end, $ex_b, $ex_c, $ex_p, $ex_w, $ex_pv); } $cinfo = array('form_id' => $form_id, 'post_id' => $post_id, 'title' => $title, 'start' => $start, 'end' => $end, 'entries' => $count, 'participants' => 0, 'verified' => 0); $paging = array('offset' => 0, 'page_size' => 200); do { $entries = GFAPI::get_entries($form_id, array('status' => 'active'), null, $paging); if (is_wp_error($entries) || !is_array($entries)) { break; } foreach ($entries as $entry) { list($email, $first, $last) = self::extract_email_name($entry, $f); if ($email === '' || !is_email($email)) { continue; } $resolved = self::resolve_eponymous_for_email($email); $verified = self::is_verified_email($email, (int) $resolved['eponymous_id']); $cinfo['participants']++; if ($verified) { $cinfo['verified']++; } if (!$dry && $post_id > 0) { $now = current_time('mysql', true); $entry_date = !empty($entry['date_created']) ? (string) $entry['date_created'] : $now; self::upsert_participant(array( 'competition_id' => (int) $post_id, 'gf_entry_id' => (int) ($entry['id'] ?? 0), 'email' => $email, 'first_name' => $first, 'last_name' => $last, 'status' => 'confirmed', 'source' => $verified ? 'customer' : 'import', 'eponymous_id' => (int) $resolved['eponymous_id'], 'wp_user_id' => (int) $resolved['wp_user_id'], 'created_at' => $entry_date, 'confirmed_at' => $now, )); } if (!isset($global[$email])) { $global[$email] = array($first, $last, $verified); } else { if ($verified) { $global[$email][2] = true; } if ($first !== '' && $global[$email][0] === '') { $global[$email][0] = $first; } if ($last !== '' && $global[$email][1] === '') { $global[$email][1] = $last; } } } $batch = count($entries); $paging['offset'] += $paging['page_size']; } while ($batch === $paging['page_size']); $report['totals']['forms']++; $report['totals']['entries'] += $cinfo['entries']; $report['totals']['participants'] += $cinfo['participants']; $report['totals']['verified'] += $cinfo['verified']; $report['competitions'][] = $cinfo; } $report['totals']['unique_emails'] = count($global); if ($do_subscribe && !$dry && !empty($global)) { if (!class_exists('AIEO_Newsletter_Registry') && defined('AIEO_DIR')) { $reg = AIEO_DIR . 'includes/dmm/push/class-aieo-newsletter-registry.php'; if (file_exists($reg)) { require_once $reg; } } $adapter = class_exists('AIEO_Newsletter_Registry') ? AIEO_Newsletter_Registry::instance()->adapter() : null; if ($adapter && method_exists($adapter, 'subscribe_one')) { $i = 0; foreach ($global as $email => $info) { if (self::has_opted_out((string) $email)) { $report['totals']['opted_out'] = (int) ($report['totals']['opted_out'] ?? 0) + 1; continue; } $opts = array('status' => 'confirmed', 'first_name' => $info[0], 'last_name' => $info[1], 'cohort' => self::LIST_COHORT); $res = $adapter->subscribe_one($email, $opts); if (is_array($res) && !empty($res['ok'])) { $report['totals']['subscribed']++; if (!empty($res['list_id']) && (int) get_option(self::LIST_OPTION, 0) <= 0) { update_option(self::LIST_OPTION, (int) $res['list_id'], false); } } else { $report['totals']['sub_failed']++; if (count($report['errors']) < 10 && is_array($res) && !empty($res['error'])) { $report['errors'][] = $email . ': ' . $res['error']; } } if ((++$i % 50) === 0) { usleep(100000); } } } else { $report['errors'][] = 'No TNP subscribe_one adapter — emails captured but not pushed.'; } } return $report; } private static function entry_date_range($form_id) { global $wpdb; $t = $wpdb->prefix . 'gf_entry'; $r = $wpdb->get_row($wpdb->prepare( "SELECT MIN(date_created) mn, MAX(date_created) mx, COUNT(*) n FROM {$t} WHERE form_id = %d AND status = 'active'", (int) $form_id )); if (!$r || (int) $r->n === 0) { return array('', '', 0); } return array(get_date_from_gmt((string) $r->mn), get_date_from_gmt((string) $r->mx), (int) $r->n); } private static function find_competition_post($form_id) { if (!class_exists('AIEO_Competition_CPT')) { return 0; } $ids = get_posts(array( 'post_type' => AIEO_Competition_CPT::POST_TYPE, 'post_status' => 'any', 'numberposts' => 1, 'fields' => 'ids', 'no_found_rows' => true, 'meta_key' => AIEO_Competition_CPT::META_GF, 'meta_value' => (int) $form_id, )); return $ids ? (int) $ids[0] : 0; } }