prefix . 'aieo_product_requests'; } public static function table_items() { global $wpdb; return $wpdb->prefix . 'aieo_product_request_items'; } public static function table_views() { global $wpdb; return $wpdb->prefix . 'aieo_product_request_views'; } public static function ready() { static $memo = null; if ( null !== $memo ) { return $memo; } global $wpdb; $t = self::table_requests(); $memo = ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) === $t ); if ( $memo ) { self::ensure_columns(); } return $memo; } private static function ensure_columns() { static $done = false; if ( $done ) { return; } $done = true; global $wpdb; $has = $wpdb->get_var( 'SHOW COLUMNS FROM `' . self::table_items() . '` LIKE \'removed_at\'' ); if ( $has ) { return; } if ( ! function_exists( 'aieo_product_requests_install_schema' ) ) { $file = ( defined( 'AIEO_DIR' ) ? AIEO_DIR : '' ) . 'includes/dmm/product-requests/sql/product-requests-schema.php'; if ( '' === $file || ! is_readable( $file ) ) { return; } require_once $file; } if ( function_exists( 'aieo_product_requests_install_schema' ) ) { aieo_product_requests_install_schema(); } } public static function create_request( array $args ) { global $wpdb; if ( ! self::ready() ) { return new WP_Error( 'aieo_pr_no_table', __( 'Requests are not available right now.', 'ai-eshop-optimizer' ) ); } $s = AIEO_Product_Request_Settings::get( true ); $types = AIEO_Product_Request_Settings::clean_types( $s['request_types'] ); $type = sanitize_key( (string) ( $args['request_type'] ?? '' ) ); if ( ! in_array( $type, $types, true ) ) { $type = $types[0]; } $email = sanitize_email( (string) ( $args['email'] ?? '' ) ); $phone = substr( sanitize_text_field( (string) ( $args['phone'] ?? '' ) ), 0, 64 ); if ( 'phone' === AIEO_Product_Request_Settings::identity_field( $type ) ) { if ( ! self::plausible_phone( $phone ) ) { return new WP_Error( 'aieo_pr_phone', __( 'Please enter a phone number we can reach you on.', 'ai-eshop-optimizer' ) ); } if ( ! is_email( $email ) ) { $email = ''; } } elseif ( ! is_email( $email ) ) { return new WP_Error( 'aieo_pr_email', __( 'Please enter a valid email address.', 'ai-eshop-optimizer' ) ); } $product_id = absint( $args['product_id'] ?? 0 ); $variation_id = absint( $args['variation_id'] ?? 0 ); if ( 'quote' === $type && $product_id <= 0 ) { return new WP_Error( 'aieo_pr_product', __( 'Invalid product.', 'ai-eshop-optimizer' ) ); } $token = self::mint_token(); $now = gmdate( 'Y-m-d H:i:s' ); $expires = gmdate( 'Y-m-d H:i:s', time() + AIEO_Product_Request_Settings::basket_ttl( $s ) ); $attr = class_exists( 'AIEO_Goal_Tracker' ) ? AIEO_Goal_Tracker::attribution() : array(); $attribution = self::attribution_payload( $attr ); $attribution['session_alt'] = self::alt_session_id(); $row = array( 'request_type' => $type, 'status' => 'new', 'email' => $email, 'name' => substr( sanitize_text_field( (string) ( $args['name'] ?? '' ) ), 0, 190 ), 'phone' => $phone, 'message' => sanitize_textarea_field( (string) ( $args['message'] ?? '' ) ), 'user_id' => get_current_user_id(), 'session_id' => self::current_session_id(), 'token' => $token, 'token_expires' => $expires, 'page_url' => substr( AIEO_Submission_Context::redact_url( esc_url_raw( (string) ( $args['page_url'] ?? '' ) ) ), 0, 512 ), 'referrer' => substr( esc_url_raw( (string) ( $attr['referrer'] ?? '' ) ), 0, 512 ), 'attribution' => wp_json_encode( $attribution ), 'seen_before' => wp_json_encode( self::recently_viewed_snapshot( (string) ( $args['seen_before'] ?? '' ), (int) ( $args['seen_now'] ?? 0 ) ) ), 'consent' => empty( $args['consent'] ) ? 0 : 1, 'locale' => substr( (string) determine_locale(), 0, 20 ), 'created_at' => $now, ); $ok = (bool) $wpdb->insert( self::table_requests(), $row, array( '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s' ) ); if ( ! $ok ) { return new WP_Error( 'aieo_pr_insert', __( 'Could not save your request. Please try again.', 'ai-eshop-optimizer' ) ); } $request_id = (int) $wpdb->insert_id; if ( $product_id > 0 ) { self::insert_item( $request_id, $product_id, $variation_id, absint( $args['qty'] ?? 1 ), 'initial' ); } do_action( 'aieo_product_request_created', $request_id, array( 'type' => $type, 'email' => $email, 'product_id' => $product_id, 'attribution' => $attr, 'session_id' => $row['session_id'], 'page_url' => $row['page_url'], 'created_at' => $now, ) ); return array( 'id' => $request_id, 'token' => $token, 'expires' => $expires ); } public static function plausible_phone( $phone ) { return strlen( preg_replace( '/\D+/', '', (string) $phone ) ) >= 6; } private static function mint_token() { if ( function_exists( 'random_bytes' ) ) { try { return bin2hex( random_bytes( 16 ) ); } catch ( Exception $e ) { } } return substr( md5( wp_generate_password( 32, true, true ) . microtime( true ) . wp_rand() ), 0, 32 ); } public static function open_request_for_token( $token ) { global $wpdb; $token = self::clean_token( $token ); if ( '' === $token || ! self::ready() ) { return null; } static $memo = array(); if ( array_key_exists( $token, $memo ) ) { return $memo[ $token ]; } $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM `' . self::table_requests() . '` WHERE token = %s LIMIT 1', $token ) ); if ( ! $row || in_array( (string) $row->status, self::CLOSED_STATUSES, true ) || strtotime( (string) $row->token_expires . ' UTC' ) < time() ) { $row = null; } $memo[ $token ] = $row; return $row; } public static function clean_token( $token ) { $token = strtolower( trim( (string) $token ) ); return preg_match( '/^[a-f0-9]{32}$/', $token ) ? $token : ''; } public static function resolve_token() { $raw = ''; if ( isset( $_POST['token'] ) ) { $raw = sanitize_text_field( wp_unslash( (string) $_POST['token'] ) ); } if ( '' === self::clean_token( $raw ) && isset( $_COOKIE[ self::COOKIE ] ) ) { $raw = sanitize_text_field( wp_unslash( (string) $_COOKIE[ self::COOKIE ] ) ); } return self::clean_token( $raw ); } public static function mirror_cookie( $token ) { $token = self::clean_token( $token ); if ( '' === $token || headers_sent() ) { return; } $s = AIEO_Product_Request_Settings::get( true ); $exp = ( 'local' === (string) $s['basket_storage'] ) ? time() + max( HOUR_IN_SECONDS, (int) $s['basket_local_hours'] * HOUR_IN_SECONDS ) : 0; setcookie( self::COOKIE, $token, array( 'expires' => $exp, 'path' => COOKIEPATH ? COOKIEPATH : '/', 'domain' => COOKIE_DOMAIN, 'secure' => is_ssl(), 'httponly' => false, 'samesite' => 'Lax', ) ); } public static function add_item( $request, $product_id, $variation_id = 0, $qty = 1 ) { $product_id = absint( $product_id ); if ( $product_id <= 0 || ! wc_get_product( $product_id ) ) { return new WP_Error( 'aieo_pr_product', __( 'Invalid product.', 'ai-eshop-optimizer' ) ); } $max = AIEO_Product_Request_Settings::max_items(); $products = array(); $lines = 0; $held = false; foreach ( self::items( (int) $request->id ) as $row ) { $lines++; $products[ (int) $row->product_id ] = true; if ( (int) $row->product_id === $product_id && (int) $row->variation_id === absint( $variation_id ) ) { $held = true; } } if ( ! $held && ! isset( $products[ $product_id ] ) && count( $products ) >= $max ) { return new WP_Error( 'aieo_pr_full', sprintf( __( 'A quote can hold at most %d products.', 'ai-eshop-optimizer' ), $max ) ); } if ( ! $held && $lines >= AIEO_Product_Request_Settings::MAX_LINES ) { return new WP_Error( 'aieo_pr_full', __( 'Your quote is full. Send it, or take something out of it first.', 'ai-eshop-optimizer' ) ); } self::insert_item( (int) $request->id, $product_id, absint( $variation_id ), absint( $qty ), 'added' ); do_action( 'aieo_product_request_item_added', (int) $request->id, $product_id ); return true; } private static function insert_item( $request_id, $product_id, $variation_id, $qty, $source ) { global $wpdb; $qty = max( 1, min( 100000, (int) $qty ) ); $wpdb->query( $wpdb->prepare( 'INSERT INTO `' . self::table_items() . '` (request_id, product_id, variation_id, qty, source, added_at) VALUES (%d, %d, %d, %d, %s, %s) ON DUPLICATE KEY UPDATE qty = VALUES(qty), added_at = VALUES(added_at), removed_at = NULL', (int) $request_id, (int) $product_id, (int) $variation_id, $qty, in_array( $source, array( 'initial', 'added' ), true ) ? $source : 'added', gmdate( 'Y-m-d H:i:s' ) ) ); } public static function remove_item( $request, $product_id, $variation_id = 0 ) { global $wpdb; return false !== $wpdb->query( $wpdb->prepare( 'UPDATE `' . self::table_items() . '` SET removed_at = %s WHERE request_id = %d AND product_id = %d AND variation_id = %d AND removed_at IS NULL', gmdate( 'Y-m-d H:i:s' ), (int) $request->id, absint( $product_id ), absint( $variation_id ) ) ); } public static function count_items( $request_id ) { global $wpdb; return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM `' . self::table_items() . '` WHERE request_id = %d AND removed_at IS NULL', (int) $request_id ) ); } public static function items( $request_id ) { global $wpdb; if ( ! self::ready() ) { return array(); } return (array) $wpdb->get_results( $wpdb->prepare( 'SELECT id, product_id, variation_id, qty, source, added_at FROM `' . self::table_items() . '` WHERE request_id = %d AND removed_at IS NULL ORDER BY added_at ASC, id ASC', (int) $request_id ) ); } public static function removed_items( $request_id ) { global $wpdb; if ( ! self::ready() ) { return array(); } return (array) $wpdb->get_results( $wpdb->prepare( 'SELECT id, product_id, variation_id, qty, source, added_at, removed_at FROM `' . self::table_items() . '` WHERE request_id = %d AND removed_at IS NOT NULL ORDER BY removed_at DESC, id DESC', (int) $request_id ) ); } public static function item_product_ids( $request_id ) { global $wpdb; if ( ! self::ready() ) { return array(); } $ids = (array) $wpdb->get_col( $wpdb->prepare( 'SELECT product_id FROM `' . self::table_items() . '` WHERE request_id = %d', (int) $request_id ) ); return array_values( array_unique( array_filter( array_map( 'absint', $ids ) ) ) ); } public static function state_for_token( $request ) { $out = array(); foreach ( self::items( (int) $request->id ) as $row ) { $pid = (int) $row->variation_id > 0 ? (int) $row->variation_id : (int) $row->product_id; $prod = wc_get_product( $pid ); if ( ! $prod ) { $prod = wc_get_product( (int) $row->product_id ); } if ( ! $prod ) { continue; } $out[] = array( 'product_id' => (int) $row->product_id, 'variation_id' => (int) $row->variation_id, 'qty' => (int) $row->qty, 'product_name' => method_exists( 'AIEO_DMM_Swatches_Runtime', 'shade_title' ) ? AIEO_DMM_Swatches_Runtime::shade_title( $prod ) : $prod->get_name(), 'permalink' => $prod->get_permalink(), 'thumb' => self::thumb_url( $prod ), ); } return $out; } private static function thumb_url( $prod ) { $id = (int) $prod->get_image_id(); if ( $id <= 0 && method_exists( $prod, 'get_parent_id' ) && $prod->get_parent_id() ) { $parent = wc_get_product( (int) $prod->get_parent_id() ); if ( $parent ) { $id = (int) $parent->get_image_id(); } } if ( $id <= 0 ) { return ''; } $src = wp_get_attachment_image_src( $id, 'woocommerce_thumbnail' ); return is_array( $src ) && ! empty( $src[0] ) ? (string) $src[0] : ''; } public static function record_view( $request, $product_id ) { global $wpdb; $product_id = absint( $product_id ); if ( $product_id <= 0 ) { return false; } $is_item = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM `' . self::table_items() . '` WHERE request_id = %d AND product_id = %d', (int) $request->id, $product_id ) ); if ( $is_item > 0 ) { return false; } $cap = AIEO_Product_Request_Settings::MAX_ITEMS_CEILING; $n = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM `' . self::table_views() . '` WHERE request_id = %d', (int) $request->id ) ); if ( $n >= $cap ) { return false; } $wpdb->query( $wpdb->prepare( 'INSERT INTO `' . self::table_views() . '` (request_id, product_id, viewed_at) VALUES (%d, %d, %s) ON DUPLICATE KEY UPDATE viewed_at = VALUES(viewed_at)', (int) $request->id, $product_id, gmdate( 'Y-m-d H:i:s' ) ) ); return true; } public static function views( $request_id ) { global $wpdb; if ( ! self::ready() ) { return array(); } return (array) $wpdb->get_results( $wpdb->prepare( 'SELECT product_id, viewed_at FROM `' . self::table_views() . '` WHERE request_id = %d ORDER BY viewed_at ASC', (int) $request_id ) ); } public static function claim_notification( $request_id ) { global $wpdb; return 1 === (int) $wpdb->query( $wpdb->prepare( 'UPDATE `' . self::table_requests() . '` SET notified_at = %s WHERE id = %d AND notified_at IS NULL', gmdate( 'Y-m-d H:i:s' ), (int) $request_id ) ); } public static function release_notification( $request_id ) { global $wpdb; $wpdb->query( $wpdb->prepare( 'UPDATE `' . self::table_requests() . '` SET notified_at = NULL WHERE id = %d', (int) $request_id ) ); } public static function claim_summary( $request_id ) { global $wpdb; return 1 === (int) $wpdb->query( $wpdb->prepare( 'UPDATE `' . self::table_requests() . '` SET summary_sent_at = %s WHERE id = %d AND summary_sent_at IS NULL', gmdate( 'Y-m-d H:i:s' ), (int) $request_id ) ); } public static function get_request( $id ) { global $wpdb; if ( ! self::ready() ) { return null; } return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM `' . self::table_requests() . '` WHERE id = %d LIMIT 1', (int) $id ) ); } public static function list_requests( array $args = array() ) { global $wpdb; if ( ! self::ready() ) { return array( 'rows' => array(), 'total' => 0 ); } $where = array( '1=1' ); $params = array(); $status = sanitize_key( (string) ( $args['status'] ?? '' ) ); if ( '' !== $status ) { $where[] = 'r.status = %s'; $params[] = $status; } $type = sanitize_key( (string) ( $args['type'] ?? '' ) ); if ( '' !== $type ) { $where[] = 'r.request_type = %s'; $params[] = $type; } $search = trim( (string) ( $args['search'] ?? '' ) ); if ( '' !== $search ) { $like = '%' . $wpdb->esc_like( $search ) . '%'; $where[] = '(r.email LIKE %s OR r.name LIKE %s OR r.phone LIKE %s)'; $params[] = $like; $params[] = $like; $params[] = $like; } $from = self::to_gmt_boundary( (string) ( $args['from'] ?? '' ), '00:00:00' ); if ( '' !== $from ) { $where[] = 'r.created_at >= %s'; $params[] = $from; } $to = self::to_gmt_boundary( (string) ( $args['to'] ?? '' ), '23:59:59' ); if ( '' !== $to ) { $where[] = 'r.created_at <= %s'; $params[] = $to; } $campaign = trim( (string) ( $args['campaign'] ?? '' ) ); if ( '' !== $campaign ) { $where[] = 'r.attribution LIKE %s'; $params[] = '%' . $wpdb->esc_like( '"utm_campaign":"' . $campaign ) . '%'; } $sql_where = implode( ' AND ', $where ); $total_sql = 'SELECT COUNT(*) FROM `' . self::table_requests() . '` r WHERE ' . $sql_where; $total = (int) $wpdb->get_var( $params ? $wpdb->prepare( $total_sql, $params ) : $total_sql ); $per_page = max( 1, min( 200, (int) ( $args['per_page'] ?? 50 ) ) ); $paged = max( 1, (int) ( $args['paged'] ?? 1 ) ); $offset = ( $paged - 1 ) * $per_page; $rows_sql = 'SELECT r.*, (SELECT COUNT(*) FROM `' . self::table_items() . '` i WHERE i.request_id = r.id AND i.removed_at IS NULL) AS item_count, (SELECT COUNT(*) FROM `' . self::table_views() . '` v WHERE v.request_id = r.id) AS view_count, (SELECT i2.product_id FROM `' . self::table_items() . '` i2 WHERE i2.request_id = r.id ORDER BY (i2.removed_at IS NOT NULL) ASC, i2.added_at ASC, i2.id ASC LIMIT 1) AS first_product FROM `' . self::table_requests() . '` r WHERE ' . $sql_where . ' ORDER BY r.created_at DESC, r.id DESC LIMIT %d OFFSET %d'; $rows = (array) $wpdb->get_results( $wpdb->prepare( $rows_sql, array_merge( $params, array( $per_page, $offset ) ) ) ); return array( 'rows' => $rows, 'total' => $total ); } public static function status_counts() { global $wpdb; if ( ! self::ready() ) { return array(); } $out = array(); foreach ( (array) $wpdb->get_results( 'SELECT status, COUNT(*) AS n FROM `' . self::table_requests() . '` GROUP BY status' ) as $r ) { $out[ (string) $r->status ] = (int) $r->n; } return $out; } public static function count_new() { $c = self::status_counts(); return isset( $c['new'] ) ? (int) $c['new'] : 0; } public static function update_admin_fields( $id, $status, $note ) { global $wpdb; $valid = array( 'new', 'in_progress', 'quoted', 'closed', 'spam' ); $status = sanitize_key( $status ); if ( ! in_array( $status, $valid, true ) ) { return false; } return false !== $wpdb->update( self::table_requests(), array( 'status' => $status, 'admin_note' => sanitize_textarea_field( (string) $note ), 'handled_at' => gmdate( 'Y-m-d H:i:s' ), 'handled_by' => get_current_user_id(), ), array( 'id' => (int) $id ), array( '%s', '%s', '%s', '%d' ), array( '%d' ) ); } public static function delete_request( $id ) { global $wpdb; $id = (int) $id; $wpdb->delete( self::table_items(), array( 'request_id' => $id ), array( '%d' ) ); $wpdb->delete( self::table_views(), array( 'request_id' => $id ), array( '%d' ) ); $ok = false !== $wpdb->delete( self::table_requests(), array( 'id' => $id ), array( '%d' ) ); if ( $ok && class_exists( 'AIEO_Submission_Context' ) && method_exists( 'AIEO_Submission_Context', 'forget_leads' ) ) { AIEO_Submission_Context::forget_leads( array( 'pr:' . $id ), array( 'pri:' . $id . ':' ) ); } return $ok; } const ERASED_EMAIL = 'deleted@site.invalid'; const ERASE_KEEPS_ATTRIBUTION = array( 'utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'landing_page', 'channel' ); public static function register_exporter( $exporters ) { $exporters = is_array( $exporters ) ? $exporters : array(); $exporters['aieo-product-requests'] = array( 'exporter_friendly_name' => __( 'Rooster One quote requests', 'ai-eshop-optimizer' ), 'callback' => array( __CLASS__, 'privacy_export' ), ); return $exporters; } public static function register_eraser( $erasers ) { $erasers = is_array( $erasers ) ? $erasers : array(); $erasers['aieo-product-requests'] = array( 'eraser_friendly_name' => __( 'Rooster One quote requests', 'ai-eshop-optimizer' ), 'callback' => array( __CLASS__, 'privacy_erase' ), ); return $erasers; } private static function privacy_where( $email ) { $user = get_user_by( 'email', $email ); if ( $user ) { return array( '( email = %s OR user_id = %d )', array( $email, (int) $user->ID ) ); } return array( 'email = %s', array( $email ) ); } public static function privacy_export( $email, $page = 1 ) { global $wpdb; $email = sanitize_email( (string) $email ); if ( '' === $email || ! self::ready() ) { return array( 'data' => array(), 'done' => true ); } $per = 50; $page = max( 1, (int) $page ); list( $where, $args ) = self::privacy_where( $email ); $rows = (array) $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM `' . self::table_requests() . "` WHERE {$where} ORDER BY id ASC LIMIT %d OFFSET %d", array_merge( $args, array( $per, ( $page - 1 ) * $per ) ) ) ); $types = class_exists( 'AIEO_Product_Request_Settings' ) ? (array) AIEO_Product_Request_Settings::types() : array(); $statuses = array( 'new' => __( 'New', 'ai-eshop-optimizer' ), 'in_progress' => __( 'In progress', 'ai-eshop-optimizer' ), 'quoted' => __( 'Quoted', 'ai-eshop-optimizer' ), 'closed' => __( 'Closed', 'ai-eshop-optimizer' ), 'spam' => __( 'Spam', 'ai-eshop-optimizer' ), ); $data = array(); foreach ( $rows as $r ) { $asked = array(); $out = array(); $lines = (array) $wpdb->get_results( $wpdb->prepare( 'SELECT product_id, variation_id, qty, removed_at FROM `' . self::table_items() . '` WHERE request_id = %d ORDER BY id ASC', (int) $r->id ) ); foreach ( $lines as $l ) { $pid = (int) $l->variation_id > 0 ? (int) $l->variation_id : (int) $l->product_id; $title = (string) get_the_title( $pid ); $label = ( '' !== $title ? $title : '#' . $pid ) . ' × ' . (int) $l->qty; if ( null === $l->removed_at ) { $asked[] = $label; } else { $out[] = $label; } } $type = (string) $r->request_type; $status = (string) $r->status; $fields = array( __( 'Date', 'ai-eshop-optimizer' ) => (string) $r->created_at . ' UTC', __( 'Type', 'ai-eshop-optimizer' ) => isset( $types[ $type ] ) ? (string) $types[ $type ] : $type, __( 'Status', 'ai-eshop-optimizer' ) => isset( $statuses[ $status ] ) ? $statuses[ $status ] : $status, __( 'Name', 'ai-eshop-optimizer' ) => (string) $r->name, __( 'Email', 'ai-eshop-optimizer' ) => (string) $r->email, __( 'Phone', 'ai-eshop-optimizer' ) => (string) $r->phone, __( 'Message', 'ai-eshop-optimizer' ) => (string) $r->message, __( 'Products', 'ai-eshop-optimizer' ) => implode( ', ', $asked ), __( 'Products taken out', 'ai-eshop-optimizer' ) => implode( ', ', $out ), __( 'Sent from', 'ai-eshop-optimizer' ) => (string) $r->page_url, __( 'Referrer', 'ai-eshop-optimizer' ) => (string) $r->referrer, __( 'Language', 'ai-eshop-optimizer' ) => (string) $r->locale, __( 'Internal note', 'ai-eshop-optimizer' ) => (string) $r->admin_note, ); $items = array(); foreach ( $fields as $label => $value ) { if ( '' !== trim( $value ) ) { $items[] = array( 'name' => $label, 'value' => $value ); } } $data[] = array( 'group_id' => 'aieo-product-requests', 'group_label' => __( 'Quote requests', 'ai-eshop-optimizer' ), 'item_id' => 'aieo-product-request-' . (int) $r->id, 'data' => $items, ); } return array( 'data' => $data, 'done' => count( $rows ) < $per ); } public static function privacy_erase( $email, $page = 1 ) { global $wpdb; $email = sanitize_email( (string) $email ); $none = array( 'items_removed' => false, 'items_retained' => false, 'messages' => array(), 'done' => true ); if ( '' === $email || ! self::ready() ) { return $none; } $per = 100; list( $where, $args ) = self::privacy_where( $email ); $rows = (array) $wpdb->get_results( $wpdb->prepare( 'SELECT id, attribution FROM `' . self::table_requests() . "` WHERE {$where} ORDER BY id ASC LIMIT %d", array_merge( $args, array( $per ) ) ) ); if ( ! $rows ) { return $none; } $now = gmdate( 'Y-m-d H:i:s' ); $n = 0; foreach ( $rows as $r ) { $a = json_decode( (string) $r->attribution, true ); $keep = is_array( $a ) ? array_intersect_key( $a, array_flip( self::ERASE_KEEPS_ATTRIBUTION ) ) : array(); $ok = $wpdb->update( self::table_requests(), array( 'email' => self::ERASED_EMAIL, 'name' => '', 'phone' => '', 'message' => '', 'admin_note' => '', 'user_id' => 0, 'session_id' => '', 'attribution' => wp_json_encode( $keep ), 'token' => self::mint_token(), 'token_expires' => $now, ), array( 'id' => (int) $r->id ), array( '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s' ), array( '%d' ) ); if ( false !== $ok ) { $n++; } } return array( 'items_removed' => $n > 0, 'items_retained' => $n > 0, 'messages' => $n > 0 ? array( __( 'Quote requests were anonymised: the products and quantities asked about, the dates and the statuses are kept for the shop\'s demand figures.', 'ai-eshop-optimizer' ) ) : array(), 'done' => count( $rows ) < $per, ); } public static function rate_ok( $bucket, $limit, $window, $key = '' ) { $id = 'aieo_pr_' . sanitize_key( $bucket ) . '_' . md5( self::client_ip() . '|' . $key ); $n = (int) get_transient( $id ); if ( $n >= $limit ) { return false; } set_transient( $id, $n + 1, $window ); return true; } public static function is_bot() { $ua = isset( $_SERVER['HTTP_USER_AGENT'] ) ? (string) wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) : ''; if ( '' === $ua ) { return true; } if ( class_exists( 'AIEO_Session_Tracker' ) && method_exists( 'AIEO_Session_Tracker', 'is_bot_user_agent' ) ) { return (bool) AIEO_Session_Tracker::is_bot_user_agent( $ua ); } return (bool) preg_match( '/bot|crawl|spider|slurp|curl|wget|headless|python-requests/i', $ua ); } public static function client_ip() { $remote = self::normalise_ip( isset( $_SERVER['REMOTE_ADDR'] ) ? (string) wp_unslash( $_SERVER['REMOTE_ADDR'] ) : '' ); $xff = ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? (string) wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) : ''; $trusted = self::is_trusted_proxy( $remote ) || ( '' !== $xff && self::is_private_ip( $remote ) ); if ( $trusted ) { if ( self::is_trusted_proxy( $remote ) && ! empty( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ) { $v = self::normalise_ip( (string) wp_unslash( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ); if ( '' !== $v && false !== filter_var( $v, FILTER_VALIDATE_IP ) ) { return $v; } } $hops = array_map( 'trim', explode( ',', $xff ) ); for ( $i = count( $hops ) - 1; $i >= 0; $i-- ) { $v = self::normalise_ip( $hops[ $i ] ); if ( '' === $v || false === filter_var( $v, FILTER_VALIDATE_IP ) ) { continue; } if ( self::is_trusted_proxy( $v ) || self::is_private_ip( $v ) ) { continue; } return $v; } } return $remote; } private static function normalise_ip( $ip ) { $ip = trim( (string) $ip ); if ( preg_match( '/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i', $ip, $m ) ) { return $m[1]; } return $ip; } private static function is_private_ip( $ip ) { return '' !== $ip && false === filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) || self::ip_in_cidr( $ip, '100.64.0.0/10' ); } private static function is_trusted_proxy( $ip ) { if ( '' === $ip ) { return false; } $ranges = array( '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13', '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22', '2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32', ); $ranges = (array) apply_filters( 'aieo_trusted_proxies', $ranges ); foreach ( $ranges as $cidr ) { if ( self::ip_in_cidr( $ip, (string) $cidr ) ) { return true; } } return false; } private static function ip_in_cidr( $ip, $cidr ) { $parts = explode( '/', trim( $cidr ), 2 ); $net = trim( $parts[0] ); $bits = ( isset( $parts[1] ) && ctype_digit( trim( $parts[1] ) ) ) ? (int) trim( $parts[1] ) : -1; $a = @inet_pton( self::normalise_ip( $ip ) ); $b = @inet_pton( $net ); if ( false === $a || false === $b || strlen( $a ) !== strlen( $b ) ) { return false; } $max = strlen( $a ) * 8; if ( $bits < 0 || $bits > $max ) { $bits = $max; } $full = intdiv( $bits, 8 ); $rest = $bits % 8; if ( $full > 0 && substr( $a, 0, $full ) !== substr( $b, 0, $full ) ) { return false; } if ( 0 === $rest ) { return true; } $mask = ( 0xFF << ( 8 - $rest ) ) & 0xFF; return ( ord( $a[ $full ] ) & $mask ) === ( ord( $b[ $full ] ) & $mask ); } public static function current_session_id() { return AIEO_Submission_Context::current_session_id(); } public static function alt_session_id() { return AIEO_Submission_Context::alt_session_id(); } public static function session_ids( $request ) { global $wpdb; static $memo = array(); $rid = (int) ( $request->id ?? 0 ); if ( isset( $memo[ $rid ] ) ) { return $memo[ $rid ]; } $ids = AIEO_Submission_Context::linked_session_ids( array( (string) ( $request->session_id ?? '' ), (string) ( self::attribution_of( $request )['session_alt'] ?? '' ), ) ); $memo[ $rid ] = $ids; return $ids; } public static function attribution_payload( $attr ) { return AIEO_Submission_Context::attribution_payload( $attr ); } public static function attribution_of( $row_or_json ) { $json = is_object( $row_or_json ) ? (string) ( $row_or_json->attribution ?? '' ) : (string) $row_or_json; $a = json_decode( $json, true ); return is_array( $a ) ? $a : array(); } public static function recently_viewed_snapshot( $client = '', $client_now = 0 ) { $by_id = array(); if ( ! empty( $_COOKIE['woocommerce_recently_viewed'] ) ) { $raw = (string) wp_unslash( $_COOKIE['woocommerce_recently_viewed'] ); foreach ( array_filter( array_map( 'absint', explode( '|', $raw ) ) ) as $pid ) { unset( $by_id[ $pid ] ); $by_id[ $pid ] = array( 'id' => $pid, 't' => 0 ); } } $list = json_decode( (string) $client, true ); if ( is_array( $list ) && array_values( $list ) === $list ) { $now = time(); $skew = ( (int) $client_now > 0 ) ? $now - (int) $client_now : 0; if ( abs( $skew ) > 900 ) { $skew = 0; } $pid_of = static function ( $x ) { if ( is_int( $x ) ) { return $x > 0 ? $x : 0; } if ( is_string( $x ) && ctype_digit( $x ) ) { return (int) $x; } return 0; }; foreach ( array_slice( $list, -1 * AIEO_Product_Request_Settings::MAX_ITEMS_CEILING ) as $entry ) { $pid = 0; $t = 0; if ( is_array( $entry ) ) { $pid = isset( $entry['id'] ) ? $pid_of( $entry['id'] ) : 0; $t = isset( $entry['t'] ) && is_numeric( $entry['t'] ) ? (int) $entry['t'] : 0; } else { $pid = $pid_of( $entry ); } if ( $pid <= 0 ) { continue; } if ( $t > 0 ) { $t += $skew; } if ( $t < 0 || $t > $now ) { $t = 0; } if ( isset( $by_id[ $pid ] ) ) { $t = max( $t, (int) $by_id[ $pid ]['t'] ); } unset( $by_id[ $pid ] ); $by_id[ $pid ] = array( 'id' => $pid, 't' => $t ); } } return array_values( array_slice( $by_id, -1 * AIEO_Product_Request_Settings::MAX_ITEMS_CEILING ) ); } public static function local_datetime( $gmt ) { $gmt = trim( (string) $gmt ); if ( '' === $gmt || '0000-00-00 00:00:00' === $gmt ) { return ''; } $ts = strtotime( $gmt . ' UTC' ); return $ts ? wp_date( 'Y-m-d H:i', $ts ) : $gmt; } private static function to_gmt_boundary( $date, $time ) { $date = trim( $date ); if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $date ) ) { return ''; } return get_gmt_from_date( $date . ' ' . $time, 'Y-m-d H:i:s' ); } } }