:not(.mtn_content) > span::after { content: "' . esc_html( $mtn_title ) . '"; text-decoration: underline dotted; } .mtn_content::before { content: "' . esc_html( $mtn_content ) . '"; }'; } } /** * Create or update the necessary database tables for the plugin. * * @global wpdb $wpdb WordPress database abstraction object. * @return bool True on success, false on failure. */ public static function affiai_bdd() { global $wpdb; // Table names $table_name = $wpdb->prefix . 'afx_cache'; $table_name2 = $wpdb->prefix . 'afx_amz_temp'; // Character set and collation $charset_collate = $wpdb->get_charset_collate(); // Include upgrade.php for dbDelta() require_once ABSPATH . 'wp-admin/includes/upgrade.php'; // SQL queries for creating tables $sqls[2] = "CREATE TABLE $table_name ( id int(11) UNSIGNED NOT NULL AUTO_INCREMENT, name varchar(32) NOT NULL, value mediumtext NOT NULL, post_id int(11) UNSIGNED NOT NULL, auto tinyint(1) DEFAULT 0, old tinyint(1), off tinyint(1), afx tinyint(1), date varchar(30), PRIMARY KEY (id), UNIQUE KEY name (name), KEY post_id (post_id) ) $charset_collate;"; $sqls[3] = "CREATE TABLE $table_name2 ( id int(11) UNSIGNED NOT NULL AUTO_INCREMENT, asin varchar(13) NOT NULL, country varchar(8) NOT NULL, title varchar(191), url varchar(191), description varchar(191), image_url varchar(191), price varchar(30), old_price varchar(30), discount varchar(30), currency varchar(5), rating varchar(5), nb_reviews varchar(10), search varchar(191), category varchar(191), gtin varchar(15), params text, offer_state varchar(16) DEFAULT NULL, source_fetched_at bigint(20) unsigned DEFAULT NULL, source_context char(64) DEFAULT NULL, sim varchar(15), date varchar(30), PRIMARY KEY (id), UNIQUE KEY asin (asin, country) ) $charset_collate;"; // Execute SQL queries using dbDelta() foreach ( $sqls as $sql ) { dbDelta( $sql ); } // Check if there were any errors $success = empty( $wpdb->last_error ); foreach ( array( 'offer_state', 'source_fetched_at', 'source_context' ) as $field ) { $success = $success && (bool) $wpdb->get_row( $wpdb->prepare( "SHOW COLUMNS FROM $table_name2 LIKE %s", $field ) ); } return $success; } /** * Encrypts a URL using AES-128-ECB encryption and returns the encrypted URL with a prefix. * * @param string $url The URL to encrypt. * @return string The encrypted URL with a prefix. */ public static function affiai_crypt_url( $url ) { $filename = AFFIAI_PLUGIN_DIR . 'admin' . DIRECTORY_SEPARATOR . 'affiai_st.json'; // If the file does not exist, return the original URL. if ( ! file_exists( $filename ) ) { return $url; } // Get the encryption key from the file. $st = file_get_contents( $filename ); $st = json_decode( $st, true ); // Encrypt the URL using the encryption key. $urlc = openssl_encrypt( $url, 'AES-128-ECB', $st['st'] ); // Replace the characters +, / and = with -, _ and , respectively. $urlc = strtr( $urlc, '+/=', '-_,' ); // Return the encrypted URL with a prefix. return AFFIAI_PLUGIN_URL . 'image/prod/' . $urlc; } /** * Update the plugin database if necessary. * * This function updates the plugin database if the version of the plugin has changed or if the version is not set yet. * It also updates the license system and the count of updates. * If the version is less than or equal to 2.5.0, it clears the cache. * * @return void */ public static function affiai_upd_bdd() { $a_version = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_version' ); $plugin_data = get_plugin_data( AFFIAI_PLUGIN_FIL, false ); $plugin_version = $plugin_data['Version']; $cache_schema_key = AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_cache_v2'; if ( $a_version === $plugin_version && ! get_option( $cache_schema_key ) ) { if ( self::affiai_bdd() ) { update_option( $cache_schema_key, 1 ); } return; } if ( empty( $a_version ) || ( $a_version != $plugin_version ) ) { self::delete_transients( AFFIAI_PLUGIN_NAME . '_march' ); if ( ! self::affiai_bdd() ) { return; } update_option( $cache_schema_key, 1 ); self::delete_transients( AFFIAI_PLUGIN_NAME . '_' ); self::delete_transients( 'aauto_' . AFFIAI_PLUGIN_NAME . '_' ); update_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_version', $plugin_version ); } } /** * Deletes cache with ID 0. * * @return void */ public static function affiai_upd_wgt() { self::delete_cache( '0' ); } /** * Register settings for the plugin. * * @return void */ public static function register_setting() { // Array of supported merchants self::$merchants = array( 'amazon' => 'Amazon', ); // Array of supported templates self::$templates = array( 'grid' => __( 'Grid (multi-column)', 'affiliate-ai-lite' ), ); // Array of supported cache time self::$time_cache = array( __( 'Every day', 'affiliate-ai-lite' ) => 86400, __( 'Every 2 days', 'affiliate-ai-lite' ) => 172800, __( 'Every 3 days', 'affiliate-ai-lite' ) => 259200, __( 'Every week', 'affiliate-ai-lite' ) => 604800, __( 'Every month', 'affiliate-ai-lite' ) => 2592000, __( 'Every 3 months', 'affiliate-ai-lite' ) => 7776000, ); // Array of user rights self::$user_right = array( __( 'Administrator', 'affiliate-ai-lite' ) => 'manage_options', __( 'Editor', 'affiliate-ai-lite' ) => 'edit_posts', __( 'Subscriber', 'affiliate-ai-lite' ) => 'read', ); // Array of all registered options $settings = array( 'template_sst' => array( 'type' => 'string', 'default' => 'small', ), 'cta_type' => array( 'type' => 'string', 'default' => 'all', ), 'rating_type' => array( 'type' => 'string', 'default' => 'scircle', ), 'pros_title' => array( 'type' => 'string', 'default' => __( 'PROS', 'affiliate-ai-lite' ), ), 'cons_title' => array( 'type' => 'string', 'default' => __( 'CONS', 'affiliate-ai-lite' ), ), 'structured_data' => array( 'type' => 'boolean', 'default' => false, ), 'auto_descr' => array( 'type' => 'boolean', 'default' => false, ), 'hide_link' => array( 'type' => 'boolean', 'default' => false, ), 'show_clock' => array( 'type' => 'boolean', 'default' => false, ), 'user_right' => array( 'type' => 'string', 'default' => 'manage_options', ), 'nb_lines' => array( 'type' => 'integer', 'default' => 4, ), 'time_cache' => array( 'type' => 'integer', 'default' => 86400, ), 'hide_price' => array( 'type' => 'boolean', 'default' => false, ), 'geoip' => array( 'type' => 'boolean', 'default' => false, ), 'debug' => array( 'type' => 'boolean', 'default' => false, ), 'mentions' => array( 'type' => 'array', 'default' => array( '0' => false, '1' => '', '2' => '', ), ), 'wpautop' => array( 'type' => 'boolean', 'default' => false, ), 'amazon_tag' => array( 'type' => 'string', 'default' => '', ), 'amazon_creators_key' => array( 'type' => 'string', 'default' => '', ), 'amazon_creators_secret' => array( 'type' => 'string', 'default' => '', ), 'amazon_api_version' => array( 'type' => 'string', 'default' => 'v3', ), 'timer_amz' => array( 'type' => 'boolean', 'default' => false, ), 'amazon_api_key' => array( 'type' => 'string', 'default' => '', ), 'amazon_api_secret' => array( 'type' => 'string', 'default' => '', ), 'amazon_country' => array( 'type' => 'string', 'default' => 'com', ), 'amazon_tag_guest' => array( 'type' => 'string', 'default' => '', ), 'conv_sst' => array( 'type' => 'boolean', 'default' => false, ), 'sst_choice' => array( 'type' => 'array', 'default' => array( 'homepage' => 0, 'categories' => 0 ), ), ); foreach ( $settings as $key => $setting ) { register_setting( AFFIAI_PLUGIN_NAME . '-shopping', AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_' . $key, $setting ); } } /** * Retrieves data from the 'afx_cache' table in the WordPress database based on the cache ID (custom transients). * * @global wpdb $wpdb WordPress database abstraction object. * @param string $cacheid The cache ID to retrieve data for. * @return mixed|false The unserialized data from the cache table if found, false otherwise. */ private static function get_cache_afx( $cacheid ) { global $wpdb; if ( ! empty( $wpdb ) && $wpdb instanceof wpdb ) { $table_name = $wpdb->prefix . 'afx_cache'; $flag = $wpdb->suppress_errors; $wpdb->suppress_errors( true ); $sql = $wpdb->prepare( "SELECT value FROM $table_name WHERE name = %s LIMIT 1", $cacheid ); $transient = $wpdb->get_results( $sql ); $wpdb->suppress_errors( $flag ); if ( empty( $transient ) ) { return false; } return maybe_unserialize( $transient[0]->value ); } return false; } /** * Adds a cache to the database table 'afx_cache' or updates an existing one if the cache already exists. * * @param array $cache An associative array containing the cache data to be added or updated. * The array must contain the following keys: * - 'name': The name of the cache. * - 'value': The value of the cache. * - 'post_id': The ID of the post associated with the cache. * - 'auto': Whether the cache was generated automatically or not. * - 'old': If an older product is stored in memory (optional). * - 'off': If a product no longer exists (optional). * - 'afx': If quota is consumed (optional). * - 'date': The date the cache was created or updated (optional). * * @return bool True if the cache was added or updated successfully, false otherwise. */ private static function add_cache_afx( $cache ) { global $wpdb; if ( ! empty( $wpdb ) && $wpdb instanceof wpdb ) { $table_name = $wpdb->prefix . 'afx_cache'; $flag = $wpdb->suppress_errors; $wpdb->suppress_errors( true ); $sql = $wpdb->prepare( "INSERT INTO $table_name (name,value,post_id,old,off,afx,date) VALUES (%s,%s,%d,%d,%d,%d,%s) ON DUPLICATE KEY UPDATE value = VALUES(value), post_id = VALUES(post_id), auto = VALUES(auto), old = VALUES(old), off = VALUES(off), afx = VALUES(afx), date = VALUES(date)", $cache['name'], $cache['value'], $cache['post_id'], ! empty( $cache['old'] ) ? $cache['old'] : 0, ! empty( $cache['off'] ) ? $cache['off'] : 0, ! empty( $cache['afx'] ) ? $cache['afx'] : 0, ! empty( $cache['date'] ) ? $cache['date'] : round( current_time( 'timestamp' ) ) ); $wpdb->query( $sql ); $wpdb->suppress_errors( $flag ); return true; } return false; } // Insert temp amazon into affi table for saving private static function add_temp_amz_afx( $save ) { global $wpdb; if ( empty( $wpdb ) || ! ( $wpdb instanceof wpdb ) ) { return false; } $table_name = $wpdb->prefix . 'afx_amz_temp'; $wpdb->query('START TRANSACTION'); foreach ( $save as $k => $s ) { // Check or clean if necessary $date_value = ! empty( $s['date'] ) ? $s['date'] : round( current_time( 'timestamp' ) ); $sql = $wpdb->prepare( "INSERT INTO $table_name (asin, country, title, url, description, image_url, price, old_price, discount, currency, rating, nb_reviews, category, gtin, params, sim, date, offer_state, source_fetched_at, source_context) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d, %s) ON DUPLICATE KEY UPDATE title = VALUES(title), url = VALUES(url), description= VALUES(description), image_url = VALUES(image_url), price = VALUES(price), old_price = VALUES(old_price), discount = VALUES(discount), currency = VALUES(currency), rating = VALUES(rating), nb_reviews = VALUES(nb_reviews), category = VALUES(category), gtin = VALUES(gtin), params = VALUES(params), sim = VALUES(sim), date = VALUES(date), offer_state = VALUES(offer_state), source_fetched_at = VALUES(source_fetched_at), source_context = VALUES(source_context)", $k, $s['country'], $s['title'], $s['url'], !empty( $s['description'] ) && is_array($s['description']) ? wp_json_encode($s['description']) : ( !empty( $s['description'] ) ? $s['description'] : null ), $s['image'], $s['price'], $s['discount_price'], $s['discount'], $s['currency'], null, null, ( $s['category'] ?? null ), $s['gtin'], $s['params'], ( $s['sim'] ?? null ), $date_value, $s['offer_state'] ?? null, $s['source_fetched_at'] ?? 0, self::integrity_context() ); if ( false === $wpdb->query( $sql ) ) { $wpdb->query('ROLLBACK'); return false; } } $wpdb->query('COMMIT'); return true; } /** * Retrieves temporary Amazon Affiliate data based on specified parameters. * * @param string $keyword The keyword to search for. * @param array $ids The array of ASINs to filter the results by. * @param string $param The parameter to filter the results by. * @param string $cauto The category to filter the results by. * @param string $country The country to filter the results by. * @return mixed Returns the retrieved data if successful, false otherwise. */ private static function get_temp_amz_afx( $keyword, $ids, $param, $cauto, $country ) { global $wpdb; if ( empty( $wpdb ) || ! ( $wpdb instanceof wpdb ) ) { return false; } $table_name = $wpdb->prefix . 'afx_amz_temp'; $flag = $wpdb->suppress_errors; $wpdb->suppress_errors( true ); $sql = $wpdb->prepare( "SELECT * FROM $table_name WHERE country = %s AND source_context = %s AND offer_state = %s", $country, self::integrity_context(), 'present' ); if ( ! empty( $keyword ) ) { $sql .= $wpdb->prepare( " AND search LIKE %s", '%' . $wpdb->esc_like( $keyword ) . '%' ); } elseif ( ! empty( $ids['asin'] ) ) { $asins = array_values( array_unique( array_filter( array_map( static function( $asin ) { return strtoupper( trim( $asin ) ); }, explode( ',', $ids['asin'] ) ), 'strlen' ) ) ); if ( ! $asins ) { $wpdb->suppress_errors( $flag ); return false; } // Escape and format each value of asin $formatted_asins = array_map(function ($asin) use ($wpdb) { return $wpdb->prepare('%s', $asin); }, $asins); // Build the IN clause with the formatted values $in_clause = '(' . implode(',', $formatted_asins) . ')'; $sql .= " AND asin IN $in_clause"; } if ( ! empty( $keyword ) && ! empty( $param ) ) { $sql .= $wpdb->prepare( " AND params LIKE %s", '%' . $wpdb->esc_like( $param ) . '%' ); } if ( ! empty( $keyword ) && ! empty( $cauto ) ) { $sql .= $wpdb->prepare( " AND category LIKE %s", '%' . $wpdb->esc_like( $cauto ) . '%' ); } //where date is not > 2 hrs $sql .= " AND date > " . ( round( current_time( 'timestamp' ) ) - 7200 ); if ( empty( $ids['asin'] ) ) { //order by id $sql .= " ORDER BY id ASC"; } else { //order by asin $sql .= " ORDER BY FIELD(asin, " . implode(',', $formatted_asins) . ")"; } $transient = $wpdb->get_results( $sql ); $wpdb->suppress_errors( $flag ); if ( empty( $transient ) ) { return false;} // Explicit multi-item requests may reuse this cache only when every // requested ASIN is present. A partial hit must reach the normal API path. if ( isset( $asins ) ) { $cached_asins = array_map( static function( $row ) { return strtoupper( trim( (string) $row->asin ) ); }, $transient ); if ( array_diff( $asins, $cached_asins ) ) { return false; } } return $transient; } /** * Check if a string is similar to any string in an array. * * @param string $sNeedle The string to search for. * @param array $aHaystack The array of strings to search in. * @return bool True if the string is similar to any string in the array, false otherwise. */ public static function similar_in_array( $sNeedle, $aHaystack ) { foreach ( $aHaystack as $sKey ) { if ( stripos( strtolower( $sKey ), strtolower( $sNeedle ) ) !== false ) { return true; } } return false; } /** * Clean GTIN array by removing invalid values and padding valid ones to 13 digits. * * @param array $array Array of GTIN values. * @param string $merch Merchant name to exclude from the cleaning process. * @return array Array of cleaned and padded GTIN values. */ public static function clean_gtin( $array, $merch ) { $resp = array(); foreach ( $array as $k => $v ) { $v = explode( '_', $v ); if ( empty( $v[1] ) ) { continue; } if ( $v[0] != $merch && ! empty( $v[1] ) ) { if ( ! preg_match( '/^[0-9]+$/', $v[1] ) ) { continue; } if ( strlen( $v[1] ) < 12 && strlen( $v[1] ) > 13 ) { continue; } $gtin = str_pad( $v[1], 13, '0', STR_PAD_LEFT ); $resp[] = $gtin; } } return $resp; } /** * Test Amazon function. * This function is used to test the Amazon API and display the response. * * @return void */ public static function affiai_test_amzn() { if ( ! current_user_can( 'manage_options' ) || ! check_ajax_referer( 'afx-admin-ajax-nonce', 'nonce', false ) ) { wp_send_json_error( 'Forbidden', 403 ); } $response = self::products_amazon( 'test', array(), array( 'test_code' => 1, 'auto' => 0 ), array() ); $output = '
'; $output .= '

' . __( 'Api\'s response', 'affiliate-ai-lite' ) . '

'; $code = isset( $response['response']['code'] ) ? $response['response']['code'] : null; if ( ! empty( $code ) ) { $output .= '
'; echo wp_json_encode( wp_kses_post( $output ) ); die(); } /** * Delete transients from the options table that match a specific cache name. * * @param string $cache The cache name to match against. * @return bool True if transients were deleted, false otherwise. */ public static function delete_transients( $cache ) { global $wpdb; // Check if $wpdb is set and is an instance of wpdb. if ( ! empty( $wpdb ) && $wpdb instanceof wpdb ) { $flag = $wpdb->suppress_errors; $wpdb->suppress_errors( true ); // Delete transients and transient timeouts that match the cache name. $like = $wpdb->esc_like( $cache ); $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->options WHERE option_name LIKE %s OR option_name LIKE %s", '_transient_' . $like . '%', '_transient_timeout_' . $like . '%' ) ); $wpdb->suppress_errors( $flag ); return true; } return false; } /** * Deletes cache data from the wp_afx_cache table in the database. * * * @param int|string|null $cache The post ID or name of the cache to delete. If null, all cache data will be deleted. * @param array|null $not_delete An array of cache names to exclude from deletion. * @return bool True on success, false on failure. */ public static function delete_cache( $cache, $not_delete = null ) { global $wpdb; if ( ! empty( $wpdb ) && $wpdb instanceof wpdb ) { $table_name = $wpdb->prefix . 'afx_cache'; $flag = $wpdb->suppress_errors; $wpdb->suppress_errors( true ); if ( isset( $cache ) && $cache != '' ) { if ( ! empty( $not_delete ) && is_array( $not_delete ) ) { $names_format = array_fill( 0, count( $not_delete ), '%s' ); $format = implode( ', ', $names_format ); $sql = $wpdb->prepare( "DELETE FROM $table_name WHERE post_id = %d AND ( name NOT IN ($format) OR value LIKE %s )", array_merge( array( $cache ), $not_delete ), array( '{"type"%' ) ); $wpdb->query( $sql ); } else { $wpdb->query( $wpdb->prepare( "DELETE FROM $table_name WHERE name = %s OR post_id = %d", (string) $cache, (int) $cache, ) ); } } else { $wpdb->query( "TRUNCATE $table_name" ); } $wpdb->suppress_errors( $flag ); return true; } return false; } /** * Deletes expired cache entries automatically for cron. * * @return bool Returns true if the cache entries were successfully deleted, false otherwise. */ public static function affiai_cron_clear_cache() { global $wpdb; if ( ! empty( $wpdb ) && $wpdb instanceof wpdb ) { $table_name = $wpdb->prefix . 'afx_cache'; $table_name2 = $wpdb->prefix . 'afx_amz_temp'; $flag = $wpdb->suppress_errors; $wpdb->suppress_errors( true ); $date_expi = ( current_time( 'timestamp' ) - ( 3600 * 24 * 30 * 6 ) ); $date_expi2 = ( current_time( 'timestamp' ) - ( 3600 * 24 ) ); $wpdb->query( $wpdb->prepare( "DELETE FROM $table_name WHERE date < %d AND auto = 1", $date_expi ) ); $wpdb->query( $wpdb->prepare( "DELETE FROM $table_name2 WHERE date < %d", $date_expi2 ) ); $wpdb->suppress_errors( $flag ); return true; } return false; } /** * Track changes in shortcodes and blocks of a post and delete cache accordingly. * * @param int $post_ID The ID of the post being updated. * @param WP_Post $post_after The post object after the update. * @param WP_Post $post_before The post object before the update. * @return void */ public static function track_shortcode_changes( $post_ID, $post_after, $post_before ) { // Get the regex pattern for shortcodes $shortcode_pattern = get_shortcode_regex(); // Extract shortcodes from the old and new post contents preg_match_all( '/' . $shortcode_pattern . '/s', $post_after->post_content, $matches_after ); $shortcodes_after = $matches_after[0]; // Array of shortcodes in the new post // Parse blocks in the post content $blocks_after = parse_blocks( $post_after->post_content ); // Filter blocks to only include those with the affiai/box block name if ( ! empty( $blocks_after ) ) { $blocks_after = array_filter( $blocks_after, function ( $block ) { return isset( $block['blockName'] ) && $block['blockName'] === AFFIAI_PLUGIN_NAME . '/box'; } ); // Render the affiai shortcode for each affiai/box block $shortc = array(); foreach ( $blocks_after as $block ) { if ( array_key_exists( 'attrs', $block ) ) { $block['attrs']['searchType'] = ! empty( $block['attrs']['searchType'] ) ? $block['attrs']['searchType'] : 'pick'; $block['attrs']['selectedMerch'] = ! empty( $block['attrs']['selectedMerch'] ) ? $block['attrs']['selectedMerch'] : null; $shortc[] = render_gut_afx( $block['attrs'], true ); } } // Merge the shortcodes from the post content and the affiai/box blocks if ( ! empty( $shortcodes_after ) ) { $shortcodes_after = array_merge( $shortcodes_after, $shortc ); } elseif ( ! empty( $shortc ) ) { $shortcodes_after = $shortc; } } // If there are shortcodes in the post content, parse them and delete the corresponding cache if ( ! empty( $shortcodes_after ) && is_array( $shortcodes_after ) ) { $to_not_delete = array(); foreach ( $shortcodes_after as $shortcode ) { // Remove the enclosing square brackets from the shortcode $shortcode = substr( $shortcode, 1, -1 ); // Split the shortcode into its name and attributes $parts = explode( ' ', $shortcode, 2 ); // The name is the first part $name = $parts[0]; // The attributes are the second part, if it exists $attributes = isset( $parts[1] ) ? $parts[1] : ''; // Parse the attributes into an associative array $attributes = shortcode_parse_atts( $attributes ); if ( $name == 'affiai') { // If the shortcode is an affiai shortcode, get its attributes and add them to the to_not_delete array if ( ! empty( $attributes['single'] ) ) { $attributes['asin'] = $attributes['single']; } $atts = shortcode_atts( self::get_attribute(), $attributes ); 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 ]; if ( ! empty( $atts['template'] ) && $atts['template'] == 'vertical' ) { $atts['template'] = 'grid'; } $cache_name = md5( implode( '|', $atts ) ); $to_not_delete[] = $cache_name; } } } $to_not_delete = ! empty( $to_not_delete ) ? array_unique( $to_not_delete ) : null; // Delete the cache for the post if ( ! empty( $post_ID ) ) { self::delete_cache( $post_ID, $to_not_delete ); } } /** * Delete transient data and save post meta data. * This function is called when a post is saved or updated. * * @param int $post_id The ID of the post being saved. * @param WP_Post $post The post object. * @param bool $update Whether this is an existing post being updated or not. * @return void */ public static function del_trans_save_post( $post_id, $post, $update ) { // @todo 11/12/23: check if this function is ok // Update meta auto keyword if ( isset( $_POST[ AFFIAI_PLUGIN_NAME . '_metabox_nonce' ] ) && wp_verify_nonce( sanitize_text_field( wp_unslash ( $_POST[ AFFIAI_PLUGIN_NAME . '_metabox_nonce'] ) ), AFFIAI_PLUGIN_NAME . '_metabox' ) ) { if ( isset( $_POST[ AFFIAI_PLUGIN_NAME . '_keyword' ] ) ) { if ( $_POST[ AFFIAI_PLUGIN_NAME . '_keyword' ] === '' ) { delete_post_meta( $post_id, AFFIAI_PLUGIN_NAME . '_keyword' ); } else { update_post_meta( $post_id, AFFIAI_PLUGIN_NAME . '_keyword', trim( sanitize_text_field( $_POST[ AFFIAI_PLUGIN_NAME . '_keyword' ] ) ) ); } } if ( isset( $_POST[ AFFIAI_PLUGIN_NAME . '_keyword_auto' ] ) ) { delete_post_meta( $post_id, AFFIAI_PLUGIN_NAME . '_keyword_auto' ); } } // Check if post is being updated if ( ! $update ) { return; } // Check if post is a revision if ( wp_is_post_revision( $post_id ) ) { return; } // Check if autosave is being done if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } // Check if post type is post or page or custom post type $custom_post_types = get_post_types(array('_builtin' => false)); if ( $post->post_type != 'post' && $post->post_type != 'page' && !in_array( $post->post_type, $custom_post_types ) ) { return; }; } /** * Delete post related transients and cache when post status changes from publish to any other status. * * @param string $new_status The new post status. * @param string $old_status The old post status. * @param WP_Post $post The post object. * @return void */ public static function del_post( $new_status, $old_status, $post ) { if ( $old_status == 'publish' && $new_status != 'publish' ) { $id = $post->ID; $id = str_replace( '__trashed', '', $id ); if ( ! empty( $slug ) ) { self::delete_transients( AFFIAI_PLUGIN_NAME . '_' . $id ); self::delete_transients( 'aauto_' . AFFIAI_PLUGIN_NAME . '_' . $id ); self::delete_cache( $id ); } } } /** * Initializes the settings for the plugin in the WordPress admin panel. * * @return void */ public static function admin_init_settings() { /** * Add a settings section for the main settings in the plugin */ add_settings_section( AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-options', __( 'Main settings', 'affiliate-ai-lite' ), null, 'afx-options' ); update_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_merch_count', 1 ); // Add settings field for "Structured data" add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_structured_data', __( 'Structured data', 'affiliate-ai-lite' ), function() { echo ' ' . sprintf( /* translators: url */esc_html__( 'Add markup to your product pages, so Google can provide detailed product information in %1$srich Search results%2$s.', 'affiliate-ai-lite' ), '', '' ) . ''; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-options', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_structured_data' ) ); // Add settings field for "Auto descriptions" add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_auto_descr', __( 'Auto descriptions', 'affiliate-ai-lite' ), function() { echo ' ' . esc_html__( 'Enable automatic descriptions for products. This data (if available) comes from Amazon.', 'affiliate-ai-lite' ) . ''; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-options', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_auto_descr' ) ); // Add settings field for "Hide links" add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_hide_link', __( 'Hide links', 'affiliate-ai-lite' ), function() { echo ' ' . esc_html__( 'Enable this option if you want to hide your affiliate links.', 'affiliate-ai-lite' ) . ''; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-options', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_hide_link' ) ); // Add settings field for "Price update date" add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_show_clock', __( 'Price update date', 'affiliate-ai-lite' ), function() { echo ' ' . esc_html__( 'Enable this option to display the date and time of the last price update.', 'affiliate-ai-lite' ) . ''; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-options', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_show_clock' ) ); // Add settings field for "Hide prices" add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_hide_price', __( 'Hide prices', 'affiliate-ai-lite' ), function() { echo ' ' . esc_html__( 'Enable this option if you want to hide prices (except for in the price list template).', 'affiliate-ai-lite' ) . ''; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-options', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_hide_price' ) ); // Add settings field for "Call to action type" add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_cta_type', __( 'Call to action type', 'affiliate-ai-lite' ), function() { $option = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_cta_type' ); echo ''; echo '

' . esc_html__( 'For some countries (like the US), we recommend using "Button only."', 'affiliate-ai-lite' ) . '

'; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-options', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_cta_type' ) ); // Check if "Call to action type" is not "Button only" to determine whether to hide the option "Merchant name in button" (with JS) if ( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_cta_type' ) != 'btn' ) { $_hide_btn = ' affiai_mcht_btn_hide'; } else { $_hide_btn = ''; } // Add settings field for "Merchant name on button" add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_mcht_btn', __( 'Merchant name on button', 'affiliate-ai-lite' ), function() { echo ' ' . esc_html__( 'Enable this option if you want to show the merchant name on the CTA button. (ex. Buy on Amazon)', 'affiliate-ai-lite' ) . ''; echo ''; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-options', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_mcht_btn', 'class' => 'affiai_mcht_btn' . $_hide_btn, ) ); // Add settings field for "Rating type" add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_rating_type', __( 'Rating type', 'affiliate-ai-lite' ), function() { $option = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_rating_type' ); echo ''; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-options', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_rating_type' ) ); // Add settings field for "Pros & cons labels" add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_pros_cons_title', __( 'Pros & cons labels', 'affiliate-ai-lite' ), function() { echo ''; echo ''; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-options', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_pros_cons_title' ) ); /** * Adds a settings section for advanced settings */ add_settings_section( AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-advanced', __( 'Advanced settings', 'affiliate-ai-lite' ), null, 'afx-options' ); // Adds a settings field for caching time add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_time_cache', __( 'Caching time', 'affiliate-ai-lite' ), function() { $option = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_time_cache' ); reset( self::$time_cache ); echo ''; echo '

' . esc_html__( 'How often the product cache will be cleared and the prices updated.', 'affiliate-ai-lite' ) . '

'; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-advanced', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_time_cache' ) ); // Adds a settings field for the number of lines displayed for automatic description add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_nb_lines', __( 'Auto description number of lines', 'affiliate-ai-lite' ), function() { echo ''; echo '

' . esc_html__( 'Number of lines to display for the automatic descriptions.', 'affiliate-ai-lite' ) . '

'; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-advanced', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_nb_lines' ) ); // Adds a settings field for user rights add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_user_right', __( 'Set access role', 'affiliate-ai-lite' ), function() { $option = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_user_right' ); reset( self::$user_right ); echo ''; echo '

' . esc_html__( 'By default you must be an administrator to access the plugin settings. This options lets you change the minimum user role required to access the plugin settings.', 'affiliate-ai-lite' ) . '

'; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-advanced', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_user_right' ) ); // Adds a settings field for disabling the wpautop filter // This option should only be enabled after contacting support add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_wpautop', __( 'Disable the wpautop filter', 'affiliate-ai-lite' ), function() { echo ''; echo '

' . esc_html__( 'Please contact support before enabling this option.', 'affiliate-ai-lite' ) . '

'; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-advanced', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_wpautop' ) ); // Check if the option for displaying price comparison disclaimers is checked to hide or not the fields if ( empty( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_mentions' )[0] ) ) { $_ment_hide = ' afx-hidden'; } else { $_ment_hide = ''; } // Adds a settings field for activating the disclaimers about the price comparison add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_mentions', __( 'Show disclaimers under boxes', 'affiliate-ai-lite' ), function() { $_ment_check = ! empty( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_mentions' )[0] ) ? get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_mentions' )[0] : false; echo ''; echo '

' . esc_html__( 'Displays disclaimer information under boxes. It is the responsibility of the site editor to adapt and/or complete these and to comply with the legislation of their country and partners.', 'affiliate-ai-lite' ) . '

'; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-advanced', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_mentions' ) ); // Adds a settings field for custom disclaimers title add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_mentions_title', __( 'Custom disclaimers title', 'affiliate-ai-lite' ), function() { echo ''; echo '

' . esc_html__( 'If not filled in, the default value will be displayed.', 'affiliate-ai-lite' ) . '

'; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-advanced', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_mentions_title', 'class' => 'afx-ments' . $_ment_hide, ) ); // Adds a settings field for custom disclaimers content add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_mentions_content', __( 'Custom disclaimers content', 'affiliate-ai-lite' ), function() { echo ''; echo '

' . esc_html__( 'If not filled in, the default value will be displayed.', 'affiliate-ai-lite' ) . '

'; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-advanced', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_content', 'class' => 'afx-ments' . $_ment_hide, ) ); // Adds a settings field for debug mode add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_debug', __( 'Debug mode', 'affiliate-ai-lite' ), function() { echo ''; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-advanced', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_debug' ) ); // Adds a settings field for support code add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_supp_code', __( 'Support code', 'affiliate-ai-lite' ), function() { echo ''; echo '

' . esc_html__( 'Please contact support before enabling this option.', 'affiliate-ai-lite' ) . '

'; }, 'afx-options', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-advanced', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_supp_code', 'class' => 'afx-supp-code', ) ); // Add a settings section for Amazon merchant add_settings_section( AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-amazon', self::$merchants['amazon'], function() { // Add a link to a tutorial on how to get Amazon Tracking ID echo '' . esc_html__( 'Tutorial: How to get your Amazon Tracking ID ?', 'affiliate-ai-lite' ) . ''; }, 'afx-merchant' ); // Add a settings field for Amazon Marketplace add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_country', __( 'Marketplace', 'affiliate-ai-lite' ), function() { echo ''; }, 'afx-merchant', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-amazon', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_country' ) ); // Add a settings field for Amazon Tracking ID add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_tag', __( 'Tracking ID', 'affiliate-ai-lite' ), function() { echo ''; }, 'afx-merchant', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-amazon', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_tag' ) ); $class_noaz = ''; add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_creators_key', __( 'Creators API Credential ID', 'affiliate-ai-lite' ), function() { echo ''; echo '

' . __( 'Enter the Credential ID for the Amazon Creators API.', 'affiliate-ai-lite' ) . '

'; }, 'afx-merchant', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-amazon', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_creators_key', 'class' => $class_noaz, ) ); add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_creators_secret', __( 'Creators API Credential Secret', 'affiliate-ai-lite' ), function() { echo ''; echo '

' . __( 'Enter the Credential Secret for the Amazon Creators API.', 'affiliate-ai-lite' ) . '

'; }, 'afx-merchant', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-amazon', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_creators_secret', 'class' => $class_noaz, ) ); // Add a settings field for Amazon Creators API credential version add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_api_version', __( 'Credential version', 'affiliate-ai-lite' ), function() { $value = trim( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_api_version', 'v3' ) ); echo ''; echo '

' . __( 'Select the version shown when you generated your Amazon Creators API credentials. New credentials should use v3.x.', 'affiliate-ai-lite' ) . '

'; }, 'afx-merchant', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-amazon', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_api_version', 'class' => $class_noaz, ) ); // Add a settings field for Amazon API Key add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_api_key', __( 'API key (legacy)', 'affiliate-ai-lite' ), function() { echo ''; echo '

' . __( 'This is for the the PA API and will be removed shortly since it is being deprecated/retired. Please use/enter your Creators API credentials above instead.', 'affiliate-ai-lite' ) . '

'; }, 'afx-merchant', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-amazon', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_api_key', 'class' => $class_noaz, ) ); // Add a settings field for Amazon API Secret add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_api_secret', __( 'API secret (legacy)', 'affiliate-ai-lite' ), function() { echo ''; echo '

' . __( 'This is for the the PA API and will be removed shortly since it is being deprecated/retired. Please use/enter your Creators API credentials above instead.', 'affiliate-ai-lite' ) . '

'; }, 'afx-merchant', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-amazon', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_api_secret', 'class' => $class_noaz, ) ); // Add a settings field for Amazon Tracking ID "guest" add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_tag_guest', __( 'Tracking ID "guest"', 'affiliate-ai-lite' ), function() { echo ''; echo '

' . esc_html__( 'Optional. Lets you assign clicks to an Amazon account other than the one used by the API.', 'affiliate-ai-lite' ) . '

'; echo '

' . esc_html__( 'Important: Please save your changes before testing your API key. ↓', 'affiliate-ai-lite' ) . '

'; echo '

'; echo '
'; }, 'afx-merchant', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-amazon', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amazon_tag_guest', 'class' => $class_noaz, ) ); add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_timer_amz', __( 'Reduce frequency of API key queries', 'affiliate-ai-lite' ), function() { echo ' ' . esc_html__( ' If you\'re getting a "429 too many requests" error with your API key, you can activate this option to reduce the frequency of API queries.', 'affiliate-ai-lite' ) . ''; // echo '

' . esc_html__( 'You just need to provide your Tracking ID.
Work only with marketplaces: US, UK, FR, ES, DE, IT, JP, IN, CA', 'affiliate-ai-lite' ) . '

'; }, 'afx-merchant', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-amazon', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_timer_amz', 'class' => $class_noaz, ) ); // Adds a settings field for geotargeting add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_geoip', __( 'Geotargeting', 'affiliate-ai-lite' ), function() { $class_geoip = 'affiai_h_geoip'; if ( checked( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_geoip' ), true, false ) ) { $class_geoip = 'affiai_s_geoip'; } $amzn_tag = array( 'AU' => '', 'BR' => '', 'BE' => '', 'CA' => '', 'DE' => '', 'ES' => '', 'FR' => '', 'IN' => '', 'IT' => '', 'JP' => '', 'MX' => '', 'TR' => '', 'GB' => '', 'US' => '', 'AE' => '', 'EG' => '', 'NL' => '', 'PL' => '', 'SA' => '', 'SE' => '', 'SG' => '', 'TR' => '', ); $amzn_tag_g = array(); if ( ! empty( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amzn_tag' ) ) ) { $amzn_tag_g = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amzn_tag' ); foreach ( $amzn_tag as $k => $v ) { if ( ! empty( $amzn_tag_g[ $k ] ) ) { $amzn_tag[ $k ] = $amzn_tag_g[ $k ]; } } } echo ' ' . esc_html__( ' Enable the geotargeting function', 'affiliate-ai-lite' ) . ''; echo '

' . esc_html__( 'Requires the creation of a new Amazon partner account (and Tracking ID) for each country\'s marketplace you want to use. Redirects the visitor to the Amazon site of their country.', 'affiliate-ai-lite' ) . '

'; echo '

' . esc_html__( 'GDPR: In order to determine the country of the visitor, their IP will be sent to a third-party service. If you enable this feature, make sure you are in compliance.', 'affiliate-ai-lite' ) . '

'; echo '
'; }, 'afx-merchant', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-amazon', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_geoip' ) ); // Amazon SiteStripe Converter add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_conv_sst', __( 'SiteStripe Converter', 'affiliate-ai-lite' ), function() { echo ' ' . esc_html__( ' Automatically converts all SiteStripe images or boxes iframes', 'affiliate-ai-lite' ) . ''; echo '

' . esc_html__( 'Image conversion is automatic and requires no setting', 'affiliate-ai-lite' ) . '

'; }, 'afx-merchant', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-amazon', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_conv_sst' ) ); $class_nosst = 'affiai_h_sst'; if ( checked( get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_conv_sst' ), true, false ) ) { $class_nosst = 'affiai_s_sst'; } add_settings_field( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_sst_choice', __( 'SiteStripe Converter on Homepage & Categories', 'affiliate-ai-lite' ), function() { $choice = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_sst_choice' ); if ( empty( $choice ) ) { $choice = array( 'homepage' => 0, 'categories' => 0 ); } echo ' Homepage '; echo ' Categories/Tags/Others Archives'; echo '

' . esc_html__( 'By default, sitestripe converter is activated only on posts/pages. You can also activate it on the homepage and on categories/tags with this option.', 'affiliate-ai-lite' ) . '

'; }, 'afx-merchant', AFFIAI_PLUGIN_OPTION_PREFIX . '-shopping-amazon', array( 'label_for' => AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_sst_choice', 'class' => $class_nosst, ) ); /** * Adds a settings section for the plugin dashboard * The section includes a form with a nonce field, a table view, and a script that selects all checkboxes when the "select all" checkbox is clicked. */ add_settings_section( AFFIAI_PLUGIN_NAME . '-shopping-save', __( 'Dashboard', 'affiliate-ai-lite' ), function() { echo '
'; echo '

' . esc_html__( 'Warning: this button will reset all the boxes on the site and some products may disappear if they are no longer available from Amazon.', 'affiliate-ai-lite' ) . '

'; ?>
views(); $affiai_save_table->prepare_items(); $affiai_save_table->display(); ?>
3 ) { $myhost = explode( '.', $myhost, 2 )[1]; } } elseif ( $count > 2 ) { $myhost = self::get_domain( explode( '.', $myhost, 2 )[1] ); } return $myhost; } /** * Orders a multidimensional array by one or more of its fields. * * @param array $data The multidimensional array to be sorted. * @param mixed $args One or more fields to sort the array by. * @return array The sorted multidimensional array. */ protected static function affiai_array_orderby( $data, ...$args ) { foreach ( $args as $n => $field ) { if ( is_string( $field ) ) { $tmp = array(); foreach ( $data as $key => $row ) { $tmp[ $key ] = $row[ $field ]; } $args[ $n ] = $tmp; } } $args[] = &$data; call_user_func_array( 'array_multisort', $args ); return array_pop( $args ); } /** * Display the options page for the plugin. * * @return void */ public static function options_page() { include AFFIAI_PLUGIN_DIR . 'views' . DIRECTORY_SEPARATOR . 'options-page.php'; } /** * Adds a link to the plugin settings page in the WordPress admin dashboard's plugin actions links. * * @param array $actions An array of plugin action links. * @return array An array of plugin action links with the added link to the plugin settings page. */ public static function plugin_action_links( $actions ) { $actions[] = sprintf( '%s', esc_url( admin_url( 'options-general.php?page=' . AFFIAI_PLUGIN_NAME ) ), esc_html__( 'Settings', 'affiliate-ai-lite' ) ); return $actions; } /** * Enqueue scripts and styles for admin pages and widgets page. * * @return void */ public static function admin_enqueue_scripts() { global $pagenow; $current_screen = get_current_screen(); // Get the current screen object. // Enqueue color picker styles and scripts. wp_enqueue_style( 'wp-color-picker' ); wp_enqueue_script( 'wp-color-picker' ); // Enqueue scripts and styles for admin pages. if ( strpos( $current_screen->base, AFFIAI_PLUGIN_NAME ) !== false or strpos( $current_screen->base, AFFIAI_PLUGIN_NAME ) !== 'affiai' ) { $cm_settings['codeEditor'] = wp_enqueue_code_editor( array( 'type' => 'text/css' ) ); wp_localize_script( 'jquery', 'affiai_cm_settings', $cm_settings ); wp_enqueue_script( 'wp-theme-plugin-editor' ); wp_enqueue_style( 'wp-codemirror' ); wp_register_style( 'affiai_admin_css', AFFIAI_PLUGIN_URL . 'assets/css/admin.css', array(), AFFIAI_PLUGIN_VER ); wp_enqueue_style( 'affiai_admin_css' ); wp_enqueue_script( 'afxshop', AFFIAI_PLUGIN_URL . 'assets/js/admin.js', array( 'jquery-ui-tabs', 'wp-color-picker' ), AFFIAI_PLUGIN_VER, true ); wp_enqueue_script( 'nouislider', AFFIAI_PLUGIN_URL . 'lib/slider/nouislider.min.js', array( 'jquery' ), '15.7.0', true); wp_enqueue_style( 'nouislider-css', AFFIAI_PLUGIN_URL . 'lib/slider/nouislider.min.css', array(), '15.7.0'); $domain = self::get_domain( wp_parse_url( home_url(), PHP_URL_HOST ) ); wp_localize_script( 'afxshop', 'affiai_admin', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( 'afx-admin-ajax-nonce' ), 'site' => $domain, ) ); } elseif ( $pagenow === 'widgets.php' ) { // Enqueue scripts and styles for widgets page. wp_enqueue_script( 'affiai_widget', AFFIAI_PLUGIN_URL . 'assets/js/widget.js', array( 'jquery' ), AFFIAI_PLUGIN_VER, false ); } // Enqueue font icon picker styles and scripts. wp_register_style( 'affiai_fonticonpicker_css', AFFIAI_PLUGIN_URL . 'assets/css/jquery.fonticonpicker.min.css', array(), AFFIAI_PLUGIN_VER ); wp_register_style( 'affiai_fonticonpicker_theme_css', AFFIAI_PLUGIN_URL . 'assets/css/jquery.fonticonpicker.grey.min.css', array(), AFFIAI_PLUGIN_VER ); wp_register_style( 'affiai_icon_font', AFFIAI_PLUGIN_URL . 'assets/css/afx-icon.css', array(), AFFIAI_PLUGIN_VER ); wp_enqueue_style( 'affiai_fonticonpicker_css' ); wp_enqueue_style( 'affiai_fonticonpicker_theme_css' ); wp_enqueue_style( 'affiai_icon_font' ); // Enqueue select2 styles and scripts. wp_register_style( 'affiai_select_css', AFFIAI_PLUGIN_URL . 'assets/css/select2.min.css', array(), AFFIAI_PLUGIN_VER ); wp_enqueue_style( 'affiai_select_css' ); wp_enqueue_script( 'affiai_select', AFFIAI_PLUGIN_URL . 'assets/js/select2.min.js', array( 'jquery' ), AFFIAI_PLUGIN_VER, false ); // Enqueue font icon picker scripts. // Source: https://github.com/farbelous/fontIconPicker wp_enqueue_script( 'affiai_fonticonpicker', AFFIAI_PLUGIN_URL . 'assets/js/jquery.fonticonpicker.min.js', array( 'jquery' ), AFFIAI_PLUGIN_VER, false ); // Enqueue menu styles. wp_register_style( 'affiai_menu_css', AFFIAI_PLUGIN_URL . 'assets/css/menu.css', array(), AFFIAI_PLUGIN_VER ); wp_enqueue_style( 'affiai_menu_css' ); } /** * This function adds an upsell banner to the admin dashboard page * * @return void */ public static function show_upsell_banner() { $current_screen = get_current_screen(); // Check if on admin page if ( strpos( $current_screen->base, 'affiai' ) === false ) { return; } $license_url = 'https://affi.ai/#prices'; ?>

upgrade now to enable all available features!', 'affiliate-ai-lite' ), $license_url ); ?>

:not(.mtn_content) > span::after { content: "' . esc_attr( $mtn_title ) . '"; text-decoration: underline dotted; } .mtn_content::before { content: " ' . esc_attr( $mtn_content ) . '"; }' ); } $bradius = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_border_radius' ); if ( ! empty( $bradius ) ) { wp_add_inline_style( 'afxshop', '.afxshop .afxshop-item { border-radius:' . esc_attr( $bradius ) . 'px !important; }' ); } // Register and enqueue the necessary scripts. wp_register_style( 'afxslick', AFFIAI_PLUGIN_URL . 'assets/css/slick.css', false, AFFIAI_PLUGIN_VER ); wp_register_style( 'afxslick-theme', AFFIAI_PLUGIN_URL . 'assets/css/slick-theme.css', false, AFFIAI_PLUGIN_VER ); wp_register_script( 'afxslick', AFFIAI_PLUGIN_URL . 'assets/js/slick.min.js', array( 'jquery' ), AFFIAI_PLUGIN_VER, true ); wp_enqueue_script( 'afxshop', AFFIAI_PLUGIN_URL . 'assets/js/script.js', array( 'jquery', 'afxslick' ), AFFIAI_PLUGIN_VER, true ); // Localize the script with plugin options. wp_localize_script( 'afxshop', 'affiai_param', array( 'tagid' => get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_amzn_tag' ), 'geoip' => get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_geoip' ), ) ); } /** * Sitestrip image & iframe replacement. * @param string $content The content of the post or page. * @return string The modified content. * */ public static function rep_sst($content) { global $post; $choice = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_sst_choice' ); if ( empty( $choice ) ) { $choice = array( 'homepage' => 0, 'categories' => 0 ); } $published_post = ( empty ( $post->ID ) || get_post_status( $post->ID ) == 'publish' ) ? true : false; $page_product = false; if ( function_exists( 'is_product' ) ) { if ( is_product() ) { $page_product = true; } } if ( is_singular() || $page_product || ( ( ( is_home() && $choice['homepage'] ) || ( ( is_archive() || is_search() ) && $choice['categories'] ) ) && $published_post ) ) { // Replace amazon-adsystem images with shortcode $content = preg_replace_callback( '/]+src="[^"]*amazon-adsystem\.com\/[^"]*ASIN=([A-Z0-9]+)&[^"]*?Format=(_SL\d+_)[^"]*"[^>]*>/i', function($matches) { $asin = $matches[1]; $format = $matches[2]; $shortcode = '[' . AFFIAI_PLUGIN_NAME . ' asin="' . $asin . '" template="image" sst="1" f="' . $format . '" rlink="1"]'; // return $shortcode; return do_shortcode($shortcode); }, $content ); // Remove pixel images $pixelPattern = '/]+src="[^"]*amazon-adsystem.com\/e\/ir[^"]*"[^>]*(width="1"[^>]*height="1"|height="1"[^>]*width="1")[^>]*>/i'; $content = preg_replace($pixelPattern, '', $content); $template = get_option( AFFIAI_PLUGIN_OPTION_PREFIX . '_shopping_template_sst', 'small' ); // Find and replace Amazon iframes with widget format $content = preg_replace_callback( '/]+src="[^"]*amazon-adsystem.com\/widgets\/[^"]*placement=([A-Z0-9]{10})[^"]*"[^>]*>.*?<\/iframe>/is', function($matches) use ($template) { // $matches[1] contains the extracted ASIN $asin = $matches[1]; // Construct the shortcode with the ASIN $shortcode = '[' . AFFIAI_PLUGIN_NAME . ' asin="' . $asin . '" template="' . $template . '" sst="1"]'; // Return the shortcode for replacement return do_shortcode($shortcode); }, $content ); // Find and replace Amazon iframes with rcm-** format $content = preg_replace_callback( '/]+src="[^"]*rcm[^"]*amazon-adsystem.com\/e\/cm[^"]*asins=([A-Z0-9]{10})[^"]*"[^>]*>.*?<\/iframe>/is', function($matches) use ($template) { // $matches[1] contains the extracted ASIN $asin = $matches[1]; // Construct the shortcode with the ASIN $shortcode = '[' . AFFIAI_PLUGIN_NAME . ' asin="' . $asin . '" template="' . $template . '" sst="1"]'; // Return the shortcode for replacement return do_shortcode($shortcode); }, $content ); } return $content; } /** * Splits a string value by '|' delimiter and maps it to an array of keys. * * @param string|array $val The value to be split by '|' delimiter. * @param string $key The comma-separated string of keys to map the values to. * @return array The array of mapped values. */ protected static function affiai_multival( $val, $key ) { $key = explode( ',', $key ); if ( ! empty( $val ) && ! is_array( $val ) ) { $results = explode( '|', $val ); } else { $results = null; } $output = array(); foreach ( $key as $k => $v ) { $output[ sanitize_key( $v ) ] = isset( $results[ $k ] ) ? $results[ $k ] : null; } return $output; } /** * Sanitizes a URL by replacing 'u0026' with '&' and '&' with '&', and then escaping the URL. * * @param string $url The URL to be sanitized. * @return string The sanitized URL. */ public static function affiai_sanitize_url( $url ) { $url = str_replace( 'u0026', '&', $url ); $url = str_replace( '&', '&', $url ); $url = esc_url_raw( $url ); return $url; } /** * Checks if the current page is a Gutenberg page. * * @return bool True if the current page is a Gutenberg page, false otherwise. */ public static function is_affiai_gut_page() { if ( function_exists( 'is_gutenberg_page' ) && is_gutenberg_page() ) { // The Gutenberg plugin is on. return true; } if ( function_exists( 'get_current_screen' ) ) { $current_screen = get_current_screen(); if ( method_exists( $current_screen, 'is_block_editor' ) && $current_screen->is_block_editor() ) { // Gutenberg page on 5+. return true; } } return false; } /** * Calculate the corpus index for a given corpus. * * @param array $corpus The corpus to calculate the index for. * @param string $separator The separator to use when splitting the corpus into terms. * @return array An array containing the document count and the dictionary. */ public static function get_corpus_index( $corpus = array(), $separator = ' ' ) { $dictionary = array(); $doc_count = array(); foreach ( $corpus as $doc_id => $doc ) { // Replace special characters with spaces $doc = str_replace( array( ',', ';', '.', '-', '_', '(', ')', '/', '*', '+', ' ' ), ' ', $doc ); $doc = preg_replace('/\s+/', ' ',$doc); // Split the document into terms $terms = explode( $separator, $doc ); // Count the number of terms in the document $doc_count[$doc_id] = max(10, count($terms)); // Calculate the tf-idf for each term in the document foreach ( $terms as $k => $term) { if ( ! isset( $dictionary[ $term ] ) ) { $dictionary[ $term ] = array( 'document_frequency' => 0, 'postings' => array(), ); } if ( ! isset( $dictionary[ $term ]['postings'][ $doc_id ] ) ) { $dictionary[ $term ]['document_frequency']++; $dictionary[ $term ]['postings'][ $doc_id ] = array( 'term_frequency' => 0 ); } $dictionary[ $term ]['postings'][ $doc_id ]['term_frequency']++; if ( !isset( $dictionary[$term]['postings'][$doc_id]['position'] ) ) { $dictionary[$term]['postings'][$doc_id]['position'] = $k; } } } // Return the document count and the dictionary return array( 'doc_count' => $doc_count, 'dictionary' => $dictionary, ); } /** * Retrieve similar documents based on a query and a corpus. * * @param string $query The query to search for. * @param array $corpus The corpus to search in. * @param string $separator The separator used to split the query and the corpus. * @param int $coef The coefficient to use for the term frequency–inverse document frequency calculation. * @param int $price The price of the product. * @return array An array of similar documents sorted from high to low. */ public static function get_similar_documents($query='', $corpus=array(), $separator=' ', $coef=1, $price=null) { $similar_documents = array(); // Calculate the coefficient with product price if ( !empty($price) && is_numeric($price) ) { $fst = substr($price, 0, 1); $dec = preg_split('/(,|\.)/', $price); $coef2 = ( strlen($dec[0]) + ( $fst / 10 ) ); if ( ($coef2) > 3 ) { $coef2 = 3; } } else { $coef2 = 1; } if ( $query != '' && ! empty( $corpus ) ) { // Split the query into words $words = explode( $separator, $query ); // Get the corpus index $corpus = self::get_corpus_index( $corpus, $separator ); // Get the number of documents in the corpus $doc_count = count( $corpus['doc_count'] ); // Loop through each word in the query foreach ( $words as $word ) { // Check if the word is in the corpus if ( isset( $corpus['dictionary'][ $word ] ) ) { // Get the entry for the word in the corpus $entry = $corpus['dictionary'][ $word ]; // Loop through each document containing the word foreach ( $entry['postings'] as $doc_id => $posting ) { // Calculate the score for the document using term frequency–inverse document frequency $score = ( $posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2) ) / ( $posting['position'] + 1 ); // Add the score to the document's total score if ( isset( $similar_documents[ $doc_id ] ) ) { $similar_documents[ $doc_id ] += $score; } else { $similar_documents[ $doc_id ] = $score; } } } } // Normalize the scores by the length of the documents foreach ( $similar_documents as $doc_id => $score ) { $similar_documents[ $doc_id ] = ( $score/$corpus['doc_count'][$doc_id] ) * $coef * $coef2; } // Sort the documents by score from high to low arsort( $similar_documents ); } if (empty($similar_documents)) { $similar_documents = array(0 => 0.001); } return $similar_documents; } /** * This function checks if the current context has a widget hook by filtering the global variable $wp_current_filter. * * @global array $wp_current_filter The current filter hook names. * @return bool Whether the current context has a widget hook or not. */ public static function affiai_has_widget_hook() { // Use the global variable $wp_current_filter to detect the context. global $wp_current_filter; // Check if $wp_current_filter is not empty. if ( ! empty( $wp_current_filter ) ) { // Filter the hooks starting with 'widget'. $filtered_hooks = array_filter( $wp_current_filter, function( $hook ) { return strpos( $hook, 'widget' ) === 0; } ); // Return whether the filtered hooks array is not empty. return ! empty( $filtered_hooks ); } // Return true if $wp_current_filter is empty. return true; } /** * Check if the user is currently in a page builder editor mode. * * @return bool Returns true if the user is in a page builder editor mode, false otherwise. */ public static function affiai_is_builder_active() { // Check if the user is logged in and has the capability to edit pages. if ( ! is_user_logged_in() || ! current_user_can( 'edit_pages' ) ) { return false; } // Check if the user is in Divi Builder editor mode. if ( ! empty( $_REQUEST['et_pb_preview'] ) || ! empty( $_REQUEST['is_fb_preview'] ) ) { return true; } // Check if the Elementor plugin class exists. if ( class_exists( '\Elementor\Plugin' ) ) { $elementor_instance = \Elementor\Plugin::$instance; // Check if the user is in Elementor editor mode. if ( $elementor_instance->editor->is_edit_mode() ) { return true; } } return false; } }