[ label, applies to t / p ]. Stored as term / post meta "_hyperdrop_{key}". */ public static function fields() { return array( 'max_qty' => array( __( 'Max per item', 'hyperdrop' ), array( 't', 'p' ), __( 'Units of each product a customer can buy in one order.', 'hyperdrop' ) ), 'max_items' => array( __( 'Max items per order', 'hyperdrop' ), array( 't' ), __( 'Total units from the whole collection in one order.', 'hyperdrop' ) ), 'max_orders' => array( __( 'Orders per customer', 'hyperdrop' ), array( 't', 'p' ), __( 'How many orders one customer (by account or email) can place.', 'hyperdrop' ) ), 'max_signups' => array( __( 'Max email sign-ups', 'hyperdrop' ), array( 't', 'p' ), __( 'Total people who can request a code by email. When full, the form says all spots are taken.', 'hyperdrop' ) ), 'activations' => array( __( 'Devices per code', 'hyperdrop' ), array( 't' ), __( 'How many times an emailed code can be entered. Limits sharing.', 'hyperdrop' ) ), 'code_uses' => array( __( 'Orders per code', 'hyperdrop' ), array( 'p' ), __( 'How many orders an emailed code can be used on.', 'hyperdrop' ) ), ); } /** Global limits => [ label, default, help ]. Stored as options "hyperdrop_limit_{key}". */ public static function globals() { return array( 'unlock_attempts' => array( __( 'Code attempts per visitor', 'hyperdrop' ), 15, __( 'Wrong or right code entries allowed per visitor (IP) every 10 minutes. Stops people guessing codes.', 'hyperdrop' ) ), 'requests' => array( __( 'Code requests per visitor', 'hyperdrop' ), 5, __( 'Email code requests allowed per visitor (IP) every 10 minutes. Stops spam.', 'hyperdrop' ) ), 'emails_per_visitor' => array( __( 'Different emails per visitor', 'hyperdrop' ), 2, __( 'How many different email addresses one visitor (IP) can request codes for in 24 hours. Stops one person collecting extra codes.', 'hyperdrop' ) ), 'resends_per_email' => array( __( 'Sends per email', 'hyperdrop' ), 3, __( 'How many times the same email can request (or re-send) its code in 24 hours.', 'hyperdrop' ) ), 'expiry_days' => array( __( 'Emailed codes expire after (days)', 'hyperdrop' ), 0, __( 'Applies to codes shoppers request by email from now on. 0 = never expire.', 'hyperdrop' ) ), ); } public static function defaults( $type ) { return 't' === $type ? array( 'max_qty' => 0, 'max_items' => 0, 'max_orders' => 0, 'max_signups' => 0, 'activations' => 3 ) : array( 'max_qty' => 0, 'max_orders' => 0, 'max_signups' => 0, 'code_uses' => 1 ); } public static function get( $scope ) { list( $type, $id ) = self::split( $scope ); $out = self::defaults( $type ); foreach ( $out as $k => $default ) { $v = 't' === $type ? get_term_meta( $id, '_hyperdrop_' . $k, true ) : get_post_meta( $id, '_hyperdrop_' . $k, true ); $out[ $k ] = '' === $v ? $default : max( 0, (int) $v ); } return $out; } public static function set( $scope, $values ) { list( $type, $id ) = self::split( $scope ); foreach ( self::defaults( $type ) as $k => $default ) { if ( ! array_key_exists( $k, $values ) ) { continue; } $v = max( 0, (int) $values[ $k ] ); if ( 't' === $type ) { update_term_meta( $id, '_hyperdrop_' . $k, $v ); } else { update_post_meta( $id, '_hyperdrop_' . $k, $v ); } } } public static function global_value( $key ) { $g = self::globals(); $v = get_option( 'hyperdrop_limit_' . $key, '' ); return '' === $v ? (int) $g[ $key ][1] : max( 0, (int) $v ); } /** * Expiry datetime for a new emailed code, or ''. */ public static function signup_expiry() { $days = self::global_value( 'expiry_days' ); return $days ? wp_date( 'Y-m-d H:i:s', time() + $days * DAY_IN_SECONDS ) : ''; } /* ------------------------------------------------------------------ * Email sign-up limits * ------------------------------------------------------------------ */ public static function signups_used( $scope ) { list( $type, $id ) = self::split( $scope ); return 't' === $type ? HyperDrop_Codes::count_signups( 0, $id ) : HyperDrop_Codes::count_signups( $id, 0 ); } /** * Spots left for email sign-ups, or null when there is no cap. */ public static function signups_left( $scope ) { $l = self::get( $scope ); if ( empty( $l['max_signups'] ) ) { return null; } return max( 0, $l['max_signups'] - self::signups_used( $scope ) ); } protected static function visitor_key() { return md5( self::client_ip() ); } /** Cloudflare's published proxy ranges (https://www.cloudflare.com/ips/). */ const CLOUDFLARE = 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', ); /** * The visitor's IP, for rate limits. * * Uses the connection address. Behind Cloudflare it uses Cloudflare's visitor * header — but only when the request really comes from Cloudflare, so the * header can't be faked to dodge the limits. Other proxies: use the * `hyperdrop_client_ip` filter. */ public static function client_ip() { $remote = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : ''; $ip = $remote; if ( $remote && ! empty( $_SERVER['HTTP_CF_CONNECTING_IP'] ) && self::in_ranges( $remote, self::CLOUDFLARE ) ) { $cf = sanitize_text_field( wp_unslash( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ); if ( filter_var( $cf, FILTER_VALIDATE_IP ) ) { $ip = $cf; } } $ip = (string) apply_filters( 'hyperdrop_client_ip', $ip, $remote ); return '' !== $ip ? $ip : 'x'; } protected static function in_ranges( $ip, $ranges ) { $bin = @inet_pton( $ip ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- invalid input just means "no match". if ( false === $bin ) { return false; } foreach ( $ranges as $range ) { list( $net, $bits ) = explode( '/', $range ); $netb = @inet_pton( $net ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged if ( false === $netb || strlen( $netb ) !== strlen( $bin ) ) { continue; } $bits = (int) $bits; $bytes = intdiv( $bits, 8 ); if ( substr( $bin, 0, $bytes ) !== substr( $netb, 0, $bytes ) ) { continue; } $rest = $bits % 8; if ( 0 === $rest ) { return true; } $mask = chr( ( 0xff << ( 8 - $rest ) ) & 0xff ); if ( ( $bin[ $bytes ] & $mask ) === ( $netb[ $bytes ] & $mask ) ) { return true; } } return false; } /** * Check an email code request. Returns an error message, or '' and records the attempt. * * @param string $scope t:ID / p:ID * @param string $email * @param object|null $existing Code already issued to this email for this scope. */ public static function email_error( $scope, $email, $existing ) { $email = strtolower( trim( $email ) ); // 1. Total sign-ups cap (only new people take a spot). if ( ! $existing ) { $left = self::signups_left( $scope ); if ( null !== $left && $left <= 0 ) { /* translators: %s: collection or product name */ return sprintf( __( 'Sorry — all spots for %s are taken.', 'hyperdrop' ), self::scope_name( $scope ) ); } } // 2. Different emails per visitor (24h). $per_visitor = self::global_value( 'emails_per_visitor' ); $vkey = 'hyperdrop_ev_' . self::visitor_key(); $seen = get_transient( $vkey ); $seen = is_array( $seen ) ? $seen : array(); if ( $per_visitor && ! in_array( $email, $seen, true ) && count( $seen ) >= $per_visitor ) { return __( "You've already requested codes for other email addresses. Please use the email you signed up with.", 'hyperdrop' ); } // 3. Sends per email (24h). $per_email = self::global_value( 'resends_per_email' ); $ekey = 'hyperdrop_es_' . md5( $scope . '|' . $email ); $sends = (int) get_transient( $ekey ); if ( $per_email && $sends >= $per_email ) { return __( 'We already sent your code to this email. Please check your inbox and spam folder.', 'hyperdrop' ); } // Passed — record it. if ( ! in_array( $email, $seen, true ) ) { $seen[] = $email; set_transient( $vkey, $seen, DAY_IN_SECONDS ); } set_transient( $ekey, $sends + 1, DAY_IN_SECONDS ); return ''; } public static function split( $scope ) { $parts = explode( ':', (string) $scope ); return array( 't' === $parts[0] ? 't' : 'p', isset( $parts[1] ) ? (int) $parts[1] : 0 ); } public static function scope_name( $scope ) { list( $type, $id ) = self::split( $scope ); if ( 't' === $type ) { $t = get_term( $id, 'product_cat' ); return ( $t && ! is_wp_error( $t ) ) ? $t->name : ''; } return get_the_title( $id ); } /** * Locked scopes a product belongs to right now. */ public static function scopes_for( $product ) { $root = HyperDrop_Drop::root_id( $product ); $scopes = array(); if ( HyperDrop_Drop::is_product_gated( $root ) ) { $scopes[] = 'p:' . $root; } foreach ( HyperDrop_Drop::gated_terms_for_product( $root ) as $t ) { $scopes[] = 't:' . $t; } return $scopes; } /* ------------------------------------------------------------------ * Cart quantity limits * ------------------------------------------------------------------ */ /** * Check the cart as it would be after a change. Returns an error message or ''. * * @param int $root Product being added/updated (0 for none). * @param int $delta Quantity change for that product. */ public static function cart_error( $root = 0, $delta = 0 ) { $per_product = array(); $per_scope = array(); $add = function ( $r, $q ) use ( &$per_product, &$per_scope ) { $scopes = self::scopes_for( $r ); if ( ! $scopes ) { return; } $per_product[ $r ] = ( isset( $per_product[ $r ] ) ? $per_product[ $r ] : 0 ) + $q; foreach ( $scopes as $s ) { $per_scope[ $s ] = ( isset( $per_scope[ $s ] ) ? $per_scope[ $s ] : 0 ) + $q; } }; if ( WC()->cart ) { foreach ( WC()->cart->get_cart() as $item ) { $add( HyperDrop_Drop::root_id( $item['data'] ), (int) $item['quantity'] ); } } if ( $root && $delta ) { $add( $root, $delta ); } foreach ( $per_product as $r => $qty ) { foreach ( self::scopes_for( $r ) as $s ) { $l = self::get( $s ); if ( $l['max_qty'] && $qty > $l['max_qty'] ) { /* translators: 1: max quantity, 2: product name */ return sprintf( _n( 'Exclusive limit: you can buy up to %1$d of "%2$s" per order.', 'Exclusive limit: you can buy up to %1$d of "%2$s" per order.', $l['max_qty'], 'hyperdrop' ), $l['max_qty'], get_the_title( $r ) ); } } } foreach ( $per_scope as $s => $qty ) { $l = self::get( $s ); if ( ! empty( $l['max_items'] ) && $qty > $l['max_items'] ) { /* translators: 1: max items, 2: collection name */ return sprintf( _n( 'Exclusive limit: up to %1$d item from %2$s per order.', 'Exclusive limit: up to %1$d items from %2$s per order.', $l['max_items'], 'hyperdrop' ), $l['max_items'], self::scope_name( $s ) ); } } return ''; } /* ------------------------------------------------------------------ * Orders per customer * ------------------------------------------------------------------ */ public static function prior_orders( $scope, $email, $user_id ) { global $wpdb; $email = strtolower( trim( (string) $email ) ); $user_id = (int) $user_id; if ( ! $user_id && '' === $email ) { return 0; } // Match by account or by email; a missing one (0 / '') never matches. return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(DISTINCT order_id) FROM %i WHERE scope = %s AND ( ( %d > 0 AND user_id = %d ) OR ( %s <> '' AND email = %s ) )", HyperDrop_DB::redemptions_table(), $scope, $user_id, $user_id, $email, $email ) ); } /** * Emails tied to the codes this visitor unlocked with (so a code owner can't * dodge the order limit by typing a different billing email). */ protected static function code_emails() { $emails = array(); foreach ( array_merge( array_values( HyperDrop_Drop::unlocked() ), array_values( HyperDrop_Drop::unlocked_terms() ) ) as $code_id ) { $row = HyperDrop_Codes::get( $code_id ); if ( $row && $row->email ) { $emails[] = strtolower( $row->email ); } } return array_unique( $emails ); } /** * Returns an error message if this customer already used up their orders, or ''. */ public static function orders_error( $billing_email = '' ) { if ( ! WC()->cart ) { return ''; } $scopes = array(); foreach ( WC()->cart->get_cart() as $item ) { foreach ( self::scopes_for( $item['data'] ) as $s ) { $scopes[ $s ] = true; } } $user = get_current_user_id(); $emails = self::code_emails(); if ( $billing_email ) { $emails[] = strtolower( $billing_email ); } $emails = array_unique( array_filter( $emails ) ); foreach ( array_keys( $scopes ) as $s ) { $l = self::get( $s ); if ( ! $l['max_orders'] ) { continue; } $count = self::prior_orders( $s, '', $user ); foreach ( $emails as $e ) { $count = max( $count, self::prior_orders( $s, $e, $user ) ); } if ( $count >= $l['max_orders'] ) { /* translators: 1: number of orders, 2: collection name */ return sprintf( _n( 'Exclusive limit: %1$d order per customer for %2$s, and you have already ordered.', 'Exclusive limit: %1$d orders per customer for %2$s, and you have reached it.', $l['max_orders'], 'hyperdrop' ), $l['max_orders'], self::scope_name( $s ) ); } } return ''; } /** * Short note for the product page, e.g. "Limit 2 per order · 1 order per customer". */ public static function product_note( $product ) { $bits = array(); foreach ( self::scopes_for( $product ) as $s ) { $l = self::get( $s ); if ( $l['max_qty'] ) { /* translators: %d: quantity */ $bits[] = sprintf( __( 'Limit %d per order', 'hyperdrop' ), $l['max_qty'] ); } if ( ! empty( $l['max_items'] ) ) { /* translators: %d: quantity */ $bits[] = sprintf( __( 'max %d exclusive items per order', 'hyperdrop' ), $l['max_items'] ); } if ( $l['max_orders'] ) { /* translators: %d: orders */ $bits[] = sprintf( _n( '%d order per customer', '%d orders per customer', $l['max_orders'], 'hyperdrop' ), $l['max_orders'] ); } } return implode( ' · ', array_unique( $bits ) ); } }