get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_template' ), // Template to use for displaying products. 'engine' => 'amazon', // Search engine to use for product search. 'cta_type' => null, // Type of call-to-action button to display. 'custom' => null, // Custom category to search for products in. 'widget_id' => null, // ID of the widget to display. 'asin' => null, // Amazon Standard Identification Number (ASIN) of the product to display. AFFIAI_PLUGIN_PROD_ID => null, // European Article Number (EAN) of the product to display. // 'pid' => null, // Product ID of the product to display. 'rank' => null, // Product ranking to display. 'title' => null, // Custom title for the product display. 'descr' => null, // Custom description for the product display. 'pros' => null, // Pros of the products to display. 'cons' => null, // Cons of the products to display. 'image' => null, // Custom image for the product display. 'btn_text' => null, // Custom text for the call-to-action button. 'rating_type' => null, // Type of rating to display. ); $attribute['no_offers_message'] = ''; $attribute['no_offers_keep_product'] = 'no'; return $attribute; } /** * Shortcode function for the plugin. * * @param array $atts Shortcode attributes. * @param string $content Shortcode content. * @param string $tag Shortcode tag. * @return void */ public static function shortcode( $atts, $content = null, $tag = null ) { global $affiai_request_observation; $affiai_request_observation = null; // Sitestripe Attribute to convert iframe or image if ( !empty($atts['sst']) ) { $sst = 1; $rlink = 1; if ( !empty($atts['f']) ) { $img_size = $atts['f']; } } else { $sst = 0; } // Hide link Attribute only for image template if ( !empty($atts['rlink']) ) { $rlink = 1; } else { $rlink = 0; } // If debug mode is enabled, return nothing if ( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_debug' ) ) { return; } // Add CSS for AMP if ( empty( self::$call_amp ) ) { add_action( 'amp_post_template_css', array( __CLASS__, 'affiai_amp_css' ), 11 ); self::$call_amp = 1; } // Remove wpautop filter if ( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_wpautop' ) ) { remove_filter( 'the_content', 'wpautop' ); } // Activate structured data $structured_data = ! empty( $atts['sdata'] ) ? true : null; // Patch (other plugin conflict) if ( ! empty( $atts['single'] ) ) { $atts['asin'] = $atts['single']; } // Set shortcode attributes. $atts = shortcode_atts( self::get_attribute(), $atts ); $atts['no_offers_message'] = is_string( $atts['no_offers_message'] ) ? $atts['no_offers_message'] : ''; $atts['no_offers_keep_product'] = in_array( $atts['no_offers_keep_product'], array( 'yes', '1', 1, true ), true ) ? 'yes' : 'no'; array_walk( $atts, function ( &$val ) { if ( ! empty( $val ) ) { $val = trim( $val ); } } ); // Remove space in attributes. $atts[ AFFIAI_PLUGIN_PROD_ID ] = ! empty( $atts[ AFFIAI_PLUGIN_PROD_ID ] ) ? strtoupper( $atts[ AFFIAI_PLUGIN_PROD_ID ] ) : $atts[ AFFIAI_PLUGIN_PROD_ID ]; // Get post status. global $post; $post_status = isset( $post->post_status ) ? $post->post_status : null; // Check if AMP is enabled. $amp = 0; if ( ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) || ( function_exists( 'ampforwp_is_amp_endpoint' ) && ampforwp_is_amp_endpoint() ) ) { $amp = 1; } // Cache post ID. if ( ( in_the_loop() || $amp == 1 || ! self::affiai_has_widget_hook() ) && ! empty( $post->ID ) ) { $cache_afx['post_id'] = $post->ID; } elseif ( ! is_preview() && empty( $_REQUEST['preview'] ) && empty( $_REQUEST['action'] ) && ! is_admin() && ! empty( $post->ID ) ) { $cache_afx['post_id'] = 0; } // Set cache name and auto. $cache_afx['name'] = md5( implode( '|', Affiai_Offer_Integrity::retrieval_attributes( $atts ) ) ); // Filter by ID. $ids = array( 'asin' => $atts['asin'], AFFIAI_PLUGIN_PROD_ID => $atts[ AFFIAI_PLUGIN_PROD_ID ], ); // Set API parameters. $URLC = self::get_domain( wp_parse_url( home_url(), PHP_URL_HOST ) ); $param = array( 'ndd' => $URLC, ); $param[ AFFIAI_PLUGIN_PROD_ID ] = $atts[ AFFIAI_PLUGIN_PROD_ID ]; // Get product information. (title, descr, pros, cons etc.) $atts_slice = array_slice( Affiai_Offer_Integrity::retrieval_attributes( $atts ), 18 ); $info_prod = array(); if ( isset( $atts['asin'] ) || isset( $atts[ AFFIAI_PLUGIN_PROD_ID ] ) ) { $key_m = ( $atts['asin'] ) ? trim( $atts['asin'] ) : implode( ',', preg_filter( '/^/', 'E_', explode( ',', trim( $atts[ AFFIAI_PLUGIN_PROD_ID ] ) ) ) ); foreach ( $atts_slice as $key_atts => $val_atts ) { $info_prod[ $key_atts ] = self::affiai_multival( $val_atts, $key_m ); } } // If no products are being called, return nothing. if ( empty( $ids[ AFFIAI_PLUGIN_PROD_ID ] ) && empty( $ids['asin'] ) && empty( $atts['custom'] ) ) { return; } // Set merchants. $merchants = self::active_merchants(); // Choose template based on shortcode attribute. reset(self::$templates); if ($atts['template'] == 'select') { $template = 'select'; } elseif ( $atts['template'] == 'small' ) { $template = 'small'; } else { $template = array_key_exists($atts['template'], self::$templates) ? $atts['template'] : key(self::$templates); } // Set template parameter. $param['template'] = $template; // Check if AMP endpoint is active. $amp = 0; if ( ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) || ( function_exists( 'ampforwp_is_amp_endpoint' ) && ampforwp_is_amp_endpoint() ) ) { $amp = 1; } // If not in loop or AMP endpoint is active, increment count_afx. if ( ( in_the_loop() || $amp == 1 ) ) { self::$count_afx++; } $integrity_context = Affiai_Offer_Integrity::context( AFFIAI_PLUGIN_OPTION_PREFIX, AFFIAI_PLUGIN_NAME, array_keys( is_array( self::$merchants ) ? self::$merchants : array() ) ); // Set cache duration time. $time_trans = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_time_cache' ); $time_trans = is_numeric( $time_trans ) && (int) $time_trans > 0 ? (int) $time_trans : DAY_IN_SECONDS; // Get current time. $actual_time = time(); // Initialize variables for cache. $diff_time = -1; $old_products = array(); // Check if cache exists. $afx_cache = 0; $products = self::get_cache_afx( $cache_afx['name'] ); if ( false !== $products ) { $afx_cache = 1; } // If cache exists, check if it's still valid. if ( $afx_cache == 1 ) { $decoded_cache = json_decode( $products, true ); $products = is_array( $decoded_cache ) ? $decoded_cache : array(); $diff_time = $products ? 0 : -1; $context_valid = Affiai_Offer_Integrity::cache_valid( $products, $integrity_context ); if ( ! $context_valid ) { $products = array(); $afx_cache = 0; } // Check if cache is still valid. $cached_at = Affiai_Offer_Integrity::cache_time( $products ); $diff_time = null === $cached_at ? -1 : $cached_at + $time_trans - $actual_time; if ( 'image' !== $template && ! array_filter( $products, 'is_array' ) && ! Affiai_Offer_Integrity::negative_cache_valid( $products, $integrity_context ) ) { $diff_time = -1; } // If cache is no longer valid, save old products and unset current products, except for image template. if ($diff_time < 0 && $template != 'image' ) { $old_products = $products; unset($products); } } // If cache exists and template is image, set cache flag. if ( !empty($products) && is_array($products) ) { if ( $template == 'image' && key($products) != "type" ) { $diff_time = 1; } } // If cache doesn't exist or is no longer valid, fetch products from merchants. if (empty($products) || $diff_time < 0) { $refresh_claim = Affiai_Refresh_Claim::acquire( $cache_afx['name'], $integrity_context ); if ( ! $refresh_claim ) { return '

' . esc_html__( 'Product refresh is in progress. Please try again shortly.', 'affiliate-ai-lite' ) . '

'; } try { $rechecked = json_decode( (string) self::get_cache_afx( $cache_afx['name'] ), true ); if ( Affiai_Offer_Integrity::cache_valid( $rechecked, $integrity_context ) && Affiai_Offer_Integrity::cache_time( $rechecked ) !== null && Affiai_Offer_Integrity::cache_time( $rechecked ) + $time_trans >= $actual_time && empty( $atts['force_cache'] ) ) { $products = $rechecked; $afx_cache = 1; $diff_time = 0; } else { // Initialize variables for fetching products. $i = 0; $products = array(); $_products = array(); $temp_prod = array(); // Retrieve the requested products from Amazon $products = self::products_amazon( null, $ids, $param, $products ); // Sort the products by merchant price in ascending order if ( ! Affiai_Refresh_Claim::renew( $refresh_claim ) ) { return '

' . esc_html__( 'Product refresh could not be completed. Please try again shortly.', 'affiliate-ai-lite' ) . '

'; } foreach ( $products as $k => $product ) { $products[ $k ]['merchant'] = self::affiai_array_orderby( $products[ $k ]['merchant'], 'price', SORT_ASC ); } // Update the product details with merchant details foreach ( $products as $k => $product ) { foreach ( $product['merchant'] as $m => $merchant ) { // Update the product title, description, image and URL with merchant details if ( empty( $products[ $k ]['title'] ) && ! empty( $merchant['title'] ) ) { $products[ $k ]['title'] = apply_filters('affiai_filtrer_title', $merchant['title']); } if ( empty( $products[ $k ]['description'] ) && ! empty( $merchant['description'] ) ) { // Shorten the description to a maximum number of lines and words if (is_array($merchant['description'])) { $numberOfLines = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_nb_lines' ); $wordsPerLine = 10; // This is just an example, this value should be adjusted $maxWords = $wordsPerLine * $numberOfLines; // Counter for the number of words $wordCount = 0; // Loop through each element in the array foreach ($merchant['description'] as $index => &$item) { $words = explode(" ", $item); // If we haven't reached the limit yet if ($wordCount + count($words) <= $maxWords) { $wordCount += count($words); } else { // Calculate how many words we can still add $remainingWords = $maxWords - $wordCount; // Shorten the text of the current element $shortenedWords = array_slice($words, 0, $remainingWords); $item = implode(" ", $shortenedWords) . ''; // Remove the remaining elements from the array array_splice($merchant['description'], $index + 1); break; } } } $products[ $k ]['description'] = apply_filters('affiai_filtrer_desc', $merchant['description']); } if ( empty( $products[ $k ]['image'] ) && ! empty( $merchant['image'] ) ) { $products[ $k ]['image'] = $merchant['image']; if ( ! empty( $merchant['url'] ) ) { $products[ $k ]['url'] = $merchant['url']; } } unset( $products[ $k ]['merchant'][ $m ]['title'] ); unset( $products[ $k ]['merchant'][ $m ]['description'] ); unset( $products[ $k ]['merchant'][ $m ]['image'] ); } // Update the date of the product update if ( ! empty( $old_products[ $k ]['date'] ) && ! empty( $old_products['type'] ) && $old_products['type'] == 'custom' ) { $products[ $k ]['date'] = $old_products[ $k ]['date']; $cache_afx['date'] = $old_products[ $k ]['date']; $_old = '_OLD'; $cache_afx['old'] = 1; } else { $products[ $k ]['date'] = round( current_time( 'timestamp' ) ); $cache_afx['date'] = round( current_time( 'timestamp' ) ); } } // Check if there are missing products if ( ! $products ) { // If there are old products, use them if ( ! empty( $old_products ) && ( $old_products['type'] ?? '' ) === 'custom' ) { $products = $old_products; $products['date'] = round( current_time( 'timestamp' ) ); $_old = '_OLD'; $cache_afx['old'] = 1; } } // If there are missing products and old products, use the old products if ( ! empty( $old_products ) && ( $old_products['type'] ?? '' ) === 'custom' && ( ! empty( $ids[ AFFIAI_PLUGIN_PROD_ID ] ) || ! empty( $ids['asin'] ) ) ) { if ( count( $old_products ) > count( $products ) ) { foreach ( $old_products as $k => $v ) { if ( array_key_exists( $k, $products ) ) { $old_products[ $k ] = $products[ $k ]; } else { $_old = '_OLD'; $cache_afx['old'] = 1; } } $products = $old_products; $products['date'] = round( current_time( 'timestamp' ) ); } } if ( self::$count_afx == 0 && $atts['auto'] == 2 ) { $products = array_merge( array_slice( $products, ( $count / 2 ) ), array_slice( $products, 0, ( $count / 2 ) ) ); } // Order the products by EAN if ( ! empty( $key_m ) && ! empty( $atts[ AFFIAI_PLUGIN_PROD_ID ] ) && empty( $atts['asin'] ) && empty( $atts['keyword'] ) && !empty($products) ) { $products = array_merge( array_flip( explode( ',', $key_m ) ), $products ); } // Check if there are missing products based on shortcode attributes // Set the product type and search based on shortcode attributes $_out = ''; if ( ! empty( $atts['asin'] ) ) { if ( count( explode( ',', $atts['asin'] ) ) > count( $products ) ) { $_out = '_OUT'; $cache_afx['off'] = 1; } $products['type'] = 'asin'; $products['search'] = $atts['asin']; } elseif ( ! empty( $atts[ AFFIAI_PLUGIN_PROD_ID ] ) ) { if ( count( explode( ',', $atts[ AFFIAI_PLUGIN_PROD_ID ] ) ) > count( $products ) ) { $_out = '_OUT'; $cache_afx['off'] = 1; } $products['type'] = AFFIAI_PLUGIN_PROD_ID; $products['search'] = $atts[ AFFIAI_PLUGIN_PROD_ID ]; } // Add a date when the products are empty if (key($products) == "type") { $products['date'] = round( current_time( 'timestamp' ) ); } if ( ! Affiai_Refresh_Claim::renew( $refresh_claim ) ) { return '

' . esc_html__( 'Product refresh could not be completed. Please try again shortly.', 'affiliate-ai-lite' ) . '

'; } // Save products to cache if post is published and cache is not empty if ( ! empty( $post_status ) && $post_status == 'publish' && isset( $cache_afx['post_id'] ) && $atts['template'] != 'select' && !self::affiai_is_builder_active() && ( 'image' === $template || Affiai_Offer_Integrity::usable_products( $products ) || in_array( $template, array( 'box', 'grid', 'list' ), true ) ) ) { $products = Affiai_Offer_Integrity::stamp_cache( Affiai_Offer_Integrity::clean_prices( $products ), $integrity_context, self::integrity_market()['country'] ?? null, in_array( $template, array( 'box', 'grid', 'list' ), true ) ); $cache_afx['value'] = wp_json_encode( $products ); self::add_cache_afx( $cache_afx ); } } } finally { Affiai_Refresh_Claim::release( $refresh_claim ); } } $unavailable_product = Affiai_Offer_Integrity::unavailable_product( $products ); $products = Affiai_Offer_Integrity::clean_prices( $products ); if ( 'image' !== $template ) { $products = Affiai_Offer_Integrity::usable_products( $products ); } // Remove unnecessary product data for display unset( $products['type'] ); unset( $products['search'] ); unset( $products['cache'] ); if ( 'image' !== $template ) { $has_products = is_array( $products ) && (bool) array_filter( $products, 'is_array' ); affiai_lite_health_record_retrieval( $has_products ? 'ready' : 'retryable', $has_products ? ( $afx_cache && $diff_time >= 0 ? 'recent_cache' : 'refreshed' ) : 'refresh_empty', $has_products ? ( $afx_cache && $diff_time >= 0 ? 'cache' : 'live' ) : 'none', Affiai_Offer_Integrity::health_details( $products, $integrity_context, $cache_afx['post_id'] ?? 0 ) ); } if ( isset( $has_products ) && ! $has_products && 'grid' === $template ) { if ( function_exists( 'affiai_first_success_observe' ) ) { affiai_first_success_observe( $cache_afx['post_id'] ?? 0, $cache_afx['name'], $atts, $products, '', $integrity_context, 'none' ); } $empty_output = Affiai_Offer_Integrity::no_offers( $atts, AFFIAI_PLUGIN_PROD_ID, $template, 'affiliate-ai-lite', (bool) $amp, $unavailable_product ); if ( null !== $empty_output ) { return $empty_output; } return '

' . esc_html__( 'Product offers are temporarily unavailable.', 'affiliate-ai-lite' ) . '

'; } // Set variables for structured data, link hiding, automatic description, clock display, price hiding, logo hiding, Amazon tags, button resizing, pros and cons titles, CTA type, color, column display, and show mentions $structured_data = ! empty( $structured_data ) ? $structured_data : (bool) get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_structured_data' ); $hide_link = (bool) get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_hide_link' ); $auto_descr = (bool) get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_auto_descr' ); $show_clock = (bool) get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_show_clock' ); $hide_price = (bool) get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_hide_price' ); $hide_logo = (bool) get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_hide_logo' ); $tag_amz = trim( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_tag' ) ); $tag_guest = trim( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_tag_guest' ) ); $noresize_btn = (bool) get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_resize_btn' ); $pros_title = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_pros_title' ) ? get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_pros_title' ) : 'PROS'; $cons_title = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_cons_title' ) ? get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_cons_title' ) : 'CONS'; $cta_type = $atts['cta_type'] ? $atts['cta_type'] : get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_cta_type' ); $color = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_color' ); $btn_type = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_btn_type' ); $show_mtn = ! empty( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_mentions' )[0] ) ? get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_mentions' )[0] : false; $column = ! empty( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_column' ) ) ? round( 100 / get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_column' ) ) : 3; // Set date and time format for creation date display // If date or time format is empty, set default values $date_format = get_option( 'date_format' ); $time_format = get_option( 'time_format' ); $date_format = ! empty( $date_format ) ? $date_format : 'd/m/Y'; $time_format = ! empty( $time_format ) ? $time_format : 'H:i'; // Get the creation date of the first product in the list if ( ! empty( array_values( array_filter( $products ) )[0]['date'] ) ) { $creation_date = date_i18n( $date_format . ' ' . $time_format, array_values( array_filter( $products ) )[0]['date'] ); } else { $creation_date = ''; } // Set the AMP template directory based on the $amp variable if ( $amp == 1 ) { $amp_t = 'amp' . DIRECTORY_SEPARATOR; } else { $amp_t = ''; } // Render the product template ob_start(); include AFFIAI_PLUGIN_DIR . 'views' . DIRECTORY_SEPARATOR . 'products' . DIRECTORY_SEPARATOR . $amp_t . $template . '.php'; $output_afx = ob_get_clean(); if ( function_exists( 'affiai_first_success_observe' ) ) { affiai_first_success_observe( $cache_afx['post_id'] ?? 0, $cache_afx['name'], $atts, $products, $output_afx, $integrity_context, $afx_cache && $diff_time >= 0 ? 'cache' : 'retrieval' ); } return $output_afx; } /** * Returns an array of active templates. * * @return array The array of active templates. */ public static function integrity_context() { return Affiai_Offer_Integrity::context( AFFIAI_PLUGIN_OPTION_PREFIX, AFFIAI_PLUGIN_NAME, array_keys( is_array( self::$merchants ) ? self::$merchants : array() ) ); } public static function integrity_market() { return self::get_amazon_creators_locale_config( (string) get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_country' ) ); } public static function active_templates() { reset( self::$templates ); return self::$templates; } /** * Returns an array of active merchants. * * @return array An array of active merchants. */ public static function active_merchants() { return array_values( array_filter( array_keys( is_array( self::$merchants ) ? self::$merchants : array() ), array( __CLASS__, 'merchant_active' ) ) ); } /** * Checks if a merchant is active. * * @param string $merchant The merchant to check. * @return bool Returns true if the merchant is active, false otherwise. */ public static function merchant_active( $merchant ) { if ( ! array_key_exists( $merchant, self::$merchants ) ) { return false; } return call_user_func( array( __CLASS__, 'merchant_active_' . $merchant ) ); } /** * Sanitizes a JSON string by escaping double quotes within the "Title" property. * * @param string $json_string The JSON string to sanitize. * @return string The sanitized JSON string. */ public static function affiai_sanitize_json_string($json_string) { return preg_replace_callback( '/"Title"\s*:\s*"((?:[^"]|"(?!\s*,))*)"/', function ($matches) { $value = $matches[1]; $escaped_value = preg_replace('/(? '', 'language' => '' ); } $parts = explode( '_', $country_setting ); return array( 'country' => ! empty( $parts[0] ) ? $parts[0] : $country_setting, 'language' => ! empty( $parts[1] ) ? $parts[1] : '', ); } protected static function get_amazon_creators_locale_config( $country_setting ) { $parts = self::get_amazon_country_parts( $country_setting ); $country = $parts['country']; $map = array( 'com.au' => array( 'marketplace' => 'www.amazon.com.au', 'default_language' => 'en_AU', 'region' => 'fe' ), 'com.be' => array( 'marketplace' => 'www.amazon.com.be', 'default_language' => 'fr_BE', 'region' => 'eu' ), 'com.br' => array( 'marketplace' => 'www.amazon.com.br', 'default_language' => 'pt_BR', 'region' => 'na' ), 'ca' => array( 'marketplace' => 'www.amazon.ca', 'default_language' => 'en_CA', 'region' => 'na' ), 'fr' => array( 'marketplace' => 'www.amazon.fr', 'default_language' => 'fr_FR', 'region' => 'eu' ), 'de' => array( 'marketplace' => 'www.amazon.de', 'default_language' => 'de_DE', 'region' => 'eu' ), 'in' => array( 'marketplace' => 'www.amazon.in', 'default_language' => 'en_IN', 'region' => 'eu' ), 'it' => array( 'marketplace' => 'www.amazon.it', 'default_language' => 'it_IT', 'region' => 'eu' ), 'co.jp' => array( 'marketplace' => 'www.amazon.co.jp', 'default_language' => 'ja_JP', 'region' => 'fe' ), 'com.mx' => array( 'marketplace' => 'www.amazon.com.mx', 'default_language' => 'es_MX', 'region' => 'na' ), 'es' => array( 'marketplace' => 'www.amazon.es', 'default_language' => 'es_ES', 'region' => 'eu' ), 'com.tr' => array( 'marketplace' => 'www.amazon.com.tr', 'default_language' => 'tr_TR', 'region' => 'eu' ), 'ae' => array( 'marketplace' => 'www.amazon.ae', 'default_language' => 'en_AE', 'region' => 'eu' ), 'co.uk' => array( 'marketplace' => 'www.amazon.co.uk', 'default_language' => 'en_GB', 'region' => 'eu' ), 'com' => array( 'marketplace' => 'www.amazon.com', 'default_language' => 'en_US', 'region' => 'na' ), 'nl' => array( 'marketplace' => 'www.amazon.nl', 'default_language' => 'nl_NL', 'region' => 'eu' ), 'sa' => array( 'marketplace' => 'www.amazon.sa', 'default_language' => 'en_AE', 'region' => 'eu' ), 'se' => array( 'marketplace' => 'www.amazon.se', 'default_language' => 'sv_SE', 'region' => 'eu' ), 'sg' => array( 'marketplace' => 'www.amazon.sg', 'default_language' => 'en_SG', 'region' => 'fe' ), 'pl' => array( 'marketplace' => 'www.amazon.pl', 'default_language' => 'pl_PL', 'region' => 'eu' ), 'eg' => array( 'marketplace' => 'www.amazon.eg', 'default_language' => 'en_GB', 'region' => 'eu' ), ); if ( ! isset( $map[ $country ] ) ) { return null; } $config = $map[ $country ]; $config['country'] = $country; $config['language'] = $config['default_language']; if ( ! empty( $parts['language'] ) ) { if ( 'ca' !== $country || 'fr' !== $parts['language'] ) { return null; } $config['language'] = 'fr_CA'; } return $config; } protected static function get_amazon_creators_token_endpoint( $version, $region ) { $version = 'v2' === $version ? 'v2' : 'v3'; if ( 'v2' === $version ) { $endpoints = array( 'na' => 'https://creatorsapi.auth.us-east-1.amazoncognito.com/oauth2/token', 'eu' => 'https://creatorsapi.auth.eu-south-2.amazoncognito.com/oauth2/token', 'fe' => 'https://creatorsapi.auth.us-west-2.amazoncognito.com/oauth2/token', ); } else { $endpoints = array( 'na' => 'https://api.amazon.com/auth/o2/token', 'eu' => 'https://api.amazon.co.uk/auth/o2/token', 'fe' => 'https://api.amazon.co.jp/auth/o2/token', ); } return isset( $endpoints[ $region ] ) ? $endpoints[ $region ] : $endpoints['na']; } protected static function get_amazon_creators_token_state_key( $client_id, $region, $suffix ) { return 'affiai_amz_creators_' . $suffix . '_' . md5( $client_id . '|' . $region ); } protected static function get_amazon_creators_token_single( $client_id, $client_secret, $version, $region ) { $cache_key = 'affiai_amz_creators_' . md5( $client_id . '|' . $version . '|' . $region ); $cached = get_transient( $cache_key ); if ( ! empty( $cached ) ) { return array( 'access_token' => $cached, 'version' => $version, 'source' => 'token_cache', ); } $token_url = self::get_amazon_creators_token_endpoint( $version, $region ); $args_variants = array(); if ( 'v2' === $version ) { $args_variants[] = array( 'method' => 'POST', 'timeout' => 20, 'headers' => array( 'Content-Type' => 'application/x-www-form-urlencoded', 'Authorization' => 'Basic ' . base64_encode( $client_id . ':' . $client_secret ), ), 'body' => array( 'grant_type' => 'client_credentials', 'scope' => 'creatorsapi/default', ), ); } else { $args_variants[] = array( 'method' => 'POST', 'timeout' => 20, 'headers' => array( 'Content-Type' => 'application/x-www-form-urlencoded', ), 'body' => array( 'grant_type' => 'client_credentials', 'client_id' => $client_id, 'client_secret' => $client_secret, 'scope' => 'creatorsapi::default', ), ); $args_variants[] = array( 'method' => 'POST', 'timeout' => 20, 'headers' => array( 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( array( 'grant_type' => 'client_credentials', 'client_id' => $client_id, 'client_secret' => $client_secret, 'scope' => 'creatorsapi::default', ) ), ); } foreach ( $args_variants as $args ) { $response = wp_remote_post( $token_url, $args ); if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) { continue; } $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( empty( $body['access_token'] ) ) { continue; } $ttl = ! empty( $body['expires_in'] ) ? max( 60, (int) $body['expires_in'] - 120 ) : 3300; set_transient( $cache_key, $body['access_token'], $ttl ); return array( 'access_token' => $body['access_token'], 'version' => $version, 'source' => 'fresh_token', ); } return false; } protected static function get_amazon_creators_token( $client_id, $client_secret, $version, $region, &$resolved_version = null ) { $version = 'v2' === $version ? 'v2' : 'v3'; $resolved_version = $version; $failure_key = self::get_amazon_creators_token_state_key( $client_id, $region, 'failed' ); $success_key = self::get_amazon_creators_token_state_key( $client_id, $region, 'version' ); $failed_state = get_transient( $failure_key ); if ( ! empty( $failed_state ) ) { return false; } $try_versions = array(); $detected_version = get_transient( $success_key ); if ( ! empty( $detected_version ) && in_array( $detected_version, array( 'v2', 'v3' ), true ) ) { $try_versions[] = $detected_version; } $try_versions[] = $version; $try_versions[] = ( 'v2' === $version ) ? 'v3' : 'v2'; $try_versions = array_values( array_unique( $try_versions ) ); foreach ( $try_versions as $try_version ) { $result = self::get_amazon_creators_token_single( $client_id, $client_secret, $try_version, $region ); if ( ! empty( $result['access_token'] ) ) { $resolved_version = $try_version; set_transient( $success_key, $try_version, 7 * DAY_IN_SECONDS ); delete_transient( $failure_key ); return $result['access_token']; } } set_transient( $failure_key, array( 'preferred_version' => $version, 'region' => $region, 'failed_at' => current_time( 'mysql', true ), ), 3 * HOUR_IN_SECONDS ); return false; } protected static function get_amazon_creators_headers( $access_token, $marketplace, $version ) { $headers = array( 'Authorization' => 'Bearer ' . $access_token, 'Content-Type' => 'application/json', 'x-marketplace' => $marketplace, ); if ( 'v2' === $version ) { $headers['Authorization'] .= ' Version 2.0'; } return $headers; } protected static function get_amazon_creators_resources() { return array( 'itemInfo.title', 'itemInfo.features', 'itemInfo.byLineInfo', 'itemInfo.externalIds', 'images.primary.large', 'images.primary.medium', 'images.primary.small', 'offersV2.listings.price', 'offersV2.listings.availability', ); } protected static function request_amazon_creators_api( $path, $payload, $headers ) { return wp_remote_post( 'https://creatorsapi.amazon' . $path, array( 'method' => 'POST', 'timeout' => 20, 'headers' => $headers, 'body' => wp_json_encode( $payload ), ) ); } protected static function get_amazon_creators_items( $response_body, $result_key ) { if ( 'itemsResult' === $result_key && is_object( $response_body ) && ! isset( $response_body->itemsResult ) && isset( $response_body->itemResults ) ) { $result_key = 'itemResults'; } if ( is_string( $response_body ) ) { $response_body = json_decode( $response_body ); } if ( empty( $response_body ) || empty( $response_body->$result_key ) ) { return array(); } $result = $response_body->$result_key; if ( isset( $result->items ) ) { return is_array( $result->items ) ? $result->items : (array) $result->items; } if ( isset( $result->Items ) ) { return is_array( $result->Items ) ? $result->Items : (array) $result->Items; } return array(); } // AMAZON /** * Retrieve Amazon products based on keyword, IDs, and parameters. * * @param string|null $keyword The keyword to search for. * @param array|null $ids The IDs to search for. * @param array $param The parameters to use for the search. * @param array $products The products to return. * @param int|null $count The number of products to return. * @param array|null $gtin The GTIN to search for. * @param bool $sa Whether to search for SA products. * * @return array The Amazon products. */ protected static function products_amazon( $keyword, $ids, $param, $products, $count = null, $gtin = null, $sa = false ) { $creators_key = trim( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_creators_key' ) ); $creators_secret = trim( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_creators_secret' ) ); if ( ! empty( $creators_key ) && ! empty( $creators_secret ) ) { return self::products_amazon_new( $keyword, $ids, $param, $products, $count, $gtin, $sa ); } return self::products_amazon_old( $keyword, $ids, $param, $products, $count, $gtin, $sa ); } protected static function products_amazon_new( $keyword, $ids, $param, $products, $count = null, $gtin = null, $sa = false ) { $is_test = ! empty( $param['test_code'] ); $ids = is_array( $ids ) ? $ids : array(); if ( ! is_array( $products ) ) { $products = array(); } if ( ! self::merchant_active_amazon() ) { if ( $is_test ) { return array( 'response' => array( 'code' => 400, 'message' => 'Amazon merchant inactive' ), 'body' => wp_json_encode( array( 'message' => 'Amazon merchant is inactive or required settings are missing.' ) ), ); } return $products; } $country_setting = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_country' ); $locale_config = self::get_amazon_creators_locale_config( $country_setting ); if ( null === $locale_config ) { return $is_test ? array( 'response' => array( 'code' => 400, 'message' => 'Unsupported Amazon marketplace' ), 'body' => '{}' ) : $products; } $country = $locale_config['country']; $lang_country = $locale_config['language']; $_SAVE = array(); if ( ! $is_test && ! empty( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_noaz' ) ) && ! empty( $gtin ) ) { return $products; } if ( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_timer_amz' ) && self::$count_afx > 1 ) { usleep( 1100000 ); } $cauto = ! empty( $keyword ) ? get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_c_auto' ) : null; if ( ! $is_test && ! empty( $ids['asin'] ) && ! isset( $gtin ) ) { $temp_amz = self::get_temp_amz_afx( $keyword, $ids, wp_json_encode( $param ), $cauto, $country ); if ( ! empty( $temp_amz ) ) { return self::products_amazon_temp( $temp_amz, $products ); } } $tag = trim( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_tag' ) ); $key = trim( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_creators_key' ) ); $secret = trim( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_creators_secret' ) ); $tag_guest = trim( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_tag_guest' ) ); $api_version = 'v3'; try { $resources = self::get_amazon_creators_resources(); $resolved_api_version = $api_version; $access_token = self::get_amazon_creators_token( $key, $secret, $api_version, $locale_config['region'], $resolved_api_version ); if ( empty( $access_token ) ) { if ( $is_test ) { return array( 'response' => array( 'code' => 401, 'message' => 'No access token' ), 'body' => wp_json_encode( array( 'message' => 'Creators API access token could not be obtained.' ) ), ); } return $products; } $headers = self::get_amazon_creators_headers( $access_token, $locale_config['marketplace'], $resolved_api_version ); $path = '/catalog/v1/searchItems'; $key_r = 'searchResult'; $config = array( 'partnerTag' => $tag, 'marketplace' => $locale_config['marketplace'], 'resources' => $resources ); if ( ! empty( $lang_country ) ) { $config['languagesOfPreference'] = array( $lang_country ); } $_asin = array(); $_ean = array(); if ( ! empty( $gtin ) ) { $_ean = array_map( function( $value ) { return str_replace( 'E_', '', $value ); }, (array) $gtin ); $config['keywords'] = implode( ' ', $_ean ); $config['itemCount'] = min( max( count( $_ean ), 1 ), 10 ); } elseif ( ! empty( $ids[ AFFIAI_PLUGIN_PROD_ID ] ) ) { $_ean = explode( ',', $ids[ AFFIAI_PLUGIN_PROD_ID ] ); foreach ( $_ean as $k => $v ) { $v = trim( $v ); if ( 0 === strpos( $v, 'AZ' ) && strlen( $v ) > 10 ) { $_asin[] = str_replace( 'AZ', '', $v ); unset( $_ean[ $k ] ); } elseif ( ! is_numeric( substr( $v, 0, 2 ) ) ) { unset( $_ean[ $k ] ); } else { $_ean[ $k ] = $v; } } if ( ! empty( $_asin ) ) { $_ids = array( 'asin' => implode( ',', $_asin ) ); $products = self::products_amazon_new( null, $_ids, $param, $products, null, null, true ); } if ( empty( $_ean ) ) { if ( $is_test ) { return array( 'response' => array( 'code' => 400, 'message' => 'No valid product identifiers' ), 'body' => wp_json_encode( array( 'message' => 'No valid ASIN/EAN identifiers were supplied.' ) ), ); } return $products; } $count = count( $_ean ); $config['keywords'] = implode( ' ', $_ean ); $config['itemCount'] = min( max( $count, 1 ), 10 ); } elseif ( ! empty( $ids['asin'] ) ) { $path = '/catalog/v1/getItems'; $key_r = 'itemsResult'; $config['itemIds'] = explode( ',', preg_replace( '/[\x00-\x1F\x80-\xFF\s]/', '', trim( $ids['asin'] ) ) ); } elseif ( ! empty( $keyword ) ) { $config['keywords'] = $keyword; if ( isset( $count ) ) { $config['itemCount'] = min( max( (int) $count, 1 ), 10 ); } } else { if ( $is_test ) { $config['keywords'] = 'test'; $config['itemCount'] = 1; } else { return $products; } } $response = self::request_amazon_creators_api( $path, $config, $headers ); if ( $is_test ) { return $response; } if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) { if ( function_exists( 'affiai_lite_provider_observation' ) ) { affiai_lite_provider_observation( is_wp_error( $response ) ? 'transport_error' : 'provider_http_' . (int) wp_remote_retrieve_response_code( $response ) ); } return $products; } $response_body = json_decode( wp_remote_retrieve_body( $response ) ); $items = self::get_amazon_creators_items( $response_body, $key_r ); if ( empty( $items ) ) { return $products; } foreach ( $items as $item ) { if ( ! empty( $config['itemIds'] ) && ( ! isset( $item->asin ) || ! in_array( strtoupper( (string) $item->asin ), array_map( 'strtoupper', $config['itemIds'] ), true ) ) ) { continue; } if ( ! isset( $item->detailPageURL ) || ! isset( $item->itemInfo->title->displayValue ) ) { continue; } $url = $item->detailPageURL; if ( ! empty( $tag_guest ) && ( $tag_guest != $tag ) ) { $url = preg_replace('/(?<=\?|&)tag=[^&]+/', 'tag=' . $tag_guest, $url); } $observed_gtin = null; $EANU = ''; $_EANU = ''; $TEANU = ''; if ( isset( $item->itemInfo->externalIds->eans->displayValues[0] ) || isset( $item->itemInfo->externalIds->upcs->displayValues[0] ) ) { if ( in_array( $country, array( 'com', 'ca' ) ) && isset( $item->itemInfo->externalIds->upcs->displayValues[0] ) ) { $EANU = $item->itemInfo->externalIds->upcs->displayValues[0]; } elseif ( isset( $item->itemInfo->externalIds->eans->displayValues[0] ) ) { $EANU = $item->itemInfo->externalIds->eans->displayValues[0]; } else { continue; } $observed_gtin = (string) $EANU; if ( strlen( $EANU ) < 13 ) { $EANU = str_pad( $EANU, 13, '0', STR_PAD_LEFT ); } $_EANU = $EANU; $TEANU = $EANU; if ( ! empty( $gtin ) && ! in_array( $EANU, $gtin ) ) { continue; } } elseif ( ! empty( $gtin ) ) { continue; } else { $EANU = 'AZ' . $item->asin; $TEANU = $item->asin; $_EANU = ''; } if ( ! isset( $EANU ) ) { continue; } if ( ! empty( $sa ) && isset( $item->asin ) ) { $EANU = 'AZ' . $item->asin; $TEANU = $item->asin; $_EANU = ''; } if ( ! empty( $_ean ) && is_array( $_ean ) && isset( $TEANU ) ) { if ( ! in_array( $TEANU, $_ean ) ) { if ( isset( $item->asin ) && in_array( $item->asin, $_ean ) ) { $EANU = 'AZ' . $item->asin; $TEANU = $item->asin; $_EANU = ''; } else { continue; } } } $amazon_offer = Affiai_Amazon_Offer::api( $item, false ); if ( null === $amazon_offer ) { $identity = Affiai_Amazon_Offer::identity( $item, false ); $requested_identity = ! empty( $ids['asin'] ) ? $ids['asin'] : ( $ids[ AFFIAI_PLUGIN_PROD_ID ] ?? null ); if ( $identity && empty( $keyword ) && is_string( $requested_identity ) && in_array( trim( $requested_identity ), array( $identity['sku'], 'AZ' . $identity['sku'] ), true ) && ! isset( $products[ 'E_' . $EANU ] ) ) { $products[ 'E_' . $EANU ] = $identity; } continue; } $price = $amazon_offer['price']; $currency = $amazon_offer['currency']; $discount = $amazon_offer['discount']; $discount_price = $amazon_offer['discount_price']; if ( ! isset( $products[ 'E_' . $EANU ] ) ) { $products[ 'E_' . $EANU ] = array( 'brand' => isset( $item->itemInfo->byLineInfo->brand->displayValue ) ? $item->itemInfo->byLineInfo->brand->displayValue : null, 'gtin13' => $EANU, 'gtin' => empty( $_EANU ) ? '' : 'amazon_' . $_EANU, 'sku' => isset( $item->asin ) ? $item->asin : null, 'pid' => isset( $item->asin ) ? 'AZ' . $item->asin : null, ); } $image_url = isset( $item->images->primary->large->url ) ? $item->images->primary->large->url : ( isset( $item->images->primary->medium->url ) ? $item->images->primary->medium->url : ( isset( $item->images->primary->small->url ) ? $item->images->primary->small->url : null ) ); $products[ 'E_' . $EANU ]['merchant']['Amazon'] = array( 'title' => trim( $item->itemInfo->title->displayValue ), 'description' => (array) ( isset( $item->itemInfo->features->displayValues ) ? $item->itemInfo->features->displayValues : null ), 'image' => $image_url, 'logo' => AFFIAI_PLUGIN_URL . 'img/logo/amazon.png', 'price' => $price, 'url' => $url, 'currency' => $currency, 'discount' => $discount, 'discount_price' => $discount_price, 'group' => 'amazon', 'source_fetched_at' => time(), ); $products[ 'E_' . $EANU ]['merchant']['Amazon']['offer_state'] = 'present'; $_SAVE[ $item->asin ] = $products[ 'E_' . $EANU ]['merchant']['Amazon']; $_SAVE[ $item->asin ]['country'] = $country; $_SAVE[ $item->asin ]['search'] = ! empty( $keyword ) ? $keyword : null; $_SAVE[ $item->asin ]['gtin'] = $EANU; $_SAVE[ $item->asin ]['params'] = ! empty( $keyword ) ? wp_json_encode( $param ) : null; } } catch ( Exception $e ) { if ( $is_test ) { return array( 'response' => array( 'code' => 500, 'message' => 'Amazon test exception' ), 'body' => wp_json_encode( array( 'message' => $e->getMessage() ) ), ); } } if ( ! empty( $_SAVE ) && ( ! empty( $keyword ) || ! empty( $ids['asin'] ) ) && ! isset( $gtin ) ) { self::add_temp_amz_afx( $_SAVE ); } return $products; } protected static function products_amazon_old( $keyword, $ids, $param, $products, $count = null, $gtin = null, $sa = false ) { $is_test = ! empty( $param['test_code'] ); $ids = is_array( $ids ) ? $ids : array(); $products = is_array( $products ) ? $products : array(); // Check if Amazon merchant is active if ( ! self::merchant_active_amazon() ) { return $products; } // Get Amazon country $country = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_country' ); $locale = self::get_amazon_creators_locale_config( $country ); if ( ! $locale ) { return $is_test ? array( 'response' => array( 'code' => 400, 'message' => 'Unsupported Amazon marketplace' ), 'body' => '{}' ) : $products; } $country = $locale['country']; $_SAVE = array(); // Get language and country $lang_country = explode( '_', $country ); if ( ! empty( $lang_country[1] ) ) { $country = $lang_country[0]; $lang_country = $lang_country[1]; } else { $lang_country = ''; } // Check if no Amazon search is allowed for noaz if ( ! $is_test && ! empty( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_noaz' ) ) && ! empty($gtin) ) { return $products; } // Temporisations for Amazon API if option is active if ( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_timer_amz' ) && self::$count_afx > 1 ) { usleep( 1100000 ); } //Search in bdd if exist and not expired (2 hours) if ( ! empty( $keyword ) ) { $cauto = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_c_auto' ); } else { $cauto = null; } if ( ! $is_test && ! empty( $ids['asin'] ) && !isset( $gtin) ) { $temp_amz = self::get_temp_amz_afx( $keyword, $ids, wp_json_encode($param), $cauto, $country ); if ( ! empty( $temp_amz ) ) { //add function cache_afx $products = self::products_amazon_temp( $temp_amz, $products ); return $products; } } // Get Amazon API credentials $tag = trim( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_tag' ) ); $key = trim( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_api_key' ) ); $secret = trim( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_api_secret' ) ); $tag_guest = trim( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_tag_guest' ) ); try { // Include AWS SDK require_once AFFIAI_PLUGIN_DIR . 'lib' . DIRECTORY_SEPARATOR . 'AwsV4.php'; // Set Amazon parameters $host = 'webservices.amazon.' . $country; $path = '/paapi5/searchitems'; $key_r = 'SearchResult'; $option_amz = 0; $header_amz = 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.SearchItems'; $config = array( 'PartnerType' => 'Associates', 'PartnerTag' => $tag, 'Resources' => array( 'ItemInfo.Title', 'ItemInfo.Features', 'ItemInfo.ByLineInfo', 'ItemInfo.ExternalIds', 'Images.Primary.Large', 'OffersV2.Listings.Price', 'OffersV2.Listings.Availability', ), ); // Set language preference if ( ! empty( $locale['language'] ) ) { $config['LanguagesOfPreference'] = array( $locale['language'] ); } // Set search parameters if ( ! empty( $gtin ) ) { $_ean = implode( '|', $gtin ); $_ean = str_replace( 'E_', '', $_ean ); $config['Keywords'] = $_ean; } elseif ( ! empty( $ids[ AFFIAI_PLUGIN_PROD_ID ] ) ) { $_ean = explode( ',', $ids[ AFFIAI_PLUGIN_PROD_ID ] ); foreach ( $_ean as $k => $v ) { if ( substr( $v, 0, 2 ) === 'AZ' && strlen( $v ) > 10 ) { $_asin[] = str_replace( 'AZ', '', $v ); unset( $_ean[ $k ] ); } elseif ( !is_numeric( substr( $v, 0, 2 ) ) ) { unset( $_ean[ $k ] ); } } // Search for ASINs contained in EANs if ( !empty( $_asin ) && is_array( $_asin ) ) { $_ids = array(); $_ids['asin'] = implode( ',', $_asin ); $products = self::products_amazon_old( null, $_ids, $param, $products, null, null, true ); } if ( empty( $_ean ) ) { return $products; } $count = count( $_ean ); $config['Keywords'] = implode( '|', $_ean ); } elseif ( ! empty( $ids['asin'] ) ) { $path = '/paapi5/getitems'; $header_amz = 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.GetItems'; $config['ItemIds'] = explode( ',', preg_replace( '/[\x00-\x1F\x80-\xFF\s]/', '', trim( $ids['asin'] ) ) ); $key_r = 'ItemsResult'; } // Encode the configuration array to JSON $payload = wp_json_encode( $config ); // Create a new instance of the AWSV4 class $awsv4 = new AFFIAI_Shopping_AwsV4( $key, $secret ); // Set the region name based on the country $awsv4->setRegionName( array( 'na' => 'us-east-1', 'eu' => 'eu-west-1', 'fe' => 'us-west-2' )[ $locale['region'] ] ); $awsv4->setServiceName( 'ProductAdvertisingAPI' ); // Set AWS request parameters $awsv4->setPath( $path ); $awsv4->setPayload( $payload ); $awsv4->setRequestMethod( 'POST' ); $awsv4->addHeader( 'content-encoding', 'amz-1.0' ); $awsv4->addHeader( 'content-type', 'application/json; charset=utf-8' ); $awsv4->addHeader( 'host', $host ); $awsv4->addHeader( 'x-amz-target', $header_amz ); // Send HTTP request to AWS $http = new WP_Http(); $response = $http->request( 'https://' . $host . $path, array( 'method' => 'POST', 'headers' => $awsv4->getHeaders(), 'body' => $payload, ) ); // If test code is set, return response if ( ! empty( $param['test_code'] ) ) { return $response; } // Handle errors and return products if ( is_wp_error( $response ) || $response['response']['code'] != 200 ) { return $products; } // Parse response and add products $response = json_decode( $response['body'] ); if ( $response === false || ! isset( $response->$key_r->Items[0] ) ) { return $products; } foreach ( $response->$key_r->Items as $item ) { if ( ! empty( $config['ItemIds'] ) && ( ! isset( $item->ASIN ) || ! in_array( strtoupper( (string) $item->ASIN ), array_map( 'strtoupper', $config['ItemIds'] ), true ) ) ) { continue; } // Check if required fields are set if ( ! isset( $item->DetailPageURL ) || ! isset( $item->ItemInfo->Title->DisplayValue ) ) { continue; } // Generate URL with guest tag if set $url = $item->DetailPageURL; if ( ! empty( $tag_guest ) && ( $tag_guest != $tag ) ) { $url = preg_replace('/(?<=\?|&)tag=[^&]+/', 'tag=' . $tag_guest, $url); //TO CHECK } // Generate EANU code $observed_gtin = null; $EANU = ''; $_EANU = ''; $TEANU = ''; if ( isset( $item->ItemInfo->ExternalIds->EANs->DisplayValues[0] ) || isset( $item->ItemInfo->ExternalIds->UPCs->DisplayValues[0] ) ) { if ( in_array( $country, array( 'com', 'ca' ) ) && isset( $item->ItemInfo->ExternalIds->UPCs->DisplayValues[0] ) ) { $EANU = $item->ItemInfo->ExternalIds->UPCs->DisplayValues[0]; } elseif ( isset( $item->ItemInfo->ExternalIds->EANs->DisplayValues[0] ) ) { $EANU = $item->ItemInfo->ExternalIds->EANs->DisplayValues[0]; } else { continue; } $observed_gtin = (string) $EANU; if ( strlen( $EANU ) < 13 ) { $EANU = str_pad( $EANU, 13, '0', STR_PAD_LEFT ); } $_EANU = $EANU; $TEANU = $EANU; if ( ! empty( $gtin ) && ! in_array( $EANU, $gtin ) ) { continue; } } elseif ( ! empty( $gtin ) ) { continue; } else { $EANU = 'AZ' . $item->ASIN; $TEANU = $item->ASIN; $_EANU = ''; } // Handle SA and _ean parameters if ( ! isset( $EANU ) ) { continue; } if ( ! empty( $sa ) && isset( $item->ASIN ) ) { $EANU = 'AZ' . $item->ASIN; $TEANU = $item->ASIN; $_EANU = ''; } if ( ! empty( $_ean ) && is_array( $_ean ) && isset( $TEANU ) ) { if ( ! in_array( $TEANU , $_ean ) ) { if ( isset( $item->ASIN ) && in_array( $item->ASIN , $_ean ) ) { $EANU = 'AZ' . $item->ASIN; $TEANU = $item->ASIN; $_EANU = ''; } else { continue; } } } // Get primary listing (OffersV2) $amazon_offer = Affiai_Amazon_Offer::api( $item, true ); if ( null === $amazon_offer ) { $identity = Affiai_Amazon_Offer::identity( $item, true ); $requested_identity = ! empty( $ids['asin'] ) ? $ids['asin'] : ( $ids[ AFFIAI_PLUGIN_PROD_ID ] ?? null ); if ( $identity && empty( $keyword ) && is_string( $requested_identity ) && in_array( trim( $requested_identity ), array( $identity['sku'], 'AZ' . $identity['sku'] ), true ) && ! isset( $products[ 'E_' . $EANU ] ) ) { $products[ 'E_' . $EANU ] = $identity; } continue; } $price = $amazon_offer['price']; $currency = $amazon_offer['currency']; $discount = $amazon_offer['discount']; $discount_price = $amazon_offer['discount_price']; if ( ! isset( $products[ 'E_' . $EANU ] ) ) { $products[ 'E_' . $EANU ] = array( 'brand' => isset( $item->ItemInfo->ByLineInfo->Brand->DisplayValue ) ? $item->ItemInfo->ByLineInfo->Brand->DisplayValue : null, 'gtin13' => $EANU, 'gtin' => empty( $_EANU ) ? '' : 'amazon_' . $_EANU, 'sku' => isset( $item->ASIN ) ? $item->ASIN : null, 'pid' => isset( $item->ASIN ) ? 'AZ' . $item->ASIN : null, ); } $products[ 'E_' . $EANU ]['merchant']['Amazon'] = array( 'title' => trim( $item->ItemInfo->Title->DisplayValue ), 'description' => (array) ( isset( $item->ItemInfo->Features->DisplayValues ) ? $item->ItemInfo->Features->DisplayValues : null ), 'image' => isset( $item->Images->Primary->Large->URL ) ? $item->Images->Primary->Large->URL : null, //@change 31/10/23 - if !isset => null 'logo' => AFFIAI_PLUGIN_URL . 'img/logo/amazon.png', 'price' => $price, 'url' => $url, 'currency' => $currency, 'discount' => $discount, 'discount_price' => $discount_price, 'group' => 'amazon', 'source_fetched_at' => time(), ); $products[ 'E_' . $EANU ]['merchant']['Amazon']['offer_state'] = 'present'; $_SAVE[$item->ASIN] = $products[ 'E_' . $EANU ]['merchant']['Amazon']; $_SAVE[$item->ASIN]['sim'] = !empty( $products[ 'E_' . $EANU ]['sim'] ) ? $products[ 'E_' . $EANU ]['sim'][0] : null; $_SAVE[$item->ASIN]['country'] = $country; $_SAVE[$item->ASIN]['category'] = !empty($_cauto) ? $_cauto : null; $_SAVE[$item->ASIN]['gtin'] = $EANU; $_SAVE[$item->ASIN]['params'] = null; } } catch ( Exception $e ) { // oops... } //Save on bdd if ( !empty($_SAVE) && ! empty( $ids['asin'] ) && !isset( $gtin) ) { self::add_temp_amz_afx( $_SAVE ); } return $products; } /** * This method is used to process and update the products array with Amazon product data. * * @param array $save The array of products to be saved. * @param array $products The existing products array. * * @return array The updated products array. */ protected static function products_amazon_temp( $save, $products ) { foreach ( $save as $item ) { if ( !empty($item->gtin) ) { $EANU = $item->gtin; if (strpos($EANU, 'AZ') === 0) { $_EANU = null; } else { $_EANU = $EANU; } } elseif ( !empty($item->asin) ) { $EANU = 'AZ' . $item->asin; $_EANU = null; } else { return $products; } if ( ! isset( $products[ 'E_' . $EANU ] ) ) { $products[ 'E_' . $EANU ] = array( 'brand' => null, 'gtin13' => $EANU, 'gtin' => empty( $_EANU ) ? '' : 'amazon_' . $_EANU, 'sku' => isset( $item->asin ) ? $item->asin : null, 'pid' => isset( $item->asin ) ? 'AZ' . $item->asin : null, ); if ( ! empty( $item->sim ) ) { $products[ 'E_' . $EANU ]['sim'] = (float) $item->sim; }; } $products[ 'E_' . $EANU ]['merchant']['Amazon'] = array( 'title' => trim( $item->title ), 'description' => (array) ( isset( $item->description ) ? json_decode($item->description, true) : null ), 'image' => $item->image_url, 'logo' => AFFIAI_PLUGIN_URL . 'img/logo/amazon.png', 'price' => $item->price, 'url' => $item->url, 'currency' => $item->currency, 'discount' => $item->discount, 'discount_price' => $item->old_price, 'group' => 'amazon', 'offer_state' => $item->offer_state ?? null, 'source_fetched_at' => ( $item->source_context ?? null ) === self::integrity_context() && is_numeric( $item->source_fetched_at ?? null ) ? (int) $item->source_fetched_at : null, ); } return $products; } /** * This function cleans a JSON string by removing specific characters, unnecessary spaces, control characters, and the UTF-8 BOM if present. It also adds quotes around JSON keys without quotes. Finally, it decodes the cleaned JSON string and returns the result. * * @param string $string The JSON string to clean and decode. * @return mixed Returns the cleaned and decoded JSON string. */ public static function affiai_clean_json_decode($string) { // Clean specific strings $search = ['\/', 'search_callback(', 'display_callback(', 'jsonp_callback(', '\"']; $replace = ['/', '', '', '', 'ยดยด']; $string = str_replace( $search, $replace, $string ); // Remove unnecessary end characters $string = rtrim( $string, ') ' ); // Add quotes around JSON keys without quotes $string = preg_replace( '/(\w+) ?:(?=(?:[^"]*"[^"]*")*[^"]*\Z)/i', '"$1" :', $string ); // Clean control characters $controlChars = array_map( 'chr', range( 0, 31 ) ); $controlChars[] = chr( 127 ); $string = str_replace( $controlChars, '', $string ); // Remove UTF-8 BOM if present if ( strpos( bin2hex( $string ), 'efbbbf' ) === 0 ) { $string = substr( $string, 3 ); } $string = str_replace('$result.getProperty("NumRecords")', '', $string); // Remove unnecessary spaces and decode the cleaned JSON string $string = trim( $string ); // print_r($string);exit; $string = json_decode( $string ); return $string; } /** * Maps the product cache and adds HTTP for the image. * * @param array $product The product to map. * @return array The mapped product with HTTP for the image. */ protected static function map_products_cache( $product ) { $product['logo'] = set_url_scheme( $product['logo'] ); return $product; } /** * Returns the currency symbol for a given product. * * @param array $product An array containing the product information. * @param bool $symbol Whether to return the currency symbol or the currency code. * @return string The currency symbol or code. */ public static function currency( array $product = array(), $symbol = false ) { return Affiai_Offer_Integrity::currency( $product['currency'] ?? null ) ?? ''; } /** * Format a price string to a float value with the correct decimal separator and currency. * * @param string $price The price string to format. * @return float The formatted price as a float value. */ public static function formatPrice( $price, $currency = null ) { $money = Affiai_Offer_Integrity::money( $price, $currency ); return $money['amount'] ?? null; } }