<?php
defined('ABSPATH') or die();
use Aws\S3\S3Client;
function aiomatic_write_content($prompt, $model, $temperature, $max_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, $no_internet = false, $no_embeddings = false, $source = 'content', $role = 'user', $assistant_id = '', $thread_id = '', $store_data = 'off')
{
    $max_tokens = aimogenpro_get_max_tokens($model);
    $bulk_longform_cap = defined('AIMOGEN_BULK_CONTENT_MAX_TOKENS') ? AIMOGEN_BULK_CONTENT_MAX_TOKENS : 4096;
    if (function_exists('aimogen_bulk_is_longform_source') && aimogen_bulk_is_longform_source($source)) {
        if (intval($max_tokens) > $bulk_longform_cap) {
            $max_tokens = $bulk_longform_cap;
        }
    } elseif(intval($max_tokens) > AIMOGEN_DEFAULT_MAX_TOKENS && ( !stristr($model, 'gpt') || aiomatic_is_trained_model($model)))
    {
        $max_tokens = AIMOGEN_DEFAULT_MAX_TOKENS;
    }
    if (function_exists('aimogen_bulk_resolve_temperature')) {
        $temperature = aimogen_bulk_resolve_temperature($temperature);
        $frequency_penalty = aimogen_bulk_resolve_frequency_penalty($frequency_penalty);
    }
    $new_post_content = false;
    $query_token_count = count(aiomatic_encode($prompt));
	$available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $prompt, $query_token_count);
	if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
	{
		$string_len = aiomatic_strlen($prompt);
		$string_len = $string_len / 2;
		$string_len = intval(0 - $string_len);
		$prompt = aiomatic_substr($prompt, 0, $string_len);
		$prompt = trim($prompt);
		if(empty($prompt))
		{
			wp_send_json_error( array( 'message' => 'Incorrect prompt provided!' ) );
		}
		$query_token_count = count(aiomatic_encode($prompt));
		$available_tokens = $max_tokens - $query_token_count;
	}
	$aierror = '';
	$finish_reason = '';
    if(!empty($global_prepend))
    {
        $prompt = $global_prepend . ' ' . $prompt;
    }
    if (function_exists('aimogen_bulk_prepend_human_voice')) {
        $prompt = aimogen_bulk_prepend_human_voice($prompt, $source);
    }
    if(!empty($global_append))
    {
        $prompt = $prompt . ' ' . $global_append;
    }
    $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
    {
        $api_service = aiomatic_get_api_service($token, $model);
        aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for topic ' . $source . ' text: ' . $prompt);
    }
	$generated_text = aiomatic_generate_text($token, $model, $prompt, $available_tokens, $temperature, $max_p, $presence_penalty, $frequency_penalty, false, 'topicContentWriter' . $source, 0, $finish_reason, $aierror, $no_internet, $no_embeddings, false, '', '', $role, $assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
	if($generated_text === false)
	{
		aiomatic_log_to_file('Failed to generate content using AI writer: ' . $model . ' - error: ' . $aierror);
	}
	else
	{
		$new_post_content = aiomatic_sanitize_ai_result($generated_text);
        if(empty($new_post_content))
        {
            aiomatic_log_to_file('No content returned by the AI writer: ' . $model . ' - prompt: ' . $prompt);
            return false;
        }
        else
        {
            if($finish_reason == 'length')
            {
                $query_token_count = count(aiomatic_encode($new_post_content));
                $available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $new_post_content, $query_token_count);
                $generated_text = aiomatic_generate_text($token, $model, $new_post_content, $available_tokens, $temperature, $max_p, $presence_penalty, $frequency_penalty, false, 'topicContentWriter' . $source, 0, $finish_reason, $aierror, $no_internet, $no_embeddings, false, '', '', $role, $assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                if($generated_text !== false)
                {
                    if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                    {
                        $new_post_content .= ' ' . ucfirst(trim(nl2br(trim($generated_text))));
                    }
                    else
                    {
                        $new_post_content .= ' ' . ucfirst(trim($generated_text));
                    }
                }
            }
        }
	}
    return $new_post_content;
}
function aiomatic_replacetopics($prompt, $title, $language, $writing_style, $writing_tone, $topics, $sections, $current_section, $sections_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list = '', $img_attr = '')
{
    $prompt = (string) ($prompt ?? '');
    $title = (string) ($title ?? '');
    $language = (string) ($language ?? '');
    $writing_style = (string) ($writing_style ?? '');
    $writing_tone = (string) ($writing_tone ?? '');
    $topics = (string) ($topics ?? '');
    $sections = (string) ($sections ?? '');
    $current_section = (string) ($current_section ?? '');
    $sections_count = (string) ($sections_count ?? '');
    $paragraph_count = (string) ($paragraph_count ?? '');
    $post_title_keywords = (string) ($post_title_keywords ?? '');
    $default_cat_list = (string) ($default_cat_list ?? '');
    $img_attr = (string) ($img_attr ?? '');
    $blog_title = html_entity_decode(get_bloginfo('title'));
    if($topics === '')
    {
        $topics = $title;
    }
    $img_attr = str_replace('%%image_source_name%%', '', $img_attr);
    $img_attr = str_replace('%%image_source_url%%', '', $img_attr);
    $img_attr = str_replace('%%image_source_website%%', '', $img_attr);
    $prompt = str_replace('%%royalty_free_image_attribution%%', $img_attr, $prompt);
    $prompt = str_replace('%%topic%%', $topics, $prompt);
    $prompt = str_replace('%%title%%', $title, $prompt);
    $prompt = str_replace('%%post_title%%', $title, $prompt);
    $prompt = str_replace('%%post_title_keywords%%', $post_title_keywords, $prompt);
    $prompt = str_replace('%%post_original_title%%', $title, $prompt);
    $prompt = str_replace('%%blog_title%%', $blog_title, $prompt);
    $prompt = str_replace('%%language%%', $language, $prompt);
    $prompt = str_replace('%%writing_style%%', $writing_style, $prompt);
    $prompt = str_replace('%%writing_tone%%', $writing_tone, $prompt);
    $prompt = str_replace('%%sections%%', $sections, $prompt);
    $prompt = str_replace('%%current_section%%', $current_section, $prompt);
    $prompt = str_replace('%%sections_count%%', $sections_count, $prompt);
    $prompt = str_replace('%%paragraphs_per_section%%', $paragraph_count, $prompt);
    $prompt = str_replace('%%random_sentence%%', aiomatic_random_sentence_generator(), $prompt);
    $prompt = str_replace('%%random_sentence2%%', aiomatic_random_sentence_generator(false), $prompt);  
    $prompt = aiomatic_replaceSynergyShortcodes($prompt);
    $prompt = str_replace('%%default_post_cats%%', $default_cat_list, $prompt);
    $prompt = apply_filters('aiomatic_replace_aicontent_shortcode', $prompt);
    preg_match_all('#%%related_questions_([^%]*?)%%#i', $prompt, $mxatches);
    if(isset($mxatches[1][0]))
    {
        foreach($mxatches[1] as $googlematch)
        {
            $mtchres = aiomatic_scrape_related_questions($googlematch, 5, '', 1, 1, 0, 0, 2000, '', '');
            if(is_array($mtchres) && !empty($mtchres))
            {
                $quests = array();
                foreach($mtchres as $mra)
                {
                    if(isset($mra['q']))
                    {
                        $quests[] = $mra['q'];
                    }
                }
                $mtchres = implode(',', $quests);
            }
            $prompt = str_ireplace('%%related_questions_' . $googlematch . '%%', $mtchres, $prompt);
        }
    }
    if($custom_shortcodes != '')
    {
        $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
        if (!aiomatic_check_api_keys($aiomatic_Main_Settings)) 
        {
            aiomatic_log_to_file('You need to insert a valid AI service API Key for the custom shortcode creator to work!');
        }
        else
        {
            $allmodels = aiomatic_get_all_models();
            $appids = preg_split('/\r\n|\r|\n/', trim($aiomatic_Main_Settings['app_id']));
            $appids = array_filter($appids);
            if(empty($appids)){$token = '';}else{$token = $appids[array_rand($appids)];}
            $token = apply_filters('aimogen_openai_api_key', $token);$token = apply_filters('aiomatic_openai_api_key', $token);
            if($custom_shortcodes != '' && !is_array($custom_shortcodes))
            {
                $custom_shortcodes = aiomatic_replacetopics($custom_shortcodes, $title, $language, $writing_style, $writing_tone, $topics, $sections, $current_section, $sections_count, $paragraph_count, $post_title_keywords, '', $global_prepend, $global_append, $default_cat_list, $img_attr);
            }
            $custom_shortcodes = str_replace('%%royalty_free_image_attribution%%', $img_attr, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%topic%%', $topics, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%title%%', $title, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%post_title%%', $title, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%post_title_keywords%%', $post_title_keywords, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%post_original_title%%', $title, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%blog_title%%', $blog_title, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%language%%', $language, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%writing_style%%', $writing_style, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%writing_tone%%', $writing_tone, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%sections%%', $sections, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%current_section%%', $current_section, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%sections_count%%', $sections_count, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%paragraphs_per_section%%', $paragraph_count, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%random_sentence%%', aiomatic_random_sentence_generator(), $custom_shortcodes);
            $custom_shortcodes = str_replace('%%random_sentence2%%', aiomatic_random_sentence_generator(false), $custom_shortcodes);  
            $custom_shortcodes = aiomatic_replaceSynergyShortcodes($custom_shortcodes);
            $custom_shortcodes = str_replace('%%default_post_cats%%', $default_cat_list, $custom_shortcodes);

            $custom_shortcodes = preg_split('/\r\n|\r|\n/', $custom_shortcodes);
            foreach($custom_shortcodes as $my_short)
            {
                $name_part = explode('=>', $my_short);
                if(isset($name_part[1]) && !empty(trim($name_part[1])))
                {
                    $shortname = trim($name_part[0]);
                    if(strstr($prompt, '%%' . $shortname . '%%'))
                    {
                        $shortval = '';
                        $ai_part = explode('@@', $name_part[1]);
                        if(isset($ai_part[1]) && !empty(trim($ai_part[1])))
                        {
                            if(!in_array(trim($ai_part[0]), $allmodels))
                            {
                                $aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            }
                            else
                            {
                                $aimodel = trim($ai_part[0]);
                            }
                            $ai_command = trim($ai_part[1]);
                            
                            $ai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $ai_command);
                            foreach($custom_shortcodes as $my_check_short)
                            {
                                $check_name_part = explode('=>', $my_check_short);
                                if(isset($check_name_part[1]) && !empty(trim($check_name_part[1])))
                                {
                                    $check_shortname = trim($check_name_part[0]);
                                    if($shortname !== $check_shortname && strstr($ai_command, '%%' . $check_shortname . '%%') !== false)
                                    {
                                        $check_shortval = '';
                                        $check_ai_part = explode('@@', $check_name_part[1]);
                                        if(!in_array(trim($check_ai_part[0]), $allmodels))
                                        {
                                            $check_aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                        }
                                        else
                                        {
                                            $check_aimodel = trim($check_ai_part[0]);
                                        }
                                        $check_ai_command = trim($check_ai_part[1]);
                                        $aierror = '';

                                        $check_ai_command = str_replace('%%royalty_free_image_attribution%%', $img_attr, $check_ai_command);
                                        $check_ai_command = str_replace('%%topic%%', $topics, $check_ai_command);
                                        $check_ai_command = str_replace('%%title%%', $title, $check_ai_command);
                                        $check_ai_command = str_replace('%%post_title%%', $title, $check_ai_command);
                                        $check_ai_command = str_replace('%%post_title_keywords%%', $post_title_keywords, $check_ai_command);
                                        $check_ai_command = str_replace('%%post_original_title%%', $title, $check_ai_command);
                                        $check_ai_command = str_replace('%%blog_title%%', $blog_title, $check_ai_command);
                                        $check_ai_command = str_replace('%%language%%', $language, $check_ai_command);
                                        $check_ai_command = str_replace('%%writing_style%%', $writing_style, $check_ai_command);
                                        $check_ai_command = str_replace('%%writing_tone%%', $writing_tone, $check_ai_command);
                                        $check_ai_command = str_replace('%%sections%%', $sections, $check_ai_command);
                                        $check_ai_command = str_replace('%%current_section%%', $current_section, $check_ai_command);
                                        $check_ai_command = str_replace('%%sections_count%%', $sections_count, $check_ai_command);
                                        $check_ai_command = str_replace('%%paragraphs_per_section%%', $paragraph_count, $check_ai_command);
                                        $check_ai_command = str_replace('%%random_sentence%%', aiomatic_random_sentence_generator(), $check_ai_command);
                                        $check_ai_command = str_replace('%%random_sentence2%%', aiomatic_random_sentence_generator(false), $check_ai_command);  
                                        $check_ai_command = aiomatic_replaceSynergyShortcodes($check_ai_command);
                                        $check_ai_command = str_replace('%%default_post_cats%%', $default_cat_list, $check_ai_command);

                                        $check_ai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $check_ai_command);
                                        $check_generated_text = aiomatic_generate_custom_shortcode_content($token, $check_aimodel, $check_ai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                                        if($check_generated_text === false)
                                        {
                                            aiomatic_log_to_file('Custom nested shortcode generator error: ' . $aierror);
                                        }
                                        else
                                        {
                                            $check_shortval = trim(trim($check_generated_text), '.');
                                        }
                                        $ai_command = str_replace('%%' . $check_shortname . '%%', $check_shortval, $ai_command);
                                    }
                                }
                            }
                            $aierror = '';
                            $generated_text = aiomatic_generate_custom_shortcode_content($token, $aimodel, $ai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                            if($generated_text === false)
                            {
                                aiomatic_log_to_file('Custom shortcode generator error: ' . $aierror);
                            }
                            else
                            {
                                $shortval = trim(trim($generated_text), '.');
                            }
                        }
                        $prompt = str_replace('%%' . $shortname . '%%', $shortval, $prompt);
                    }
                }
            }
        }
    }
    return $prompt;
}
function aiomatic_generate_custom_shortcode_content($token, $aimodel, $ai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, &$aierror)
{
    $max_tokens = aimogenpro_get_max_tokens($aimodel);
    $query_token_count = count(aiomatic_encode($ai_command));
    $available_tokens = aiomatic_compute_available_tokens($aimodel, $max_tokens, $ai_command, $query_token_count);
    if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
    {
        $string_len = aiomatic_strlen($ai_command);
        $string_len = $string_len / 2;
        $string_len = intval(0 - $string_len);
        $ai_command = aiomatic_substr($ai_command, 0, $string_len);
        $ai_command = trim($ai_command);
        $query_token_count = count(aiomatic_encode($ai_command));
        $available_tokens = $max_tokens - $query_token_count;
    }
    $thread_id = '';
    $finish_reason = '';
    $temperature = 1;
    $top_p = 1;
    $presence_penalty = 0;
    $frequency_penalty = 0;
    if(!empty($global_prepend))
    {
        $ai_command = $global_prepend . ' ' . $ai_command;
    }
    if(!empty($global_append))
    {
        $ai_command = $ai_command . ' ' . $global_append;
    }
    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
    {
        $api_service = aiomatic_get_api_service($token, $aimodel);
        aiomatic_log_to_file('Calling ' . $api_service . ' (' . $aimodel . ')(' . $available_tokens . ') for custom shortcode content: ' . $ai_command);
    }
    $generated_text = aiomatic_generate_text($token, $aimodel, $ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'customShortcode', 0, $finish_reason, $aierror, true, false, false, '', '', 'user', '', $thread_id, '', 'disabled', '', true, false, array(), '', '', '');
    return $generated_text;
}
function aiomatic_replace_youtube($prompt, $video_title, $post_desc, $vid_url, $returned_caption, $language, $writing_style, $writing_tone, $sections, $current_section, $sections_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list = '')
{
    $blog_title = html_entity_decode(get_bloginfo('title'));
    $prompt = str_replace('%%video_title%%', $video_title, $prompt);
    $prompt = str_replace('%%video_descripton%%', $post_desc, $prompt);
    $prompt = str_replace('%%video_url%%', $vid_url, $prompt);
    $regex = '/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/';
    if (preg_match($regex, $vid_url, $matches)) 
    {
        $prompt = str_replace('%%video_id%%', $matches[1], $prompt);
    } 
    else 
    {
        $prompt = str_replace('%%video_id%%', '', $prompt);
    }
    $prompt = str_replace('%%video_captions%%', $returned_caption, $prompt);
    $prompt = str_replace('%%post_title_keywords%%', $post_title_keywords, $prompt);
    $prompt = str_replace('%%blog_title%%', $blog_title, $prompt);
    $prompt = str_replace('%%language%%', $language, $prompt);
    $prompt = str_replace('%%writing_style%%', $writing_style, $prompt);
    $prompt = str_replace('%%writing_tone%%', $writing_tone, $prompt);
    $prompt = str_replace('%%sections%%', $sections, $prompt);
    $prompt = str_replace('%%current_section%%', $current_section, $prompt);
    $prompt = str_replace('%%sections_count%%', $sections_count, $prompt);
    $prompt = str_replace('%%paragraphs_per_section%%', $paragraph_count, $prompt);
    $prompt = str_replace('%%random_sentence%%', aiomatic_random_sentence_generator(), $prompt);
    $prompt = str_replace('%%random_sentence2%%', aiomatic_random_sentence_generator(false), $prompt);  
    $prompt = aiomatic_replaceSynergyShortcodes($prompt);
    if($custom_shortcodes != '')
    {
        $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
        if (!aiomatic_check_api_keys($aiomatic_Main_Settings)) 
        {
            aiomatic_log_to_file('You need to insert a valid AI service API Key for the custom shortcode creator to work!');
        }
        else
        {
            $allmodels = aiomatic_get_all_models();
            $appids = preg_split('/\r\n|\r|\n/', trim($aiomatic_Main_Settings['app_id']));
            $appids = array_filter($appids);
            if(empty($appids)){$token = '';}else{$token = $appids[array_rand($appids)];}
            $token = apply_filters('aimogen_openai_api_key', $token);$token = apply_filters('aiomatic_openai_api_key', $token);
            if($custom_shortcodes != '' && !is_array($custom_shortcodes))
            {
                $custom_shortcodes = aiomatic_replace_youtube($custom_shortcodes, $video_title, $post_desc, $vid_url, $returned_caption, $language, $writing_style, $writing_tone, $sections, $current_section, $sections_count, $paragraph_count, $post_title_keywords, '', $global_prepend, $global_append, $default_cat_list);
            }
            $custom_shortcodes = str_replace('%%video_title%%', $video_title, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%video_descripton%%', $post_desc, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%video_url%%', $vid_url, $custom_shortcodes);
            $regex = '/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/';
            if (preg_match($regex, $vid_url, $matches)) 
            {
                $custom_shortcodes = str_replace('%%video_id%%', $matches[1], $custom_shortcodes);
            } 
            else 
            {
                $custom_shortcodes = str_replace('%%video_id%%', '', $custom_shortcodes);
            }
            $custom_shortcodes = str_replace('%%video_captions%%', $returned_caption, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%post_title_keywords%%', $post_title_keywords, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%blog_title%%', $blog_title, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%language%%', $language, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%writing_style%%', $writing_style, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%writing_tone%%', $writing_tone, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%sections%%', $sections, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%current_section%%', $current_section, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%sections_count%%', $sections_count, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%paragraphs_per_section%%', $paragraph_count, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%random_sentence%%', aiomatic_random_sentence_generator(), $custom_shortcodes);
            $custom_shortcodes = str_replace('%%random_sentence2%%', aiomatic_random_sentence_generator(false), $custom_shortcodes);  
            $custom_shortcodes = preg_split('/\r\n|\r|\n/', $custom_shortcodes);
            foreach($custom_shortcodes as $my_short)
            {
                $name_part = explode('=>', $my_short);
                if(isset($name_part[1]) && !empty(trim($name_part[1])))
                {
                    $shortname = trim($name_part[0]);
                    if(strstr($prompt, '%%' . $shortname . '%%'))
                    {
                        $shortval = '';
                        $ai_part = explode('@@', $name_part[1]);
                        if(isset($ai_part[1]) && !empty(trim($ai_part[1])))
                        {
                            if(!in_array(trim($ai_part[0]), $allmodels))
                            {
                                $aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            }
                            else
                            {
                                $aimodel = trim($ai_part[0]);
                            }
                            $ai_command = trim($ai_part[1]);
                            $ai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $ai_command);
                            foreach($custom_shortcodes as $my_check_short)
                            {
                                $check_name_part = explode('=>', $my_check_short);
                                if(isset($check_name_part[1]) && !empty(trim($check_name_part[1])))
                                {
                                    $check_shortname = trim($check_name_part[0]);
                                    if($shortname !== $check_shortname && strstr($ai_command, '%%' . $check_shortname . '%%') !== false)
                                    {
                                        $check_shortval = '';
                                        $check_ai_part = explode('@@', $check_name_part[1]);
                                        if(!in_array(trim($check_ai_part[0]), $allmodels))
                                        {
                                            $check_aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                        }
                                        else
                                        {
                                            $check_aimodel = trim($check_ai_part[0]);
                                        }
                                        $check_ai_command = trim($check_ai_part[1]);
                                        $aierror = '';

                                        $check_ai_command = str_replace('%%video_title%%', $video_title, $check_ai_command);
                                        $check_ai_command = str_replace('%%video_descripton%%', $post_desc, $check_ai_command);
                                        $check_ai_command = str_replace('%%video_url%%', $vid_url, $check_ai_command);
                                        $regex = '/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/';
                                        if (preg_match($regex, $vid_url, $matches)) 
                                        {
                                            $check_ai_command = str_replace('%%video_id%%', $matches[1], $check_ai_command);
                                        } 
                                        else 
                                        {
                                            $check_ai_command = str_replace('%%video_id%%', '', $check_ai_command);
                                        }
                                        $check_ai_command = str_replace('%%video_captions%%', $returned_caption, $check_ai_command);
                                        $check_ai_command = str_replace('%%post_title_keywords%%', $post_title_keywords, $check_ai_command);
                                        $check_ai_command = str_replace('%%blog_title%%', $blog_title, $check_ai_command);
                                        $check_ai_command = str_replace('%%language%%', $language, $check_ai_command);
                                        $check_ai_command = str_replace('%%writing_style%%', $writing_style, $check_ai_command);
                                        $check_ai_command = str_replace('%%writing_tone%%', $writing_tone, $check_ai_command);
                                        $check_ai_command = str_replace('%%sections%%', $sections, $check_ai_command);
                                        $check_ai_command = str_replace('%%current_section%%', $current_section, $check_ai_command);
                                        $check_ai_command = str_replace('%%sections_count%%', $sections_count, $check_ai_command);
                                        $check_ai_command = str_replace('%%paragraphs_per_section%%', $paragraph_count, $check_ai_command);
                                        $check_ai_command = str_replace('%%random_sentence%%', aiomatic_random_sentence_generator(), $check_ai_command);
                                        $check_ai_command = str_replace('%%random_sentence2%%', aiomatic_random_sentence_generator(false), $check_ai_command);  

                                        $check_ai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $check_ai_command);

                                        $check_generated_text = aiomatic_generate_custom_shortcode_content($token, $check_aimodel, $check_ai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                                        if($check_generated_text === false)
                                        {
                                            aiomatic_log_to_file('Custom nested shortcode generator error: ' . $aierror);
                                        }
                                        else
                                        {
                                            $check_shortval = trim(trim($check_generated_text), '.');
                                        }
                                        $ai_command = str_replace('%%' . $check_shortname . '%%', $check_shortval, $ai_command);
                                    }
                                }
                            }
                            $aierror = '';
                            $generated_text = aiomatic_generate_custom_shortcode_content($token, $aimodel, $ai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                            if($generated_text === false)
                            {
                                aiomatic_log_to_file('Custom shortcode generator error: ' . $aierror);
                            }
                            else
                            {
                                $shortval = trim(trim($generated_text), '.');
                            }
                        }
                        $prompt = str_replace('%%' . $shortname . '%%', $shortval, $prompt);
                    }
                }
            }
        }
    }
    $prompt = str_replace('%%default_post_cats%%', $default_cat_list, $prompt);
    $prompt = apply_filters('aiomatic_replace_aicontent_shortcode', $prompt);
    preg_match_all('#%%related_questions_([^%]*?)%%#i', $prompt, $mxatches);
    if(isset($mxatches[1][0]))
    {
        foreach($mxatches[1] as $googlematch)
        {
            $mtchres = aiomatic_scrape_related_questions($googlematch, 5, '', 1, 1, 0, 0, 2000, '', '');
            if(is_array($mtchres) && !empty($mtchres))
            {
                $quests = array();
                foreach($mtchres as $mra)
                {
                    if(isset($mra['q']))
                    {
                        $quests[] = $mra['q'];
                    }
                }
                $mtchres = implode(',', $quests);
            }
            $prompt = str_ireplace('%%related_questions_' . $googlematch . '%%', $mtchres, $prompt);
        }
    }
    return $prompt;
}

function aiomatic_replace_amazon($prompt, $post_title, $search_keywords, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $sections, $current_section, $sections_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list = '', $item_score = '', $edition = '', $language = '', $pages_count = '', $publication_date = '', $contributors = '', $manufacturer = '', $binding = '', $product_group = '', $rating = '', $eans = '', $part_no = '', $model = '', $warranty = '', $color = '', $is_adult = 'false', $dimensions = '', $date = '', $size = '', $unit_count = '', $amazresult = array())
{
    $blog_title = html_entity_decode(get_bloginfo('title'));
    
    $product_info = '';
    foreach($amazresult as $amr)
    {
        if(empty($product_info))
        {
            $product_info .= '\n\n--------------\n\n';
        }
        $product_info .= 'Title: ' . $amr->offer_title . '\n\n';
        $product_info .= 'Desciption: ' . $amr->offer_desc . '\n\n';
        $product_info .= 'Price: ' . $amr->offer_price . '\n\n';
        $product_info .= 'Image: ' . $amr->offer_img . '\n\n';
        $product_info .= 'URL: ' . $amr->offer_url . '\n\n';
        $product_info .= '--------------\n\n';
    }
    if($color === null)
    {
        $color = '';
    }
    $prompt = str_replace('%%search_keywords%%', $search_keywords, $prompt);
    $prompt = str_replace('%%post_title%%', $post_title, $prompt);
    $prompt = str_replace('%%product_title%%', $product_title, $prompt);
    $prompt = str_replace('%%product_description%%', $product_description, $prompt);
    $prompt = str_replace('%%aff_url%%', $aff_url, $prompt);
    $prompt = str_replace('%%product_author%%', $product_author, $prompt);
    $prompt = str_replace('%%offer_price%%', $offer_price, $prompt);
    $prompt = str_replace('%%product_price%%', $product_price, $prompt);
    $prompt = str_replace('%%product_list_price%%', $product_list_price, $prompt);
    $prompt = str_replace('%%price_numeric%%', $price_numeric, $prompt);
    $prompt = str_replace('%%price_currency%%', $price_currency, $prompt);
    $prompt = str_replace('%%product_brand%%', $product_brand, $prompt);
    $prompt = str_replace('%%product_reviews%%', $product_reviews, $prompt);
    $prompt = str_replace('%%product_isbn%%', $product_isbn, $prompt);
    $prompt = str_replace('%%product_upc%%', $product_upc, $prompt);
    $prompt = str_replace('%%product_asin%%', $product_asin, $prompt);
    $prompt = str_replace('%%cart_url%%', $cart_url, $prompt);
    $prompt = str_replace('%%list_price_numeric%%', $list_price_numeric, $prompt);
    $prompt = str_replace('%%product_imgs%%', $product_imgs, $prompt);
    $prompt = str_replace('%%product_imgs%%', $product_imgs, $prompt);
    //new
    $prompt = str_replace('%%product_score%%', $item_score, $prompt);
    $prompt = str_replace('%%product_edition%%', $edition, $prompt);
    $prompt = str_replace('%%product_language%%', $language, $prompt);
    $prompt = str_replace('%%product_pages_count%%', $pages_count, $prompt);
    $prompt = str_replace('%%product_publication_date%%', $publication_date, $prompt);
    $prompt = str_replace('%%product_contributors%%', $contributors, $prompt);
    $prompt = str_replace('%%product_manufacturer%%', $manufacturer, $prompt);
    $prompt = str_replace('%%product_binding%%', $binding, $prompt);
    $prompt = str_replace('%%product_product_group%%', $product_group, $prompt);
    $prompt = str_replace('%%product_rating%%', $rating, $prompt);
    $prompt = str_replace('%%product_ean%%', $eans, $prompt);
    $prompt = str_replace('%%product_part_no%%', $part_no, $prompt);
    $prompt = str_replace('%%product_model%%', $model, $prompt);
    $prompt = str_replace('%%product_warranty%%', $warranty, $prompt);
    $prompt = str_replace('%%product_color%%', $color, $prompt);
    $prompt = str_replace('%%product_is_adult%%', $is_adult, $prompt);
    $prompt = str_replace('%%product_dimensions%%', $dimensions, $prompt);
    $prompt = str_replace('%%product_date%%', $date, $prompt);
    $prompt = str_replace('%%product_size%%', $size, $prompt);
    $prompt = str_replace('%%product_unit_count%%', $unit_count, $prompt);

    $prompt = str_replace('%%all_product_info%%', $product_info, $prompt);
    $prompt = str_replace('%%all_product_titles%%', $product_titles, $prompt);
    $prompt = str_replace('%%post_title_keywords%%', $post_title_keywords, $prompt);
    $prompt = str_replace('%%blog_title%%', $blog_title, $prompt);
    $prompt = str_replace('%%language%%', $content_language, $prompt);
    $prompt = str_replace('%%writing_style%%', $writing_style, $prompt);
    $prompt = str_replace('%%writing_tone%%', $writing_tone, $prompt);
    $prompt = str_replace('%%sections%%', $sections, $prompt);
    $prompt = str_replace('%%current_section%%', $current_section, $prompt);
    $prompt = str_replace('%%sections_count%%', $sections_count, $prompt);
    $prompt = str_replace('%%paragraphs_per_section%%', $paragraph_count, $prompt);
    $prompt = str_replace('%%random_sentence%%', aiomatic_random_sentence_generator(), $prompt);
    $prompt = str_replace('%%random_sentence2%%', aiomatic_random_sentence_generator(false), $prompt);  
    $prompt = aiomatic_replaceSynergyShortcodes($prompt);
    if($custom_shortcodes != '')
    {
        $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
        if (!aiomatic_check_api_keys($aiomatic_Main_Settings)) 
        {
            aiomatic_log_to_file('You need to insert a valid AI service API Key for the custom shortcode creator to work!');
        }
        else
        {
            $allmodels = aiomatic_get_all_models();
            $appids = preg_split('/\r\n|\r|\n/', trim($aiomatic_Main_Settings['app_id']));
            $appids = array_filter($appids);
            if(empty($appids)){$token = '';}else{$token = $appids[array_rand($appids)];}
            $token = apply_filters('aimogen_openai_api_key', $token);$token = apply_filters('aiomatic_openai_api_key', $token);
            if($custom_shortcodes != '' && !is_array($custom_shortcodes))
            {
                $custom_shortcodes = aiomatic_replace_amazon($custom_shortcodes, $post_title, $search_keywords, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $language, $writing_style, $writing_tone, $sections, $current_section, $sections_count, $paragraph_count, $post_title_keywords, '', $global_prepend, $global_append, $product_reviews, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $default_cat_list);
            }
            
            $custom_shortcodes = str_replace('%%search_keywords%%', $search_keywords, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%post_title%%', $post_title, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_title%%', $product_title, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_description%%', $product_description, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%aff_url%%', $aff_url, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_author%%', $product_author, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%offer_price%%', $offer_price, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_price%%', $product_price, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_list_price%%', $product_list_price, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%price_numeric%%', $price_numeric, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%price_currency%%', $price_currency, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_brand%%', $product_brand, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_reviews%%', $product_reviews, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_isbn%%', $product_isbn, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_upc%%', $product_upc, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_asin%%', $product_asin, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%cart_url%%', $cart_url, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%list_price_numeric%%', $list_price_numeric, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_imgs%%', $product_imgs, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_imgs%%', $product_imgs, $custom_shortcodes);
            //new
            $custom_shortcodes = str_replace('%%product_score%%', $item_score, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_edition%%', $edition, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_language%%', $language, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_pages_count%%', $pages_count, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_publication_date%%', $publication_date, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_contributors%%', $contributors, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_manufacturer%%', $manufacturer, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_binding%%', $binding, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_product_group%%', $product_group, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_rating%%', $rating, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_ean%%', $eans, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_part_no%%', $part_no, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_model%%', $model, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_warranty%%', $warranty, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_color%%', $color, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_is_adult%%', $is_adult, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_dimensions%%', $dimensions, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_date%%', $date, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_size%%', $size, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_unit_count%%', $unit_count, $custom_shortcodes);

            $custom_shortcodes = str_replace('%%all_product_info%%', $product_info, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%all_product_titles%%', $product_titles, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%post_title_keywords%%', $post_title_keywords, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%blog_title%%', $blog_title, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%language%%', $content_language, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%writing_style%%', $writing_style, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%writing_tone%%', $writing_tone, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%sections%%', $sections, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%current_section%%', $current_section, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%sections_count%%', $sections_count, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%paragraphs_per_section%%', $paragraph_count, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%random_sentence%%', aiomatic_random_sentence_generator(), $custom_shortcodes);
            $custom_shortcodes = str_replace('%%random_sentence2%%', aiomatic_random_sentence_generator(false), $custom_shortcodes); 
            $custom_shortcodes = preg_split('/\r\n|\r|\n/', $custom_shortcodes);
            foreach($custom_shortcodes as $my_short)
            {
                $name_part = explode('=>', $my_short);
                if(isset($name_part[1]) && !empty(trim($name_part[1])))
                {
                    $shortname = trim($name_part[0]);
                    if(strstr($prompt, '%%' . $shortname . '%%'))
                    {
                        $shortval = '';
                        $ai_part = explode('@@', $name_part[1]);
                        if(isset($ai_part[1]) && !empty(trim($ai_part[1])))
                        {
                            if(!in_array(trim($ai_part[0]), $allmodels))
                            {
                                $aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            }
                            else
                            {
                                $aimodel = trim($ai_part[0]);
                            }
                            $ai_command = trim($ai_part[1]);
                            $ai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $ai_command);
                            foreach($custom_shortcodes as $my_check_short)
                            {
                                $check_name_part = explode('=>', $my_check_short);
                                if(isset($check_name_part[1]) && !empty(trim($check_name_part[1])))
                                {
                                    $check_shortname = trim($check_name_part[0]);
                                    if($shortname !== $check_shortname && strstr($ai_command, '%%' . $check_shortname . '%%') !== false)
                                    {
                                        $check_shortval = '';
                                        $check_ai_part = explode('@@', $check_name_part[1]);
                                        if(!in_array(trim($check_ai_part[0]), $allmodels))
                                        {
                                            $check_aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                        }
                                        else
                                        {
                                            $check_aimodel = trim($check_ai_part[0]);
                                        }
                                        $check_ai_command = trim($check_ai_part[1]);
                                        $aierror = '';

                                        $check_ai_command = str_replace('%%search_keywords%%', $search_keywords, $check_ai_command);
                                        $check_ai_command = str_replace('%%post_title%%', $post_title, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_title%%', $product_title, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_description%%', $product_description, $check_ai_command);
                                        $check_ai_command = str_replace('%%aff_url%%', $aff_url, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_author%%', $product_author, $check_ai_command);
                                        $check_ai_command = str_replace('%%offer_price%%', $offer_price, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_price%%', $product_price, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_list_price%%', $product_list_price, $check_ai_command);
                                        $check_ai_command = str_replace('%%price_numeric%%', $price_numeric, $check_ai_command);
                                        $check_ai_command = str_replace('%%price_currency%%', $price_currency, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_brand%%', $product_brand, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_reviews%%', $product_reviews, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_isbn%%', $product_isbn, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_upc%%', $product_upc, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_asin%%', $product_asin, $check_ai_command);
                                        $check_ai_command = str_replace('%%cart_url%%', $cart_url, $check_ai_command);
                                        $check_ai_command = str_replace('%%list_price_numeric%%', $list_price_numeric, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_imgs%%', $product_imgs, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_imgs%%', $product_imgs, $check_ai_command);
                                        //new
                                        $check_ai_command = str_replace('%%product_score%%', $item_score, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_edition%%', $edition, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_language%%', $language, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_pages_count%%', $pages_count, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_publication_date%%', $publication_date, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_contributors%%', $contributors, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_manufacturer%%', $manufacturer, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_binding%%', $binding, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_product_group%%', $product_group, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_rating%%', $rating, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_ean%%', $eans, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_part_no%%', $part_no, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_model%%', $model, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_warranty%%', $warranty, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_color%%', $color, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_is_adult%%', $is_adult, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_dimensions%%', $dimensions, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_date%%', $date, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_size%%', $size, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_unit_count%%', $unit_count, $check_ai_command);

                                        $check_ai_command = str_replace('%%all_product_info%%', $product_info, $check_ai_command);
                                        $check_ai_command = str_replace('%%all_product_titles%%', $product_titles, $check_ai_command);
                                        $check_ai_command = str_replace('%%post_title_keywords%%', $post_title_keywords, $check_ai_command);
                                        $check_ai_command = str_replace('%%blog_title%%', $blog_title, $check_ai_command);
                                        $check_ai_command = str_replace('%%language%%', $content_language, $check_ai_command);
                                        $check_ai_command = str_replace('%%writing_style%%', $writing_style, $check_ai_command);
                                        $check_ai_command = str_replace('%%writing_tone%%', $writing_tone, $check_ai_command);
                                        $check_ai_command = str_replace('%%sections%%', $sections, $check_ai_command);
                                        $check_ai_command = str_replace('%%current_section%%', $current_section, $check_ai_command);
                                        $check_ai_command = str_replace('%%sections_count%%', $sections_count, $check_ai_command);
                                        $check_ai_command = str_replace('%%paragraphs_per_section%%', $paragraph_count, $check_ai_command);
                                        $check_ai_command = str_replace('%%random_sentence%%', aiomatic_random_sentence_generator(), $check_ai_command);
                                        $check_ai_command = str_replace('%%random_sentence2%%', aiomatic_random_sentence_generator(false), $check_ai_command); 

                                        $check_ai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $check_ai_command);
                                        $check_generated_text = aiomatic_generate_custom_shortcode_content($token, $check_aimodel, $check_ai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                                        if($check_generated_text === false)
                                        {
                                            aiomatic_log_to_file('Custom nested shortcode generator error: ' . $aierror);
                                        }
                                        else
                                        {
                                            $check_shortval = trim(trim($check_generated_text), '.');
                                        }
                                        $ai_command = str_replace('%%' . $check_shortname . '%%', $check_shortval, $ai_command);
                                    }
                                }
                            }
                            $aierror = '';
                            $generated_text = aiomatic_generate_custom_shortcode_content($token, $aimodel, $ai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                            if($generated_text === false)
                            {
                                aiomatic_log_to_file('Custom shortcode generator error: ' . $aierror);
                            }
                            else
                            {
                                $shortval = trim(trim($generated_text), '.');
                            }
                        }
                        $prompt = str_replace('%%' . $shortname . '%%', $shortval, $prompt);
                    }
                }
            }
        }
    }
    $prompt = str_replace('%%default_post_cats%%', $default_cat_list, $prompt);
    $prompt = apply_filters('aiomatic_replace_aicontent_shortcode', $prompt);
    preg_match_all('#%%related_questions_([^%]*?)%%#i', $prompt, $mxatches);
    if(isset($mxatches[1][0]))
    {
        foreach($mxatches[1] as $googlematch)
        {
            $mtchres = aiomatic_scrape_related_questions($googlematch, 5, '', 1, 1, 0, 0, 2000, '', '');
            if(is_array($mtchres) && !empty($mtchres))
            {
                $quests = array();
                foreach($mtchres as $mra)
                {
                    if(isset($mra['q']))
                    {
                        $quests[] = $mra['q'];
                    }
                }
                $mtchres = implode(',', $quests);
            }
            $prompt = str_ireplace('%%related_questions_' . $googlematch . '%%', $mtchres, $prompt);
        }
    }
    return $prompt;
}
function aiomatic_replace_review($prompt, $post_title, $search_keywords, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $sections, $current_section, $sections_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list = '', $item_score = '', $edition = '', $language = '', $pages_count = '', $publication_date = '', $contributors = '', $manufacturer = '', $binding = '', $product_group = '', $rating = '', $eans = '', $part_no = '', $model = '', $warranty = '', $color = '', $is_adult = '', $dimensions = '', $date = '', $size = '', $unit_count = '')
{
    $blog_title = html_entity_decode(get_bloginfo('title'));
    $prompt = str_replace('%%search_keywords%%', $search_keywords, $prompt);
    $prompt = str_replace('%%post_title%%', $post_title, $prompt);
    $prompt = str_replace('%%product_title%%', $product_title, $prompt);
    $prompt = str_replace('%%product_description%%', $product_description, $prompt);
    $prompt = str_replace('%%aff_url%%', $aff_url, $prompt);
    $prompt = str_replace('%%product_author%%', $product_author, $prompt);
    $prompt = str_replace('%%offer_price%%', $offer_price, $prompt);
    $prompt = str_replace('%%product_price%%', $product_price, $prompt);
    $prompt = str_replace('%%product_list_price%%', $product_list_price, $prompt);
    $prompt = str_replace('%%price_numeric%%', $price_numeric, $prompt);
    $prompt = str_replace('%%price_currency%%', $price_currency, $prompt);
    $prompt = str_replace('%%product_brand%%', $product_brand, $prompt);
    $prompt = str_replace('%%product_reviews%%', $product_reviews, $prompt);
    $prompt = str_replace('%%product_isbn%%', $product_isbn, $prompt);
    $prompt = str_replace('%%product_upc%%', $product_upc, $prompt);
    $prompt = str_replace('%%product_asin%%', $product_asin, $prompt);
    $prompt = str_replace('%%cart_url%%', $cart_url, $prompt);
    $prompt = str_replace('%%list_price_numeric%%', $list_price_numeric, $prompt);
    $prompt = str_replace('%%product_imgs%%', $product_imgs, $prompt);
    $prompt = str_replace('%%all_product_titles%%', $product_titles, $prompt);
    $prompt = str_replace('%%post_title_keywords%%', $post_title_keywords, $prompt);
    $prompt = str_replace('%%blog_title%%', $blog_title, $prompt);
    $prompt = str_replace('%%language%%', $content_language, $prompt);
    $prompt = str_replace('%%writing_style%%', $writing_style, $prompt);
    $prompt = str_replace('%%writing_tone%%', $writing_tone, $prompt);
    $prompt = str_replace('%%sections%%', $sections, $prompt);
    $prompt = str_replace('%%current_section%%', $current_section, $prompt);
    $prompt = str_replace('%%sections_count%%', $sections_count, $prompt);
    $prompt = str_replace('%%paragraphs_per_section%%', $paragraph_count, $prompt);
    $prompt = str_replace('%%random_sentence%%', aiomatic_random_sentence_generator(), $prompt);
    $prompt = str_replace('%%random_sentence2%%', aiomatic_random_sentence_generator(false), $prompt);  
    $prompt = str_replace('%%point_of_view%%', $point_of_view, $prompt);
    //new
    $prompt = str_replace('%%product_score%%', $item_score, $prompt);
    $prompt = str_replace('%%product_edition%%', $edition, $prompt);
    $prompt = str_replace('%%product_language%%', $language, $prompt);
    $prompt = str_replace('%%product_pages_count%%', $pages_count, $prompt);
    $prompt = str_replace('%%product_publication_date%%', $publication_date, $prompt);
    $prompt = str_replace('%%product_contributors%%', $contributors, $prompt);
    $prompt = str_replace('%%product_manufacturer%%', $manufacturer, $prompt);
    $prompt = str_replace('%%product_binding%%', $binding, $prompt);
    $prompt = str_replace('%%product_product_group%%', $product_group, $prompt);
    $prompt = str_replace('%%product_rating%%', $rating, $prompt);
    $prompt = str_replace('%%product_ean%%', $eans, $prompt);
    $prompt = str_replace('%%product_part_no%%', $part_no, $prompt);
    $prompt = str_replace('%%product_model%%', $model, $prompt);
    $prompt = str_replace('%%product_warranty%%', $warranty, $prompt);
    $prompt = str_replace('%%product_color%%', $color, $prompt);
    $prompt = str_replace('%%product_is_adult%%', $is_adult, $prompt);
    $prompt = str_replace('%%product_dimensions%%', $dimensions, $prompt);
    $prompt = str_replace('%%product_date%%', $date, $prompt);
    $prompt = str_replace('%%product_size%%', $size, $prompt);
    $prompt = str_replace('%%product_unit_count%%', $unit_count, $prompt);
    $prompt = aiomatic_replaceSynergyShortcodes($prompt);
    if($custom_shortcodes != '')
    {
        $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
        if (!aiomatic_check_api_keys($aiomatic_Main_Settings)) 
        {
            aiomatic_log_to_file('You need to insert a valid AI service API Key for the custom shortcode creator to work!');
        }
        else
        {
            $allmodels = aiomatic_get_all_models();
            $appids = preg_split('/\r\n|\r|\n/', trim($aiomatic_Main_Settings['app_id']));
            $appids = array_filter($appids);
            if(empty($appids)){$token = '';}else{$token = $appids[array_rand($appids)];}
            $token = apply_filters('aimogen_openai_api_key', $token);$token = apply_filters('aiomatic_openai_api_key', $token);
            if($custom_shortcodes != '' && !is_array($custom_shortcodes))
            {
                $custom_shortcodes = aiomatic_replace_review($custom_shortcodes, $post_title, $search_keywords, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $language, $writing_style, $writing_tone, $sections, $current_section, $sections_count, $paragraph_count, $post_title_keywords, '', $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
            }
            $custom_shortcodes = str_replace('%%search_keywords%%', $search_keywords, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%post_title%%', $post_title, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_title%%', $product_title, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_description%%', $product_description, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%aff_url%%', $aff_url, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_author%%', $product_author, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%offer_price%%', $offer_price, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_price%%', $product_price, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_list_price%%', $product_list_price, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%price_numeric%%', $price_numeric, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%price_currency%%', $price_currency, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_brand%%', $product_brand, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_reviews%%', $product_reviews, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_isbn%%', $product_isbn, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_upc%%', $product_upc, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_asin%%', $product_asin, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%cart_url%%', $cart_url, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%list_price_numeric%%', $list_price_numeric, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_imgs%%', $product_imgs, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%all_product_titles%%', $product_titles, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%post_title_keywords%%', $post_title_keywords, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%blog_title%%', $blog_title, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%language%%', $content_language, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%writing_style%%', $writing_style, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%writing_tone%%', $writing_tone, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%sections%%', $sections, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%current_section%%', $current_section, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%sections_count%%', $sections_count, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%paragraphs_per_section%%', $paragraph_count, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%random_sentence%%', aiomatic_random_sentence_generator(), $custom_shortcodes);
            $custom_shortcodes = str_replace('%%random_sentence2%%', aiomatic_random_sentence_generator(false), $custom_shortcodes);  
            $custom_shortcodes = str_replace('%%point_of_view%%', $point_of_view, $custom_shortcodes);
            //new
            $custom_shortcodes = str_replace('%%product_score%%', $item_score, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_edition%%', $edition, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_language%%', $language, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_pages_count%%', $pages_count, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_publication_date%%', $publication_date, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_contributors%%', $contributors, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_manufacturer%%', $manufacturer, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_binding%%', $binding, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_product_group%%', $product_group, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_rating%%', $rating, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_ean%%', $eans, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_part_no%%', $part_no, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_model%%', $model, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_warranty%%', $warranty, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_color%%', $color, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_is_adult%%', $is_adult, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_dimensions%%', $dimensions, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_date%%', $date, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_size%%', $size, $custom_shortcodes);
            $custom_shortcodes = str_replace('%%product_unit_count%%', $unit_count, $custom_shortcodes);
            $custom_shortcodes = preg_split('/\r\n|\r|\n/', $custom_shortcodes);
            foreach($custom_shortcodes as $my_short)
            {
                $name_part = explode('=>', $my_short);
                if(isset($name_part[1]) && !empty(trim($name_part[1])))
                {
                    $shortname = trim($name_part[0]);
                    if(strstr($prompt, '%%' . $shortname . '%%'))
                    {
                        $shortval = '';
                        $ai_part = explode('@@', $name_part[1]);
                        if(isset($ai_part[1]) && !empty(trim($ai_part[1])))
                        {
                            if(!in_array(trim($ai_part[0]), $allmodels))
                            {
                                $aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            }
                            else
                            {
                                $aimodel = trim($ai_part[0]);
                            }
                            $ai_command = trim($ai_part[1]);
                            $ai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $ai_command);
                            foreach($custom_shortcodes as $my_check_short)
                            {
                                $check_name_part = explode('=>', $my_check_short);
                                if(isset($check_name_part[1]) && !empty(trim($check_name_part[1])))
                                {
                                    $check_shortname = trim($check_name_part[0]);
                                    if($shortname !== $check_shortname && strstr($ai_command, '%%' . $check_shortname . '%%') !== false)
                                    {
                                        $check_shortval = '';
                                        $check_ai_part = explode('@@', $check_name_part[1]);
                                        if(!in_array(trim($check_ai_part[0]), $allmodels))
                                        {
                                            $check_aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                        }
                                        else
                                        {
                                            $check_aimodel = trim($check_ai_part[0]);
                                        }
                                        $check_ai_command = trim($check_ai_part[1]);
                                        $aierror = '';

                                        $check_ai_command = str_replace('%%search_keywords%%', $search_keywords, $check_ai_command);
                                        $check_ai_command = str_replace('%%post_title%%', $post_title, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_title%%', $product_title, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_description%%', $product_description, $check_ai_command);
                                        $check_ai_command = str_replace('%%aff_url%%', $aff_url, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_author%%', $product_author, $check_ai_command);
                                        $check_ai_command = str_replace('%%offer_price%%', $offer_price, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_price%%', $product_price, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_list_price%%', $product_list_price, $check_ai_command);
                                        $check_ai_command = str_replace('%%price_numeric%%', $price_numeric, $check_ai_command);
                                        $check_ai_command = str_replace('%%price_currency%%', $price_currency, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_brand%%', $product_brand, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_reviews%%', $product_reviews, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_isbn%%', $product_isbn, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_upc%%', $product_upc, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_asin%%', $product_asin, $check_ai_command);
                                        $check_ai_command = str_replace('%%cart_url%%', $cart_url, $check_ai_command);
                                        $check_ai_command = str_replace('%%list_price_numeric%%', $list_price_numeric, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_imgs%%', $product_imgs, $check_ai_command);
                                        $check_ai_command = str_replace('%%all_product_titles%%', $product_titles, $check_ai_command);
                                        $check_ai_command = str_replace('%%post_title_keywords%%', $post_title_keywords, $check_ai_command);
                                        $check_ai_command = str_replace('%%blog_title%%', $blog_title, $check_ai_command);
                                        $check_ai_command = str_replace('%%language%%', $content_language, $check_ai_command);
                                        $check_ai_command = str_replace('%%writing_style%%', $writing_style, $check_ai_command);
                                        $check_ai_command = str_replace('%%writing_tone%%', $writing_tone, $check_ai_command);
                                        $check_ai_command = str_replace('%%sections%%', $sections, $check_ai_command);
                                        $check_ai_command = str_replace('%%current_section%%', $current_section, $check_ai_command);
                                        $check_ai_command = str_replace('%%sections_count%%', $sections_count, $check_ai_command);
                                        $check_ai_command = str_replace('%%paragraphs_per_section%%', $paragraph_count, $check_ai_command);
                                        $check_ai_command = str_replace('%%random_sentence%%', aiomatic_random_sentence_generator(), $check_ai_command);
                                        $check_ai_command = str_replace('%%random_sentence2%%', aiomatic_random_sentence_generator(false), $check_ai_command);  
                                        $check_ai_command = str_replace('%%point_of_view%%', $point_of_view, $check_ai_command);
                                        //new
                                        $check_ai_command = str_replace('%%product_score%%', $item_score, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_edition%%', $edition, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_language%%', $language, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_pages_count%%', $pages_count, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_publication_date%%', $publication_date, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_contributors%%', $contributors, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_manufacturer%%', $manufacturer, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_binding%%', $binding, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_product_group%%', $product_group, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_rating%%', $rating, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_ean%%', $eans, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_part_no%%', $part_no, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_model%%', $model, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_warranty%%', $warranty, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_color%%', $color, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_is_adult%%', $is_adult, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_dimensions%%', $dimensions, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_date%%', $date, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_size%%', $size, $check_ai_command);
                                        $check_ai_command = str_replace('%%product_unit_count%%', $unit_count, $check_ai_command);

                                        $check_ai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $check_ai_command);
                                        $check_generated_text = aiomatic_generate_custom_shortcode_content($token, $check_aimodel, $check_ai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                                        if($check_generated_text === false)
                                        {
                                            aiomatic_log_to_file('Custom nested shortcode generator error: ' . $aierror);
                                        }
                                        else
                                        {
                                            $check_shortval = trim(trim($check_generated_text), '.');
                                        }
                                        $ai_command = str_replace('%%' . $check_shortname . '%%', $check_shortval, $ai_command);
                                    }
                                }
                            }
                            preg_match_all('#%%related_questions_([^%]*?)%%#i', $ai_command, $mxatches);
                            if(isset($mxatches[1][0]))
                            {
                                foreach($mxatches[1] as $googlematch)
                                {
                                    $mtchres = aiomatic_scrape_related_questions($googlematch, 5, '', 1, 1, 0, 0, 2000, '', '');
                                    if(is_array($mtchres) && !empty($mtchres))
                                    {
                                        $quests = array();
                                        foreach($mtchres as $mra)
                                        {
                                            if(isset($mra['q']))
                                            {
                                                $quests[] = $mra['q'];
                                            }
                                        }
                                        $mtchres = implode(',', $quests);
                                    }
                                    $ai_command = str_ireplace('%%related_questions_' . $googlematch . '%%', $mtchres, $ai_command);
                                }
                            }
                            $aierror = '';
                            $generated_text = aiomatic_generate_custom_shortcode_content($token, $aimodel, $ai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                            if($generated_text === false)
                            {
                                aiomatic_log_to_file('Custom shortcode generator error: ' . $aierror);
                            }
                            else
                            {
                                $shortval = trim(trim($generated_text), '.');
                            }
                        }
                        $prompt = str_replace('%%' . $shortname . '%%', $shortval, $prompt);
                    }
                }
            }
        }
    }
    $prompt = str_replace('%%default_post_cats%%', $default_cat_list, $prompt);
    $prompt = apply_filters('aiomatic_replace_aicontent_shortcode', $prompt);
    preg_match_all('#%%related_questions_([^%]*?)%%#i', $prompt, $mxatches);
    if(isset($mxatches[1][0]))
    {
        foreach($mxatches[1] as $googlematch)
        {
            $mtchres = aiomatic_scrape_related_questions($googlematch, 5, '', 1, 1, 0, 0, 2000, '', '');
            if(is_array($mtchres) && !empty($mtchres))
            {
                $quests = array();
                foreach($mtchres as $mra)
                {
                    if(isset($mra['q']))
                    {
                        $quests[] = $mra['q'];
                    }
                }
                $mtchres = implode(',', $quests);
            }
            $prompt = str_ireplace('%%related_questions_' . $googlematch . '%%', $mtchres, $prompt);
        }
    }
    return $prompt;
}
function aiomatic_get_royalty_free_image($query_words, $enable_ai_images, $image_size, &$images_arr, $token, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, &$img_attr, $old_title, $custom_shortcodes, $global_prepend, $global_append, $image_url, &$attached_id, &$raw_img_list = array(), $default_cat_list = '', $image_model = 'gpt-image-2')
{
    $ret_image = false;
    $full_result_list = array();
    $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
    if(count($images_arr) > 0)
    {
        $first_el = array_shift($images_arr);
        $ret_image = $first_el;
    }
    elseif($enable_ai_images == '1')
    {
        if(aiomatic_strlen($query_words) > 1000)
        {
            $query_words = aiomatic_substr($query_words, 0, 1000);
        }
        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
        {
            $api_service = aiomatic_get_api_service($token, $image_model);
            aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $query_words);
        }
        $aierror = '';
        $temp_get_imgs = aiomatic_generate_ai_image($token, 1, $query_words, $image_size, 'contentImageAI', false, 0, $aierror, $image_model, $old_title);
        if($temp_get_imgs !== false)
        {
            foreach($temp_get_imgs as $tmpimg)
            {
                $ret_image = $tmpimg;
            }
        }
        else
        {
            aiomatic_log_to_file('Failed to generate AI image: ' . $aierror);
        }
    }
    elseif($enable_ai_images == '2')
    {
        if(aiomatic_strlen($query_words) > 2000)
        {
            $query_words = aiomatic_substr($query_words, 0, 2000);
        }
        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
        {
            $api_service = 'Stability.AI';
            aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $query_words);
        }
        if($image_size == '256x256')
        {
            $width = '512';
            $height = '512';
        }
        elseif($image_size == '512x512')
        {
            $width = '512';
            $height = '512';
        }
        elseif($image_size == '1024x1024')
        {
            $width = '1024';
            $height = '1024';
        }
        else
        {
            $width = '512';
            $height = '512';
        }
        $ierror = '';
        $temp_get_imgs = aiomatic_generate_stability_image($query_words, $height, $width, 'contentStableImageAI', 0, false, $ierror, false, false, '', 0);
        if($temp_get_imgs !== false)
        {
            $ret_image = $temp_get_imgs[1];
        }
        else
        {
            aiomatic_log_to_file('Failed to generate Stability.AI image: ' . $ierror);
        }
    }
    elseif($enable_ai_images == '7')
    {
        if(aiomatic_strlen($query_words) > 2000)
        {
            $query_words = aiomatic_substr($query_words, 0, 2000);
        }
        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
        {
            $api_service = 'Google';
            aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $query_words);
        }
        if (isset($aiomatic_Main_Settings['google_ai_image_model']) && trim($aiomatic_Main_Settings['google_ai_image_model']) != '') 
        {
            $model = trim($aiomatic_Main_Settings['google_ai_image_model']);
        }
        else
        {
            $model = AIMOGEN_GOOGLE_IMAGE_DEFAULT_MODEL;
        }
        $ierror = '';
        $temp_get_imgs = aiomatic_generate_image_google($query_words, $model, 'contentGoogleImageAI', false, $ierror, false);
        if($temp_get_imgs !== false)
        {
            $ret_image = $temp_get_imgs[1];
        }
        else
        {
            aiomatic_log_to_file('Failed to generate Google image: ' . $ierror);
        }
    }
    elseif($enable_ai_images == '4')
    {
        if(aiomatic_strlen($query_words) > 2000)
        {
            $query_words = aiomatic_substr($query_words, 0, 2000);
        }
        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
        {
            $api_service = 'Midjourney';
            aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $query_words);
        }
        if($image_size == '256x256')
        {
            $width = '512';
            $height = '512';
        }
        elseif($image_size == '512x512')
        {
            $width = '512';
            $height = '512';
        }
        elseif($image_size == '1024x1024')
        {
            $width = '1024';
            $height = '1024';
        }
        elseif($image_size == '1024x1792')
        {
            $width = '1024';
            $height = '1792';
        }
        elseif($image_size == '1792x1024')
        {
            $width = '1792';
            $height = '1024';
        }
        else
        {
            $width = '512';
            $height = '512';
        }
        $ierror = '';
        $temp_get_imgs = aiomatic_generate_ai_image_midjourney($query_words, $width, $height, 'contentMidjourneyImageAI', false, $ierror);
        if($temp_get_imgs !== false)
        {
            $ret_image = $temp_get_imgs;
        }
        else
        {
            aiomatic_log_to_file('Failed to generate Midjourney image: ' . $ierror);
        }
    }
    elseif($enable_ai_images == '5')
    {
        if(aiomatic_strlen($query_words) > 2000)
        {
            $query_words = aiomatic_substr($query_words, 0, 2000);
        }
        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
        {
            $api_service = 'Replicate';
            aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $query_words);
        }
        if($image_size == '256x256')
        {
            $width = '512';
            $height = '512';
        }
        elseif($image_size == '512x512')
        {
            $width = '512';
            $height = '512';
        }
        elseif($image_size == '1024x1024')
        {
            $width = '1024';
            $height = '1024';
        }
        elseif($image_size == '1024x1792')
        {
            $width = '1024';
            $height = '1792';
        }
        elseif($image_size == '1792x1024')
        {
            $width = '1792';
            $height = '1024';
        }
        else
        {
            $width = '512';
            $height = '512';
        }
        $ierror = '';
        $temp_get_imgs = aiomatic_generate_replicate_image($query_words, $width, $height, 'contentReplicateImageAI', false, $ierror);
        if($temp_get_imgs !== false)
        {
            $ret_image = $temp_get_imgs;
        }
        else
        {
            aiomatic_log_to_file('Failed to generate Replicate image: ' . $ierror);
        }
    }
    elseif($enable_ai_images == '6')
    {
        if(aiomatic_strlen($query_words) > 3000)
        {
            $query_words = aiomatic_substr($query_words, 0, 3000);
        }
        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
        {
            $api_service = 'Ideogram';
            aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $query_words);
        }
        if($image_size == '256x256')
        {
            $width = '512';
            $height = '512';
        }
        elseif($image_size == '512x512')
        {
            $width = '512';
            $height = '512';
        }
        elseif($image_size == '1024x1024')
        {
            $width = '1024';
            $height = '1024';
        }
        elseif($image_size == '1024x1792')
        {
            $width = '1024';
            $height = '1792';
        }
        elseif($image_size == '1792x1024')
        {
            $width = '1792';
            $height = '1024';
        }
        else
        {
            $width = '512';
            $height = '512';
        }
        $ierror = '';
        $temp_get_imgs = aiomatic_generate_ideogram_image($query_words, $width, $height, 'contentIdeogramImageAI', false, $ierror);
        if($temp_get_imgs !== false)
        {
            $ret_image = $temp_get_imgs;
        }
        else
        {
            aiomatic_log_to_file('Failed to generate Ideogram image: ' . $ierror);
        }
    }
    elseif($enable_ai_images == '8')
    {
        if(aiomatic_strlen($query_words) > 3000)
        {
            $query_words = aiomatic_substr($query_words, 0, 3000);
        }
        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
        {
            $api_service = 'Cloudflare';
            aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $query_words);
        }
        if($image_size == '256x256')
        {
            $width = '512';
            $height = '512';
        }
        elseif($image_size == '512x512')
        {
            $width = '512';
            $height = '512';
        }
        elseif($image_size == '1024x1024')
        {
            $width = '1024';
            $height = '1024';
        }
        elseif($image_size == '1024x1792')
        {
            $width = '1024';
            $height = '1792';
        }
        elseif($image_size == '1792x1024')
        {
            $width = '1792';
            $height = '1024';
        }
        else
        {
            $width = '512';
            $height = '512';
        }
        $ierror = '';
        $temp_get_imgs = aiomatic_generate_cloudflare_image($query_words, $width, $height, 'contentCloudflareImageAI', false, $ierror);
        if($temp_get_imgs !== false)
        {
            $ret_image = $temp_get_imgs;
        }
        else
        {
            aiomatic_log_to_file('Failed to generate Cloudflare image: ' . $ierror);
        }
    }
    elseif($enable_ai_images == '3')
    {
        if ($image_url != '') 
        {
            $replacement = str_replace(array('[', ']'), '', $query_words);
            $image_url_temp = str_replace('%%item_title%%', $replacement, $image_url);
            $image_url_temp = preg_replace_callback('#%%random_image\[([^\]]*?)\](\[\d+\])?%%#', function ($matches) {
                if(isset($matches[2]))
                {
                    $chance = trim($matches[2], '[]');
                }
                else
                {
                    $chance = '';
                }
                $arv = array();
                $my_img = aiomatic_get_random_image_google($matches[1], 0, 0, $chance, $arv);
                return $my_img;
            }, $image_url_temp);
            $spintax = new Aiomatic_Spintax();
            $img_rulx = $spintax->Parse(trim($image_url_temp));
            $img_rulx = explode(',', $img_rulx);
            $img_rulx = trim($img_rulx[array_rand($img_rulx)]);
            if($img_rulx != '')
            {
                $ret_image = $img_rulx;
            }
        }
    }
    elseif($enable_ai_images == '9')
    {
        global $wpdb;

        $attachment_id = $wpdb->get_var(
            "
            SELECT ID
            FROM {$wpdb->posts}
            WHERE post_type = 'attachment'
            AND post_mime_type LIKE 'image/%'
            AND post_status = 'inherit'
            ORDER BY RAND()
            LIMIT 1
            "
        );

        if (!empty($attachment_id))
        {
            $ret_image = wp_get_attachment_url($attachment_id);

            if (isset($aiomatic_Main_Settings['enable_detailed_logging']))
            {
                aiomatic_log_to_file(
                    'Random Media Library image selected: ' .
                    $ret_image .
                    ' (ID: ' . $attachment_id . ')'
                );
            }
        }
        else
        {
            aiomatic_log_to_file(
                'Failed to find a random image in Media Library.'
            );
        }
    }
    else
    {
        $image_query = aiomatic_extract_keyword($query_words, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $token, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
        if(!empty($image_query))
        {
            $kws = explode(',', $image_query);
            $image_query = trim($kws[0]);
            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
            {
                aiomatic_log_to_file('Keyword "' . $image_query . '" was extracted from text: ' . $query_words);
            }
            $query_words = $image_query;
        }
        $attached_id = '';
        $temp_get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, false, $raw_img_list, array(), $full_result_list);
        if($temp_get_img == '' || $temp_get_img === false)
        {
            aiomatic_log_to_file('Failed to find royalty free image for: ' . $query_words);
        }
        else
        {
            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
            {
                aiomatic_log_to_file('Got royalty free image: ' . $temp_get_img);
            }
            $ret_image = $temp_get_img;
        }
    }
    return $ret_image;
}
function aiomatic_extract_keyword($image_query, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $token, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list)
{
    $query_words = '';
    $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
    if(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'textrazor')
    {
        if(isset($aiomatic_Main_Settings['textrazor_key']) && trim($aiomatic_Main_Settings['textrazor_key']) != '')
        {
            try
            {
                if(!class_exists('TextRazor'))
                {
                    require_once(dirname(__FILE__) . "/res/TextRazor.php");
                }
                TextRazorSettings::setApiKey(trim($aiomatic_Main_Settings['textrazor_key']));
                $textrazor = new TextRazor();
                $textrazor->addExtractor('entities');
                $response = $textrazor->analyze($image_query);
                if (isset($response['response']['entities'])) 
                {
                    foreach ($response['response']['entities'] as $entity) 
                    {
                        if(isset($entity['entityEnglishId']))
                        {
                            $query_words = $entity['entityEnglishId'];
                            if(!empty($query_words))
                            {
                                break;
                            }
                        }
                        else
                        {
                            $query_words = $entity['entityId'];
                            if(!empty($query_words))
                            {
                                break;
                            }
                        }
                    }
                }
            }
            catch(Exception $e)
            {
                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                    aiomatic_log_to_file('Failed to search for keywords using TextRazor (!): ' . $e->getMessage());
                }
            }
        }
    }
    elseif(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'openai')
    {
        if(isset($aiomatic_Main_Settings['keyword_prompts']) && trim($aiomatic_Main_Settings['keyword_prompts']) != '')
        {
            if(isset($aiomatic_Main_Settings['keyword_model']) && $aiomatic_Main_Settings['keyword_model'] != '')
            {
                $kw_model = $aiomatic_Main_Settings['keyword_model'];
            }
            else
            {
                $kw_model = aiomatic_get_default_model_name($aiomatic_Main_Settings);
            }
            if(isset($aiomatic_Main_Settings['keyword_assistant_id']) && $aiomatic_Main_Settings['keyword_assistant_id'] != '')
            {
                $keyword_assistant_id = $aiomatic_Main_Settings['keyword_assistant_id'];
            }
            else
            {
                $keyword_assistant_id = '';
            }
            $title_ai_command = trim($aiomatic_Main_Settings['keyword_prompts']);
            $title_ai_command = str_replace('%%default_post_cats%%', $default_cat_list, $title_ai_command);
            $title_ai_command = str_replace('%%original_post_title%%', $post_title, $title_ai_command);
            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
            {
                $title_ai_command = preg_split('/\r\n|\r|\n/', $title_ai_command);
                $title_ai_command = array_filter($title_ai_command);
                if(count($title_ai_command) > 0)
                {
                    $title_ai_command = $title_ai_command[array_rand($title_ai_command)];
                }
                else
                {
                    $title_ai_command = '';
                }
            }
            $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
            if(!empty($title_ai_command))
            {
                $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $image_query, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, $global_prepend, $global_append);
            }
            $title_ai_command = trim($title_ai_command);
            if (filter_var($title_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($title_ai_command, '.txt'))
            {
                $txt_content = aiomatic_get_web_page($title_ai_command);
                if ($txt_content !== FALSE) 
                {
                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                    $txt_content = array_filter($txt_content);
                    if(count($txt_content) > 0)
                    {
                        $txt_content = $txt_content[array_rand($txt_content)];
                        if(trim($txt_content) != '') 
                        {
                            $title_ai_command = $txt_content;
                            $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                            $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $image_query, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, $global_prepend, $global_append);
                        }
                    }
                }
            }
            if(empty($title_ai_command))
            {
                aiomatic_log_to_file('Empty API keyword extractor seed expression provided!');
                $title_ai_command = 'Type the most relevant keyword, no other text before or after it, for a blog post titled:  ' . trim(strip_tags($image_query));
            }
            $max_seed_tokens = AIMOGEN_DEFAULT_COMPLETION_TOKENS;
            if(aiomatic_strlen($title_ai_command) > $max_seed_tokens * 4)
            {
                $title_ai_command = aiomatic_substr($title_ai_command, 0, (0 - ($max_seed_tokens * 4)));
            }
            $title_ai_command = trim($title_ai_command);
            if(empty($title_ai_command))
            {
                aiomatic_log_to_file('Empty API title seed expression provided(3)! ' . print_r($title_ai_command, true));
            }
            else
            {
                $max_tokens = 2048;
                $query_token_count = count(aiomatic_encode($title_ai_command));
                $available_tokens = aiomatic_compute_available_tokens($kw_model, $max_tokens, $title_ai_command, $query_token_count);
                if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                {
                    $string_len = aiomatic_strlen($title_ai_command);
                    $string_len = $string_len / 2;
                    $string_len = intval(0 - $string_len);
                    $title_ai_command = aiomatic_substr($title_ai_command, 0, $string_len);
                    $title_ai_command = trim($title_ai_command);
                    $query_token_count = count(aiomatic_encode($title_ai_command));
                    $available_tokens = $max_tokens - $query_token_count;
                }
                $thread_id = '';
                $aierror = '';
                $finish_reason = '';
                $temperature = 0;
                $top_p = 0;
                $presence_penalty = 0;
                $frequency_penalty = 0;
                if(!empty($global_prepend))
                {
                    $title_ai_command = $global_prepend . ' ' . $title_ai_command;
                }
                if(!empty($global_append))
                {
                    $title_ai_command = $title_ai_command . ' ' . $global_append;
                }
                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                {
                    $api_service = aiomatic_get_api_service($token, $kw_model);
                    aiomatic_log_to_file('Calling ' . $api_service . ' (' . $kw_model . ')(' . $available_tokens . ') for keyword text: ' . $title_ai_command);
                }
                $generated_text = aiomatic_generate_text($token, $kw_model, $title_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'keywordImg', 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $keyword_assistant_id, $thread_id, '', 'disabled', '', true, false, array(), '', '', '');
                if($generated_text === false)
                {
                    aiomatic_log_to_file('Keyword generator error: ' . $aierror);
                }
                else
                {
                    $query_words = trim(trim($generated_text), '.');
                }
            }
        }
    }
    if(empty($query_words))
    {
        $keyword_class = new Aiomatic_keywords();
        $query_words = $keyword_class->keywords($image_query, 1);
    }
    return $query_words;
}
function aiomatic_load_meta_index($meta_key, array $post_stati) 
{
    $result = [];
    $paged  = 0;
    $limit  = 5000;

    do {
        $posts = get_posts([
            'post_status'    => $post_stati,
            'post_type'      => 'any',
            'posts_per_page' => $limit,
            'paged'          => ++$paged,
            'fields'         => 'ids',
            'meta_key'       => $meta_key,
            'no_found_rows'  => true,
        ]);

        foreach ($posts as $pid) {
            $val = get_post_meta($pid, $meta_key, true);
            if ($val !== '') {
                $result[$val] = $pid;
            }
        }
    } while ($posts);

    return $result;
}

function aiomatic_run_rule($param, $type = 0, $auto = 1, $ret_content = 0, $rules = null, $stop_omnmiblock_id = '', $omniWebhookID = '', $return_last_result = false, $load_variables = [])
{
    global $shortcode_tags;
    $param = intval($param);
    $type = intval($type);
    $plugin = plugin_basename(__FILE__);
    $plugin_slug = explode('/', $plugin);
    $plugin_slug = $plugin_slug[0]; 
    $uoptions = array();
    $event_context = array();
    $is_activated = aiomatic_is_activated($plugin_slug, $uoptions);
    if($is_activated !== true && $is_activated !== 2 && $is_activated !== -2)
    {
        aiomatic_log_to_file('The plugin is not activated using a valid purchase code. You need to activate the plugin for this feature to work.');
        return 'fail';
    }
    $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
    if (!aiomatic_check_api_keys($aiomatic_Main_Settings)) 
    {
        aiomatic_log_to_file('You need to insert a valid AI service API Key for this to work!');
        return 'fail';
    }
    if(is_array($omniWebhookID) && !empty($omniWebhookID) && isset($omniWebhookID[1]))
    {
        $event_context = $omniWebhookID[1];
        $omniWebhookID = $omniWebhookID[0];
    }
	$appids = preg_split('/\r\n|\r|\n/', trim($aiomatic_Main_Settings['app_id']));
    $appids = array_filter($appids);
    if(empty($appids)){$token = '';}else{$token = $appids[array_rand($appids)];}
    $token = apply_filters('aimogen_openai_api_key', $token);$token = apply_filters('aiomatic_openai_api_key', $token);
    if($ret_content == 0)
    {
        $f = fopen(get_temp_dir() . 'aiomatic_' . $type . '_' . $param, 'w');
        if($f !== false)
        {
            $flock_disabled = explode(',', ini_get('disable_functions'));
            if(!in_array('flock', $flock_disabled))
            {
                if (!flock($f, LOCK_EX | LOCK_NB)) {
                    return 'nochange';
                }
            }
        }
        
        $GLOBALS['wp_object_cache']->delete('aiomatic_running_list', 'options');
        if (!get_option('aiomatic_running_list')) {
            $running = array();
        } else {
            $running = get_option('aiomatic_running_list');
        }
        if (!empty($running)) {
            if (in_array(array(
                $param => $type
            ), $running))
            {
                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                    aiomatic_log_to_file('Only one instance of this rule is allowed. Rule is already running!');
                }
                return 'nochange';
            }
        }
        $running[] = array(
            $param => $type
        );
        aiomatic_update_option('aiomatic_running_list', $running, false);
        register_shutdown_function('aiomatic_clear_flag_at_shutdown', $param, $type);
        if (isset($aiomatic_Main_Settings['enable_detailed_logging']) && $aiomatic_Main_Settings['enable_detailed_logging'] == 'on') 
        {
            aiomatic_log_exec_time('Run Rule Type ' . $type . ' ID ' . $param);
        }
    }
    if (isset($aiomatic_Main_Settings['rule_timeout']) && $aiomatic_Main_Settings['rule_timeout'] != '') {
        $timeout = intval($aiomatic_Main_Settings['rule_timeout']);
    } else {
        $timeout = 36000;
    }
    ini_set('safe_mode', 'Off');
    ini_set('max_execution_time', $timeout);
    ini_set('ignore_user_abort', 1);
    ini_set('user_agent', aiomatic_get_random_user_agent());
    if(function_exists('ignore_user_abort'))
    {
        ignore_user_abort(true);
    }
    if(function_exists('set_time_limit'))
    {
        set_time_limit($timeout);
    }
    require_once(dirname(__FILE__) . "/res/aiomatic-chars.php");
    $posts_inserted         = 0;
    $attached_id = '';
    $additional_attachments = array();
    if (isset($aiomatic_Main_Settings['aiomatic_enabled']) && $aiomatic_Main_Settings['aiomatic_enabled'] == 'on') {
        try 
        {
            $old_title        = '';
            $selected_forum   = 0;
            $cont             = 0;
            $found            = 0;
            $enable_comments  = '1';
            $enable_pingback  = '1';
            $ai_command       = '';
            $headings         = '';
            $images           = '';
            $videos           = '';
            $post_title       = '';
            $default_category = '';
            $extra_categories = '';
            $min_char         = '1';
            $post_status     = 'publish';
            $remove_default  = '';
            $random_order    = '';
            $csv_separator   = '';
            $title_ai_command = '';
            $strip_title     = '';
            $img_all_headings = '';
            $heading_img_location = '';
            $title_source    = '';
            $skipt = 0;
            $headings_ai_command = '';
            $title_once      = '';
            $category_model  = aiomatic_get_default_model_name($aiomatic_Main_Settings);
            $category_ai_command  = '';
            $custom_shortcodes= '';
            $strip_by_regex  = '';
            $strip_by_regex_prompts = '';
            $replace_regex   = '';
            $replace_regex_prompts = '';
            $run_regex_on    = '';
            $max_links       = '';
            $search_query_repetition = '';
            $link_post_types = 'post';
            $enable_toc      = '';
            $tag_model       = aiomatic_get_default_model_name($aiomatic_Main_Settings);
            $tag_ai_command  = '';
            $min_time        = '';
            $max_time        = '';
            $assistant_id    = '';
            $skip_spin       = '';
            $skip_translate  = '';
            $title_model     = aiomatic_get_default_model_name($aiomatic_Main_Settings);
            $post_type       = 'post';
            $accept_comments = 'closed';
            $post_user_name  = 1;
            $item_create_tag = '';
            $can_create_tag  = 'disabled';
            $item_tags       = '';
            $max             = 50;
            $auto_categories = 'disabled';
            $custom_fields   = '';
            $custom_tax      = '';
            $temperature     = '';
            $post_prepend    = '';
            $post_append     = '';
            $enable_ai_images = '';
            $enable_ai_images_article = '';
            $ai_command_image_article = '';
            $image_model_article = '';
            $image_size_article = '';
            $top_p           = '';
            $presence_penalty = '';
            $frequency_penalty = '';
            $royalty_free    = '';
            $image_size      = '256x256';
            $headings_list   = '';
            $images_list     = '';
            $headings_model  = aiomatic_get_default_model_name($aiomatic_Main_Settings);
            $wpml_lang       = '';
            $post_format     = 'post-format-standard';
            $max_tokens      = AIMOGEN_DEFAULT_MAX_TOKENS;
            $max_seed_tokens = AIMOGEN_DEFAULT_COMPLETION_TOKENS;
            $posting_mode    = 'title';
            $post_topic_list = '';
            $post_sections_list = '';
            $content_language = '';
            $writing_style   = '';
            $writing_tone    = '';
            $topic_proscons_model = '';
            $proscons_prompt = '';
            $topic_reviews_model = '';
            $reviews_prompt = '';
            $sections_prompt = '';
            $title_prompt    = '';
            $content_prompt  = '';
            $excerpt_prompt  = '';
            $section_count   = '';
            $paragraph_count = '';
            $topic_title_model = '';
            $topic_sections_model = '';
            $topic_content_model = '';
            $topic_excerpt_model = '';
            $single_content_call = '';
            $intro_prompt    = '';
            $topic_intro_model = aiomatic_get_default_model_name($aiomatic_Main_Settings);
            $outro_prompt    = '';
            $topic_outro_model = aiomatic_get_default_model_name($aiomatic_Main_Settings);
            $model           = aiomatic_get_default_model_name($aiomatic_Main_Settings);
            $topic_qa_model  = aiomatic_get_default_model_name($aiomatic_Main_Settings);
            $topic_images    = '';
            $qa_prompt       = '';
            $topic_videos    = '';
            $no_random       = '';
            $title_toc       = '';
            $title_qa        = '';
            $title_outro     = '';
            $link_type       = 'internal';
            $link_list       = '';
            $link_nofollow   = '';
            $parent_id       = '';
            $skip_inexist    = '';
            $global_prepend  = '';
            $image_url       = '';
            $draft_me        = false;
            $global_append   = '';
            $enable_qa       = '';
            $sections_role   = '';
            $url_list        = '';
            $affiliate_id    = '';
            $first_hand      = '';
            $default_lang    = '';
            $max_products    = '';
            $min_price       = '';
            $max_price       = '';
            $sort_results    = '';
            $title_proscons  = '';
            $enable_proscons = '';
            $enable_reviews  = '';
            $title_reviews   = '';
            $shuffle_products = '';
            $amazon_keyword  = '';
            $rule_description = '';
            $ai_titles       = '';
            $days_no_run     = '';
            $overwrite_existing = '';
            $max_caption     = '';
            $max_continue_tokens = 500;
            $title_generator_method = '';
            $update_post_id  = '';
            $point_of_view   = '';
            $user_role       = '';
            $ai_command_image = '';
            $rule_unique_id  = '';
            $no_headlink     = '';
            $enable_table    = '';
            $table_prompt    = '';
            $topic_table_model= '';
            $more_replies    = '';
            $neg_keywords    = '';
            $cb_affiliate_id = '';
            $max_products_cb = '';
            $item_category   = '';
            $one_time        = '';
            $recurring       = '';
            $affiliate_tools = '';
            $spotlight       = '';
            $mobile_hoplink  = '';
            $shipable_only   = '';
            $pitch_plus      = '';
            $item_gravity    = '';
            $dollar_sale     = '';
            $dollar_sale_av  = '';
            $rebill_total    = '';
            $per_sale        = '';
            $per_rebill      = '';
            $product_source  = '';
            $item_language   = '';
            $sort_results_cb = '';
            $activation      = '';
            $image_model     = 'gpt-image-2';
            $reply_count = '';
            $reply_model = aiomatic_get_default_model_name($aiomatic_Main_Settings);
            $choose_prompt = '';
            $reply_prompt = '';
            if (isset($aiomatic_Main_Settings['store_data_rules']) && $aiomatic_Main_Settings['store_data_rules'] == 'on') 
            {
                $store_data = 'on';
            }
            else
            {
                $store_data = 'off';
            }
            if($type == 0 || empty($type))
            {
                if($rules === null)
                {
                    $GLOBALS['wp_object_cache']->delete('aiomatic_rules_list', 'options');
                    if (!get_option('aiomatic_rules_list')) {
                        $rules = array();
                    } else {
                        $rules = get_option('aiomatic_rules_list');
                    }
                }
                if (!empty($rules)) {
                    foreach ($rules as $request => $bundle[]) {
                        if ($cont == $param) {
                            $bundle_values    = array_values($bundle);
                            $myValues         = $bundle_values[$cont];
                            $array_my_values  = array_values($myValues);for($iji=0;$iji<count($array_my_values);++$iji){if(is_string($array_my_values[$iji])){$array_my_values[$iji]=stripslashes($array_my_values[$iji]);}}
                            $schedule         = isset($array_my_values[0]) ? $array_my_values[0] : '';
                            $active           = isset($array_my_values[1]) ? $array_my_values[1] : '';
                            $last_run         = isset($array_my_values[2]) ? $array_my_values[2] : '';
                            $max              = isset($array_my_values[3]) ? $array_my_values[3] : '';
                            $post_status      = isset($array_my_values[4]) ? $array_my_values[4] : '';
                            $post_type        = isset($array_my_values[5]) ? $array_my_values[5] : '';
                            $post_user_name   = isset($array_my_values[6]) ? $array_my_values[6] : '';
                            $item_create_tag  = isset($array_my_values[7]) ? $array_my_values[7] : '';
                            $default_category = isset($array_my_values[8]) ? $array_my_values[8] : '';
                            $auto_categories  = isset($array_my_values[9]) ? $array_my_values[9] : '';
                            $can_create_tag   = isset($array_my_values[10]) ? $array_my_values[10] : '';
                            $enable_comments  = isset($array_my_values[11]) ? $array_my_values[11] : '';
                            $image_url        = isset($array_my_values[12]) ? $array_my_values[12] : '';
                            $post_title       = isset($array_my_values[13]) ? htmlspecialchars_decode($array_my_values[13]) : '';
                            $enable_pingback  = isset($array_my_values[14]) ? $array_my_values[14] : '';
                            $post_format      = isset($array_my_values[15]) ? $array_my_values[15] : '';
                            $min_char         = isset($array_my_values[16]) ? $array_my_values[16] : '';
                            $custom_fields    = isset($array_my_values[17]) ? $array_my_values[17] : '';
                            $custom_tax       = isset($array_my_values[18]) ? $array_my_values[18] : '';
                            $temperature      = isset($array_my_values[19]) ? $array_my_values[19] : '';
                            $top_p            = isset($array_my_values[20]) ? $array_my_values[20] : '';
                            $presence_penalty = isset($array_my_values[21]) ? $array_my_values[21] : '';
                            $frequency_penalty = isset($array_my_values[22]) ? $array_my_values[22] : '';
                            $royalty_free     = isset($array_my_values[23]) ? $array_my_values[23] : '';
                            $ai_command       = isset($array_my_values[24]) ? $array_my_values[24] : '';
                            $max_tokens       = isset($array_my_values[25]) ? $array_my_values[25] : '';
                            $max_seed_tokens  = isset($array_my_values[26]) ? $array_my_values[26] : AIMOGEN_DEFAULT_COMPLETION_TOKENS;
                            $max_continue_tokens= isset($array_my_values[27]) ? $array_my_values[27] : AIMOGEN_DEFAULT_COMPLETION_TOKENS;
                            $model            = isset($array_my_values[28]) ? $array_my_values[28] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $headings         = isset($array_my_values[29]) ? $array_my_values[29] : '';
                            $images           = isset($array_my_values[30]) ? $array_my_values[30] : '';
                            $videos           = isset($array_my_values[31]) ? $array_my_values[31] : '';
                            $post_prepend     = isset($array_my_values[32]) ? $array_my_values[32] : '';
                            $post_append      = isset($array_my_values[33]) ? $array_my_values[33] : '';
                            $enable_ai_images = isset($array_my_values[34]) ? $array_my_values[34] : '';
                            $ai_command_image = isset($array_my_values[35]) ? $array_my_values[35] : '';
                            $image_size       = isset($array_my_values[36]) ? $array_my_values[36] : '';
                            $headings_list    = isset($array_my_values[37]) ? $array_my_values[37] : '';
                            $images_list      = isset($array_my_values[38]) ? $array_my_values[38] : '';
                            $wpml_lang        = isset($array_my_values[39]) ? $array_my_values[39] : '';
                            $remove_default   = isset($array_my_values[40]) ? $array_my_values[40] : '';
                            $title_model      = isset($array_my_values[41]) ? $array_my_values[41] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $title_ai_command = isset($array_my_values[42]) ? $array_my_values[42] : '';
                            $strip_title      = isset($array_my_values[43]) ? $array_my_values[43] : '';
                            $title_once       = isset($array_my_values[44]) ? $array_my_values[44] : '';
                            $category_model   = isset($array_my_values[45]) ? $array_my_values[45] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $category_ai_command= isset($array_my_values[46]) ? $array_my_values[46] : '';
                            $tag_model        = isset($array_my_values[47]) ? $array_my_values[47] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $tag_ai_command   = isset($array_my_values[48]) ? $array_my_values[48] : '';
                            $min_time         = isset($array_my_values[49]) ? $array_my_values[49] : '';
                            $max_time         = isset($array_my_values[50]) ? $array_my_values[50] : '';
                            $skip_spin        = isset($array_my_values[51]) ? $array_my_values[51] : '';
                            $skip_translate   = isset($array_my_values[52]) ? $array_my_values[52] : '';
                            $title_source     = isset($array_my_values[53]) ? $array_my_values[53] : '';
                            $headings_ai_command= isset($array_my_values[54]) ? $array_my_values[54] : '';
                            $headings_model   = isset($array_my_values[55]) ? $array_my_values[55] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $posting_mode     = isset($array_my_values[56]) ? $array_my_values[56] : 'topic';
                            $post_topic_list  = isset($array_my_values[57]) ? $array_my_values[57] : '';
                            $post_sections_list= isset($array_my_values[58]) ? $array_my_values[58] : '';
                            $content_language = isset($array_my_values[59]) ? $array_my_values[59] : '';
                            $writing_style    = isset($array_my_values[60]) ? $array_my_values[60] : '';
                            $writing_tone     = isset($array_my_values[61]) ? $array_my_values[61] : '';
                            $title_prompt     = isset($array_my_values[62]) ? $array_my_values[62] : '';
                            $sections_prompt  = isset($array_my_values[63]) ? $array_my_values[63] : '';
                            $content_prompt   = isset($array_my_values[64]) ? $array_my_values[64] : '';
                            $excerpt_prompt   = isset($array_my_values[65]) ? $array_my_values[65] : '';
                            $section_count    = isset($array_my_values[66]) ? $array_my_values[66] : '';
                            $paragraph_count  = isset($array_my_values[67]) ? $array_my_values[67] : '';
                            $topic_title_model = isset($array_my_values[68]) ? $array_my_values[68] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_sections_model  = isset($array_my_values[69]) ? $array_my_values[69] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_content_model  = isset($array_my_values[70]) ? $array_my_values[70] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_excerpt_model  = isset($array_my_values[71]) ? $array_my_values[71] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $single_content_call  = isset($array_my_values[72]) ? $array_my_values[72] : '';
                            $intro_prompt         = isset($array_my_values[73]) ? $array_my_values[73] : '';
                            $topic_intro_model    = isset($array_my_values[74]) ? $array_my_values[74] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $outro_prompt         = isset($array_my_values[75]) ? $array_my_values[75] : '';
                            $topic_outro_model    = isset($array_my_values[76]) ? $array_my_values[76] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_images         = isset($array_my_values[77]) ? $array_my_values[77] : '';
                            $sections_role        = isset($array_my_values[78]) ? $array_my_values[78] : '';
                            $topic_videos         = isset($array_my_values[79]) ? $array_my_values[79] : '';
                            $rule_description     = isset($array_my_values[80]) ? $array_my_values[80] : '';
                            $custom_shortcodes    = isset($array_my_values[81]) ? $array_my_values[81] : '';
                            $strip_by_regex       = isset($array_my_values[82]) ? $array_my_values[82] : '';
                            $replace_regex        = isset($array_my_values[83]) ? $array_my_values[83] : '';
                            $strip_by_regex_prompts= isset($array_my_values[84]) ? $array_my_values[84] : '';
                            $replace_regex_prompts= isset($array_my_values[85]) ? $array_my_values[85] : '';
                            $run_regex_on     = isset($array_my_values[86]) ? $array_my_values[86] : '';
                            $max_links        = isset($array_my_values[87]) ? $array_my_values[87] : '';
                            $link_post_types  = isset($array_my_values[88]) ? $array_my_values[88] : '';
                            $enable_toc       = isset($array_my_values[89]) ? $array_my_values[89] : '';
                            $title_toc        = isset($array_my_values[90]) ? $array_my_values[90] : '';
                            $qa_prompt        = isset($array_my_values[91]) ? $array_my_values[91] : '';
                            $topic_qa_model   = isset($array_my_values[92]) ? $array_my_values[92] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $enable_qa        = isset($array_my_values[93]) ? $array_my_values[93] : '';
                            $title_qa         = isset($array_my_values[94]) ? $array_my_values[94] : '';
                            $title_outro      = isset($array_my_values[95]) ? $array_my_values[95] : '';
                            $link_type        = isset($array_my_values[96]) ? $array_my_values[96] : 'internal';
                            $link_list        = isset($array_my_values[97]) ? $array_my_values[97] : '';
                            $skip_inexist     = isset($array_my_values[98]) ? $array_my_values[98] : '';
                            $global_prepend   = isset($array_my_values[99]) ? $array_my_values[99] : '';
                            $global_append    = isset($array_my_values[100]) ? $array_my_values[100] : '';
                            $search_query_repetition = isset($array_my_values[101]) ? $array_my_values[101] : '';
                            $img_all_headings = isset($array_my_values[102]) ? $array_my_values[102] : '';
                            $heading_img_location = isset($array_my_values[103]) ? $array_my_values[103] : 'bottom';
                            $days_no_run      = isset($array_my_values[104]) ? $array_my_values[104] : '';
                            $overwrite_existing= isset($array_my_values[105]) ? $array_my_values[105] : '';
                            $link_nofollow    = isset($array_my_values[106]) ? $array_my_values[106] : '';
                            $title_generator_method = isset($array_my_values[107]) ? $array_my_values[107] : '';
                            $parent_id        = isset($array_my_values[108]) ? $array_my_values[108] : '';
                            $rule_unique_id   = isset($array_my_values[109]) ? $array_my_values[109] : '';
                            $image_model      = isset($array_my_values[110]) ? $array_my_values[110] : '';
                            $assistant_id     = isset($array_my_values[111]) ? $array_my_values[111] : '';
                            $enable_ai_images_article = isset($array_my_values[112]) ? $array_my_values[112] : '';
                            $ai_command_image_article = isset($array_my_values[113]) ? $array_my_values[113] : '';
                            $image_model_article = isset($array_my_values[114]) ? $array_my_values[114] : '';
                            $image_size_article = isset($array_my_values[115]) ? $array_my_values[115] : '';
                            $found            = 1;
                            break;
                        }
                        $cont = $cont + 1;
                    }
                } else {
                    aiomatic_log_to_file('No rules found for aiomatic_rules_list!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
            }
            elseif($type == 1)
            {
                if($rules === null)
                {
                    $GLOBALS['wp_object_cache']->delete('aiomatic_youtube_list', 'options');
                    if (!get_option('aiomatic_youtube_list')) {
                        $rules = array();
                    } else {
                        $rules = get_option('aiomatic_youtube_list');
                    }
                }
                if (!empty($rules)) {
                    foreach ($rules as $request => $bundle[]) {
                        if ($cont == $param) {
                            $bundle_values    = array_values($bundle);
                            $myValues         = $bundle_values[$cont];
                            $array_my_values  = array_values($myValues);for($iji=0;$iji<count($array_my_values);++$iji){if(is_string($array_my_values[$iji])){$array_my_values[$iji]=stripslashes($array_my_values[$iji]);}}
                            $schedule         = isset($array_my_values[0]) ? $array_my_values[0] : '';
                            $active           = isset($array_my_values[1]) ? $array_my_values[1] : '';
                            $last_run         = isset($array_my_values[2]) ? $array_my_values[2] : '';
                            $max              = isset($array_my_values[3]) ? $array_my_values[3] : '';
                            $post_status      = isset($array_my_values[4]) ? $array_my_values[4] : '';
                            $post_type        = isset($array_my_values[5]) ? $array_my_values[5] : '';
                            $post_user_name   = isset($array_my_values[6]) ? $array_my_values[6] : '';
                            $item_create_tag  = isset($array_my_values[7]) ? $array_my_values[7] : '';
                            $default_category = isset($array_my_values[8]) ? $array_my_values[8] : '';
                            $auto_categories  = isset($array_my_values[9]) ? $array_my_values[9] : '';
                            $can_create_tag   = isset($array_my_values[10]) ? $array_my_values[10] : '';
                            $enable_comments  = isset($array_my_values[11]) ? $array_my_values[11] : '';
                            $image_url        = isset($array_my_values[12]) ? $array_my_values[12] : '';
                            $url_list         = isset($array_my_values[13]) ? $array_my_values[13] : '';
                            $enable_pingback  = isset($array_my_values[14]) ? $array_my_values[14] : '';
                            $post_format      = isset($array_my_values[15]) ? $array_my_values[15] : '';
                            $custom_fields    = isset($array_my_values[16]) ? $array_my_values[16] : '';
                            $custom_tax       = isset($array_my_values[17]) ? $array_my_values[17] : '';
                            $temperature      = isset($array_my_values[18]) ? $array_my_values[18] : '';
                            $top_p            = isset($array_my_values[19]) ? $array_my_values[19] : '';
                            $presence_penalty = isset($array_my_values[20]) ? $array_my_values[20] : '';
                            $frequency_penalty = isset($array_my_values[21]) ? $array_my_values[21] : '';
                            $royalty_free     = isset($array_my_values[22]) ? $array_my_values[22] : '';
                            $max_tokens       = isset($array_my_values[23]) ? $array_my_values[23] : '';
                            $max_seed_tokens  = isset($array_my_values[24]) ? $array_my_values[24] : AIMOGEN_DEFAULT_COMPLETION_TOKENS;
                            $max_continue_tokens= isset($array_my_values[25]) ? $array_my_values[25] : AIMOGEN_DEFAULT_COMPLETION_TOKENS;
                            $post_prepend     = isset($array_my_values[26]) ? $array_my_values[26] : '';
                            $post_append      = isset($array_my_values[27]) ? $array_my_values[27] : '';
                            $enable_ai_images = isset($array_my_values[28]) ? $array_my_values[28] : '';
                            $ai_command_image = isset($array_my_values[29]) ? $array_my_values[29] : '';
                            $image_size       = isset($array_my_values[30]) ? $array_my_values[30] : '';
                            $wpml_lang        = isset($array_my_values[31]) ? $array_my_values[31] : '';
                            $remove_default   = isset($array_my_values[32]) ? $array_my_values[32] : '';
                            $strip_title      = isset($array_my_values[33]) ? $array_my_values[33] : '';
                            $title_once       = isset($array_my_values[34]) ? $array_my_values[34] : '';
                            $category_model   = isset($array_my_values[35]) ? $array_my_values[35] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $category_ai_command= isset($array_my_values[36]) ? $array_my_values[36] : '';
                            $tag_model        = isset($array_my_values[37]) ? $array_my_values[37] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $tag_ai_command   = isset($array_my_values[38]) ? $array_my_values[38] : '';
                            $min_time         = isset($array_my_values[39]) ? $array_my_values[39] : '';
                            $max_time         = isset($array_my_values[40]) ? $array_my_values[40] : '';
                            $skip_spin        = isset($array_my_values[41]) ? $array_my_values[41] : '';
                            $skip_translate   = isset($array_my_values[42]) ? $array_my_values[42] : '';
                            $default_lang     = isset($array_my_values[43]) ? $array_my_values[43] : '';
                            $ai_titles        = isset($array_my_values[44]) ? $array_my_values[44] : '';
                            $post_sections_list= isset($array_my_values[45]) ? $array_my_values[45] : '';
                            $content_language = isset($array_my_values[46]) ? $array_my_values[46] : '';
                            $writing_style    = isset($array_my_values[47]) ? $array_my_values[47] : '';
                            $writing_tone     = isset($array_my_values[48]) ? $array_my_values[48] : '';
                            $title_prompt     = isset($array_my_values[49]) ? $array_my_values[49] : '';
                            $sections_prompt  = isset($array_my_values[50]) ? $array_my_values[50] : '';
                            $content_prompt   = isset($array_my_values[51]) ? $array_my_values[51] : '';
                            $excerpt_prompt   = isset($array_my_values[52]) ? $array_my_values[52] : '';
                            $section_count    = isset($array_my_values[53]) ? $array_my_values[53] : '';
                            $paragraph_count  = isset($array_my_values[54]) ? $array_my_values[54] : '';
                            $topic_title_model = isset($array_my_values[55]) ? $array_my_values[55] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_sections_model  = isset($array_my_values[56]) ? $array_my_values[56] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_content_model  = isset($array_my_values[57]) ? $array_my_values[57] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_excerpt_model  = isset($array_my_values[58]) ? $array_my_values[58] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $single_content_call  = isset($array_my_values[59]) ? $array_my_values[59] : '';
                            $intro_prompt         = isset($array_my_values[60]) ? $array_my_values[60] : '';
                            $topic_intro_model    = isset($array_my_values[61]) ? $array_my_values[61] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $outro_prompt         = isset($array_my_values[62]) ? $array_my_values[62] : '';
                            $topic_outro_model    = isset($array_my_values[63]) ? $array_my_values[63] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_images         = isset($array_my_values[64]) ? $array_my_values[64] : '';
                            $sections_role        = isset($array_my_values[65]) ? $array_my_values[65] : '';
                            $topic_videos         = isset($array_my_values[66]) ? $array_my_values[66] : '';
                            $rule_description     = isset($array_my_values[67]) ? $array_my_values[67] : '';
                            $custom_shortcodes    = isset($array_my_values[68]) ? $array_my_values[68] : '';
                            $strip_by_regex       = isset($array_my_values[69]) ? $array_my_values[69] : '';
                            $replace_regex        = isset($array_my_values[70]) ? $array_my_values[70] : '';
                            $strip_by_regex_prompts= isset($array_my_values[71]) ? $array_my_values[71] : '';
                            $replace_regex_prompts= isset($array_my_values[72]) ? $array_my_values[72] : '';
                            $run_regex_on     = isset($array_my_values[73]) ? $array_my_values[73] : '';
                            $max_links        = isset($array_my_values[74]) ? $array_my_values[74] : '';
                            $link_post_types  = isset($array_my_values[75]) ? $array_my_values[75] : '';
                            $enable_toc       = isset($array_my_values[76]) ? $array_my_values[76] : '';
                            $title_toc        = isset($array_my_values[77]) ? $array_my_values[77] : '';
                            $qa_prompt        = isset($array_my_values[78]) ? $array_my_values[78] : '';
                            $topic_qa_model   = isset($array_my_values[79]) ? $array_my_values[79] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $enable_qa        = isset($array_my_values[80]) ? $array_my_values[80] : '';
                            $title_qa         = isset($array_my_values[81]) ? $array_my_values[81] : '';
                            $title_outro      = isset($array_my_values[82]) ? $array_my_values[82] : '';
                            $link_type        = isset($array_my_values[83]) ? $array_my_values[83] : 'internal';
                            $link_list        = isset($array_my_values[84]) ? $array_my_values[84] : '';
                            $skip_inexist     = isset($array_my_values[85]) ? $array_my_values[85] : '';
                            $max_caption      = isset($array_my_values[86]) ? $array_my_values[86] : '';
                            $global_prepend   = isset($array_my_values[87]) ? $array_my_values[87] : '';
                            $global_append    = isset($array_my_values[88]) ? $array_my_values[88] : '';
                            $search_query_repetition = isset($array_my_values[89]) ? $array_my_values[89] : '';
                            $img_all_headings = isset($array_my_values[90]) ? $array_my_values[90] : '';
                            $heading_img_location = isset($array_my_values[91]) ? $array_my_values[91] : 'bottom';
                            $days_no_run      = isset($array_my_values[92]) ? $array_my_values[92] : '';
                            $no_random        = isset($array_my_values[93]) ? $array_my_values[93] : '';
                            $overwrite_existing= isset($array_my_values[94]) ? $array_my_values[94] : '';
                            $link_nofollow    = isset($array_my_values[95]) ? $array_my_values[95] : '';
                            $parent_id        = isset($array_my_values[96]) ? $array_my_values[96] : '';
                            $rule_unique_id   = isset($array_my_values[97]) ? $array_my_values[97] : '';
                            $image_model      = isset($array_my_values[98]) ? $array_my_values[98] : '';
                            $assistant_id     = isset($array_my_values[99]) ? $array_my_values[99] : '';
                            $found            = 1;
                            break;
                        }
                        $cont = $cont + 1;
                    }
                } else {
                    aiomatic_log_to_file('No rules found for aiomatic_youtube_list!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
            }
            elseif($type == 2)
            {
                if($rules === null)
                {
                    $GLOBALS['wp_object_cache']->delete('aiomatic_amazon_list', 'options');
                    if (!get_option('aiomatic_amazon_list')) {
                        $rules = array();
                    } else {
                        $rules = get_option('aiomatic_amazon_list');
                    }
                }
                if (!empty($rules)) {
                    foreach ($rules as $request => $bundle[]) {
                        if ($cont == $param) {
                            $bundle_values    = array_values($bundle);
                            $myValues         = $bundle_values[$cont];
                            $array_my_values  = array_values($myValues);for($iji=0;$iji<count($array_my_values);++$iji){if(is_string($array_my_values[$iji])){$array_my_values[$iji]=stripslashes($array_my_values[$iji]);}}
                            $schedule         = isset($array_my_values[0]) ? $array_my_values[0] : '';
                            $active           = isset($array_my_values[1]) ? $array_my_values[1] : '';
                            $last_run         = isset($array_my_values[2]) ? $array_my_values[2] : '';
                            $max              = isset($array_my_values[3]) ? $array_my_values[3] : '';
                            $post_status      = isset($array_my_values[4]) ? $array_my_values[4] : '';
                            $post_type        = isset($array_my_values[5]) ? $array_my_values[5] : '';
                            $post_user_name   = isset($array_my_values[6]) ? $array_my_values[6] : '';
                            $item_create_tag  = isset($array_my_values[7]) ? $array_my_values[7] : '';
                            $default_category = isset($array_my_values[8]) ? $array_my_values[8] : '';
                            $auto_categories  = isset($array_my_values[9]) ? $array_my_values[9] : '';
                            $can_create_tag   = isset($array_my_values[10]) ? $array_my_values[10] : '';
                            $enable_comments  = isset($array_my_values[11]) ? $array_my_values[11] : '';
                            $image_url        = isset($array_my_values[12]) ? $array_my_values[12] : '';
                            $amazon_keyword   = isset($array_my_values[13]) ? $array_my_values[13] : '';
                            $enable_pingback  = isset($array_my_values[14]) ? $array_my_values[14] : '';
                            $post_format      = isset($array_my_values[15]) ? $array_my_values[15] : '';
                            $custom_fields    = isset($array_my_values[16]) ? $array_my_values[16] : '';
                            $custom_tax       = isset($array_my_values[17]) ? $array_my_values[17] : '';
                            $temperature      = isset($array_my_values[18]) ? $array_my_values[18] : '';
                            $top_p            = isset($array_my_values[19]) ? $array_my_values[19] : '';
                            $presence_penalty = isset($array_my_values[20]) ? $array_my_values[20] : '';
                            $frequency_penalty = isset($array_my_values[21]) ? $array_my_values[21] : '';
                            $royalty_free     = isset($array_my_values[22]) ? $array_my_values[22] : '';
                            $max_tokens       = isset($array_my_values[23]) ? $array_my_values[23] : '';
                            $max_seed_tokens  = isset($array_my_values[24]) ? $array_my_values[24] : AIMOGEN_DEFAULT_COMPLETION_TOKENS;
                            $max_continue_tokens= isset($array_my_values[25]) ? $array_my_values[25] : AIMOGEN_DEFAULT_COMPLETION_TOKENS;
                            $post_prepend     = isset($array_my_values[26]) ? $array_my_values[26] : '';
                            $post_append      = isset($array_my_values[27]) ? $array_my_values[27] : '';
                            $enable_ai_images = isset($array_my_values[28]) ? $array_my_values[28] : '';
                            $ai_command_image = isset($array_my_values[29]) ? $array_my_values[29] : '';
                            $image_size       = isset($array_my_values[30]) ? $array_my_values[30] : '';
                            $wpml_lang        = isset($array_my_values[31]) ? $array_my_values[31] : '';
                            $remove_default   = isset($array_my_values[32]) ? $array_my_values[32] : '';
                            $strip_title      = isset($array_my_values[33]) ? $array_my_values[33] : '';
                            $title_once       = isset($array_my_values[34]) ? $array_my_values[34] : '';
                            $category_model   = isset($array_my_values[35]) ? $array_my_values[35] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $category_ai_command= isset($array_my_values[36]) ? $array_my_values[36] : '';
                            $tag_model        = isset($array_my_values[37]) ? $array_my_values[37] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $tag_ai_command   = isset($array_my_values[38]) ? $array_my_values[38] : '';
                            $min_time         = isset($array_my_values[39]) ? $array_my_values[39] : '';
                            $max_time         = isset($array_my_values[40]) ? $array_my_values[40] : '';
                            $skip_spin        = isset($array_my_values[41]) ? $array_my_values[41] : '';
                            $skip_translate   = isset($array_my_values[42]) ? $array_my_values[42] : '';
                            $affiliate_id     = isset($array_my_values[43]) ? $array_my_values[43] : '';
                            $first_hand       = isset($array_my_values[44]) ? $array_my_values[44] : '';
                            $content_language = isset($array_my_values[45]) ? $array_my_values[45] : '';
                            $writing_style    = isset($array_my_values[46]) ? $array_my_values[46] : '';
                            $writing_tone     = isset($array_my_values[47]) ? $array_my_values[47] : '';
                            $title_prompt     = isset($array_my_values[48]) ? $array_my_values[48] : '';
                            $content_prompt   = isset($array_my_values[49]) ? $array_my_values[49] : '';
                            $excerpt_prompt   = isset($array_my_values[50]) ? $array_my_values[50] : '';
                            $max_products     = isset($array_my_values[51]) ? $array_my_values[51] : '';
                            $paragraph_count  = isset($array_my_values[52]) ? $array_my_values[52] : '';
                            $topic_title_model = isset($array_my_values[53]) ? $array_my_values[53] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_content_model  = isset($array_my_values[54]) ? $array_my_values[54] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_excerpt_model  = isset($array_my_values[55]) ? $array_my_values[55] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $intro_prompt         = isset($array_my_values[56]) ? $array_my_values[56] : '';
                            $topic_intro_model    = isset($array_my_values[57]) ? $array_my_values[57] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $outro_prompt         = isset($array_my_values[58]) ? $array_my_values[58] : '';
                            $topic_outro_model    = isset($array_my_values[59]) ? $array_my_values[59] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_images         = isset($array_my_values[60]) ? $array_my_values[60] : '';
                            $sections_role        = isset($array_my_values[61]) ? $array_my_values[61] : '';
                            $topic_videos         = isset($array_my_values[62]) ? $array_my_values[62] : '';
                            $rule_description     = isset($array_my_values[63]) ? $array_my_values[63] : '';
                            $custom_shortcodes    = isset($array_my_values[64]) ? $array_my_values[64] : '';
                            $strip_by_regex   = isset($array_my_values[65]) ? $array_my_values[65] : '';
                            $replace_regex    = isset($array_my_values[66]) ? $array_my_values[66] : '';
                            $strip_by_regex_prompts= isset($array_my_values[67]) ? $array_my_values[67] : '';
                            $replace_regex_prompts= isset($array_my_values[68]) ? $array_my_values[68] : '';
                            $run_regex_on     = isset($array_my_values[69]) ? $array_my_values[69] : '';
                            $max_links        = isset($array_my_values[70]) ? $array_my_values[70] : '';
                            $link_post_types  = isset($array_my_values[71]) ? $array_my_values[71] : '';
                            $enable_toc       = isset($array_my_values[72]) ? $array_my_values[72] : '';
                            $title_toc        = isset($array_my_values[73]) ? $array_my_values[73] : '';
                            $qa_prompt        = isset($array_my_values[74]) ? $array_my_values[74] : '';
                            $topic_qa_model   = isset($array_my_values[75]) ? $array_my_values[75] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $enable_qa        = isset($array_my_values[76]) ? $array_my_values[76] : '';
                            $title_qa         = isset($array_my_values[77]) ? $array_my_values[77] : '';
                            $title_outro      = isset($array_my_values[78]) ? $array_my_values[78] : '';
                            $link_type        = isset($array_my_values[79]) ? $array_my_values[79] : 'internal';
                            $link_list        = isset($array_my_values[80]) ? $array_my_values[80] : '';
                            $skip_inexist     = isset($array_my_values[81]) ? $array_my_values[81] : '';
                            $target_country   = isset($array_my_values[82]) ? $array_my_values[82] : '';
                            $min_price        = isset($array_my_values[83]) ? $array_my_values[83] : '';
                            $max_price        = isset($array_my_values[84]) ? $array_my_values[84] : '';
                            $sort_results     = isset($array_my_values[85]) ? $array_my_values[85] : '';
                            $shuffle_products = isset($array_my_values[86]) ? $array_my_values[86] : '';
                            $global_prepend   = isset($array_my_values[87]) ? $array_my_values[87] : '';
                            $global_append    = isset($array_my_values[88]) ? $array_my_values[88] : '';
                            $search_query_repetition = isset($array_my_values[89]) ? $array_my_values[89] : '';
                            $days_no_run      = isset($array_my_values[90]) ? $array_my_values[90] : '';
                            $overwrite_existing= isset($array_my_values[91]) ? $array_my_values[91] : '';
                            $link_nofollow    = isset($array_my_values[92]) ? $array_my_values[92] : '';
                            $parent_id        = isset($array_my_values[93]) ? $array_my_values[93] : '';
                            $rule_unique_id   = isset($array_my_values[94]) ? $array_my_values[94] : '';
                            $no_headlink      = isset($array_my_values[95]) ? $array_my_values[95] : '';
                            $enable_table     = isset($array_my_values[96]) ? $array_my_values[96] : '';
                            $table_prompt     = isset($array_my_values[97]) ? $array_my_values[97] : '';
                            $topic_table_model= isset($array_my_values[98]) ? $array_my_values[98] : '';
                            $image_model      = isset($array_my_values[99]) ? $array_my_values[99] : '';
                            $assistant_id     = isset($array_my_values[100]) ? $array_my_values[100] : '';
                            $product_source   = isset($array_my_values[101]) ? $array_my_values[101] : '';
                            $neg_keywords     = isset($array_my_values[102]) ? $array_my_values[102] : '';
                            $item_category    = isset($array_my_values[103]) ? $array_my_values[103] : '';
                            $one_time         = isset($array_my_values[104]) ? $array_my_values[104] : '';
                            $recurring        = isset($array_my_values[105]) ? $array_my_values[105] : '';
                            $affiliate_tools  = isset($array_my_values[106]) ? $array_my_values[106] : '';
                            $spotlight        = isset($array_my_values[107]) ? $array_my_values[107] : '';
                            $mobile_hoplink   = isset($array_my_values[108]) ? $array_my_values[108] : '';
                            $shipable_only    = isset($array_my_values[109]) ? $array_my_values[109] : '';
                            $pitch_plus       = isset($array_my_values[110]) ? $array_my_values[110] : '';
                            $item_gravity     = isset($array_my_values[111]) ? $array_my_values[111] : '';
                            $dollar_sale      = isset($array_my_values[112]) ? $array_my_values[112] : '';
                            $dollar_sale_av   = isset($array_my_values[113]) ? $array_my_values[113] : '';
                            $rebill_total     = isset($array_my_values[114]) ? $array_my_values[114] : '';
                            $per_sale         = isset($array_my_values[115]) ? $array_my_values[115] : '';
                            $per_rebill       = isset($array_my_values[116]) ? $array_my_values[116] : '';
                            $item_language    = isset($array_my_values[117]) ? $array_my_values[117] : '';
                            $sort_results_cb  = isset($array_my_values[118]) ? $array_my_values[118] : '';
                            $activation       = isset($array_my_values[119]) ? $array_my_values[119] : '';
                            $cb_affiliate_id  = isset($array_my_values[120]) ? $array_my_values[120] : '';
                            $max_products_cb  = isset($array_my_values[121]) ? $array_my_values[121] : '';
                            $found            = 1;
                            break;
                        }
                        $cont = $cont + 1;
                    }
                } else {
                    aiomatic_log_to_file('No rules found for aiomatic_amazon_list!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
            }
            elseif($type == 3)
            {
                if($rules === null)
                {
                    $GLOBALS['wp_object_cache']->delete('aiomatic_review_list', 'options');
                    if (!get_option('aiomatic_review_list')) {
                        $rules = array();
                    } else {
                        $rules = get_option('aiomatic_review_list');
                    }
                }
                if (!empty($rules)) {
                    foreach ($rules as $request => $bundle[]) {
                        if ($cont == $param) {
                            $bundle_values    = array_values($bundle);
                            $myValues         = $bundle_values[$cont];
                            $array_my_values  = array_values($myValues);for($iji=0;$iji<count($array_my_values);++$iji){if(is_string($array_my_values[$iji])){$array_my_values[$iji]=stripslashes($array_my_values[$iji]);}}
                            $schedule         = isset($array_my_values[0]) ? $array_my_values[0] : '';
                            $active           = isset($array_my_values[1]) ? $array_my_values[1] : '';
                            $last_run         = isset($array_my_values[2]) ? $array_my_values[2] : '';
                            $max              = isset($array_my_values[3]) ? $array_my_values[3] : '';
                            $post_status      = isset($array_my_values[4]) ? $array_my_values[4] : '';
                            $post_type        = isset($array_my_values[5]) ? $array_my_values[5] : '';
                            $post_user_name   = isset($array_my_values[6]) ? $array_my_values[6] : '';
                            $item_create_tag  = isset($array_my_values[7]) ? $array_my_values[7] : '';
                            $default_category = isset($array_my_values[8]) ? $array_my_values[8] : '';
                            $auto_categories  = isset($array_my_values[9]) ? $array_my_values[9] : '';
                            $can_create_tag   = isset($array_my_values[10]) ? $array_my_values[10] : '';
                            $enable_comments  = isset($array_my_values[11]) ? $array_my_values[11] : '';
                            $image_url        = isset($array_my_values[12]) ? $array_my_values[12] : '';
                            $amazon_keyword   = isset($array_my_values[13]) ? $array_my_values[13] : '';
                            $enable_pingback  = isset($array_my_values[14]) ? $array_my_values[14] : '';
                            $post_format      = isset($array_my_values[15]) ? $array_my_values[15] : '';
                            $custom_fields    = isset($array_my_values[16]) ? $array_my_values[16] : '';
                            $custom_tax       = isset($array_my_values[17]) ? $array_my_values[17] : '';
                            $temperature      = isset($array_my_values[18]) ? $array_my_values[18] : '';
                            $top_p            = isset($array_my_values[19]) ? $array_my_values[19] : '';
                            $presence_penalty = isset($array_my_values[20]) ? $array_my_values[20] : '';
                            $frequency_penalty = isset($array_my_values[21]) ? $array_my_values[21] : '';
                            $royalty_free     = isset($array_my_values[22]) ? $array_my_values[22] : '';
                            $max_tokens       = isset($array_my_values[23]) ? $array_my_values[23] : '';
                            $max_seed_tokens  = isset($array_my_values[24]) ? $array_my_values[24] : AIMOGEN_DEFAULT_COMPLETION_TOKENS;
                            $max_continue_tokens= isset($array_my_values[25]) ? $array_my_values[25] : AIMOGEN_DEFAULT_COMPLETION_TOKENS;
                            $post_prepend     = isset($array_my_values[26]) ? $array_my_values[26] : '';
                            $post_append      = isset($array_my_values[27]) ? $array_my_values[27] : '';
                            $enable_ai_images = isset($array_my_values[28]) ? $array_my_values[28] : '';
                            $ai_command_image = isset($array_my_values[29]) ? $array_my_values[29] : '';
                            $image_size       = isset($array_my_values[30]) ? $array_my_values[30] : '';
                            $wpml_lang        = isset($array_my_values[31]) ? $array_my_values[31] : '';
                            $remove_default   = isset($array_my_values[32]) ? $array_my_values[32] : '';
                            $strip_title      = isset($array_my_values[33]) ? $array_my_values[33] : '';
                            $title_once       = isset($array_my_values[34]) ? $array_my_values[34] : '';
                            $category_model   = isset($array_my_values[35]) ? $array_my_values[35] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $category_ai_command= isset($array_my_values[36]) ? $array_my_values[36] : '';
                            $tag_model        = isset($array_my_values[37]) ? $array_my_values[37] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $tag_ai_command   = isset($array_my_values[38]) ? $array_my_values[38] : '';
                            $min_time         = isset($array_my_values[39]) ? $array_my_values[39] : '';
                            $max_time         = isset($array_my_values[40]) ? $array_my_values[40] : '';
                            $skip_spin        = isset($array_my_values[41]) ? $array_my_values[41] : '';
                            $skip_translate   = isset($array_my_values[42]) ? $array_my_values[42] : '';
                            $affiliate_id     = isset($array_my_values[43]) ? $array_my_values[43] : '';
                            $content_language = isset($array_my_values[44]) ? $array_my_values[44] : '';
                            $writing_style    = isset($array_my_values[45]) ? $array_my_values[45] : '';
                            $writing_tone     = isset($array_my_values[46]) ? $array_my_values[46] : '';
                            $title_prompt     = isset($array_my_values[47]) ? $array_my_values[47] : '';
                            $content_prompt   = isset($array_my_values[48]) ? $array_my_values[48] : '';
                            $excerpt_prompt   = isset($array_my_values[49]) ? $array_my_values[49] : '';
                            $paragraph_count  = isset($array_my_values[50]) ? $array_my_values[50] : '';
                            $topic_title_model = isset($array_my_values[51]) ? $array_my_values[51] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_content_model  = isset($array_my_values[52]) ? $array_my_values[52] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_excerpt_model  = isset($array_my_values[53]) ? $array_my_values[53] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $intro_prompt         = isset($array_my_values[54]) ? $array_my_values[54] : '';
                            $topic_intro_model    = isset($array_my_values[55]) ? $array_my_values[55] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $outro_prompt         = isset($array_my_values[56]) ? $array_my_values[56] : '';
                            $topic_outro_model    = isset($array_my_values[57]) ? $array_my_values[57] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_images         = isset($array_my_values[58]) ? $array_my_values[58] : '';
                            $sections_role        = isset($array_my_values[59]) ? $array_my_values[59] : '';
                            $topic_videos         = isset($array_my_values[60]) ? $array_my_values[60] : '';
                            $rule_description     = isset($array_my_values[61]) ? $array_my_values[61] : '';
                            $custom_shortcodes    = isset($array_my_values[62]) ? $array_my_values[62] : '';
                            $strip_by_regex   = isset($array_my_values[63]) ? $array_my_values[63] : '';
                            $replace_regex    = isset($array_my_values[64]) ? $array_my_values[64] : '';
                            $strip_by_regex_prompts= isset($array_my_values[65]) ? $array_my_values[65] : '';
                            $replace_regex_prompts= isset($array_my_values[66]) ? $array_my_values[66] : '';
                            $run_regex_on     = isset($array_my_values[67]) ? $array_my_values[67] : '';
                            $max_links        = isset($array_my_values[68]) ? $array_my_values[68] : '';
                            $link_post_types  = isset($array_my_values[69]) ? $array_my_values[69] : '';
                            $enable_toc       = isset($array_my_values[70]) ? $array_my_values[70] : '';
                            $title_toc        = isset($array_my_values[71]) ? $array_my_values[71] : '';
                            $qa_prompt        = isset($array_my_values[72]) ? $array_my_values[72] : '';
                            $topic_qa_model   = isset($array_my_values[73]) ? $array_my_values[73] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $enable_qa        = isset($array_my_values[74]) ? $array_my_values[74] : '';
                            $title_qa         = isset($array_my_values[75]) ? $array_my_values[75] : '';
                            $title_outro      = isset($array_my_values[76]) ? $array_my_values[76] : '';
                            $link_type        = isset($array_my_values[77]) ? $array_my_values[77] : 'internal';
                            $link_list        = isset($array_my_values[78]) ? $array_my_values[78] : '';
                            $skip_inexist     = isset($array_my_values[79]) ? $array_my_values[79] : '';
                            $target_country   = isset($array_my_values[80]) ? $array_my_values[80] : '';
                            $global_prepend   = isset($array_my_values[81]) ? $array_my_values[81] : '';
                            $global_append    = isset($array_my_values[82]) ? $array_my_values[82] : '';
                            $search_query_repetition = isset($array_my_values[83]) ? $array_my_values[83] : '';
                            $days_no_run      = isset($array_my_values[84]) ? $array_my_values[84] : '';
                            $overwrite_existing= isset($array_my_values[85]) ? $array_my_values[85] : '';
                            $link_nofollow    = isset($array_my_values[86]) ? $array_my_values[86] : '';
                            $parent_id        = isset($array_my_values[87]) ? $array_my_values[87] : '';
                            $rule_unique_id   = isset($array_my_values[88]) ? $array_my_values[88] : '';
                            $point_of_view    = isset($array_my_values[89]) ? $array_my_values[89] : '';
                            $sections_prompt  = isset($array_my_values[90]) ? $array_my_values[90] : '';
                            $topic_sections_model= isset($array_my_values[91]) ? $array_my_values[91] : '';
                            $post_sections_list= isset($array_my_values[92]) ? $array_my_values[92] : '';
                            $section_count    = isset($array_my_values[93]) ? $array_my_values[93] : '';
                            $proscons_prompt  = isset($array_my_values[94]) ? $array_my_values[94] : '';
                            $topic_proscons_model= isset($array_my_values[95]) ? $array_my_values[95] : '';
                            $title_proscons   = isset($array_my_values[96]) ? $array_my_values[96] : '';
                            $enable_proscons  = isset($array_my_values[97]) ? $array_my_values[97] : '';
                            $title_reviews    = isset($array_my_values[98]) ? $array_my_values[98] : '';
                            $enable_reviews   = isset($array_my_values[99]) ? $array_my_values[99] : '';
                            $reviews_prompt   = isset($array_my_values[100]) ? $array_my_values[100] : '';
                            $topic_reviews_model= isset($array_my_values[101]) ? $array_my_values[101] : '';
                            $no_headlink      = isset($array_my_values[102]) ? $array_my_values[102] : '';
                            $image_model      = isset($array_my_values[103]) ? $array_my_values[103] : '';
                            $assistant_id     = isset($array_my_values[104]) ? $array_my_values[104] : '';
                            $product_source   = isset($array_my_values[105]) ? $array_my_values[105] : '';
                            $neg_keywords     = isset($array_my_values[106]) ? $array_my_values[106] : '';
                            $item_category    = isset($array_my_values[107]) ? $array_my_values[107] : '';
                            $one_time         = isset($array_my_values[108]) ? $array_my_values[108] : '';
                            $recurring        = isset($array_my_values[109]) ? $array_my_values[109] : '';
                            $affiliate_tools  = isset($array_my_values[110]) ? $array_my_values[110] : '';
                            $spotlight        = isset($array_my_values[111]) ? $array_my_values[111] : '';
                            $mobile_hoplink   = isset($array_my_values[112]) ? $array_my_values[112] : '';
                            $shipable_only    = isset($array_my_values[113]) ? $array_my_values[113] : '';
                            $pitch_plus       = isset($array_my_values[114]) ? $array_my_values[114] : '';
                            $item_gravity     = isset($array_my_values[115]) ? $array_my_values[115] : '';
                            $dollar_sale      = isset($array_my_values[116]) ? $array_my_values[116] : '';
                            $dollar_sale_av   = isset($array_my_values[117]) ? $array_my_values[117] : '';
                            $rebill_total     = isset($array_my_values[118]) ? $array_my_values[118] : '';
                            $per_sale         = isset($array_my_values[119]) ? $array_my_values[119] : '';
                            $per_rebill       = isset($array_my_values[120]) ? $array_my_values[120] : '';
                            $item_language    = isset($array_my_values[121]) ? $array_my_values[121] : '';
                            $sort_results_cb  = isset($array_my_values[122]) ? $array_my_values[122] : '';
                            $activation       = isset($array_my_values[123]) ? $array_my_values[123] : '';
                            $cb_affiliate_id  = isset($array_my_values[124]) ? $array_my_values[124] : '';
                            $found            = 1;
                            break;
                        }
                        $cont = $cont + 1;
                    }
                } else {
                    aiomatic_log_to_file('No rules found for aiomatic_review_list!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
            }
            elseif($type == 4)
            {
                if($rules === null)
                {
                    $GLOBALS['wp_object_cache']->delete('aiomatic_csv_list', 'options');
                    if (!get_option('aiomatic_csv_list')) {
                        $rules = array();
                    } else {
                        $rules = get_option('aiomatic_csv_list');
                    }
                }
                if (!empty($rules)) {
                    foreach ($rules as $request => $bundle[]) {
                        if ($cont == $param) {
                            $bundle_values    = array_values($bundle);
                            $myValues         = $bundle_values[$cont];
                            $array_my_values  = array_values($myValues);for($iji=0;$iji<count($array_my_values);++$iji){if(is_string($array_my_values[$iji])){$array_my_values[$iji]=stripslashes($array_my_values[$iji]);}}
                            $schedule         = isset($array_my_values[0]) ? $array_my_values[0] : '';
                            $active           = isset($array_my_values[1]) ? $array_my_values[1] : '';
                            $last_run         = isset($array_my_values[2]) ? $array_my_values[2] : '';
                            $max              = isset($array_my_values[3]) ? $array_my_values[3] : '';
                            $post_status      = isset($array_my_values[4]) ? $array_my_values[4] : '';
                            $post_type        = isset($array_my_values[5]) ? $array_my_values[5] : '';
                            $post_user_name   = isset($array_my_values[6]) ? $array_my_values[6] : '';
                            $enable_comments  = isset($array_my_values[7]) ? $array_my_values[7] : '';
                            $post_title       = isset($array_my_values[8]) ? htmlspecialchars_decode($array_my_values[8]) : '';
                            $enable_pingback  = isset($array_my_values[9]) ? $array_my_values[9] : '';
                            $post_format      = isset($array_my_values[10]) ? $array_my_values[10] : '';
                            $custom_fields    = isset($array_my_values[11]) ? $array_my_values[11] : '';
                            $custom_tax       = isset($array_my_values[12]) ? $array_my_values[12] : '';
                            $wpml_lang        = isset($array_my_values[13]) ? $array_my_values[13] : '';
                            $strip_title      = isset($array_my_values[14]) ? $array_my_values[14] : '';
                            $title_once       = isset($array_my_values[15]) ? $array_my_values[15] : '';
                            $min_time         = isset($array_my_values[16]) ? $array_my_values[16] : '';
                            $max_time         = isset($array_my_values[17]) ? $array_my_values[17] : '';
                            $skip_spin        = isset($array_my_values[18]) ? $array_my_values[18] : '';
                            $skip_translate   = isset($array_my_values[19]) ? $array_my_values[19] : '';
                            $rule_description     = isset($array_my_values[20]) ? $array_my_values[20] : '';
                            $strip_by_regex       = isset($array_my_values[21]) ? $array_my_values[21] : '';
                            $replace_regex        = isset($array_my_values[22]) ? $array_my_values[22] : '';
                            $max_links        = isset($array_my_values[23]) ? $array_my_values[23] : '';
                            $link_post_types  = isset($array_my_values[24]) ? $array_my_values[24] : '';
                            $link_type        = isset($array_my_values[25]) ? $array_my_values[25] : 'internal';
                            $link_list        = isset($array_my_values[26]) ? $array_my_values[26] : '';
                            $days_no_run      = isset($array_my_values[27]) ? $array_my_values[27] : '';
                            $overwrite_existing= isset($array_my_values[28]) ? $array_my_values[28] : '';
                            $link_nofollow    = isset($array_my_values[29]) ? $array_my_values[29] : '';
                            $parent_id        = isset($array_my_values[30]) ? $array_my_values[30] : '';
                            $rule_unique_id   = isset($array_my_values[31]) ? $array_my_values[31] : '';
                            $remove_default   = isset($array_my_values[32]) ? $array_my_values[32] : '';
                            $random_order     = isset($array_my_values[33]) ? $array_my_values[33] : '';
                            $csv_separator    = isset($array_my_values[34]) ? $array_my_values[34] : '';
                            $found            = 1;
                            break;
                        }
                        $cont = $cont + 1;
                    }
                } else {
                    aiomatic_log_to_file('No rules found for aiomatic_csv_list!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
            }
            elseif($type == 5)
            {
                if($rules === null)
                {
                    $GLOBALS['wp_object_cache']->delete('aiomatic_omni_list', 'options');
                    if (!get_option('aiomatic_omni_list')) {
                        $rules = array();
                    } else {
                        $rules = get_option('aiomatic_omni_list');
                    }
                }
                if (!empty($rules)) {
                    foreach ($rules as $request => $bundle[]) {
                        if ($cont == $param) {
                            $bundle_values    = array_values($bundle);
                            $myValues         = $bundle_values[$cont];
                            $array_my_values  = array_values($myValues);for($iji=0;$iji<count($array_my_values);++$iji){if(is_string($array_my_values[$iji])){$array_my_values[$iji]=stripslashes($array_my_values[$iji]);}}
                            $schedule         = isset($array_my_values[0]) ? $array_my_values[0] : '';
                            $active           = isset($array_my_values[1]) ? $array_my_values[1] : '';
                            $last_run         = isset($array_my_values[2]) ? $array_my_values[2] : '';
                            $max              = isset($array_my_values[3]) ? $array_my_values[3] : '';
                            $main_keywords    = isset($array_my_values[4]) ? $array_my_values[4] : '';
                            $title_once       = isset($array_my_values[5]) ? $array_my_values[5] : '';
                            $rule_description = isset($array_my_values[6]) ? $array_my_values[6] : '';
                            $rule_unique_id   = isset($array_my_values[7]) ? $array_my_values[7] : '';
                            $sortable_cards   = isset($array_my_values[8]) ? $array_my_values[8] : '';
                            $more_keywords    = isset($array_my_values[9]) ? $array_my_values[9] : '';
                            $days_no_run      = isset($array_my_values[10]) ? $array_my_values[10] : '';
                            $found            = 1;
                            break;
                        }
                        $cont = $cont + 1;
                    }
                } else {
                    aiomatic_log_to_file('No rules found for aiomatic_omni_list!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
            }
            elseif($type == 6)
            {
                if($rules === null)
                {
                    $GLOBALS['wp_object_cache']->delete('aiomatic_listicle_list', 'options');
                    if (!get_option('aiomatic_listicle_list')) {
                        $rules = array();
                    } else {
                        $rules = get_option('aiomatic_listicle_list');
                    }
                }
                if (!empty($rules)) {
                    foreach ($rules as $request => $bundle[]) {
                        if ($cont == $param) {
                            $bundle_values    = array_values($bundle);
                            $myValues         = $bundle_values[$cont];
                            $array_my_values  = array_values($myValues);for($iji=0;$iji<count($array_my_values);++$iji){if(is_string($array_my_values[$iji])){$array_my_values[$iji]=stripslashes($array_my_values[$iji]);}}
                            $schedule         = isset($array_my_values[0]) ? $array_my_values[0] : '';
                            $active           = isset($array_my_values[1]) ? $array_my_values[1] : '';
                            $last_run         = isset($array_my_values[2]) ? $array_my_values[2] : '';
                            $max              = isset($array_my_values[3]) ? $array_my_values[3] : '';
                            $post_status      = isset($array_my_values[4]) ? $array_my_values[4] : '';
                            $post_type        = isset($array_my_values[5]) ? $array_my_values[5] : '';
                            $post_user_name   = isset($array_my_values[6]) ? $array_my_values[6] : '';
                            $item_create_tag  = isset($array_my_values[7]) ? $array_my_values[7] : '';
                            $default_category = isset($array_my_values[8]) ? $array_my_values[8] : '';
                            $auto_categories  = isset($array_my_values[9]) ? $array_my_values[9] : '';
                            $can_create_tag   = isset($array_my_values[10]) ? $array_my_values[10] : '';
                            $enable_comments  = isset($array_my_values[11]) ? $array_my_values[11] : '';
                            $image_url        = isset($array_my_values[12]) ? $array_my_values[12] : '';
                            $post_title       = isset($array_my_values[13]) ? htmlspecialchars_decode($array_my_values[13]) : '';
                            $enable_pingback  = isset($array_my_values[14]) ? $array_my_values[14] : '';
                            $post_format      = isset($array_my_values[15]) ? $array_my_values[15] : '';
                            $custom_fields    = isset($array_my_values[16]) ? $array_my_values[16] : '';
                            $custom_tax       = isset($array_my_values[17]) ? $array_my_values[17] : '';
                            $temperature      = isset($array_my_values[18]) ? $array_my_values[18] : '';
                            $top_p            = isset($array_my_values[19]) ? $array_my_values[19] : '';
                            $presence_penalty = isset($array_my_values[20]) ? $array_my_values[20] : '';
                            $frequency_penalty = isset($array_my_values[21]) ? $array_my_values[21] : '';
                            $royalty_free     = isset($array_my_values[22]) ? $array_my_values[22] : '';
                            $max_tokens       = isset($array_my_values[23]) ? $array_my_values[23] : '';
                            $max_seed_tokens  = isset($array_my_values[24]) ? $array_my_values[24] : AIMOGEN_DEFAULT_COMPLETION_TOKENS;
                            $post_prepend     = isset($array_my_values[25]) ? $array_my_values[25] : '';
                            $post_append      = isset($array_my_values[26]) ? $array_my_values[26] : '';
                            $enable_ai_images = isset($array_my_values[27]) ? $array_my_values[27] : '';
                            $ai_command_image = isset($array_my_values[28]) ? $array_my_values[28] : '';
                            $image_size       = isset($array_my_values[29]) ? $array_my_values[29] : '';
                            $wpml_lang        = isset($array_my_values[30]) ? $array_my_values[30] : '';
                            $remove_default   = isset($array_my_values[31]) ? $array_my_values[31] : '';
                            $strip_title      = isset($array_my_values[32]) ? $array_my_values[32] : '';
                            $title_once       = isset($array_my_values[33]) ? $array_my_values[33] : '';
                            $category_model   = isset($array_my_values[34]) ? $array_my_values[34] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $category_ai_command= isset($array_my_values[35]) ? $array_my_values[35] : '';
                            $tag_model        = isset($array_my_values[36]) ? $array_my_values[36] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $tag_ai_command   = isset($array_my_values[37]) ? $array_my_values[37] : '';
                            $min_time         = isset($array_my_values[38]) ? $array_my_values[38] : '';
                            $max_time         = isset($array_my_values[39]) ? $array_my_values[39] : '';
                            $skip_spin        = isset($array_my_values[40]) ? $array_my_values[40] : '';
                            $skip_translate   = isset($array_my_values[41]) ? $array_my_values[41] : '';
                            $post_topic_list  = isset($array_my_values[42]) ? $array_my_values[42] : '';
                            $post_sections_list= isset($array_my_values[43]) ? $array_my_values[43] : '';
                            $content_language = isset($array_my_values[44]) ? $array_my_values[44] : '';
                            $writing_style    = isset($array_my_values[45]) ? $array_my_values[45] : '';
                            $writing_tone     = isset($array_my_values[46]) ? $array_my_values[46] : '';
                            $title_prompt     = isset($array_my_values[47]) ? $array_my_values[47] : '';
                            $sections_prompt  = isset($array_my_values[48]) ? $array_my_values[48] : '';
                            $content_prompt   = isset($array_my_values[49]) ? $array_my_values[49] : '';
                            $excerpt_prompt   = isset($array_my_values[50]) ? $array_my_values[50] : '';
                            $section_count    = isset($array_my_values[51]) ? $array_my_values[51] : '';
                            $paragraph_count  = isset($array_my_values[52]) ? $array_my_values[52] : '';
                            $topic_title_model = isset($array_my_values[53]) ? $array_my_values[53] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_sections_model  = isset($array_my_values[54]) ? $array_my_values[54] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_content_model  = isset($array_my_values[55]) ? $array_my_values[55] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_excerpt_model  = isset($array_my_values[56]) ? $array_my_values[56] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $single_content_call  = isset($array_my_values[57]) ? $array_my_values[57] : '';
                            $intro_prompt         = isset($array_my_values[58]) ? $array_my_values[58] : '';
                            $topic_intro_model    = isset($array_my_values[59]) ? $array_my_values[59] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $outro_prompt         = isset($array_my_values[60]) ? $array_my_values[60] : '';
                            $topic_outro_model    = isset($array_my_values[61]) ? $array_my_values[61] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $topic_images         = isset($array_my_values[62]) ? $array_my_values[62] : '';
                            $sections_role        = isset($array_my_values[63]) ? $array_my_values[63] : '';
                            $topic_videos         = isset($array_my_values[64]) ? $array_my_values[64] : '';
                            $rule_description     = isset($array_my_values[65]) ? $array_my_values[65] : '';
                            $custom_shortcodes    = isset($array_my_values[66]) ? $array_my_values[66] : '';
                            $strip_by_regex       = isset($array_my_values[67]) ? $array_my_values[67] : '';
                            $replace_regex        = isset($array_my_values[68]) ? $array_my_values[68] : '';
                            $strip_by_regex_prompts= isset($array_my_values[69]) ? $array_my_values[69] : '';
                            $replace_regex_prompts= isset($array_my_values[70]) ? $array_my_values[70] : '';
                            $run_regex_on     = isset($array_my_values[71]) ? $array_my_values[71] : '';
                            $max_links        = isset($array_my_values[72]) ? $array_my_values[72] : '';
                            $link_post_types  = isset($array_my_values[73]) ? $array_my_values[73] : '';
                            $enable_toc       = isset($array_my_values[74]) ? $array_my_values[74] : '';
                            $title_toc        = isset($array_my_values[75]) ? $array_my_values[75] : '';
                            $qa_prompt        = isset($array_my_values[76]) ? $array_my_values[76] : '';
                            $topic_qa_model   = isset($array_my_values[77]) ? $array_my_values[77] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $enable_qa        = isset($array_my_values[78]) ? $array_my_values[78] : '';
                            $title_qa         = isset($array_my_values[79]) ? $array_my_values[79] : '';
                            $title_outro      = isset($array_my_values[80]) ? $array_my_values[80] : '';
                            $link_type        = isset($array_my_values[81]) ? $array_my_values[81] : 'internal';
                            $link_list        = isset($array_my_values[82]) ? $array_my_values[82] : '';
                            $skip_inexist     = isset($array_my_values[83]) ? $array_my_values[83] : '';
                            $global_prepend   = isset($array_my_values[84]) ? $array_my_values[84] : '';
                            $global_append    = isset($array_my_values[85]) ? $array_my_values[85] : '';
                            $search_query_repetition = isset($array_my_values[86]) ? $array_my_values[86] : '';
                            $img_all_headings = isset($array_my_values[87]) ? $array_my_values[87] : '';
                            $heading_img_location = isset($array_my_values[88]) ? $array_my_values[88] : 'bottom';
                            $days_no_run      = isset($array_my_values[89]) ? $array_my_values[89] : '';
                            $overwrite_existing= isset($array_my_values[90]) ? $array_my_values[90] : '';
                            $link_nofollow    = isset($array_my_values[91]) ? $array_my_values[91] : '';
                            $title_generator_method = isset($array_my_values[92]) ? $array_my_values[92] : '';
                            $parent_id        = isset($array_my_values[93]) ? $array_my_values[93] : '';
                            $rule_unique_id   = isset($array_my_values[94]) ? $array_my_values[94] : '';
                            $image_model      = isset($array_my_values[95]) ? $array_my_values[95] : '';
                            $assistant_id     = isset($array_my_values[96]) ? $array_my_values[96] : '';
                            $found            = 1;
                            $posting_mode     = 'topic';
                            break;
                        }
                        $cont = $cont + 1;
                    }
                } else {
                    aiomatic_log_to_file('No rules found for aiomatic_listicle_list!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
            }
            elseif($type == 7)
            {
                if($rules === null)
                {
                    $GLOBALS['wp_object_cache']->delete('aiomatic_forum_list', 'options');
                    if (!get_option('aiomatic_forum_list')) {
                        $rules = array();
                    } else {
                        $rules = get_option('aiomatic_forum_list');
                    }
                }
                if (!empty($rules)) {
                    foreach ($rules as $request => $bundle[]) {
                        if ($cont == $param) {
                            $bundle_values    = array_values($bundle);
                            $myValues         = $bundle_values[$cont];
                            $array_my_values  = array_values($myValues);for($iji=0;$iji<count($array_my_values);++$iji){if(is_string($array_my_values[$iji])){$array_my_values[$iji]=stripslashes($array_my_values[$iji]);}}
                            $schedule         = isset($array_my_values[0]) ? $array_my_values[0] : '';
                            $active           = isset($array_my_values[1]) ? $array_my_values[1] : '';
                            $last_run         = isset($array_my_values[2]) ? $array_my_values[2] : '';
                            $max              = isset($array_my_values[3]) ? $array_my_values[3] : '';
                            $post_user_name   = isset($array_my_values[4]) ? $array_my_values[4] : '';
                            $post_title       = isset($array_my_values[5]) ? htmlspecialchars_decode($array_my_values[5]) : '';
                            $min_char         = isset($array_my_values[6]) ? $array_my_values[6] : '';
                            $temperature      = isset($array_my_values[7]) ? $array_my_values[7] : '';
                            $top_p            = isset($array_my_values[8]) ? $array_my_values[8] : '';
                            $presence_penalty = isset($array_my_values[9]) ? $array_my_values[9] : '';
                            $frequency_penalty = isset($array_my_values[10]) ? $array_my_values[10] : '';
                            $ai_command       = isset($array_my_values[11]) ? $array_my_values[11] : '';
                            $max_tokens       = isset($array_my_values[12]) ? $array_my_values[12] : '';
                            $max_seed_tokens  = isset($array_my_values[13]) ? $array_my_values[13] : AIMOGEN_DEFAULT_COMPLETION_TOKENS;
                            $model            = isset($array_my_values[14]) ? $array_my_values[14] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $post_prepend     = isset($array_my_values[15]) ? $array_my_values[15] : '';
                            $post_append      = isset($array_my_values[16]) ? $array_my_values[16] : '';
                            $title_model      = isset($array_my_values[17]) ? $array_my_values[17] : aiomatic_get_default_model_name($aiomatic_Main_Settings);
                            $title_ai_command = isset($array_my_values[18]) ? $array_my_values[18] : '';
                            $strip_title      = isset($array_my_values[19]) ? $array_my_values[19] : '';
                            $min_time         = isset($array_my_values[20]) ? $array_my_values[20] : '';
                            $max_time         = isset($array_my_values[21]) ? $array_my_values[21] : '';
                            $skip_spin        = isset($array_my_values[22]) ? $array_my_values[22] : '';
                            $skip_translate   = isset($array_my_values[23]) ? $array_my_values[23] : '';
                            $title_source     = isset($array_my_values[24]) ? $array_my_values[24] : '';
                            $selected_forum   = isset($array_my_values[25]) ? $array_my_values[25] : 0;
                            $rule_description     = isset($array_my_values[26]) ? $array_my_values[26] : '';
                            $custom_shortcodes    = isset($array_my_values[27]) ? $array_my_values[27] : '';
                            $strip_by_regex       = isset($array_my_values[28]) ? $array_my_values[28] : '';
                            $replace_regex        = isset($array_my_values[29]) ? $array_my_values[29] : '';
                            $link_post_types  = isset($array_my_values[30]) ? $array_my_values[30] : '';
                            $link_type        = isset($array_my_values[31]) ? $array_my_values[31] : 'internal';
                            $link_list        = isset($array_my_values[32]) ? $array_my_values[32] : '';
                            $global_prepend   = isset($array_my_values[33]) ? $array_my_values[33] : '';
                            $global_append    = isset($array_my_values[34]) ? $array_my_values[34] : '';
                            $overwrite_existing= isset($array_my_values[35]) ? $array_my_values[35] : '';
                            $link_nofollow    = isset($array_my_values[36]) ? $array_my_values[36] : '';
                            $rule_unique_id   = isset($array_my_values[37]) ? $array_my_values[37] : '';
                            $assistant_id     = isset($array_my_values[38]) ? $array_my_values[38] : '';
                            $max_links        = isset($array_my_values[39]) ? $array_my_values[39] : '';
                            $title_once       = isset($array_my_values[40]) ? $array_my_values[40] : '';
                            $reply_count      = isset($array_my_values[41]) ? $array_my_values[41] : '';
                            $reply_model      = isset($array_my_values[42]) ? $array_my_values[42] : '';
                            $choose_prompt    = isset($array_my_values[43]) ? $array_my_values[43] : '';
                            $reply_prompt     = isset($array_my_values[44]) ? $array_my_values[44] : '';
                            $content_language = isset($array_my_values[45]) ? $array_my_values[45] : '';
                            $writing_style    = isset($array_my_values[46]) ? $array_my_values[46] : '';
                            $writing_tone     = isset($array_my_values[47]) ? $array_my_values[47] : '';
                            $user_role        = isset($array_my_values[48]) ? $array_my_values[48] : '';
                            $found            = 1;
                            break;
                        }
                        $cont = $cont + 1;
                    }
                } else {
                    aiomatic_log_to_file('No rules found for aiomatic_forum_list!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
            }
            elseif($type == 8)
            {
                if($rules === null)
                {
                    $GLOBALS['wp_object_cache']->delete('aiomatic_reply_list', 'options');
                    if (!get_option('aiomatic_reply_list')) {
                        $rules = array();
                    } else {
                        $rules = get_option('aiomatic_reply_list');
                    }
                }
                if (!empty($rules)) {
                    foreach ($rules as $request => $bundle[]) {
                        if ($cont == $param) {
                            $bundle_values    = array_values($bundle);
                            $myValues         = $bundle_values[$cont];
                            $array_my_values  = array_values($myValues);for($iji=0;$iji<count($array_my_values);++$iji){if(is_string($array_my_values[$iji])){$array_my_values[$iji]=stripslashes($array_my_values[$iji]);}}
                            $schedule         = isset($array_my_values[0]) ? $array_my_values[0] : '';
                            $active           = isset($array_my_values[1]) ? $array_my_values[1] : '';
                            $last_run         = isset($array_my_values[2]) ? $array_my_values[2] : '';
                            $max              = isset($array_my_values[3]) ? $array_my_values[3] : '';
                            $post_title       = isset($array_my_values[4]) ? htmlspecialchars_decode($array_my_values[4]) : '';
                            $temperature      = isset($array_my_values[5]) ? $array_my_values[5] : '';
                            $top_p            = isset($array_my_values[6]) ? $array_my_values[6] : '';
                            $presence_penalty = isset($array_my_values[7]) ? $array_my_values[7] : '';
                            $frequency_penalty = isset($array_my_values[8]) ? $array_my_values[8] : '';
                            $max_tokens       = isset($array_my_values[9]) ? $array_my_values[9] : '';
                            $max_seed_tokens  = isset($array_my_values[10]) ? $array_my_values[10] : AIMOGEN_DEFAULT_COMPLETION_TOKENS;
                            $post_prepend     = isset($array_my_values[11]) ? $array_my_values[11] : '';
                            $post_append      = isset($array_my_values[12]) ? $array_my_values[12] : '';
                            $skip_spin        = isset($array_my_values[13]) ? $array_my_values[13] : '';
                            $skip_translate   = isset($array_my_values[14]) ? $array_my_values[14] : '';
                            $selected_forum   = isset($array_my_values[15]) ? $array_my_values[15] : 0;
                            $rule_description     = isset($array_my_values[16]) ? $array_my_values[16] : '';
                            $custom_shortcodes    = isset($array_my_values[17]) ? $array_my_values[17] : '';
                            $strip_by_regex       = isset($array_my_values[18]) ? $array_my_values[18] : '';
                            $replace_regex        = isset($array_my_values[19]) ? $array_my_values[19] : '';
                            $global_prepend   = isset($array_my_values[20]) ? $array_my_values[20] : '';
                            $global_append    = isset($array_my_values[21]) ? $array_my_values[21] : '';
                            $rule_unique_id   = isset($array_my_values[22]) ? $array_my_values[22] : '';
                            $assistant_id     = isset($array_my_values[23]) ? $array_my_values[23] : '';
                            $reply_count      = isset($array_my_values[24]) ? $array_my_values[24] : '';
                            $reply_model      = isset($array_my_values[25]) ? $array_my_values[25] : '';
                            $choose_prompt    = isset($array_my_values[26]) ? $array_my_values[26] : '';
                            $reply_prompt     = isset($array_my_values[27]) ? $array_my_values[27] : '';
                            $content_language = isset($array_my_values[28]) ? $array_my_values[28] : '';
                            $writing_style    = isset($array_my_values[29]) ? $array_my_values[29] : '';
                            $writing_tone     = isset($array_my_values[30]) ? $array_my_values[30] : '';
                            $more_replies     = isset($array_my_values[31]) ? $array_my_values[31] : '';
                            $user_role        = isset($array_my_values[32]) ? $array_my_values[32] : '';
                            $found            = 1;
                            break;
                        }
                        $cont = $cont + 1;
                    }
                } else {
                    aiomatic_log_to_file('No rules found for aiomatic_reply_list!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
            }
            else
            {
                aiomatic_log_to_file('Invalid rule type provided: ' . $type);
                if($auto == 1)
                {
                    aiomatic_clearFromList($param, $type);
                }
                return 'fail';
            }
            if(empty($enable_ai_images_article))
            {
                $enable_ai_images_article = $enable_ai_images;
            }
            if(empty($ai_command_image_article))
            {
                $ai_command_image_article = $ai_command_image;
            }
            if(empty($image_model_article))
            {
                $image_model_article = $image_model;
            }
            if(empty($image_size_article))
            {
                $image_size_article = $image_size;
            }
            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Parameters parsed'));
            $default_cat_list = '';
            if (isset($default_category) && $default_category != '' && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678') 
            {
                if(is_array($default_category))
                {
                    $cextra = '';
                    foreach($default_category as $dc)
                    {
                        $cextra .= ',' . get_cat_name($dc);
                    }
                    $default_cat_list = trim( $cextra, ',');
                }
                else
                {
                    $default_cat_list = trim(get_cat_name($default_category) . ',');
                }
            }
            $days_no_run = explode(',', $days_no_run);
            $days_no_run = array_map('trim', $days_no_run);
            if(!empty($days_no_run))
            {
                if(in_array(date('l', time()), $days_no_run))
                {
                    aiomatic_log_to_file('Skipping rule ID from running today: ' . $param . ', rule type: ' . $type);
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'nochange';
                }
                else
                {
                    foreach($days_no_run as $nrd)
                    {
                        if(strtolower($nrd) == 'mo' && date('l', time()) == 'Monday')
                        {
                            aiomatic_log_to_file('Skipping rule ID from running on Monday: ' . $param . ', rule type: ' . $type);
                            if($auto == 1)
                            {
                                aiomatic_clearFromList($param, $type);
                            }
                            return 'nochange';
                        }
                        elseif(strtolower($nrd) == 'tu' && date('l', time()) == 'Tuesday')
                        {
                            aiomatic_log_to_file('Skipping rule ID from running on Tuesday: ' . $param . ', rule type: ' . $type);
                            if($auto == 1)
                            {
                                aiomatic_clearFromList($param, $type);
                            }
                            return 'nochange';
                        }
                        elseif(strtolower($nrd) == 'we' && date('l', time()) == 'Wednesday')
                        {
                            aiomatic_log_to_file('Skipping rule ID from running on Wednesday: ' . $param . ', rule type: ' . $type);
                            if($auto == 1)
                            {
                                aiomatic_clearFromList($param, $type);
                            }
                            return 'nochange';
                        }
                        elseif(strtolower($nrd) == 'th' && date('l', time()) == 'Thursday')
                        {
                            aiomatic_log_to_file('Skipping rule ID from running on Thursday: ' . $param . ', rule type: ' . $type);
                            if($auto == 1)
                            {
                                aiomatic_clearFromList($param, $type);
                            }
                            return 'nochange';
                        }
                        elseif(strtolower($nrd) == 'fr' && date('l', time()) == 'Friday')
                        {
                            aiomatic_log_to_file('Skipping rule ID from running on Friday: ' . $param . ', rule type: ' . $type);
                            if($auto == 1)
                            {
                                aiomatic_clearFromList($param, $type);
                            }
                            return 'nochange';
                        }
                        elseif(strtolower($nrd) == 'sa' && date('l', time()) == 'Saturday')
                        {
                            aiomatic_log_to_file('Skipping rule ID from running on Saturday: ' . $param . ', rule type: ' . $type);
                            if($auto == 1)
                            {
                                aiomatic_clearFromList($param, $type);
                            }
                            return 'nochange';
                        }
                        elseif(strtolower($nrd) == 'su' && date('l', time()) == 'Sunday')
                        {
                            aiomatic_log_to_file('Skipping rule ID from running on Sunday: ' . $param . ', rule type: ' . $type);
                            if($auto == 1)
                            {
                                aiomatic_clearFromList($param, $type);
                            }
                            return 'nochange';
                        }
                    }
                }
            }
            $topic_images_bck = $topic_images;
            $inboundlinker = null;
            if($max_links !== '' && $type != '5')
            {
                preg_match_all('#\s*(\d+)\s*-\s*(\d+)\s*#', $max_links, $mxatches);
                if(isset($mxatches[2][0]))
                {
                    $min_l = $mxatches[1][0];
                    $max_l = $mxatches[2][0];
                    $max_links = wp_rand(intval($min_l), intval($max_l));
                }
                else
                {
                    $max_links = intval($max_links);
                }
                require_once(dirname(__FILE__) . "/res/InboundLinks.php");
                $inboundlinker = new AiomaticAutoInboundLinks();
            }
            if(empty($max_tokens) || intval($max_tokens) <= 0)
            {
                $max_tokens = aimogenpro_get_max_tokens($model);
            }
            if(intval($max_tokens) > AIMOGEN_DEFAULT_MAX_TOKENS && ( !stristr($model, 'gpt') || aiomatic_is_trained_model($model)))
            {
                $max_tokens = AIMOGEN_DEFAULT_MAX_TOKENS;
            }
            if($max_seed_tokens === '')
            {
                $max_seed_tokens = AIMOGEN_DEFAULT_COMPLETION_TOKENS;
            }
            if($max_continue_tokens === '')
            {
                $max_continue_tokens = AIMOGEN_DEFAULT_COMPLETION_TOKENS;
            }
            if($type == 0 || empty($type))
            {
                if ($found == 0) {
                    aiomatic_log_to_file($type . ' - ' . $param . ' not found in rules!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                } else {
                    if($ret_content == 0)
                    {
                        $GLOBALS['wp_object_cache']->delete('aiomatic_rules_list', 'options');
                        $rules = get_option('aiomatic_rules_list');
                        $rules[$param][2] = aiomatic_get_date_now();
                        aiomatic_update_option('aiomatic_rules_list', $rules, false);
                    }
                }
            }
            elseif($type == 1)
            {
                if ($found == 0) {
                    aiomatic_log_to_file($type . ' - ' . $param . ' not found in YouTube rules!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                } else {
                    if($ret_content == 0)
                    {
                        $GLOBALS['wp_object_cache']->delete('aiomatic_youtube_list', 'options');
                        $rules = get_option('aiomatic_youtube_list');
                        $rules[$param][2] = aiomatic_get_date_now();
                        aiomatic_update_option('aiomatic_youtube_list', $rules, false);
                    }
                }
            }
            elseif($type == 2)
            {
                if ($found == 0) {
                    aiomatic_log_to_file($type . ' - ' . $param . ' not found in Amazon rules!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                } else {
                    if($ret_content == 0)
                    {
                        $GLOBALS['wp_object_cache']->delete('aiomatic_amazon_list', 'options');
                        $rules = get_option('aiomatic_amazon_list');
                        $rules[$param][2] = aiomatic_get_date_now();
                        aiomatic_update_option('aiomatic_amazon_list', $rules, false);
                    }
                }
            }
            elseif($type == 3)
            {
                if ($found == 0) {
                    aiomatic_log_to_file($type . ' - ' . $param . ' not found in Amazon review rules!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                } else {
                    if($ret_content == 0)
                    {
                        $GLOBALS['wp_object_cache']->delete('aiomatic_review_list', 'options');
                        $rules = get_option('aiomatic_review_list');
                        $rules[$param][2] = aiomatic_get_date_now();
                        aiomatic_update_option('aiomatic_review_list', $rules, false);
                    }
                }
            }
            elseif($type == 4)
            {
                if ($found == 0) {
                    aiomatic_log_to_file($type . ' - ' . $param . ' not found in CSV rules!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                } else {
                    if($ret_content == 0)
                    {
                        $GLOBALS['wp_object_cache']->delete('aiomatic_csv_list', 'options');
                        $rules = get_option('aiomatic_csv_list');
                        $rules[$param][2] = aiomatic_get_date_now();
                        aiomatic_update_option('aiomatic_csv_list', $rules, false);
                    }
                }
            }
            elseif($type == 5)
            {
                if ($found == 0) {
                    aiomatic_log_to_file($type . ' - ' . $param . ' not found in OmniBlock rules!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                } else {
                    if($ret_content == 0)
                    {
                        $GLOBALS['wp_object_cache']->delete('aiomatic_omni_list', 'options');
                        $rules = get_option('aiomatic_omni_list');
                        $rules[$param][2] = aiomatic_get_date_now();
                        aiomatic_update_option('aiomatic_omni_list', $rules, false);
                    }
                }
            }
            elseif($type == 6)
            {
                if ($found == 0) {
                    aiomatic_log_to_file($type . ' - ' . $param . ' not found in rules!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                } else {
                    if($ret_content == 0)
                    {
                        $GLOBALS['wp_object_cache']->delete('aiomatic_listicle_list', 'options');
                        $rules = get_option('aiomatic_listicle_list');
                        $rules[$param][2] = aiomatic_get_date_now();
                        aiomatic_update_option('aiomatic_listicle_list', $rules, false);
                    }
                }
            }
            elseif($type == 7)
            {
                if ($found == 0) {
                    aiomatic_log_to_file($type . ' - ' . $param . ' not found in rules!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                } else {
                    if($ret_content == 0)
                    {
                        $GLOBALS['wp_object_cache']->delete('aiomatic_forum_list', 'options');
                        $rules = get_option('aiomatic_forum_list');
                        $rules[$param][2] = aiomatic_get_date_now();
                        aiomatic_update_option('aiomatic_forum_list', $rules, false);
                    }
                }
            }
            elseif($type == 8)
            {
                if ($found == 0) {
                    aiomatic_log_to_file($type . ' - ' . $param . ' not found in rules!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                } else {
                    if($ret_content == 0)
                    {
                        $GLOBALS['wp_object_cache']->delete('aiomatic_reply_list', 'options');
                        $rules = get_option('aiomatic_reply_list');
                        $rules[$param][2] = aiomatic_get_date_now();
                        aiomatic_update_option('aiomatic_reply_list', $rules, false);
                    }
                }
            }
            $post_link = '';
            $rss_items = array();
            if ($enable_comments == '1') {
                $accept_comments = 'open';
            }
            $count = 1;
            if($temperature == '')
            {
                $temperature = 1;
            }
            else
            {
                $temperature = floatval($temperature);
            }
            if($top_p == '')
            {
                $top_p = 1;
            }
            else
            {
                $top_p = floatval($top_p);
            }
            if($frequency_penalty == '')
            {
                $frequency_penalty = 0;
            }
            else
            {
                $frequency_penalty = floatval($frequency_penalty);
            }
            if($presence_penalty == '')
            {
                $presence_penalty = 0;
            }
            else
            {
                $presence_penalty = floatval($presence_penalty);
            }
            $max_tokens = intval($max_tokens);
            $max_seed_tokens = intval($max_seed_tokens);
            $max_continue_tokens = intval($max_continue_tokens);
            $blog_title       = html_entity_decode(get_bloginfo('title'));
            $post_title = aiomatic_replaceSynergyShortcodes($post_title);
            $posted_items = array();
            $posted_topics = array();
            if(($title_once == '1' || $overwrite_existing == '1') && $type != '5' && $type != '7')
            {
                $post_stati = array_diff(
                    get_post_stati(),
                    [
                        'auto-draft',
                        'inherit',
                        'request-pending',
                        'request-confirmed',
                        'request-failed',
                        'request-completed',
                    ]
                );

                wp_suspend_cache_addition(true);

                $posted_items  = aiomatic_load_meta_index('aiomatic_source_title', $post_stati);
                $posted_topics = aiomatic_load_meta_index('aiomatic_post_topic',  $post_stati);

                wp_suspend_cache_addition(false);
                
                // Clear WordPress object cache to free memory
                wp_cache_flush();
            }
            $user_name_type = $post_user_name;
            if($title_once == '1' && $type != '4' && $type != '5')
            {
                $postsPerPage = 1000;
                $paged = 0;
                wp_suspend_cache_addition(true);
                $post_stati = get_post_stati();
                foreach ($post_stati as $key => $val) {
                    if ($val == 'auto-draft') {
                        unset($post_stati[$key]);
                    }
                    if ($val == 'inherit') {
                        unset($post_stati[$key]);
                    }
                    if ($val == 'request-pending') {
                        unset($post_stati[$key]);
                    }
                    if ($val == 'request-confirmed') {
                        unset($post_stati[$key]);
                    }
                    if ($val == 'request-failed') {
                        unset($post_stati[$key]);
                    }
                    if ($val == 'request-completed') {
                        unset($post_stati[$key]);
                    }
                }
                do
                {
                    $postOffset = $paged * $postsPerPage;
                    $query     = array(
                        'post_status' => $post_stati,
                        'post_type' => array(
                            'any'
                        ),
                        'numberposts' => $postsPerPage,
                        'fields' => 'ids',
                        'meta_key' => 'aiomatic_rss_link',
                        'offset'  => $postOffset
                    );
                    $zpost_list = get_posts($query);
                    foreach ($zpost_list as $zpost) {
                        $orig_link = get_post_meta($zpost, 'aiomatic_rss_link', true);
                        if(!empty($orig_link))
                        {
                            $rss_items[$orig_link] = $zpost;
                        }
                    }
                    $paged++;
                }while(!empty($zpost_list));
                unset($zpost_list);
                wp_suspend_cache_addition(false);
            }
            if($type == 0 || $type == 6 || empty($type))
            {
                if($post_title != '')
                {
                    $post_title_lines = preg_split('/\r\n|\r|\n/', $post_title);
                }
                else
                {
                    $post_title_lines = array();
                }
                $additional_kws = array();
                $user_name        = '';
                $featured_image   = '';
                $post_cats = '';
                $post_tagz = '';
                $post_excerpt = '';
                $final_content = '';
                $postID = '';
                $heading_val = '';
                $image_query = '';
                $temp_post = '';
                $cntx = count($post_title_lines);
                $rss_feeds = array();
                for($ji = 0; $ji < $cntx; $ji++)
                {
                    if (filter_var($post_title_lines[$ji], FILTER_VALIDATE_URL) !== false) 
                    {
                        if(aiomatic_endsWith($post_title_lines[$ji], '.txt'))
                        {
                            
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing txt file'));
                            $txt_content = aiomatic_get_web_page($post_title_lines[$ji]);
                            if ($txt_content === FALSE) 
                            {
                                aiomatic_log_to_file('Failed to read text file: ' . $post_title_lines[$ji]);
                                unset($post_title_lines[$ji]);
                                if($auto == 1)
                                {
                                    aiomatic_log_to_file($param);
                                }
                                continue;
                            }
                            unset($post_title_lines[$ji]);
                            $additional_kws = preg_split('/\r\n|\r|\n/', $txt_content);
                        }
                        else
                        {
                            aiomatic_log_to_file('Trying to parse RSS feed items(1): ' . $post_title_lines[$ji]);
                            try
                            {
                                if(!class_exists('SimplePie_Autoloader', false))
                                {
                                    require_once(dirname(__FILE__) . "/res/simplepie/autoloader.php");
                                }
                            }
                            catch(Exception $e) 
                            {
                                unset($post_title_lines[$ji]);
                                aiomatic_log_to_file('Exception thrown in SimplePie autoloader: ' . $e->getMessage());
                                if($auto == 1)
                                {
                                    aiomatic_log_to_file($param);
                                }
                                continue;
                            }
                            
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing RSS feed'));
                            $feed = new SimplePie();
                            $feed->set_timeout(120);
                            $feed->set_feed_url($post_title_lines[$ji]);
                            $feed->enable_cache(false);
                            $feed->strip_htmltags(false);
                            $feed->init();
                            $feed->handle_content_type();
                            if ($feed->error()) 
                            {
                                aiomatic_log_to_file('Error in parsing RSS feed: ' . $feed->error() . ' for ' . $post_title_lines[$ji]);
                                unset($post_title_lines[$ji]);
                                if($auto == 1)
                                {
                                    aiomatic_clearFromList($param, $type);
                                }
                                continue;
                            }
                            $items = $feed->get_items();
                            $zero = true;
                            foreach($items as $itemx)
                            {
                                if($zero == true)
                                {
                                    $post_link = trim($itemx->get_permalink());
                                    if(isset($rss_items[$post_link]))
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Skipping RSS title because it was already processed before: ' . $itemx->get_title());
                                        }
                                        continue;
                                    }
                                    if ($fauthor = $itemx->get_author()) 
                                    {
                                        $user_name = $fauthor->get_name();
                                    }
                                    else
                                    {
                                        $user_name = '';
                                    }
                                    $feed_cats = array();
                                    $varx = $itemx->get_categories();
                                    if(is_array($varx))
                                    {
                                        foreach ($varx as $xcategory)
                                        {
                                            $feed_cats[] = $xcategory->get_label();
                                        }
                                    }
                                    $post_cats = implode(',', $feed_cats);
                                    $post_excerpt = $itemx->get_description();
                                    $final_content = $itemx->get_content();
                                    $rss_feeds[$itemx->get_title()] = array('url' => $post_link, 'author' => $user_name,  'cats' => $post_cats, 'excerpt' => $post_excerpt, 'content' => $final_content );
                                }
                                else
                                {
                                    $post_link_temp = trim($itemx->get_permalink());
                                    if(isset($rss_items[$post_link_temp]))
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Skipping RSS title because it was already processed before: ' . $itemx->get_title());
                                        }
                                        continue;
                                    }
                                    if ($fauthor = $itemx->get_author()) 
                                    {
                                        $user_name_temp = $fauthor->get_name();
                                    }
                                    else
                                    {
                                        $user_name_temp = '';
                                    }
                                    $feed_cats = array();
                                    $varx = $itemx->get_categories();
                                    if(is_array($varx))
                                    {
                                        foreach ($varx as $xcategory)
                                        {
                                            $feed_cats[] = $xcategory->get_label();
                                        }
                                    }
                                    $post_cats_temp = implode(',', $feed_cats);
                                    $post_excerpt_temp = $itemx->get_description();
                                    $final_content_temp = $itemx->get_content();
                                    $rss_feeds[$itemx->get_title()] = array('url' => $post_link_temp, 'author' => $user_name_temp,  'cats' => $post_cats_temp, 'excerpt' => $post_excerpt_temp, 'content' => $final_content_temp );
                                }
                                $additional_kws[] = $itemx->get_title();
                                $zero = false;
                            }
                            unset($post_title_lines[$ji]);
                        }
                    }
                }
                if(count($additional_kws) > 0)
                {
                    $post_title_lines = array_merge($post_title_lines, $additional_kws);
                }
                $post_title_lines = array_unique($post_title_lines);
                if($overwrite_existing == '1')
                {
                    $post_title_lines_processed = array();
                    foreach($post_title_lines as $zind => $ptl)
                    {
                        $ptlprocessed = explode('!###!', $ptl);
                        if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                        {
                            $post_title_lines_processed[$zind] = $ptlprocessed[0];
                        }
                        else
                        {
                            $post_title_lines_processed[$zind] = $ptl;
                        }
                    }
                    foreach($posted_items as $ptit => $pid)
                    {
                        if (($key = array_search($ptit, $post_title_lines_processed)) !== false) {
                            $update_post_id = $pid;
                            break;
                        }
                    }
                }
                if($title_once == '1')
                {
                    $skipt = 0;
                    $post_title_lines_processed = array();
                    foreach($post_title_lines as $zind => $ptl)
                    {
                        $ptlprocessed = explode('!###!', $ptl);
                        if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                        {
                            $post_title_lines_processed[$zind] = $ptlprocessed[0];
                        }
                        else
                        {
                            $post_title_lines_processed[$zind] = $ptl;
                        }
                    }
                    foreach($posted_items as $ptit => $pid)
                    {
                        if (($key = array_search($ptit, $post_title_lines_processed)) !== false) {
                            if (filter_var($post_title_lines[$key], FILTER_VALIDATE_URL) === false && stristr($post_title_lines[$key], '%%ai_generated_title%%') === false)
                            {
                                aiomatic_log_to_file('Skipping title, already processed: ' . $ptit);
                                unset($post_title_lines[$key]);
                                unset($post_title_lines_processed[$key]);
                                $skipt++;
                            }
                        }
                    }
                    if(count($post_title_lines) == 0 && $skipt > 0)
                    {
                        if (isset($aiomatic_Main_Settings['email_notification']) && $aiomatic_Main_Settings['email_notification'] != '')
                        {
                            if($count === 1)
                            {
                                $email_list = explode(',', $aiomatic_Main_Settings['email_notification']);
                                foreach($email_list as $thisaddr)
                                {
                                    $thisaddr = trim($thisaddr);
                                    try
                                    {
                                        $admin_mail = get_option('admin_email');
                                        $to        = $thisaddr;
                                        $subject   = '[Aimogen] Titles depleted rule ID ' . $param . ' - ' . aiomatic_get_date_now();
                                        $message   = 'Rule ID ' . esc_html($param) . ' (' . $rule_description . ') depleted its titles, no new posts publised! Website URL: ' . get_site_url();
                                        $headers[] = 'From: Aimogen Plugin <' . $admin_mail . '>';
                                        $headers[] = 'Reply-To: ' . $admin_mail;
                                        $headers[] = 'X-Mailer: PHP/' . phpversion();
                                        $headers[] = 'Content-Type: text/html';
                                        $headers[] = 'Charset: ' . get_option('blog_charset', 'UTF-8');
                                        wp_mail($to, $subject, $message, $headers);
                                    }
                                    catch (Exception $e) {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Failed to send mail: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                        }
                                    }
                                }
                            }
                        }
                        aiomatic_log_to_file('All titles already processed, nothing to do.');
                        if($auto == 1)
                        {
                            aiomatic_clearFromList($param, $type);
                        }
                        return 'nochange';
                    }
                }
                $spintax = new Aiomatic_Spintax();
                $orig_ai_command = $ai_command;
                $orig_ai_command_title = $title_ai_command;
                $orig_ai_command_category = $category_ai_command;
                $orig_ai_command_tag = $tag_ai_command;
                $orig_ai_command_image = $ai_command_image;
                $orig_ai_command_image_article = $ai_command_image_article;
                $already_spinned = 0;
                if(isset($aiomatic_Main_Settings['attr_text']) && $aiomatic_Main_Settings['attr_text'] != '')
                {
                    $img_attr = $aiomatic_Main_Settings['attr_text'];
                }
                else
                {
                    $img_attr = '';
                }
                if($headings_list != '')
                {
                    $headings_arr_temp = preg_split('/\r\n|\r|\n/', $headings_list);
                    $headings_arr_temp = array_map('trim', $headings_arr_temp);
                    $headings_arr = array();
                    foreach($headings_arr_temp as $hat)
                    {
                        $hat = aiomatic_replaceSynergyShortcodes($hat);
                        $hat = aiomatic_replaceAIPostShortcodes($hat, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, $global_prepend, $global_append);
                        $headings_arr[] = array('q' => $hat, 'a' => '');
                    }
                }
                else
                {
                    $headings_arr = array();
                }
                if($images_list != '')
                {
                    $images_arr = preg_split('/\r\n|\r|\n/', $images_list);
                    $images_arr = array_map('trim', $images_arr);
                }
                else
                {
                    $images_arr = array();
                }
                $no_init_topics = false;
                if(empty($post_topic_list))
                {
                    $no_init_topics = true;
                    $post_topic_list_arr = array();
                }
                else
                {
                    $post_topic_list_arr = preg_split('/\r\n|\r|\n/', $post_topic_list);
                    $post_topic_list_arr = array_unique($post_topic_list_arr);
                    if(count($post_topic_list_arr) == 0 || empty($post_topic_list))
                    {
                        $no_init_topics = true;
                    }
                }
                while(true) 
                {
                    // Periodic memory cleanup every 10 posts to prevent memory accumulation
                    if($count > 1 && ($count % 10 == 0)) {
                        wp_cache_flush();
                        if(function_exists('gc_collect_cycles')) {
                            gc_collect_cycles();
                        }
                    }
                    
                    $thread_id = '';
                    $post_link = '';
                    $user_name = '';
                    $post_cats = '';
                    $post_title = '';
                    $post_excerpt = '';
                    $final_content = '';
                    $my_title_outro = '';
                    $update_post_id = '';
                    $featured_image = '';
                    $post_tagz = '';
                    $postID = '';
                    if(isset($aiomatic_Main_Settings['attr_text']) && $aiomatic_Main_Settings['attr_text'] != '')
                    {
                        $img_attr = $aiomatic_Main_Settings['attr_text'];
                    }
                    else
                    {
                        $img_attr = '';
                    }
                    $old_title = '';
                    if ($count > intval($max)) {
                        break;
                    }
                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Starting processing post ID #' . $count));
                    $heading_image_loc = $heading_img_location;
                    if($heading_image_loc == 'random')
                    {
                        $xwords = array('top', 'heading', 'bottom');
                        $randomWord = $xwords[array_rand($xwords)];
                        $heading_image_loc = $randomWord;
                    }
                    $current_section = '';
                    $post_sections = '';
                    $post_topic = '';
                    $post_title_keywords = '';
                    $added_vid_list = array();
                    if($posting_mode == 'topic')
                    {
                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Topic based posting detected'));

                        $norm = function($s){
                            $s = html_entity_decode($s, ENT_QUOTES | ENT_HTML5, 'UTF-8');
                            if (function_exists('mb_strtolower')) {
                                $s = mb_strtolower($s, 'UTF-8');
                            } else {
                                $s = strtolower($s);
                            }
                            if (class_exists('Normalizer')) {
                                $s = Normalizer::normalize($s, Normalizer::FORM_C);
                            }
                            $s = preg_replace('/\s+/u', ' ', $s);
                            $s = trim($s);
                            return $s;
                        };

                        $posted_lookup = [];
                        foreach ($posted_topics as $ptit => $_pid) {
                            if (!strstr($ptit, '%%title%%')) {
                                $posted_lookup[$norm($ptit)] = true;
                            }
                        }

                        if ($title_once == '1' && !empty($post_topic_list_arr)) {
                            $post_topic_list_arr = array_values(array_filter(
                                $post_topic_list_arr,
                                function($t) use ($posted_lookup, $norm){
                                    return !isset($posted_lookup[$norm($t)]);
                                }
                            ));
                        }
                        if(!empty($post_topic_list_arr))
                        {
                            if (!isset($aiomatic_Main_Settings['no_random_titles']) || $aiomatic_Main_Settings['no_random_titles'] != 'on')
                            {
                                $nrx = array_rand($post_topic_list_arr);
                            }
                            else
                            {
                                $nrx = array_key_first($post_topic_list_arr);
                            }
                        }
                        else
                        {
                            $nrx = null;
                        }

                        if(($nrx === null || $nrx === false) && $no_init_topics === false)
                        {
                            aiomatic_log_to_file('No more topics to process.');
                            if($auto == 1)
                            {
                                aiomatic_clearFromList($param, $type);
                            }
                            return 'nochange';
                        }

                        if($nrx !== null && $nrx !== false)
                        {
                            $post_topic = $post_topic_list_arr[$nrx];
                            if (filter_var($post_topic, FILTER_VALIDATE_URL) !== false) 
                            {
                                $additional_topics = array();
                                if(aiomatic_endsWith($post_topic, '.txt'))
                                {
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing txt file'));
                                    $txt_content = aiomatic_get_web_page($post_topic);
                                    if ($txt_content === FALSE) 
                                    {
                                        unset($post_topic_list_arr[$nrx]);
                                        $post_topic_list_arr = array_values($post_topic_list_arr);
                                        aiomatic_log_to_file('Failed to read text file: ' . $post_topic);
                                        if($auto == 1)
                                        {
                                            aiomatic_log_to_file($param);
                                        }
                                        break;
                                    }
                                    $additional_topics = preg_split('/\r\n|\r|\n/', $txt_content);
                                }
                                else
                                {
                                    aiomatic_log_to_file('Trying to parse RSS feed items(2): ' . $post_topic);
                                    try
                                    {
                                        if(!class_exists('SimplePie_Autoloader', false))
                                        {
                                            require_once(dirname(__FILE__) . "/res/simplepie/autoloader.php");
                                        }
                                    }
                                    catch(Exception $e) 
                                    {
                                        unset($post_topic_list_arr[$nrx]);
                                        $post_topic_list_arr = array_values($post_topic_list_arr);
                                        aiomatic_log_to_file('Exception thrown in SimplePie autoloader: ' . $e->getMessage());
                                        if($auto == 1)
                                        {
                                            aiomatic_log_to_file($param);
                                        }
                                        break;
                                    }
                                    
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing RSS feed'));
                                    $feed = new SimplePie();
                                    $feed->set_timeout(120);
                                    $feed->set_feed_url($post_topic);
                                    $feed->enable_cache(false);
                                    $feed->strip_htmltags(false);
                                    $feed->init();
                                    $feed->handle_content_type();
                                    if ($feed->error()) 
                                    {
                                        aiomatic_log_to_file('Error in parsing RSS feed: ' . $feed->error() . ' for ' . $post_topic);
                                        unset($post_topic_list_arr[$nrx]);
                                        $post_topic_list_arr = array_values($post_topic_list_arr);
                                        if($auto == 1)
                                        {
                                            aiomatic_clearFromList($param, $type);
                                        }
                                        break;
                                    }
                                    unset($post_topic_list_arr[$nrx]);
                                    $post_topic_list_arr = array_values($post_topic_list_arr);
                                    $items = $feed->get_items();
                                    // Limit RSS feed items to prevent memory exhaustion (max 500 items per feed)
                                    $max_rss_items = 500;
                                    $rss_item_count = 0;
                                    foreach($items as $itemx)
                                    {
                                        if($rss_item_count >= $max_rss_items) {
                                            break;
                                        }
                                        $additional_topics[] = $itemx->get_title();
                                        $post_topic_list_arr[] = $itemx->get_title();
                                        $rss_item_count++;
                                    }
                                    // Free memory after processing RSS feed
                                    unset($items);
                                    unset($feed);
                                }
                                if(!empty($additional_topics))
                                {
                                    $post_topic = $additional_topics[array_rand($additional_topics)];
                                }
                            }

                        }
                        else
                        {
                            $post_topic = '';
                        }

                        if($overwrite_existing == '1')
                        {
                            foreach($posted_topics as $ptit => $pid)
                            {
                                if(!strstr($ptit, '%%title%%'))
                                {
                                    if (($key = array_search($ptit, $post_topic_list_arr)) !== false) 
                                    {
                                        $post_topic     = $ptit;
                                        $update_post_id = $pid; 
                                        break;
                                    }
                                }
                            }
                        }
                        if($title_once == '1')
                        {
                            $post_topic_list_arr = array_values($post_topic_list_arr);
                        }
                        if($no_init_topics === false && count($post_topic_list_arr) == 0)
                        {
                            if($title_once == '1')
                            {
                                if (isset($aiomatic_Main_Settings['email_notification']) && $aiomatic_Main_Settings['email_notification'] != '')
                                {
                                    if($count === 1)
                                    {
                                        $email_list = explode(',', $aiomatic_Main_Settings['email_notification']);
                                        foreach($email_list as $thisaddr)
                                        {
                                            $thisaddr = trim($thisaddr);
                                            try
                                            {
                                                $admin_mail = get_option('admin_email');
                                                $to        = $thisaddr;
                                                $subject   = '[Aimogen] Topics depleted rule ID ' . $param . ' - ' . aiomatic_get_date_now();
                                                $message   = 'Rule ID ' . esc_html($param) . ' (' . $rule_description . ') depleted its topics, no new posts publised! Website URL: ' . get_site_url();
                                                $headers[] = 'From: Aimogen Plugin <' . $admin_mail . '>';
                                                $headers[] = 'Reply-To: ' . $admin_mail;
                                                $headers[] = 'X-Mailer: PHP/' . phpversion();
                                                $headers[] = 'Content-Type: text/html';
                                                $headers[] = 'Charset: ' . get_option('blog_charset', 'UTF-8');
                                                wp_mail($to, $subject, $message, $headers);
                                            }
                                            catch (Exception $e) {
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                    aiomatic_log_to_file('Failed to send mail: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            aiomatic_log_to_file('All topics already processed, nothing to do.');
                            if($auto == 1)
                            {
                                aiomatic_clearFromList($param, $type);
                            }
                            return 'nochange';
                        }
                        
                        if ($title_once == '1' && isset($posted_lookup[$norm($post_topic)])) {
                            aiomatic_log_to_file('Duplicate detected after selection: ' . $post_topic);
                            unset($post_topic_list_arr[$nrx]);
                            continue;
                        }
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                        {
                            if(empty($post_topic))
                            {
                                if($type == 6)
                                {
                                    aiomatic_log_to_file('Starting processing listicle keyword by title');
                                }
                                else
                                {
                                    aiomatic_log_to_file('Starting processing post topic by title');
                                }
                            }
                            else
                            {
                                if($type == 6)
                                {
                                    aiomatic_log_to_file('Starting processing listicle keyword: ' . $post_topic);
                                }
                                else
                                {
                                    aiomatic_log_to_file('Starting processing post topic: ' . $post_topic);
                                }
                            }
                        }
                        if($title_once == '1')
                        {
                            if(!empty($post_topic_list))
                            {
                                unset($post_topic_list_arr[$nrx]);
                            }
                        }
                        $post_sections = '';
                        $current_section = '';
                        $headings_arr_copy = $headings_arr;
                        $added_img_list = array();
                        $raw_img_list = array();
                        $full_result_list = array();
                        $added_images = 0;
                        $added_videos = 0;
                        $heading_results = array();
                        $za_post_title = '';
                        if (!empty($post_title)) {
                            $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                        } elseif (!empty($post_topic)) {
                            $za_post_title = aiomatic_replaceContentShortcodes($post_topic, $img_attr, $ai_command);
                        }
                        if(!empty($global_prepend))
                        {
                            $global_prepend = aiomatic_replaceSynergyShortcodes($global_prepend);
                            $global_prepend = aiomatic_replaceContentShortcodes($global_prepend, $img_attr, $ai_command);
                            $global_prepend = aiomatic_replacetopics($global_prepend, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, '', '', $default_cat_list, $img_attr);
                            $global_prepend = aiomatic_replaceAIPostShortcodes($global_prepend, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', '');     
                        }
                        if(!empty($global_append))
                        {
                            $global_append = aiomatic_replaceSynergyShortcodes($global_append);
                            $global_append = aiomatic_replaceContentShortcodes($global_append, $img_attr, $ai_command);
                            $global_append = aiomatic_replacetopics($global_append, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, '', '', $default_cat_list, $img_attr);
                            $global_append = aiomatic_replaceAIPostShortcodes($global_append, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', '');     
                        }
                        if(($title_generator_method == 'ai' || empty($title_generator_method)) && $title_prompt != '' && $post_topic_list != '')
                        {
                            if(count($post_title_lines) == 0)
                            {
                                aiomatic_log_to_file('Stopping execution, no titles added: ' . $post_topic);
                                break;
                            }
                            if (!isset($aiomatic_Main_Settings['no_random_titles']) || $aiomatic_Main_Settings['no_random_titles'] != 'on')
                            {
                                $current_index = array_rand($post_title_lines);
                                $post_title = trim($post_title_lines[$current_index]);
                            }
                            else
                            {
                                $current_index = array_key_first($post_title_lines);
                                $post_title = trim($post_title_lines[$current_index]);
                                if (filter_var($post_title, FILTER_VALIDATE_URL) === false && stristr($post_title, '%%ai_generated_title%%') === false)
                                {
                                    unset($post_title_lines[$current_index]);
                                }
                            }
                            $ptlprocessed = explode('!###!', $post_title);
                            if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                            {
                                $post_title = $ptlprocessed[0];
                                $post_title_keywords = $ptlprocessed[1];
                            }
                            $post_title = apply_filters('aiomatic_replace_aicontent_shortcode', $post_title);
                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                            {
                                $title_prompt_arr = preg_split('/\r\n|\r|\n/', $title_prompt);
                                $my_title_prompt = $title_prompt_arr[array_rand($title_prompt_arr)];
                            }
                            else
                            {
                                $my_title_prompt = $title_prompt;
                            }
                            $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                            $zatitle_prompt = aiomatic_replacetopics($my_title_prompt, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                            $zatitle_prompt = aiomatic_replaceAIPostShortcodes($zatitle_prompt, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                            if(stristr($run_regex_on, 'title') !== false)
                            {
                                if ($strip_by_regex_prompts !== '')
                                {
                                    $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                    $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                    $xcnt = 0;
                                    foreach($xstrip_by_regex as $sbr)
                                    {
                                        if(isset($xreplace_regex[$xcnt]))
                                        {
                                            $repreg = $xreplace_regex[$xcnt];
                                        }
                                        else
                                        {
                                            $repreg = '';
                                        }
                                        $xcnt++;
                                        $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $zatitle_prompt);
                                        if($temp_cont !== NULL)
                                        {
                                            $zatitle_prompt = $temp_cont;
                                        }
                                    }
                                }
                            }
                            if($zatitle_prompt != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating topic based title'));
                                $written = aiomatic_write_content($zatitle_prompt, $topic_title_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, true, false, 'title', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate title!');
                                    if($auto == 1)
                                    {
                                        aiomatic_clearFromList($param, $type);
                                    }
                                    return 'fail';
                                }
                                else
                                {
                                    $written = ucfirst(trim(trim($written), '.'));
                                    $post_title = $written;
                                    if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                                    {
                                        $posts = get_posts(
                                            array(
                                                'post_type'              => $post_type,
                                                'title'                  => html_entity_decode($post_title),
                                                'post_status'            => 'any',
                                                'numberposts'            => 1,
                                                'update_post_term_cache' => false,
                                                'update_post_meta_cache' => false,           
                                                'orderby'                => 'post_date ID',
                                                'order'                  => 'ASC',
                                            )
                                        );
                                        if ( ! empty( $posts ) ) {
                                            $zap = $posts[0];
                                        } else {
                                            $zap = null;
                                        }
                                        if($zap !== null)
                                        {
                                            if($overwrite_existing)
                                            {
                                                $update_post_id = $zap->ID;
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Post with specified AI generated title already published, skipping it: ' . $post_title);
                                                unset($post_topic_list_arr[$nrx]);
                                                continue;
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed title prompt. Nothing to do.');
                                if($auto == 1)
                                {
                                    aiomatic_clearFromList($param, $type);
                                }
                                return 'fail';
                            }
                        }
                        elseif($title_generator_method == 'serp' && $post_topic_list != '')
                        {
                            $post_topic = apply_filters('aiomatic_replace_aicontent_shortcode', $post_topic);
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Getting title from SERP results'));
                            $heading_results_ai = aiomatic_scrape_related_questions($post_topic, $headings, $headings_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $headings_ai_command, $assistant_id);
                            if(is_array($heading_results_ai) && !empty($heading_results_ai))
                            {
                                $rand_index = array_rand($heading_results_ai);
                                $post_title = ucfirst($heading_results_ai[$rand_index]['q']);
                                if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                                {
                                    $posts = get_posts(
                                        array(
                                            'post_type'              => $post_type,
                                            'title'                  => html_entity_decode($post_title),
                                            'post_status'            => 'any',
                                            'numberposts'            => 1,
                                            'update_post_term_cache' => false,
                                            'update_post_meta_cache' => false,           
                                            'orderby'                => 'post_date ID',
                                            'order'                  => 'ASC',
                                        )
                                    );
                                    if ( ! empty( $posts ) ) {
                                        $zap = $posts[0];
                                    } else {
                                        $zap = null;
                                    }
                                    if($zap !== null)
                                    {
                                        if($overwrite_existing)
                                        {
                                            $update_post_id = $zap->ID;
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Post with specified SERP results generated title already published, skipping it: ' . $post_title);
                                            unset($post_title_lines[$current_index]);
                                            continue;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if(count($post_title_lines) == 0)
                            {
                                aiomatic_log_to_file('Stopping execution because no titles added: ' . $post_topic);
                                break;
                            }
                            if (!isset($aiomatic_Main_Settings['no_random_titles']) || $aiomatic_Main_Settings['no_random_titles'] != 'on')
                            {
                                $current_index = array_rand($post_title_lines);
                            }
                            else
                            {
                                $current_index = array_key_first($post_title_lines);
                            }
                            $post_title = trim($post_title_lines[$current_index]);
                            $ptlprocessed = explode('!###!', $post_title);
                            if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                            {
                                $post_title = $ptlprocessed[0];
                                $post_title_keywords = $ptlprocessed[1];
                            }
                            if(isset($rss_feeds[$post_title]))
                            {
                                $post_link = $rss_feeds[$post_title]['url'];
                                $user_name = $rss_feeds[$post_title]['author'];
                                $post_cats = $rss_feeds[$post_title]['cats'];
                                $post_excerpt = $rss_feeds[$post_title]['excerpt'];
                                $final_content = $rss_feeds[$post_title]['content'];
                            }
                            $tprepp = $spintax->Parse($post_title);
                            if($tprepp != false && $tprepp != '')
                            {
                                $post_title = $tprepp;
                            }
                            $old_title = $post_title;
                            $already_spinned = 0;
                            if (filter_var($post_title, FILTER_VALIDATE_URL) === false && stristr($post_title, '%%ai_generated_title%%') === false)
                            {
                                unset($post_title_lines[$current_index]);
                            }
                            $post_title = apply_filters('aiomatic_replace_aicontent_shortcode', $post_title);
                            if (strpos($post_title, '%%') === false)
                            {
                                if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                                {
                                    $posts = get_posts(
                                        array(
                                            'post_type'              => $post_type,
                                            'title'                  => html_entity_decode($post_title),
                                            'post_status'            => 'any',
                                            'numberposts'            => 1,
                                            'update_post_term_cache' => false,
                                            'update_post_meta_cache' => false,           
                                            'orderby'                => 'post_date ID',
                                            'order'                  => 'ASC',
                                        )
                                    );
                                    if ( ! empty( $posts ) ) {
                                        $zap = $posts[0];
                                    } else {
                                        $zap = null;
                                    }
                                    if($zap !== null)
                                    {
                                        if($overwrite_existing)
                                        {
                                            $update_post_id = $zap->ID;
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Post with specified title existing, skipping it: ' . $post_title);
                                            unset($post_title_lines[$current_index]);
                                            continue;
                                        }
                                    }
                                }
                                $new_post_title = $post_title;
                            }
                            else
                            {
                                $new_post_title = $post_title;
                                $new_post_title = aiomatic_replaceContentShortcodes($new_post_title, $img_attr, $ai_command);
                                if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                                {
                                    $posts = get_posts(
                                        array(
                                            'post_type'              => $post_type,
                                            'title'                  => html_entity_decode($new_post_title),
                                            'post_status'            => 'any',
                                            'numberposts'            => 1,
                                            'update_post_term_cache' => false,
                                            'update_post_meta_cache' => false,           
                                            'orderby'                => 'post_date ID',
                                            'order'                  => 'ASC',
                                        )
                                    );
                                    if ( ! empty( $posts ) ) {
                                        $zap = $posts[0];
                                    } else {
                                        $zap = null;
                                    }
                                    if($zap !== null)
                                    {
                                        if($overwrite_existing)
                                        {
                                            $update_post_id = $zap->ID;
                                        }
                                        else
                                        {
                                            if (filter_var($post_title, FILTER_VALIDATE_URL) === false && stristr($post_title, '%%ai_generated_title%%') === false)
                                            {
                                                aiomatic_log_to_file('Post with specified title already published, skipping it: ' . $new_post_title);
                                                unset($post_title_lines[$current_index]);
                                                continue;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if(empty($post_title))
                        {
                            aiomatic_log_to_file('Empty post title submitted, nothing to do!');
                            unset($post_title_lines[$current_index]);
                            continue;
                        }
                        if(stristr($run_regex_on, 'sections') !== false)
                        {
                            if ($strip_by_regex_prompts !== '')
                            {
                                $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                $xcnt = 0;
                                foreach($xstrip_by_regex as $sbr)
                                {
                                    if(isset($xreplace_regex[$xcnt]))
                                    {
                                        $repreg = $xreplace_regex[$xcnt];
                                    }
                                    else
                                    {
                                        $repreg = '';
                                    }
                                    $xcnt++;
                                    $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $sections_prompt);
                                    if($temp_cont !== NULL)
                                    {
                                        $sections_prompt = $temp_cont;
                                    }
                                }
                            }
                        }
                        if($sections_prompt != '' && $post_sections_list == '')
                        {
                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                            {
                                $sections_prompt_arr = preg_split('/\r\n|\r|\n/', $sections_prompt);
                                $my_post_section = $sections_prompt_arr[array_rand($sections_prompt_arr)];
                            }
                            else
                            {
                                $my_post_section = $sections_prompt;
                            }
                            $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                            $my_post_section = aiomatic_replacetopics($my_post_section, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                            $my_post_section = aiomatic_replaceAIPostShortcodes($my_post_section, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                            if($my_post_section != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating topic based sections'));
                                $written = aiomatic_write_content($my_post_section, $topic_sections_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, true, false, 'sections', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate sections!');
                                    if($auto == 1)
                                    {
                                        aiomatic_clearFromList($param, $type);
                                    }
                                    return 'fail';
                                }
                                else
                                {
                                    $post_sections = $written;
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed sections prompt (2). Nothing to do.');
                                if($auto == 1)
                                {
                                    aiomatic_clearFromList($param, $type);
                                }
                                return 'fail';
                            }
                        }
                        else
                        {
                            if($post_sections_list != '')
                            {
                                $post_sections = $spintax->Parse($post_sections_list);
                                $post_sections = str_replace('%%topic%%', $post_topic, $post_sections);
                            }
                        }
                        $post_sections = aiomatic_filter_sections($post_sections);
                        $new_post_content = '';
                        if(stristr($run_regex_on, 'intro') !== false)
                        {
                            if ($strip_by_regex_prompts !== '')
                            {
                                $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                $xcnt = 0;
                                foreach($xstrip_by_regex as $sbr)
                                {
                                    if(isset($xreplace_regex[$xcnt]))
                                    {
                                        $repreg = $xreplace_regex[$xcnt];
                                    }
                                    else
                                    {
                                        $repreg = '';
                                    }
                                    $xcnt++;
                                    $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $intro_prompt);
                                    if($temp_cont !== NULL)
                                    {
                                        $intro_prompt = $temp_cont;
                                    }
                                }
                            }
                        }
                        if($intro_prompt != '')
                        {
                            $my_intro_prompt = $intro_prompt;
                            $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                            $my_intro_prompt = aiomatic_replacetopics($my_intro_prompt, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                            $my_intro_prompt = aiomatic_replaceAIPostShortcodes($my_intro_prompt, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                            if($my_intro_prompt != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating topic based intro'));
                                $written = aiomatic_write_content($my_intro_prompt, $topic_intro_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'intro', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate intro for section: ' . $current_section);
                                    unset($post_title_lines[$current_index]);
                                    continue;
                                }
                                else
                                {
                                    if($new_post_content != '')
                                    {
                                        $new_post_content .= ' ';
                                    }
                                    $new_post_content .= $written;
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed intro prompt. Nothing to do.');
                            }
                        }
                        if(stristr($topic_images_bck, '-') !== false)
                        {
                            preg_match('/\s*(\d+)\s*-\s*(\d+)\s*/', $topic_images_bck, $matches);
                            if(isset($matches[2]) && $matches[2] != '' && isset($matches[1]) && $matches[1] != '')
                            {
                                $txmin = intval($matches[1]);
                                $txmax = intval($matches[2]);
                                $topic_images = mt_rand($txmin, $txmax);
                            }
                            else
                            {
                                $topic_images = $topic_images_bck;
                            }
                        }
                        if($heading_image_loc == 'bottom')
                        {
                            $img_go = false;
                            $vid_go = false;
                            $vid_stopped = false;
                            $imgage_fail = true;
                            if($img_all_headings == '1' || ($topic_images != '' && is_numeric($topic_images) && $topic_images > $added_images))
                            {
                                $img_go = true;
                            }
                            if($topic_videos != '' && is_numeric($topic_videos) && $topic_videos > $added_videos)
                            {
                                $vid_go = true;
                            }
                            if($img_go == true && $vid_go == true)
                            {
                                $locrandme = wp_rand(1,100);
                                if($locrandme > 50)
                                {
                                    $vid_go = false;
                                    $vid_stopped = true;
                                }
                                else
                                {
                                    $img_go = false;
                                }
                            }
                            if(isset($aiomatic_Main_Settings['no_intro_image']) && trim($aiomatic_Main_Settings['no_intro_image']) == 'on')
                            {
                                $img_go = false;
                            }
                            if($img_go == true)
                            {
                                if($new_post_content !== '')
                                {
                                    $the_image_prompt = $post_title;
                                    if($enable_ai_images_article != '0' && $enable_ai_images_article != '3')
                                    {
                                        $ai_command_image_article = $orig_ai_command_image_article;
                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                        {
                                            $ai_command_image_article = preg_split('/\r\n|\r|\n/', $ai_command_image_article);
                                            $ai_command_image_article = array_filter($ai_command_image_article);
                                            if(count($ai_command_image_article) > 0)
                                            {
                                                $ai_command_image_article = $ai_command_image_article[array_rand($ai_command_image_article)];
                                            }
                                            else
                                            {
                                                $ai_command_image_article = '';
                                            }
                                        }
                                        $za_post_title = aiomatic_replaceContentShortcodes($the_image_prompt, $img_attr, $ai_command);
                                        $ai_command_image_article = aiomatic_replacetopics($ai_command_image_article, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                        $ai_command_image_article = aiomatic_replaceSynergyShortcodes($ai_command_image_article);
                                        if(!empty($ai_command_image_article))
                                        {
                                            $ai_command_image_article = aiomatic_replaceAIPostShortcodes($ai_command_image_article, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        }
                                        else
                                        {
                                            $ai_command_image_article = trim(strip_tags($the_image_prompt));
                                        }
                                        $ai_command_image_article = trim($ai_command_image_article);
                                        if (filter_var($ai_command_image_article, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image_article, '.txt'))
                                        {
                                            $txt_content = aiomatic_get_web_page($ai_command_image_article);
                                            if ($txt_content !== FALSE) 
                                            {
                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                $txt_content = array_filter($txt_content);
                                                if(count($txt_content) > 0)
                                                {
                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                    if(trim($txt_content) != '') 
                                                    {
                                                        $ai_command_image_article = $txt_content;
                                                        $ai_command_image_article = aiomatic_replaceSynergyShortcodes($ai_command_image_article);
                                                        $ai_command_image_article = aiomatic_replaceAIPostShortcodes($ai_command_image_article, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                }
                                            }
                                        }
                                        if(empty($ai_command_image_article))
                                        {
                                            aiomatic_log_to_file('Empty API image seed expression provided!');
                                        }
                                        else
                                        {
                                            if(aiomatic_strlen($ai_command_image_article) > 1000)
                                            {
                                                $ai_command_image_article = aiomatic_substr($ai_command_image_article, 0, 1000);
                                            }
                                            $the_image_prompt = $ai_command_image_article;
                                        }
                                    }
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Searching for images'));
                                    $new_img = aiomatic_get_royalty_free_image($the_image_prompt, $enable_ai_images_article, $image_size_article, $images_arr, $token, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $custom_shortcodes, $global_prepend, $global_append, $image_url, $attached_id, $raw_img_list, $default_cat_list, $image_model_article);
                                    if(!empty($attached_id))
                                    {
                                        $additional_attachments[] = $attached_id;
                                    }
                                    if($new_img !== false && !in_array($new_img, $added_img_list))
                                    {
                                        $new_post_content .= '<br/><img class="timage_class" src="' . $new_img . '" alt="' . esc_attr($post_title) . '"><br/>';
                                        $added_img_list[] = $new_img;
                                        $added_images++;
                                        $imgage_fail = false;
                                    }
                                }
                            }
                            if($vid_go == true || ($imgage_fail == true && $vid_stopped == true))
                            {
                                if(isset($aiomatic_Main_Settings['social_list']) && !empty($aiomatic_Main_Settings['social_list']) && is_array($aiomatic_Main_Settings['social_list']))
                                {
                                    $social_list = $aiomatic_Main_Settings['social_list'];
                                }
                                else
                                {
                                    $social_list = array();
                                }
                                $new_vid = aiomatic_get_video($current_section, '', $social_list);
                                if($new_vid !== false && !in_array($new_vid, $added_vid_list))
                                {
                                    $new_post_content .= $new_vid;
                                    $added_vid_list[] = $new_vid;
                                    $added_videos++;
                                }
                            }
                        }
                        if($title_outro != '')
                        {
                            $my_title_outro = $title_outro;
                            $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                            $my_title_outro = aiomatic_replacetopics($my_title_outro, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                            $my_title_outro = aiomatic_replaceAIPostShortcodes($my_title_outro, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                            $my_title_outro = $spintax->Parse(trim($my_title_outro));
                        }
                        if(!empty($title_toc))
                        {
                            $my_title_toc = $title_toc;
                            $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                            $my_title_toc = aiomatic_replacetopics($my_title_toc, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                            $my_title_toc = aiomatic_replaceAIPostShortcodes($my_title_toc, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                            $my_title_toc = $spintax->Parse(trim($my_title_toc));
                        }
                        if($title_qa != '')
                        {
                            $my_title_qa = $title_qa;
                            $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                            $my_title_qa = aiomatic_replacetopics($my_title_qa, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                            $my_title_qa = aiomatic_replaceAIPostShortcodes($my_title_qa, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                            $my_title_qa = $spintax->Parse(trim($my_title_qa));
                        }
                        if($content_prompt != '')
                        {
                            $last_section_content = '';
                            if($single_content_call == '1')
                            {
                                $current_section = $post_sections;
                                $my_post_content = $content_prompt;
                                $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                                $my_post_content = aiomatic_replacetopics($my_post_content, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                $my_post_content = aiomatic_replaceAIPostShortcodes($my_post_content, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                $my_post_content = str_replace('%%article_so_far%%', $new_post_content, $my_post_content);
                                $my_post_content = str_replace('%%last_section_content%%', $last_section_content, $my_post_content);
                                if(stristr($run_regex_on, 'content') !== false)
                                {
                                    if ($strip_by_regex_prompts !== '')
                                    {
                                        $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                        $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                        $xcnt = 0;
                                        foreach($xstrip_by_regex as $sbr)
                                        {
                                            if(isset($xreplace_regex[$xcnt]))
                                            {
                                                $repreg = $xreplace_regex[$xcnt];
                                            }
                                            else
                                            {
                                                $repreg = '';
                                            }
                                            $xcnt++;
                                            $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_post_content);
                                            if($temp_cont !== NULL)
                                            {
                                                $my_post_content = $temp_cont;
                                            }
                                        }
                                    }
                                }
                                if($my_post_content != '')
                                {
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating topic based single content'));
                                    $written = aiomatic_write_content($my_post_content, $topic_content_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'content', 'user', $assistant_id, $thread_id, $store_data);
                                    if($written === false)
                                    {
                                        aiomatic_log_to_file('Failed to generate topic list for section: ' . $current_section);
                                        unset($post_title_lines[$current_index]);
                                        continue;
                                    }
                                    else
                                    {
                                        if($new_post_content != '')
                                        {
                                            $new_post_content .= ' ';
                                        }
                                        $new_img_arr = array();
                                        if($topic_images != '' && is_numeric($topic_images) && intval($topic_images) - 2 > $added_images)
                                        {
                                            $howmore = intval($topic_images) - 2;
                                            for($cont = 0; $cont < $howmore; $cont++)
                                            {
                                                if($search_query_repetition == '1')
                                                {
                                                    $the_image_prompt = $post_title;
                                                }
                                                else
                                                {
                                                    $the_image_prompt = $current_section;
                                                }
                                                if($enable_ai_images_article != '0' && $enable_ai_images_article != '3')
                                                {
                                                    $ai_command_image_article = $orig_ai_command_image_article;
                                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                                    {
                                                        $ai_command_image_article = preg_split('/\r\n|\r|\n/', $ai_command_image_article);
                                                        $ai_command_image_article = array_filter($ai_command_image_article);
                                                        if(count($ai_command_image_article) > 0)
                                                        {
                                                            $ai_command_image_article = $ai_command_image_article[array_rand($ai_command_image_article)];
                                                        }
                                                        else
                                                        {
                                                            $ai_command_image_article = '';
                                                        }
                                                    }
                                                    $za_post_title = aiomatic_replaceContentShortcodes($the_image_prompt, $img_attr, $ai_command);
                                                    $ai_command_image_article = aiomatic_replacetopics($ai_command_image_article, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                                    $ai_command_image_article = aiomatic_replaceSynergyShortcodes($ai_command_image_article);
                                                    if(!empty($ai_command_image_article))
                                                    {
                                                        $ai_command_image_article = aiomatic_replaceAIPostShortcodes($ai_command_image_article, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                    else
                                                    {
                                                        $ai_command_image_article = trim(strip_tags($the_image_prompt));
                                                    }
                                                    $ai_command_image_article = trim($ai_command_image_article);
                                                    if (filter_var($ai_command_image_article, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image_article, '.txt'))
                                                    {
                                                        $txt_content = aiomatic_get_web_page($ai_command_image_article);
                                                        if ($txt_content !== FALSE) 
                                                        {
                                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                            $txt_content = array_filter($txt_content);
                                                            if(count($txt_content) > 0)
                                                            {
                                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                                if(trim($txt_content) != '') 
                                                                {
                                                                    $ai_command_image_article = $txt_content;
                                                                    $ai_command_image_article = aiomatic_replaceSynergyShortcodes($ai_command_image_article);
                                                                    $ai_command_image_article = aiomatic_replaceAIPostShortcodes($ai_command_image_article, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                                }
                                                            }
                                                        }
                                                    }
                                                    if(empty($ai_command_image_article))
                                                    {
                                                        aiomatic_log_to_file('Empty API image seed expression provided!');
                                                    }
                                                    else
                                                    {
                                                        if(aiomatic_strlen($ai_command_image_article) > 1000)
                                                        {
                                                            $ai_command_image_article = aiomatic_substr($ai_command_image_article, 0, 1000);
                                                        }
                                                        $the_image_prompt = $ai_command_image_article;
                                                    }
                                                }
                                                $new_img = aiomatic_get_royalty_free_image($the_image_prompt, $enable_ai_images_article, $image_size_article, $images_arr, $token, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $custom_shortcodes, $global_prepend, $global_append, $image_url, $attached_id, $raw_img_list, $default_cat_list, $image_model_article);
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                                if($new_img !== false && !in_array($new_img, $added_img_list))
                                                {
                                                    $new_post_content .= '<br/><img class="pimage_class" src="' . $new_img . '" alt="' . esc_attr($current_section) . '"><br/>';
                                                    $added_img_list[] = $new_img;
                                                    $new_img_arr[] = $new_img;
                                                    $added_images++;
                                                }
                                            } 
                                        }
                                        if(count($new_img_arr) > 0)
                                        {
                                            $written_arr = preg_split("/\r\n|\n|\r/", $written);
                                            if(count($written_arr) > 1)
                                            {
                                                foreach($new_img_arr as $new_img_x)
                                                {
                                                    array_splice($written_arr, wp_rand(0, count($written_arr)), 0, '<br/><img src="' . $new_img_x . '">');
                                                }
                                                $written = implode('\r\n', $written_arr);
                                            }
                                        }
                                        $new_vid_arr = array();
                                        $new_post_content .= $written;
                                        if($topic_videos != '' && is_numeric($topic_videos) && intval($topic_videos) > $added_videos)
                                        {
                                            if(isset($aiomatic_Main_Settings['social_list']) && !empty($aiomatic_Main_Settings['social_list']) && is_array($aiomatic_Main_Settings['social_list']))
                                            {
                                                $social_list = $aiomatic_Main_Settings['social_list'];
                                            }
                                            else
                                            {
                                                $social_list = array();
                                            }
                                            $howmore = intval($topic_videos) - $added_videos;
                                            for($cont = 0; $cont < $howmore; $cont++)
                                            {
                                                $new_vid = aiomatic_get_video($current_section, '', $social_list);
                                                if($new_vid !== false && !in_array($new_vid, $added_vid_list))
                                                {
                                                    $new_post_content .= $new_vid;
                                                    $added_vid_list[] = $new_vid;
                                                    $new_vid_arr[] = $new_vid;
                                                    $added_videos++;
                                                }
                                            } 
                                        }
                                        if(count($new_vid_arr) > 0)
                                        {
                                            $written_arr = preg_split("/\r\n|\n|\r/", $written);
                                            if(count($written_arr) > 1)
                                            {
                                                foreach($new_vid_arr as $new_img_x)
                                                {
                                                    array_splice($written_arr, wp_rand(0, count($written_arr)), 0, '<br/><img src="' . $new_img_x . '">');
                                                }
                                                $written = implode('\r\n', $written_arr);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty processed topic prompt. Nothing to do.');
                                }
                            }
                            else
                            {
                                if($post_sections != '')
                                {
                                    $post_sections_arr = preg_split('/\r\n|\r|\n/', $post_sections);
                                }
                                else
                                {
                                    $post_sections_arr = array();
                                }
                                if(stristr($section_count, '-') === false && is_numeric($section_count))
                                {
                                    $snum = intval($section_count);
                                    if($snum > 0 && count($post_sections_arr) > $snum)
                                    {
                                        $post_sections_arr = array_slice($post_sections_arr, 0, $snum);
                                    }
                                }
                                $toc = '';
                                if($enable_toc == '1')
                                {
                                    if(!empty($title_toc))
                                    {
                                        if($my_title_toc != '')
                                        {
                                            $toc .= '<h2>' . $my_title_toc . '</h2>';
                                        }
                                    }
                                    $toc .= '<ul class="toc-class">';
                                    foreach($post_sections_arr as $current_section)
                                    {
                                        if(!empty($current_section))
                                        {
                                            $toc .= '<li><a href="#' . sanitize_title($current_section) . '">' . $current_section . '</a></li>';
                                        }
                                    }
                                    if($title_qa != '')
                                    {
                                        if($my_title_qa != '')
                                        {
                                            if($qa_prompt != '' && $enable_qa == '1')
                                            {
                                                $toc .= '<li><a href="#qa">' . $my_title_qa . '</a></li>';
                                            }
                                        }
                                    }
                                    if($title_outro != '')
                                    {
                                        if($my_title_outro != '')
                                        {
                                            if($outro_prompt != '')
                                            {
                                                $toc .= '<li><a href="#outro">' . $my_title_outro . '</a></li>';
                                            }
                                        }
                                    }
                                    $toc .= '</ul>';
                                    $new_post_content .= '<br/>' . $toc . '<br/>';
                                }
                                $section_cont = 1;
                                $last_section_content = '';
                                foreach($post_sections_arr as $current_section)
                                {
                                    $current_section = trim($current_section);
                                    $current_section = trim($current_section, '.;');
                                    if(empty($current_section))
                                    {
                                        continue;
                                    }
                                    $my_post_content = $content_prompt;
                                    $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                                    $my_post_content = aiomatic_replacetopics($my_post_content, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                    $my_post_content = aiomatic_replaceAIPostShortcodes($my_post_content, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    $my_post_content = str_replace('%%article_so_far%%', $new_post_content, $my_post_content);
                                    $my_post_content = str_replace('%%last_section_content%%', $last_section_content, $my_post_content);
                                    if(stristr($run_regex_on, 'content') !== false)
                                    {
                                        if ($strip_by_regex_prompts !== '')
                                        {
                                            $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                            $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                            $xcnt = 0;
                                            foreach($xstrip_by_regex as $sbr)
                                            {
                                                if(isset($xreplace_regex[$xcnt]))
                                                {
                                                    $repreg = $xreplace_regex[$xcnt];
                                                }
                                                else
                                                {
                                                    $repreg = '';
                                                }
                                                $xcnt++;
                                                $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_post_content);
                                                if($temp_cont !== NULL)
                                                {
                                                    $my_post_content = $temp_cont;
                                                }
                                            }
                                        }
                                    }
                                    if($my_post_content != '')
                                    {
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating topic based section #' . $section_cont));
                                        $section_cont++;
                                        $written = aiomatic_write_content($my_post_content, $topic_content_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'content', 'user', $assistant_id, $thread_id, $store_data);
                                        if($written === false)
                                        {
                                            aiomatic_log_to_file('Failed to generate content for section: ' . $current_section);
                                            continue;
                                        }
                                        else
                                        {
                                            if($heading_image_loc == 'top')
                                            {
                                                $img_go = false;
                                                $vid_go = false;
                                                $vid_stopped = false;
                                                $imgage_fail = true;
                                                if($img_all_headings == '1' || ($topic_images != '' && is_numeric($topic_images) && $topic_images > $added_images))
                                                {
                                                    $img_go = true;
                                                }
                                                if($topic_videos != '' && is_numeric($topic_videos) && $topic_videos > $added_videos)
                                                {
                                                    $vid_go = true;
                                                }
                                                if($img_go == true && $vid_go == true)
                                                {
                                                    $locrandme = wp_rand(1,100);
                                                    if($locrandme > 50)
                                                    {
                                                        $vid_go = false;
                                                        $vid_stopped = true;
                                                    }
                                                    else
                                                    {
                                                        $img_go = false;
                                                    }
                                                }
                                                if($img_go == true)
                                                {
                                                    if($new_post_content !== '')
                                                    {
                                                        if($search_query_repetition == '1')
                                                        {
                                                            $the_image_prompt = $post_title;
                                                        }
                                                        else
                                                        {
                                                            $the_image_prompt = $current_section;
                                                        }
                                                        if($enable_ai_images_article != '0' && $enable_ai_images_article != '3')
                                                        {
                                                            $ai_command_image_article = $orig_ai_command_image_article;
                                                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                                            {
                                                                $ai_command_image_article = preg_split('/\r\n|\r|\n/', $ai_command_image_article);
                                                                $ai_command_image_article = array_filter($ai_command_image_article);
                                                                if(count($ai_command_image_article) > 0)
                                                                {
                                                                    $ai_command_image_article = $ai_command_image_article[array_rand($ai_command_image_article)];
                                                                }
                                                                else
                                                                {
                                                                    $ai_command_image_article = '';
                                                                }
                                                            }
                                                            $za_post_title = aiomatic_replaceContentShortcodes($the_image_prompt, $img_attr, $ai_command);
                                                            $ai_command_image_article = aiomatic_replacetopics($ai_command_image_article, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                                            $ai_command_image_article = aiomatic_replaceSynergyShortcodes($ai_command_image_article);
                                                            if(!empty($ai_command_image_article))
                                                            {
                                                                $ai_command_image_article = aiomatic_replaceAIPostShortcodes($ai_command_image_article, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                            }
                                                            else
                                                            {
                                                                $ai_command_image_article = trim(strip_tags($the_image_prompt));
                                                            }
                                                            $ai_command_image_article = trim($ai_command_image_article);
                                                            if (filter_var($ai_command_image_article, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image_article, '.txt'))
                                                            {
                                                                $txt_content = aiomatic_get_web_page($ai_command_image_article);
                                                                if ($txt_content !== FALSE) 
                                                                {
                                                                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                                    $txt_content = array_filter($txt_content);
                                                                    if(count($txt_content) > 0)
                                                                    {
                                                                        $txt_content = $txt_content[array_rand($txt_content)];
                                                                        if(trim($txt_content) != '') 
                                                                        {
                                                                            $ai_command_image_article = $txt_content;
                                                                            $ai_command_image_article = aiomatic_replaceSynergyShortcodes($ai_command_image_article);
                                                                            $ai_command_image_article = aiomatic_replaceAIPostShortcodes($ai_command_image_article, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            if(empty($ai_command_image_article))
                                                            {
                                                                aiomatic_log_to_file('Empty API image seed expression provided!');
                                                            }
                                                            else
                                                            {
                                                                if(aiomatic_strlen($ai_command_image_article) > 1000)
                                                                {
                                                                    $ai_command_image_article = aiomatic_substr($ai_command_image_article, 0, 1000);
                                                                }
                                                                $the_image_prompt = $ai_command_image_article;
                                                            }
                                                        }
                                                        $new_img = aiomatic_get_royalty_free_image($the_image_prompt, $enable_ai_images_article, $image_size_article, $images_arr, $token, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $custom_shortcodes, $global_prepend, $global_append, $image_url, $attached_id, $raw_img_list, $default_cat_list, $image_model_article);
                                                        if(!empty($attached_id))
                                                        {
                                                            $additional_attachments[] = $attached_id;
                                                        }
                                                        if($new_img !== false && !in_array($new_img, $added_img_list))
                                                        {
                                                            $new_post_content .= '<br/><img class="kimage_class" src="' . $new_img . '" alt="' . esc_attr($current_section) . '"><br/>';
                                                            $added_img_list[] = $new_img;
                                                            $added_images++;
                                                            $imgage_fail = false;
                                                        }
                                                    }
                                                }
                                                if($vid_go == true || ($imgage_fail == true && $vid_stopped == true))
                                                {
                                                    if(isset($aiomatic_Main_Settings['social_list']) && !empty($aiomatic_Main_Settings['social_list']) && is_array($aiomatic_Main_Settings['social_list']))
                                                    {
                                                        $social_list = $aiomatic_Main_Settings['social_list'];
                                                    }
                                                    else
                                                    {
                                                        $social_list = array();
                                                    }
                                                    $new_vid = aiomatic_get_video($current_section, '', $social_list);
                                                    if($new_vid !== false && !in_array($new_vid, $added_vid_list))
                                                    {
                                                        $new_post_content .= $new_vid;
                                                        $added_vid_list[] = $new_vid;
                                                        $added_videos++;
                                                    }
                                                }
                                            }
                                            $written = str_ireplace($current_section, '', $written);
                                            preg_match_all('#\d+\.\s*([\s\S]*)#', $current_section, $mxatches);
                                            if(isset($mxatches[1][0]))
                                            {
                                                $written = str_ireplace(trim($mxatches[1][0]), '', $written);
                                                $written = str_ireplace(str_replace(['"', '\''], '', $mxatches[1][0]), '', $written);
                                            }
                                            $written = str_ireplace('<h2></h2>', '', $written);
                                            $written = str_ireplace('<h3></h3>', '', $written);
                                            if($sections_role == 'h2')
                                            {
                                                $new_post_content .= '<h2 id="' . sanitize_title($current_section) . '">' . $current_section . '</h2>';
                                            }
                                            elseif($sections_role == 'h3')
                                            {
                                                $new_post_content .= '<h3 id="' . sanitize_title($current_section) . '">' . $current_section . '</h3>';
                                            }
                                            elseif($sections_role == 'b')
                                            {
                                                $new_post_content .= '<b id="' . sanitize_title($current_section) . '">' . $current_section . '</b>';
                                            }
                                            elseif($sections_role == 'i')
                                            {
                                                $new_post_content .= '<i id="' . sanitize_title($current_section) . '">' . $current_section . '</i>';
                                            }
                                            elseif($sections_role == 'bi')
                                            {
                                                $new_post_content .= '<b><i id="' . sanitize_title($current_section) . '">' . $current_section . '</i></b>';
                                            }
                                            elseif($sections_role == 'p')
                                            {
                                                $new_post_content .= '<p id="' . sanitize_title($current_section) . '">' . $current_section . '</p>';
                                            }
                                            elseif($sections_role == 'x')
                                            {
                                                $new_post_content .= '<br/><span id="' . sanitize_title($current_section) . '">' . $current_section . '</span><br/>';
                                            }
                                            if($heading_image_loc == 'heading')
                                            {
                                                $img_go = false;
                                                $vid_go = false;
                                                $vid_stopped = false;
                                                $imgage_fail = true;
                                                if($img_all_headings == '1' || ($topic_images != '' && is_numeric($topic_images) && $topic_images > $added_images))
                                                {
                                                    $img_go = true;
                                                }
                                                if($topic_videos != '' && is_numeric($topic_videos) && $topic_videos > $added_videos)
                                                {
                                                    $vid_go = true;
                                                }
                                                if($img_go == true && $vid_go == true)
                                                {
                                                    $locrandme = wp_rand(1,100);
                                                    if($locrandme > 50)
                                                    {
                                                        $vid_go = false;
                                                        $vid_stopped = true;
                                                    }
                                                    else
                                                    {
                                                        $img_go = false;
                                                    }
                                                }
                                                if($img_go == true)
                                                {
                                                    if($new_post_content !== '')
                                                    {
                                                        if($search_query_repetition == '1')
                                                        {
                                                            $the_image_prompt = $post_title;
                                                        }
                                                        else
                                                        {
                                                            $the_image_prompt = $current_section;
                                                        }
                                                        if($enable_ai_images_article != '0' && $enable_ai_images_article != '3')
                                                        {
                                                            $ai_command_image_article = $orig_ai_command_image_article;
                                                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                                            {
                                                                $ai_command_image_article = preg_split('/\r\n|\r|\n/', $ai_command_image_article);
                                                                $ai_command_image_article = array_filter($ai_command_image_article);
                                                                if(count($ai_command_image_article) > 0)
                                                                {
                                                                    $ai_command_image_article = $ai_command_image_article[array_rand($ai_command_image_article)];
                                                                }
                                                                else
                                                                {
                                                                    $ai_command_image_article = '';
                                                                }
                                                            }
                                                            $za_post_title = aiomatic_replaceContentShortcodes($the_image_prompt, $img_attr, $ai_command);
                                                            $ai_command_image_article = aiomatic_replacetopics($ai_command_image_article, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                                            $ai_command_image_article = aiomatic_replaceSynergyShortcodes($ai_command_image_article);
                                                            if(!empty($ai_command_image_article))
                                                            {
                                                                $ai_command_image_article = aiomatic_replaceAIPostShortcodes($ai_command_image_article, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                            }
                                                            else
                                                            {
                                                                $ai_command_image_article = trim(strip_tags($the_image_prompt));
                                                            }
                                                            $ai_command_image_article = trim($ai_command_image_article);
                                                            if (filter_var($ai_command_image_article, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image_article, '.txt'))
                                                            {
                                                                $txt_content = aiomatic_get_web_page($ai_command_image_article);
                                                                if ($txt_content !== FALSE) 
                                                                {
                                                                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                                    $txt_content = array_filter($txt_content);
                                                                    if(count($txt_content) > 0)
                                                                    {
                                                                        $txt_content = $txt_content[array_rand($txt_content)];
                                                                        if(trim($txt_content) != '') 
                                                                        {
                                                                            $ai_command_image_article = $txt_content;
                                                                            $ai_command_image_article = aiomatic_replaceSynergyShortcodes($ai_command_image_article);
                                                                            $ai_command_image_article = aiomatic_replaceAIPostShortcodes($ai_command_image_article, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            if(empty($ai_command_image_article))
                                                            {
                                                                aiomatic_log_to_file('Empty API image seed expression provided!');
                                                            }
                                                            else
                                                            {
                                                                if(aiomatic_strlen($ai_command_image_article) > 1000)
                                                                {
                                                                    $ai_command_image_article = aiomatic_substr($ai_command_image_article, 0, 1000);
                                                                }
                                                                $the_image_prompt = $ai_command_image_article;
                                                            }
                                                        }
                                                        $new_img = aiomatic_get_royalty_free_image($the_image_prompt, $enable_ai_images_article, $image_size_article, $images_arr, $token, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $custom_shortcodes, $global_prepend, $global_append, $image_url, $attached_id, $raw_img_list, $default_cat_list, $image_model_article);
                                                        if(!empty($attached_id))
                                                        {
                                                            $additional_attachments[] = $attached_id;
                                                        }
                                                        if($new_img !== false && !in_array($new_img, $added_img_list))
                                                        {
                                                            $new_post_content .= '<br/><img class="gimage_class" src="' . $new_img . '" alt="' . esc_attr($current_section) . '"><br/>';
                                                            $added_img_list[] = $new_img;
                                                            $added_images++;
                                                            $imgage_fail = false;
                                                        }
                                                    }
                                                }
                                                if($vid_go == true || ($imgage_fail == true && $vid_stopped == true))
                                                {
                                                    if(isset($aiomatic_Main_Settings['social_list']) && !empty($aiomatic_Main_Settings['social_list']) && is_array($aiomatic_Main_Settings['social_list']))
                                                    {
                                                        $social_list = $aiomatic_Main_Settings['social_list'];
                                                    }
                                                    else
                                                    {
                                                        $social_list = array();
                                                    }
                                                    $new_vid = aiomatic_get_video($current_section, '', $social_list);
                                                    if($new_vid !== false && !in_array($new_vid, $added_vid_list))
                                                    {
                                                        $new_post_content .= $new_vid;
                                                        $added_vid_list[] = $new_vid;
                                                        $added_videos++;
                                                    }
                                                }
                                            }
                                            $last_section_content = $written;
                                            $new_post_content .= $written;
                                        }
                                        if($heading_image_loc == 'bottom')
                                        {
                                            $img_go = false;
                                            $vid_go = false;
                                            $vid_stopped = false;
                                            $imgage_fail = true;
                                            if($img_all_headings == '1' || ($topic_images != '' && is_numeric($topic_images) && $topic_images > $added_images))
                                            {
                                                $img_go = true;
                                            }
                                            if($topic_videos != '' && is_numeric($topic_videos) && $topic_videos > $added_videos)
                                            {
                                                $vid_go = true;
                                            }
                                            if($img_go == true && $vid_go == true)
                                            {
                                                $locrandme = wp_rand(1,100);
                                                if($locrandme > 50)
                                                {
                                                    $vid_go = false;
                                                    $vid_stopped = true;
                                                }
                                                else
                                                {
                                                    $img_go = false;
                                                }
                                            }
                                            if($img_go)
                                            {
                                                if($new_post_content !== '')
                                                {
                                                    if($search_query_repetition == '1')
                                                    {
                                                        $the_image_prompt = $post_title;
                                                    }
                                                    else
                                                    {
                                                        $the_image_prompt = $current_section;
                                                    }
                                                    if($enable_ai_images_article != '0' && $enable_ai_images_article != '3')
                                                    {
                                                        $ai_command_image_article = $orig_ai_command_image_article;
                                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                                        {
                                                            $ai_command_image_article = preg_split('/\r\n|\r|\n/', $ai_command_image_article);
                                                            $ai_command_image_article = array_filter($ai_command_image_article);
                                                            if(count($ai_command_image_article) > 0)
                                                            {
                                                                $ai_command_image_article = $ai_command_image_article[array_rand($ai_command_image_article)];
                                                            }
                                                            else
                                                            {
                                                                $ai_command_image_article = '';
                                                            }
                                                        }
                                                        $za_post_title = aiomatic_replaceContentShortcodes($the_image_prompt, $img_attr, $ai_command);
                                                        $ai_command_image_article = aiomatic_replacetopics($ai_command_image_article, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                                        $ai_command_image_article = aiomatic_replaceSynergyShortcodes($ai_command_image_article);
                                                        if(!empty($ai_command_image_article))
                                                        {
                                                            $ai_command_image_article = aiomatic_replaceAIPostShortcodes($ai_command_image_article, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                        }
                                                        else
                                                        {
                                                            $ai_command_image_article = trim(strip_tags($the_image_prompt));
                                                        }
                                                        $ai_command_image_article = trim($ai_command_image_article);
                                                        if (filter_var($ai_command_image_article, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image_article, '.txt'))
                                                        {
                                                            $txt_content = aiomatic_get_web_page($ai_command_image_article);
                                                            if ($txt_content !== FALSE) 
                                                            {
                                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                                $txt_content = array_filter($txt_content);
                                                                if(count($txt_content) > 0)
                                                                {
                                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                                    if(trim($txt_content) != '') 
                                                                    {
                                                                        $ai_command_image_article = $txt_content;
                                                                        $ai_command_image_article = aiomatic_replaceSynergyShortcodes($ai_command_image_article);
                                                                        $ai_command_image_article = aiomatic_replaceAIPostShortcodes($ai_command_image_article, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        if(empty($ai_command_image_article))
                                                        {
                                                            aiomatic_log_to_file('Empty API image seed expression provided!');
                                                        }
                                                        else
                                                        {
                                                            if(aiomatic_strlen($ai_command_image_article) > 1000)
                                                            {
                                                                $ai_command_image_article = aiomatic_substr($ai_command_image_article, 0, 1000);
                                                            }
                                                            $the_image_prompt = $ai_command_image_article;
                                                        }
                                                    }
                                                    $new_img = aiomatic_get_royalty_free_image($the_image_prompt, $enable_ai_images_article, $image_size_article, $images_arr, $token, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $custom_shortcodes, $global_prepend, $global_append, $image_url, $attached_id, $raw_img_list, $default_cat_list, $image_model_article);
                                                    if(!empty($attached_id))
                                                    {
                                                        $additional_attachments[] = $attached_id;
                                                    }
                                                    if($new_img !== false && !in_array($new_img, $added_img_list))
                                                    {
                                                        $new_post_content .= '<br/><img class="kimage_class" src="' . $new_img . '" alt="' . esc_attr($current_section) . '"><br/>';
                                                        $added_img_list[] = $new_img;
                                                        $added_images++;
                                                        $imgage_fail = false;
                                                    }
                                                }
                                            }
                                            if($vid_go == true || ($imgage_fail == true && $vid_stopped == true))
                                            {
                                                if(isset($aiomatic_Main_Settings['social_list']) && !empty($aiomatic_Main_Settings['social_list']) && is_array($aiomatic_Main_Settings['social_list']))
                                                {
                                                    $social_list = $aiomatic_Main_Settings['social_list'];
                                                }
                                                else
                                                {
                                                    $social_list = array();
                                                }
                                                $new_vid = aiomatic_get_video($current_section, '', $social_list);
                                                if($new_vid !== false && !in_array($new_vid, $added_vid_list))
                                                {
                                                    $new_post_content .= $new_vid;
                                                    $added_vid_list[] = $new_vid;
                                                    $added_videos++;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Empty processed content prompt. Nothing to do.');
                                    }
                                }
                            }
                        }
                        if($enable_qa == '1')
                        {
                            if($qa_prompt != '')
                            {
                                $my_qa_prompt = $qa_prompt;
                                $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                                $my_qa_prompt = aiomatic_replacetopics($my_qa_prompt, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                $my_qa_prompt = aiomatic_replaceAIPostShortcodes($my_qa_prompt, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                if(stristr($run_regex_on, 'qa') !== false)
                                {
                                    if ($strip_by_regex_prompts !== '')
                                    {
                                        $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                        $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                        $xcnt = 0;
                                        foreach($xstrip_by_regex as $sbr)
                                        {
                                            if(isset($xreplace_regex[$xcnt]))
                                            {
                                                $repreg = $xreplace_regex[$xcnt];
                                            }
                                            else
                                            {
                                                $repreg = '';
                                            }
                                            $xcnt++;
                                            $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_qa_prompt);
                                            if($temp_cont !== NULL)
                                            {
                                                $my_qa_prompt = $temp_cont;
                                            }
                                        }
                                    }
                                }
                                if($my_qa_prompt != '')
                                {
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating topic based qa'));
                                    $written = aiomatic_write_content($my_qa_prompt, $topic_qa_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'qa', 'user', $assistant_id, $thread_id, $store_data);
                                    if($written === false)
                                    {
                                        aiomatic_log_to_file('Failed to generate Q&A for topic: ' . $current_section);
                                        unset($post_title_lines[$current_index]);
                                        continue;
                                    }
                                    else
                                    {
                                        if($new_post_content != '')
                                        {
                                            $new_post_content .= ' ';
                                        }
                                        if($my_title_qa !== '')
                                        {
                                            if($sections_role == 'h2')
                                            {
                                                $new_post_content .= '<h2 id="qa">' . $my_title_qa . '</h2>';
                                            }
                                            elseif($sections_role == 'h3')
                                            {
                                                $new_post_content .= '<h3 id="qa">' . $my_title_qa . '</h3>';
                                            }
                                            elseif($sections_role == 'b')
                                            {
                                                $new_post_content .= '<b id="qa">' . $my_title_qa . '</b>';
                                            }
                                            elseif($sections_role == 'i')
                                            {
                                                $new_post_content .= '<i id="qa">' . $my_title_qa . '</i>';
                                            }
                                            elseif($sections_role == 'bi')
                                            {
                                                $new_post_content .= '<b><i id="qa">' . $my_title_qa . '</i></b>';
                                            }
                                            elseif($sections_role == 'p')
                                            {
                                                $new_post_content .= '<p id="qa">' . $my_title_qa . '</p>';
                                            }
                                            elseif($sections_role == 'x')
                                            {
                                                $new_post_content .= '<br/><span id="qa">' . $my_title_qa . '</span><br/>';
                                            }
                                            else
                                            {
                                                $new_post_content .= '<br/>' . $my_title_qa . '<br/>';
                                            }
                                        }
                                        $new_post_content .= $written;
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty processed Q&A prompt. Nothing to do.');
                                }
                            }
                        }
                        if($outro_prompt != '')
                        {
                            $my_outro_prompt = $outro_prompt;
                            $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                            $my_outro_prompt = aiomatic_replacetopics($my_outro_prompt, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                            $my_outro_prompt = aiomatic_replaceAIPostShortcodes($my_outro_prompt, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                            if(stristr($run_regex_on, 'outro') !== false)
                            {
                                if ($strip_by_regex_prompts !== '')
                                {
                                    $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                    $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                    $xcnt = 0;
                                    foreach($xstrip_by_regex as $sbr)
                                    {
                                        if(isset($xreplace_regex[$xcnt]))
                                        {
                                            $repreg = $xreplace_regex[$xcnt];
                                        }
                                        else
                                        {
                                            $repreg = '';
                                        }
                                        $xcnt++;
                                        $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_outro_prompt);
                                        if($temp_cont !== NULL)
                                        {
                                            $my_outro_prompt = $temp_cont;
                                        }
                                    }
                                }
                            }
                            if($my_outro_prompt != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating topic based outro'));
                                $written = aiomatic_write_content($my_outro_prompt, $topic_outro_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'outro', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate outro for section: ' . $current_section);
                                    unset($post_title_lines[$current_index]);
                                    continue;
                                }
                                else
                                {
                                    if($new_post_content != '')
                                    {
                                        $new_post_content .= ' ';
                                    }
                                    if($title_outro !== '')
                                    {
                                        if($my_title_outro != '')
                                        {
                                            if($sections_role == 'h2')
                                            {
                                                $new_post_content .= '<h2 id="outro">' . $my_title_outro . '</h2>';
                                            }
                                            elseif($sections_role == 'h3')
                                            {
                                                $new_post_content .= '<h3 id="outro">' . $my_title_outro . '</h3>';
                                            }
                                            elseif($sections_role == 'b')
                                            {
                                                $new_post_content .= '<b id="outro">' . $my_title_outro . '</b>';
                                            }
                                            elseif($sections_role == 'i')
                                            {
                                                $new_post_content .= '<i id="outro">' . $my_title_outro . '</i>';
                                            }
                                            elseif($sections_role == 'bi')
                                            {
                                                $new_post_content .= '<b><i id="outro">' . $my_title_outro . '</i></b>';
                                            }
                                            elseif($sections_role == 'p')
                                            {
                                                $new_post_content .= '<p id="outro">' . $my_title_outro . '</p>';
                                            }
                                            elseif($sections_role == 'x')
                                            {
                                                $new_post_content .= '<br/><span id="outro">' . $my_title_outro . '</span><br/>';
                                            }
                                            else
                                            {
                                                $new_post_content .= '<br/>' . $my_title_outro . '<br/>';
                                            }
                                        }
                                    }
                                    else
                                    {
                                        $new_post_content .= '<br/><br/>';
                                    }
                                    $new_post_content .= $written;
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed outro prompt. Nothing to do.');
                            }
                        }
                        if($topic_images != '' && is_numeric($topic_images) && $topic_images > $added_images)
                        {
                            if($new_post_content !== '')
                            {
                                $the_image_prompt = $post_title;
                                if($enable_ai_images_article != '0' && $enable_ai_images_article != '3')
                                {
                                    $ai_command_image_article = $orig_ai_command_image_article;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image_article = preg_split('/\r\n|\r|\n/', $ai_command_image_article);
                                        $ai_command_image_article = array_filter($ai_command_image_article);
                                        if(count($ai_command_image_article) > 0)
                                        {
                                            $ai_command_image_article = $ai_command_image_article[array_rand($ai_command_image_article)];
                                        }
                                        else
                                        {
                                            $ai_command_image_article = '';
                                        }
                                    }
                                    $za_post_title = aiomatic_replaceContentShortcodes($the_image_prompt, $img_attr, $ai_command);
                                    $ai_command_image_article = aiomatic_replacetopics($ai_command_image_article, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                    $ai_command_image_article = aiomatic_replaceSynergyShortcodes($ai_command_image_article);
                                    if(!empty($ai_command_image_article))
                                    {
                                        $ai_command_image_article = aiomatic_replaceAIPostShortcodes($ai_command_image_article, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image_article = trim(strip_tags($the_image_prompt));
                                    }
                                    $ai_command_image_article = trim($ai_command_image_article);
                                    if (filter_var($ai_command_image_article, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image_article, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image_article);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image_article = $txt_content;
                                                    $ai_command_image_article = aiomatic_replaceSynergyShortcodes($ai_command_image_article);
                                                    $ai_command_image_article = aiomatic_replaceAIPostShortcodes($ai_command_image_article, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image_article))
                                    {
                                        aiomatic_log_to_file('Empty API image seed expression provided!');
                                    }
                                    else
                                    {
                                        if(aiomatic_strlen($ai_command_image_article) > 1000)
                                        {
                                            $ai_command_image_article = aiomatic_substr($ai_command_image_article, 0, 1000);
                                        }
                                        $the_image_prompt = $ai_command_image_article;
                                    }
                                }
                                $new_img = aiomatic_get_royalty_free_image($the_image_prompt, $enable_ai_images_article, $image_size_article, $images_arr, $token, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $custom_shortcodes, $global_prepend, $global_append, $image_url, $attached_id, $raw_img_list, $default_cat_list, $image_model_article);
                                if(!empty($attached_id))
                                {
                                    $additional_attachments[] = $attached_id;
                                }
                                if($new_img !== false && !in_array($new_img, $added_img_list))
                                {
                                    $new_post_content .= '<br/><img class="bimage_class" src="' . $new_img . '" alt="' . esc_attr($post_title) . '"><br/>';
                                    $added_img_list[] = $new_img;
                                    $added_images++;
                                }
                            }
                        }
                        if($new_post_content == '')
                        {
                            aiomatic_log_to_file("Warning, empty post content because of empty content prompt!");
                        }

                        $new_post_excerpt = '';
                        $current_section = $post_sections;
                        if($excerpt_prompt != '')
                        {
                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                            {
                                $excerpt_prompt_arr = preg_split('/\r\n|\r|\n/', $excerpt_prompt);
                                $my_post_excerpt = $excerpt_prompt_arr[array_rand($excerpt_prompt_arr)];
                            }
                            else
                            {
                                $my_post_excerpt = $excerpt_prompt;
                            }
                            $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                            $my_post_excerpt = aiomatic_replacetopics($my_post_excerpt, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                            $my_post_excerpt = aiomatic_replaceAIPostShortcodes($my_post_excerpt, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                            if(stristr($run_regex_on, 'excerpt') !== false)
                            {
                                if ($strip_by_regex_prompts !== '')
                                {
                                    $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                    $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                    $xcnt = 0;
                                    foreach($xstrip_by_regex as $sbr)
                                    {
                                        if(isset($xreplace_regex[$xcnt]))
                                        {
                                            $repreg = $xreplace_regex[$xcnt];
                                        }
                                        else
                                        {
                                            $repreg = '';
                                        }
                                        $xcnt++;
                                        $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_post_excerpt);
                                        if($temp_cont !== NULL)
                                        {
                                            $my_post_excerpt = $temp_cont;
                                        }
                                    }
                                }
                            }
                            if($my_post_excerpt != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating topic based excerpt'));
                                $written = aiomatic_write_content($my_post_excerpt, $topic_excerpt_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, true, false, 'excerpt', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate excerpt!');
                                }
                                else
                                {
                                    $new_post_excerpt = $written;
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed excerpt prompt. Nothing to do.');
                            }
                        }

                        $get_img = '';
                        if($royalty_free == '1')
                        {
                            if($enable_ai_images == '1')
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                                    $ai_command_image = aiomatic_replacetopics($ai_command_image, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image))
                                    {
                                        aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                    }
                                    else
                                    {
                                        
                                        
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = aiomatic_get_api_service($token, $image_model);
                                            aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                        }
                                        $skip_this_copy = true;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                        {
                                            $skip_this_copy = false;
                                        }
                                        if (isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] == 'on')
                                        {
                                            $skip_this_copy = false;
                                        }
                                        $aierror = '';
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating AI image'));
                                        $get_img = aiomatic_generate_ai_image($token, 1, $ai_command_image, $image_size, 'featuredImage', $skip_this_copy, 0, $aierror, $image_model, $post_title);
                                        if($get_img !== false)
                                        {
                                            foreach($get_img as $tmpimg)
                                            {
                                                $get_img = $tmpimg;
                                                break;
                                            }
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate AI featured image: ' . $aierror);
                                            $get_img = '';
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty AI featured image query entered.');
                                }
                            }
                            elseif($enable_ai_images == '2')
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                                    $ai_command_image = aiomatic_replacetopics($ai_command_image, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image))
                                    {
                                        aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                    }
                                    else
                                    {
                                        
                                        
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = 'Stability.AI';
                                            aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                        }
                                        if($image_size == '256x256')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '512x512')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '1024x1024')
                                        {
                                            $width = '1024';
                                            $height = '1024';
                                        }
                                        else
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        $skip_this_copy = true;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                        {
                                            $skip_this_copy = false;
                                        }
                                        $ierror = '';
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating ai image (Stable Diffusion)'));
                                        $get_img = aiomatic_generate_stability_image($ai_command_image, $height, $width, 'featuredStableImage', 0, false, $ierror, $skip_this_copy, false, '', 0);
                                        if($get_img !== false)
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                aiomatic_log_to_file('AI generated featured image returned: ' . $get_img[1]);
                                            }
                                            if(is_array($get_img) && isset($get_img[1]))
                                            {
                                                $get_img = $get_img[1];
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate Stability.AI featured image: ' . $ierror);
                                            $get_img = '';
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty AI featured image query entered.');
                                }
                            }
                            elseif($enable_ai_images == '7')
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                                    $ai_command_image = aiomatic_replacetopics($ai_command_image, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image))
                                    {
                                        aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                    }
                                    else
                                    {
                                        if (isset($aiomatic_Main_Settings['google_ai_image_model']) && trim($aiomatic_Main_Settings['google_ai_image_model']) != '') 
                                        {
                                            $model = trim($aiomatic_Main_Settings['google_ai_image_model']);
                                        }
                                        else
                                        {
                                            $model = AIMOGEN_GOOGLE_IMAGE_DEFAULT_MODEL;
                                        }
                                        
                                        
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = 'Google';
                                            aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                        }
                                        $skip_this_copy = true;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                        {
                                            $skip_this_copy = false;
                                        }
                                        $ierror = '';
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating ai image (Google)'));
                                        $get_img = aiomatic_generate_image_google($ai_command_image, $model, 'featuredGoogleImage', false, $ierror, false);
                                        if($get_img !== false)
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                aiomatic_log_to_file('AI generated featured image returned: ' . $get_img[1]);
                                            }
                                            if(is_array($get_img) && isset($get_img[1]))
                                            {
                                                $get_img = $get_img[1];
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate Stability.AI featured image: ' . $ierror);
                                            $get_img = '';
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty AI featured image query entered.');
                                }
                            }
                            elseif($enable_ai_images == '4')
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                                    $ai_command_image = aiomatic_replacetopics($ai_command_image, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image))
                                    {
                                        aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                    }
                                    else
                                    {
                                        
                                        
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = 'Midjourney';
                                            aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                        }
                                        if($image_size == '256x256')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '512x512')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '1024x1024')
                                        {
                                            $width = '1024';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1792x1024')
                                        {
                                            $width = '1792';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1024x1792')
                                        {
                                            $width = '1024';
                                            $height = '1792';
                                        }
                                        else
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        $skip_this_copy = true;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                        {
                                            $skip_this_copy = false;
                                        }
                                        $ierror = '';
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating ai image (Midjourney)'));
                                        $get_img = aiomatic_generate_ai_image_midjourney($ai_command_image, $width, $height, 'featuredMidjourneyImage', false, $ierror);
                                        if($get_img !== false)
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate Midjourney featured image: ' . $ierror);
                                            $get_img = '';
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty AI featured image query entered.');
                                }
                            }
                            elseif($enable_ai_images == '5')
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                                    $ai_command_image = aiomatic_replacetopics($ai_command_image, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image))
                                    {
                                        aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                    }
                                    else
                                    {
                                        
                                        
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = 'Replicate';
                                            aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                        }
                                        if($image_size == '256x256')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '512x512')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '1024x1024')
                                        {
                                            $width = '1024';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1792x1024')
                                        {
                                            $width = '1792';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1024x1792')
                                        {
                                            $width = '1024';
                                            $height = '1792';
                                        }
                                        else
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        $skip_this_copy = true;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                        {
                                            $skip_this_copy = false;
                                        }
                                        $ierror = '';
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating ai image (Replicate)'));
                                        $get_img = aiomatic_generate_replicate_image($ai_command_image, $width, $height, 'featuredReplicateImage', false, $ierror);
                                        if($get_img !== false)
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate Replicate featured image: ' . $ierror);
                                            $get_img = '';
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty AI featured image query entered.');
                                }
                            }
                            elseif($enable_ai_images == '6')
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                                    $ai_command_image = aiomatic_replacetopics($ai_command_image, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image))
                                    {
                                        aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                    }
                                    else
                                    {
                                        
                                        
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = 'Ideogram';
                                            aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                        }
                                        if($image_size == '256x256')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '512x512')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '1024x1024')
                                        {
                                            $width = '1024';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1792x1024')
                                        {
                                            $width = '1792';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1024x1792')
                                        {
                                            $width = '1024';
                                            $height = '1792';
                                        }
                                        else
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        $skip_this_copy = true;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                        {
                                            $skip_this_copy = false;
                                        }
                                        $ierror = '';
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating ai image (Ideogram)'));
                                        $get_img = aiomatic_generate_ideogram_image($ai_command_image, $width, $height, 'featuredIdeogramImage', false, $ierror);
                                        if($get_img !== false)
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate Ideogram featured image: ' . $ierror);
                                            $get_img = '';
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty AI featured image query entered.');
                                }
                            }
                            elseif($enable_ai_images == '8')
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                                    $ai_command_image = aiomatic_replacetopics($ai_command_image, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image))
                                    {
                                        aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                    }
                                    else
                                    {
                                        
                                        
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = 'Cloudflare';
                                            aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                        }
                                        if($image_size == '256x256')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '512x512')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '1024x1024')
                                        {
                                            $width = '1024';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1792x1024')
                                        {
                                            $width = '1792';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1024x1792')
                                        {
                                            $width = '1024';
                                            $height = '1792';
                                        }
                                        else
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        $skip_this_copy = true;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                        {
                                            $skip_this_copy = false;
                                        }
                                        $ierror = '';
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating ai image (Cloudflare)'));
                                        $get_img = aiomatic_generate_cloudflare_image($ai_command_image, $width, $height, 'featuredCloudflareImage', false, $ierror);
                                        if($get_img !== false)
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate Cloudflare featured image: ' . $ierror);
                                            $get_img = '';
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty AI featured image query entered.');
                                }
                            }
                            elseif($enable_ai_images == '9')
                            {
                                global $wpdb;

                                $attachment_id = $wpdb->get_var(
                                    "
                                    SELECT ID
                                    FROM {$wpdb->posts}
                                    WHERE post_type = 'attachment'
                                    AND post_mime_type LIKE 'image/%'
                                    AND post_status = 'inherit'
                                    ORDER BY RAND()
                                    LIMIT 1
                                    "
                                );

                                if (!empty($attachment_id))
                                {
                                    $get_img = wp_get_attachment_url($attachment_id);

                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging']))
                                    {
                                        aiomatic_log_to_file(
                                            'Random Media Library featured image selected: ' .
                                            $get_img .
                                            ' (ID: ' . $attachment_id . ')'
                                        );
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file(
                                        'Failed to find a random image in Media Library for featured image.'
                                    );

                                    $get_img = '';
                                }
                            }
                            elseif($enable_ai_images == '3')
                            {
                                if ($image_url != '') 
                                {
                                    $replacement = str_replace(array('[', ']'), '', $query_words);
                                    $image_url_temp = str_replace('%%item_title%%', $replacement, $image_url);
                                    $image_url_temp = preg_replace_callback('#%%random_image\[([^\]]*?)\](\[\d+\])?%%#', function ($matches) {
                                        if(isset($matches[2]))
                                        {
                                            $chance = trim($matches[2], '[]');
                                        }
                                        else
                                        {
                                            $chance = '';
                                        }
                                        $arv = array();
                                        $my_img = aiomatic_get_random_image_google($matches[1], 0, 0, $chance, $arv);
                                        return $my_img;
                                    }, $image_url_temp);
                                    $img_rulx = $spintax->Parse(trim($image_url_temp));
                                    $selected_img = aiomatic_select_ai_image($post_title, $img_rulx);
                                    if($selected_img === false)
                                    {
                                        $img_rulx = explode(',', $img_rulx);
                                        $img_rulx = trim($img_rulx[array_rand($img_rulx)]);
                                        if($img_rulx != '')
                                        {
                                            $get_img = $img_rulx;
                                        }
                                    }
                                    else
                                    {
                                        $get_img = $selected_img;
                                    }
                                }
                            }
                            else
                            {
                                $image_query_set = false;
                                $query_words = '';
                                $ai_command_image = '';
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                                    $ai_command_image = aiomatic_replacetopics($ai_command_image, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                }
                                if($ai_command_image != '')
                                {
                                    $query_words = $ai_command_image;
                                    $image_query = $ai_command_image;
                                    $image_query_set = true;
                                }
                                if(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'textrazor')
                                {
                                    if(isset($aiomatic_Main_Settings['textrazor_key']) && trim($aiomatic_Main_Settings['textrazor_key']) != '')
                                    {
                                        try
                                        {
                                            if(!class_exists('TextRazor'))
                                            {
                                                require_once(dirname(__FILE__) . "/res/TextRazor.php");
                                            }
                                            TextRazorSettings::setApiKey(trim($aiomatic_Main_Settings['textrazor_key']));
                                            $textrazor = new TextRazor();
                                            $textrazor->addExtractor('entities');
                                            $response = $textrazor->analyze($image_query);
                                            if (isset($response['response']['entities'])) 
                                            {
                                                foreach ($response['response']['entities'] as $entity) 
                                                {
                                                    $query_words = '';
                                                    if(isset($entity['entityEnglishId']))
                                                    {
                                                        $query_words = $entity['entityEnglishId'];
                                                    }
                                                    else
                                                    {
                                                        $query_words = $entity['entityId'];
                                                    }
                                                    if($query_words != '')
                                                    {
                                                        $attached_id = '';
                                                        $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                                        if(!empty($attached_id))
                                                        {
                                                            $additional_attachments[] = $attached_id;
                                                        }
                                                        if(!empty($z_img))
                                                        {
                                                            $get_img = $z_img;
                                                            $go_local_image = false;
                                                            if(!function_exists('is_plugin_active'))
                                                            {
                                                                include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                                            }
                                                            if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                                            {
                                                                $go_local_image = true;
                                                            }
                                                            if($go_local_image == true)
                                                            {
                                                                $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, $query_words);
                                                                if(!empty($attached_id))
                                                                {
                                                                    $additional_attachments[] = $attached_id;
                                                                }
                                                                if($localpath !== false)
                                                                {
                                                                    $get_img = $localpath[0];
                                                                }
                                                            }
                                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                                aiomatic_log_to_file('Royalty Free Image Generated with help of TextRazor (kw: "' . $query_words . '"): ' . $z_img);
                                                            }
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        catch(Exception $e)
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                aiomatic_log_to_file('Failed to search for keywords using TextRazor (2): ' . $e->getMessage());
                                            }
                                        }
                                    }
                                }
                                elseif(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'openai')
                                {
                                    if(isset($aiomatic_Main_Settings['keyword_prompts']) && trim($aiomatic_Main_Settings['keyword_prompts']) != '')
                                    {
                                        if(isset($aiomatic_Main_Settings['keyword_model']) && $aiomatic_Main_Settings['keyword_model'] != '')
                                        {
                                            $kw_model = $aiomatic_Main_Settings['keyword_model'];
                                        }
                                        else
                                        {
                                            $kw_model = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                        }
                                        if(isset($aiomatic_Main_Settings['keyword_assistant_id']) && $aiomatic_Main_Settings['keyword_assistant_id'] != '')
                                        {
                                            $keyword_assistant_id = $aiomatic_Main_Settings['keyword_assistant_id'];
                                        }
                                        else
                                        {
                                            $keyword_assistant_id = '';
                                        }
                                        $title_ai_command = trim($aiomatic_Main_Settings['keyword_prompts']);
                                        $title_ai_command = str_replace('%%default_post_cats%%', $default_cat_list, $title_ai_command);
                                        $title_ai_command = str_replace('%%original_post_title%%', $post_title, $title_ai_command);
                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                        {
                                            $title_ai_command = preg_split('/\r\n|\r|\n/', $title_ai_command);
                                            $title_ai_command = array_filter($title_ai_command);
                                            if(count($title_ai_command) > 0)
                                            {
                                                $title_ai_command = $title_ai_command[array_rand($title_ai_command)];
                                            }
                                            else
                                            {
                                                $title_ai_command = '';
                                            }
                                        }
                                        $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                        if(!empty($title_ai_command))
                                        {
                                            $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        }
                                        $title_ai_command = trim($title_ai_command);
                                        if (filter_var($title_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($title_ai_command, '.txt'))
                                        {
                                            $txt_content = aiomatic_get_web_page($title_ai_command);
                                            if ($txt_content !== FALSE) 
                                            {
                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                $txt_content = array_filter($txt_content);
                                                if(count($txt_content) > 0)
                                                {
                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                    if(trim($txt_content) != '') 
                                                    {
                                                        $title_ai_command = $txt_content;
                                                        $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                                        $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                }
                                            }
                                        }
                                        if(empty($title_ai_command))
                                        {
                                            aiomatic_log_to_file('Empty API keyword extractor seed expression provided!');
                                            $title_ai_command = 'Type the most relevant keyword, no other text before or after it, for a blog post titled:  ' . trim(strip_tags($post_title));
                                        }
                                        if(aiomatic_strlen($title_ai_command) > $max_seed_tokens * 4)
                                        {
                                            $title_ai_command = aiomatic_substr($title_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                                        }
                                        $title_ai_command = trim($title_ai_command);
                                        if(empty($title_ai_command))
                                        {
                                            aiomatic_log_to_file('Empty API title seed expression provided(3)! ' . print_r($title_ai_command, true));
                                        }
                                        else
                                        {
                                            $query_token_count = count(aiomatic_encode($title_ai_command));
                                            $available_tokens = aiomatic_compute_available_tokens($kw_model, $max_tokens, $title_ai_command, $query_token_count);
                                            if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                            {
                                                $string_len = aiomatic_strlen($title_ai_command);
                                                $string_len = $string_len / 2;
                                                $string_len = intval(0 - $string_len);
                                                $title_ai_command = aiomatic_substr($title_ai_command, 0, $string_len);
                                                $title_ai_command = trim($title_ai_command);
                                                $query_token_count = count(aiomatic_encode($title_ai_command));
                                                $available_tokens = $max_tokens - $query_token_count;
                                            }
                                            $aierror = '';
                                            $finish_reason = '';
                                            if(!empty($global_prepend))
                                            {
                                                $title_ai_command = $global_prepend . ' ' . $title_ai_command;
                                            }
                                            if(!empty($global_append))
                                            {
                                                $title_ai_command = $title_ai_command . ' ' . $global_append;
                                            }
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                $api_service = aiomatic_get_api_service($token, $kw_model);
                                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $kw_model . ')(' . $available_tokens . ') for title text: ' . $title_ai_command);
                                            }
                                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Improving royalty free image search keywords'));
                                            $generated_text = aiomatic_generate_text($token, $kw_model, $title_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'keywordID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $keyword_assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                            if($generated_text === false)
                                            {
                                                aiomatic_log_to_file('Keyword generator error: ' . $aierror);
                                                $ai_title = '';
                                            }
                                            else
                                            {
                                                $ai_title = trim(trim($generated_text), '.');
                                                $ai_titles = explode(',', $ai_title);
                                                foreach($ai_titles as $query_words)
                                                {
                                                    $attached_id = '';
                                                    $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, trim($query_words), $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                                    if(!empty($attached_id))
                                                    {
                                                        $additional_attachments[] = $attached_id;
                                                    }
                                                    if(!empty($z_img))
                                                    {
                                                        $get_img = $z_img;
                                                        $go_local_image = false;
                                                        if(!function_exists('is_plugin_active'))
                                                        {
                                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                                        }
                                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                                        {
                                                            $go_local_image = true;
                                                        }
                                                        if($go_local_image == true)
                                                        {
                                                            $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, $query_words);
                                                            if(!empty($attached_id))
                                                            {
                                                                $additional_attachments[] = $attached_id;
                                                            }
                                                            if($localpath !== false)
                                                            {
                                                                $get_img = $localpath[0];
                                                            }
                                                        }
                                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                            aiomatic_log_to_file('Royalty Free Image Generated with help of AI (kw: "' . $query_words . '"): ' . $z_img);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                $api_service = aiomatic_get_api_service($token, $kw_model);
                                                aiomatic_log_to_file('Successfully got API keyword result from ' . $api_service . ': ' . $ai_title);
                                            }
                                        }
                                    }
                                }
                                if(empty($get_img))
                                {
                                    if($image_query_set == true && !empty($image_query))
                                    {
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating royalty free image'));
                                        $attached_id = '';
                                        $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $image_query, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                        if(!empty($attached_id))
                                        {
                                            $additional_attachments[] = $attached_id;
                                        }
                                        if($get_img == '' || $get_img === false)
                                        {
                                            if(isset($aiomatic_Main_Settings['bimage']) && $aiomatic_Main_Settings['bimage'] == 'on')
                                            {
                                                $keyword_class = new Aiomatic_keywords();
                                                $image_query = $keyword_class->keywords($image_query, 1);
                                                $attached_id = '';
                                                $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $image_query, $img_attr, $attached_id, 20, true, $raw_img_list, array(), $full_result_list);
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                            }
                                        }
                                    }
                                    if(empty($get_img))
                                    {
                                        $keyword_class = new Aiomatic_keywords();
                                        $query_words = $keyword_class->keywords($post_title, 2);
                                        $attached_id = '';
                                        $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                        if(!empty($attached_id))
                                        {
                                            $additional_attachments[] = $attached_id;
                                        }
                                        if($get_img == '' || $get_img === false)
                                        {
                                            if(isset($aiomatic_Main_Settings['bimage']) && $aiomatic_Main_Settings['bimage'] == 'on')
                                            {
                                                $query_words = $keyword_class->keywords($post_title, 1);
                                                $attached_id = '';
                                                $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 20, true, $raw_img_list, array(), $full_result_list);
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                                if($get_img == '' || $get_img === false)
                                                {
                                                    if(isset($aiomatic_Main_Settings['no_royalty_skip']) && $aiomatic_Main_Settings['no_royalty_skip'] == 'on')
                                                    {
                                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                            aiomatic_log_to_file('Skipping importing because no royalty free image found.');
                                                        }
                                                        unset($post_title_lines[$current_index]);
                                                        continue;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if(isset($aiomatic_Main_Settings['no_royalty_skip']) && $aiomatic_Main_Settings['no_royalty_skip'] == 'on')
                                                {
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                        aiomatic_log_to_file('Skipping importing because no royalty free image found.');
                                                    }
                                                    unset($post_title_lines[$current_index]);
                                                    continue;
                                                }
                                            }
                                        }
                                    }
                                    if(!empty($get_img))
                                    {
                                        $go_local_image = false;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                        {
                                            $go_local_image = true;
                                        }
                                        if($go_local_image == true)
                                        {
                                            $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, '');
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                            if($localpath !== false)
                                            {
                                                $get_img = $localpath[0];
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                        {
                            $already_spinned = '1';
                        }
                        $my_post                              = array();
                        $my_post['aiomatic_post_image']       = $get_img;
                        if($enable_ai_images == '2')
                        {
                            $my_post['aiomatic_local_image']      = '1';
                        }
                        else
                        {
                            $my_post['aiomatic_local_image']      = '0';
                        }
                        $my_post['aiomatic_enable_pingbacks'] = $enable_pingback;
                        $my_post['default_category']          = $default_category;
                        $my_post['post_type']                 = $post_type;
                        $my_post['comment_status']            = $accept_comments;
                        
                        if (isset($aiomatic_Main_Settings['draft_first']) && $aiomatic_Main_Settings['draft_first'] != 'on')
                        {
                            if($post_status == 'publish')
                            {
                                $draft_me = true;
                                $my_post['post_status'] = 'draft';
                            }
                            else
                            {
                                $my_post['post_status']   = $post_status;
                            }
                        }
                        else
                        {
                            $my_post['post_status']               = $post_status;
                        }
                        if($user_name_type == 'rand')
                        {
                            $randid = aiomatic_display_random_user();
                            if($randid === false)
                            {
                                $my_post['post_author']               = aimogen_get_admin_user_id();
                            }
                            else
                            {
                                $my_post['post_author']               = $randid->ID;
                            }
                        }
                        else
                        {
                            $my_post['post_author']               = $post_user_name;
                        }
                        if($strip_title == '1')
                        {
                            $new_post_content = str_replace($post_title, '', $new_post_content);
                            $new_post_content = str_replace('<h2></h2>', '', $new_post_content);
                            $new_post_content = str_replace('<h3></h3>', '', $new_post_content);
                        }
                        if (isset($aiomatic_Main_Settings['swear_filter']) && $aiomatic_Main_Settings['swear_filter'] == 'on') 
                        {
                            require_once(dirname(__FILE__) . "/res/swear.php");
                            $new_post_content = aimogenpro_filterwords($new_post_content);
                        }
                        if(isset($aiomatic_Main_Settings['global_ban_words']) && $aiomatic_Main_Settings['global_ban_words'] != '') {
                            $continue    = false;
                            $aiomatic_Main_Settings['global_ban_words'] = trim(trim(trim($aiomatic_Main_Settings['global_ban_words']), ','));
                            $banned_list = explode(',', $aiomatic_Main_Settings['global_ban_words']);
                            foreach ($banned_list as $banned_word) {
                                if (stripos($new_post_content, trim($banned_word)) !== FALSE) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s content contains global banned word: ' . $banned_word);
                                    }
                                    $continue = true;
                                    break;
                                }
                                if (stripos($post_title, trim($banned_word)) !== FALSE) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s title contains global banned word: ' . $banned_word);
                                    }
                                    $continue = true;
                                    break;
                                }
                            }
                            if ($continue === true) {
                                unset($post_title_lines[$current_index]);
                                continue;
                            }
                        }
                        if(isset($aiomatic_Main_Settings['global_req_words']) && $aiomatic_Main_Settings['global_req_words'] != '')
                        {
                            if(isset($aiomatic_Main_Settings['require_only_one']) && $aiomatic_Main_Settings['require_only_one'] == 'on')
                            {
                                $continue      = true;
                                $aiomatic_Main_Settings['global_req_words'] = trim(trim(trim($aiomatic_Main_Settings['global_req_words']), ','));
                                $required_list = explode(',', $aiomatic_Main_Settings['global_req_words']);
                                foreach ($required_list as $required_word) {
                                    if (stripos($new_post_content, trim($required_word)) !== FALSE || stripos($post_title, trim($required_word)) !== FALSE) {
                                        $continue = false;
                                        break;
                                    }
                                }
                                if ($continue === true) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s content doesn\'t contain global required words.');
                                    }
                                    unset($post_title_lines[$current_index]);
                                    continue;
                                }
                            }
                            else
                            {
                                $continue      = false;
                                $aiomatic_Main_Settings['global_req_words'] = trim(trim(trim($aiomatic_Main_Settings['global_req_words']), ','));
                                $required_list = explode(',', $aiomatic_Main_Settings['global_req_words']);
                                foreach ($required_list as $required_word) {
                                    if (stripos($new_post_content, trim($required_word)) === FALSE && stripos($post_title, trim($required_word)) === FALSE) {
                                        $continue = true;
                                        break;
                                    }
                                }
                                if ($continue === true) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s content doesn\'t contain global required words.');
                                    }
                                    unset($post_title_lines[$current_index]);
                                    continue;
                                }
                            }
                        }
                        $new_post_title = $post_title;
                        if (isset($aiomatic_Main_Settings['spin_what']) && $aiomatic_Main_Settings['spin_what'] === 'omni') 
                        {
                            $skip_spin = '1';
                        }
                        $arr = aiomatic_spin_and_translate($new_post_title, $new_post_content, '3', $skip_spin, $skip_translate);
                        if($arr[0] != $new_post_title)
                        {
                            $new_post_title = $arr[0];
                            if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                            {
                                $posts = get_posts(
                                    array(
                                        'post_type'              => $post_type,
                                        'title'                  => html_entity_decode($new_post_title),
                                        'post_status'            => 'any',
                                        'numberposts'            => 1,
                                        'update_post_term_cache' => false,
                                        'update_post_meta_cache' => false,           
                                        'orderby'                => 'post_date ID',
                                        'order'                  => 'ASC',
                                    )
                                );
                                if ( ! empty( $posts ) ) {
                                    $zap = $posts[0];
                                } else {
                                    $zap = null;
                                }
                                if($zap !== null)
                                {
                                    if($overwrite_existing)
                                    {
                                        $update_post_id = $zap->ID;
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Post with specified title already existing (after spin/translate), skipping it: ' . $new_post_title);
                                        unset($post_title_lines[$current_index]);
                                        continue;
                                    }
                                }
                            }
                        }
                        $new_post_content            = $arr[1];
                        if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                        {
                            $already_spinned = '1';
                        }
                        if ($auto_categories == 'content') {
                            $extra_categories            = aiomatic_extractKeyWords($new_post_content);
                            $extra_categories            = implode(',', $extra_categories);
                        }
                        elseif ($auto_categories == 'title') {
                            $extra_categories            = aiomatic_extractKeyWords($new_post_title);
                            $extra_categories            = implode(',', $extra_categories);
                        }
                        elseif ($auto_categories == 'both') {
                            $extra_categories            = aiomatic_extractKeyWords($new_post_content);
                            $extra_categories            = implode(',', $extra_categories);
                            $extra_categories2            = aiomatic_extractKeyWords($new_post_title);
                            $extra_categories2            = implode(',', $extra_categories2);
                            if($extra_categories2 != '')
                            {
                                $extra_categories .= ',' . $extra_categories2;
                            }
                        }
                        elseif ($auto_categories == 'ai') 
                        {
                            $category_ai_command = $orig_ai_command_category;
                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                            {
                                $category_ai_command = preg_split('/\r\n|\r|\n/', $category_ai_command);
                                $category_ai_command = array_filter($category_ai_command);
                                if(count($category_ai_command) > 0)
                                {
                                    $category_ai_command = $category_ai_command[array_rand($category_ai_command)];
                                }
                                else
                                {
                                    $category_ai_command = '';
                                }
                            }
                            $category_ai_command = aiomatic_replaceSynergyShortcodes($category_ai_command);
                            if(!empty($category_ai_command))
                            {
                                $category_ai_command = aiomatic_replaceAIPostShortcodes($category_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                $category_ai_command = aiomatic_replacetopics($category_ai_command, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                            }
                            else
                            {
                                $category_ai_command = trim(strip_tags('Write a comma separated list of categories, for the post title: %%post_title%%'));
                            }
                            $category_ai_command = trim($category_ai_command);
                            if (filter_var($category_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($category_ai_command, '.txt'))
                            {
                                $txt_content = aiomatic_get_web_page($category_ai_command);
                                if ($txt_content !== FALSE) 
                                {
                                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                    $txt_content = array_filter($txt_content);
                                    if(count($txt_content) > 0)
                                    {
                                        $txt_content = $txt_content[array_rand($txt_content)];
                                        if(trim($txt_content) != '') 
                                        {
                                            $category_ai_command = $txt_content;
                                            $category_ai_command = aiomatic_replaceSynergyShortcodes($category_ai_command);
                                            $category_ai_command = aiomatic_replaceAIPostShortcodes($category_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            $category_ai_command = aiomatic_replacetopics($category_ai_command, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                        }
                                    }
                                }
                            }
                            if(empty($category_ai_command))
                            {
                                aiomatic_log_to_file('Empty API post category seed expression provided!');
                            }
                            else
                            {
                                if(aiomatic_strlen($category_ai_command) > $max_seed_tokens * 4)
                                {
                                    $category_ai_command = aiomatic_substr($category_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                                }
                                $category_ai_command = trim($category_ai_command);
                                if(empty($category_ai_command))
                                {
                                    aiomatic_log_to_file('Empty API category seed expression provided! ' . print_r($category_ai_command, true));
                                    break;
                                }
                                $query_token_count = count(aiomatic_encode($category_ai_command));
                                $available_tokens = aiomatic_compute_available_tokens($category_model, $max_tokens, $category_ai_command, $query_token_count);
                                if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                {
                                    $string_len = aiomatic_strlen($category_ai_command);
                                    $string_len = $string_len / 2;
                                    $string_len = intval(0 - $string_len);
                                    $category_ai_command = aiomatic_substr($category_ai_command, 0, $string_len);
                                    $category_ai_command = trim($category_ai_command);
                                    if(empty($category_ai_command))
                                    {
                                        aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($category_ai_command, true));
                                        break;
                                    }
                                    $query_token_count = count(aiomatic_encode($category_ai_command));
                                    $available_tokens = $max_tokens - $query_token_count;
                                }
                                $aierror = '';
                                $finish_reason = '';
                                if(!empty($global_prepend))
                                {
                                    $category_ai_command = $global_prepend . ' ' . $category_ai_command;
                                }
                                if(!empty($global_append))
                                {
                                    $category_ai_command = $category_ai_command . ' ' . $global_append;
                                }
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = aiomatic_get_api_service($token, $category_model);
                                    aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $category_model . ')(' . $available_tokens . ') for category generator: ' . $category_ai_command);
                                }
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating category'));
                                $generated_text = aiomatic_generate_text($token, $category_model, $category_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'categoryID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', false, $store_data, array(), '', '', '');
                                if($generated_text === false)
                                {
                                    aiomatic_log_to_file('Category generator error: ' . $aierror);
                                    break;
                                }
                                else
                                {
                                    $extra_categories = $generated_text;
                                }
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = aiomatic_get_api_service($token, $category_model);
                                    aiomatic_log_to_file('Successfully got API category result from ' . $api_service . ': ' . $generated_text);
                                }
                            }
                        }
                        else
                        {
                            $extra_categories = '';
                        }
                        $my_post['extra_categories'] = $extra_categories;
                        
                        $item_tags                   = aiomatic_extractKeyWords($new_post_content, 3);
                        $item_tags                   = implode(',', $item_tags);
                        $title_tags                   = aiomatic_extractKeyWords($new_post_title, 3);
                        $title_tags                   = implode(',', $title_tags);
                        $item_create_tag_sp = $spintax->Parse($item_create_tag);
                        if ($can_create_tag == 'content') {
                            $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $item_tags;
                            $my_post['extra_tags']       = $item_tags;
                        } else if ($can_create_tag == 'title') {
                            $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $title_tags;
                            $my_post['extra_tags']       = $title_tags;
                        } else if ($can_create_tag == 'both') {
                            $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . ($item_tags != '' ? $item_tags . ',' : '') . $title_tags;
                            $my_post['extra_tags']       = ($item_tags != '' ? $item_tags . ',' : '') . $title_tags;
                        } else if ($can_create_tag == 'ai') {
                            $ai_tags = '';
                            $tag_ai_command = $orig_ai_command_tag;
                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                            {
                                $tag_ai_command = preg_split('/\r\n|\r|\n/', $tag_ai_command);
                                $tag_ai_command = array_filter($tag_ai_command);
                                if(count($tag_ai_command) > 0)
                                {
                                    $tag_ai_command = $tag_ai_command[array_rand($tag_ai_command)];
                                }
                                else
                                {
                                    $tag_ai_command = '';
                                }
                            }
                            $tag_ai_command = aiomatic_replaceSynergyShortcodes($tag_ai_command);
                            if(!empty($tag_ai_command))
                            {
                                $tag_ai_command = aiomatic_replaceAIPostShortcodes($tag_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                $tag_ai_command = aiomatic_replacetopics($tag_ai_command, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                            }
                            else
                            {
                                $tag_ai_command = trim(strip_tags('Write a comma separated list of tags, for the post title: %%post_title%%'));
                            }
                            $tag_ai_command = trim($tag_ai_command);
                            if (filter_var($tag_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($tag_ai_command, '.txt'))
                            {
                                $txt_content = aiomatic_get_web_page($tag_ai_command);
                                if ($txt_content !== FALSE) 
                                {
                                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                    $txt_content = array_filter($txt_content);
                                    if(count($txt_content) > 0)
                                    {
                                        $txt_content = $txt_content[array_rand($txt_content)];
                                        if(trim($txt_content) != '') 
                                        {
                                            $tag_ai_command = $txt_content;
                                            $tag_ai_command = aiomatic_replaceSynergyShortcodes($tag_ai_command);
                                            $tag_ai_command = aiomatic_replaceAIPostShortcodes($tag_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            $tag_ai_command = aiomatic_replacetopics($tag_ai_command, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                        }
                                    }
                                }
                            }
                            if(empty($tag_ai_command))
                            {
                                aiomatic_log_to_file('Empty API post tag seed expression provided!');
                            }
                            else
                            {
                                if(aiomatic_strlen($tag_ai_command) > $max_seed_tokens * 4)
                                {
                                    $tag_ai_command = aiomatic_substr($tag_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                                }
                                $tag_ai_command = trim($tag_ai_command);
                                if(empty($tag_ai_command))
                                {
                                    aiomatic_log_to_file('Empty API tag seed expression provided! ' . print_r($tag_ai_command, true));
                                    break;
                                }
                                $query_token_count = count(aiomatic_encode($tag_ai_command));
                                $available_tokens = aiomatic_compute_available_tokens($tag_model, $max_tokens, $tag_ai_command, $query_token_count);
                                if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                {
                                    $string_len = aiomatic_strlen($tag_ai_command);
                                    $string_len = $string_len / 2;
                                    $string_len = intval(0 - $string_len);
                                    $tag_ai_command = aiomatic_substr($tag_ai_command, 0, $string_len);
                                    $tag_ai_command = trim($tag_ai_command);
                                    if(empty($tag_ai_command))
                                    {
                                        aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($tag_ai_command, true));
                                        break;
                                    }
                                    $query_token_count = count(aiomatic_encode($tag_ai_command));
                                    $available_tokens = $max_tokens - $query_token_count;
                                }
                                $aierror = '';
                                $finish_reason = '';
                                if(!empty($global_prepend))
                                {
                                    $tag_ai_command = $global_prepend . ' ' . $tag_ai_command;
                                }
                                if(!empty($global_append))
                                {
                                    $tag_ai_command = $tag_ai_command . ' ' . $global_append;
                                }
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = aiomatic_get_api_service($token, $tag_model);
                                    aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $tag_model . ')(' . $available_tokens . ') for tag generator: ' . $tag_ai_command);
                                }
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating tags'));
                                $generated_text = aiomatic_generate_text($token, $tag_model, $tag_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'tagID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', false, $store_data, array(), '', '', '');
                                if($generated_text === false)
                                {
                                    aiomatic_log_to_file('Tag generator error: ' . $aierror);
                                    break;
                                }
                                else
                                {
                                    $ai_tags = $generated_text;
                                }
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = aiomatic_get_api_service($token, $tag_model);
                                    aiomatic_log_to_file('Successfully got API tag result from ' . $api_service . ': ' . $generated_text);
                                }
                            }
                            $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $ai_tags;
                            $my_post['extra_tags']       = $ai_tags;
                        } else {
                            $post_the_tags = $item_create_tag_sp;
                            $my_post['extra_tags']       = '';
                        }
                        $my_post['tags_input'] = $post_the_tags;
                        $new_post_content = aimogen_bulk_polish_article_content($new_post_content, array('title' => isset($new_post_title) ? $new_post_title : '', 'topic' => isset($post_topic) ? $post_topic : '', 'language' => isset($content_language) ? $content_language : '', 'model' => (isset($topic_content_model) && $topic_content_model !== '') ? $topic_content_model : (isset($model) ? $model : ''), 'token' => isset($token) ? $token : '', 'temperature' => isset($temperature) ? $temperature : '', 'top_p' => isset($top_p) ? $top_p : '', 'presence_penalty' => isset($presence_penalty) ? $presence_penalty : '', 'frequency_penalty' => isset($frequency_penalty) ? $frequency_penalty : '', 'rule_id' => isset($rule_unique_id) ? $rule_unique_id : '', 'global_prepend' => isset($global_prepend) ? $global_prepend : '', 'global_append' => isset($global_append) ? $global_append : '', 'assistant_id' => isset($assistant_id) ? $assistant_id : '', 'thread_id' => isset($thread_id) ? $thread_id : '', 'store_data' => isset($store_data) ? $store_data : 'off'));
                    $new_post_content        = html_entity_decode($new_post_content);
                        $new_post_content = str_replace('</ iframe>', '</iframe>', $new_post_content);
                        if ($strip_by_regex !== '')
                        {
                            $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex);
                            $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex);
                            $xcnt = 0;
                            foreach($xstrip_by_regex as $sbr)
                            {
                                if(isset($xreplace_regex[$xcnt]))
                                {
                                    $repreg = $xreplace_regex[$xcnt];
                                }
                                else
                                {
                                    $repreg = '';
                                }
                                $xcnt++;
                                $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $new_post_content);
                                if($temp_cont !== NULL)
                                {
                                    $new_post_content = $temp_cont;
                                }
                            }
                        }
                        $post_prepender = aiomatic_replaceAIPostShortcodes($post_prepend, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                        $post_prepender = aiomatic_replacetopics($post_prepender, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                        $post_appender = aiomatic_replaceAIPostShortcodes($post_append, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                        $post_appender = aiomatic_replacetopics($post_appender, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                        $post_appender = aiomatic_replaceSynergyShortcodes($post_appender);
                        $post_prepender = aiomatic_replaceSynergyShortcodes($post_prepender);
                        if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                        {
                            if($new_post_content === strip_tags($new_post_content)) 
                            {
                                $new_post_content = nl2br($new_post_content);
                            }
                        }
                        if (!isset($aiomatic_Main_Settings['no_undetectibility']) || $aiomatic_Main_Settings['no_undetectibility'] != 'on') 
                        {
                            if (!isset($aiomatic_Main_Settings['no_undetectibility_bulk']) || $aiomatic_Main_Settings['no_undetectibility_bulk'] != 'on') 
                            {
                                if(!isset($xchars))
                                {
                                    $xchars = array();
                                }
                                $rand_percentage = wp_rand(10, 30);
                                $new_post_content = aiomatic_make_unique($new_post_content, $xchars, $rand_percentage);
                            }
                        }
                        $zlang = 'en_US';
                        if (isset($aiomatic_Main_Settings['kw_lang']) && !empty($aiomatic_Main_Settings['kw_lang'])) {
                            $zlang = $aiomatic_Main_Settings['kw_lang'];
                        }
                        $rel_search = array('post_title', 'post_content');
                        if (isset($aiomatic_Main_Settings['rel_search']) && is_array($aiomatic_Main_Settings['rel_search'])) {
                            $rel_search = $aiomatic_Main_Settings['rel_search'];
                        }
                        if($max_links !== '' && $inboundlinker !== null && $link_type != 'disabled')
                        {
                            try
                            {
                                $new_post_content = $inboundlinker->add_inbound_links($new_post_content, $max_links, $link_post_types, $zlang, $rel_search, null, $link_type, $link_list, $link_nofollow, '', '', array());
                            }
                            catch(Exception $ex)
                            {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Failed to add new inbound links to content: ' . $ex->getMessage());
                                }
                            }
                        }
                        if($ret_content == 1)
                        {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('Returning AI generated content, finished.');
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Finished processing'));
                            return array($post_prepender . ' ' . $new_post_content . ' ' . $post_appender, $new_post_title);
                        }
                        $the_final_cont = $post_prepender . ' ' . $new_post_content . ' ' . $post_appender;
                        $trunchi_content = aiomatic_truncate_content($the_final_cont, 16777215);
                        if (isset($aiomatic_Main_Settings['convert_gutenberg']) && trim($aiomatic_Main_Settings['convert_gutenberg']) == 'on')
                        {
                            $my_post['post_content'] = aiomatic_convert_html_to_gutenberg_blocks($trunchi_content);
                        }
                        else
                        {
                            $my_post['post_content'] = $trunchi_content;
                        }
                        if(stristr($my_post['post_content'], '<pre><code>&lt;') !== false)
                        {
                            if (!isset($aiomatic_Main_Settings['pre_code_off']) || trim($aiomatic_Main_Settings['pre_code_off']) != 'on')
                            {
                                $my_post['post_content'] = aiomatic_parse_pre_code_entities($my_post['post_content']);
                            }
                        }
                        $my_post['post_content'] = aimogen_bulk_finalize_prose($my_post['post_content']);
                        $my_post['post_title']           = aiomatic_truncate_title($new_post_title);
                        $my_post['aiomatic_source_title']   = $post_title;
                        $my_post['aiomatic_timestamp']   = aiomatic_get_date_now();
                        $my_post['aiomatic_post_format'] = $post_format;
                        if (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678') 
                        {
                            if(is_array($default_category))
                            {
                                $cextra = '';
                                foreach($default_category as $dc)
                                {
                                    $cextra .= ',' . get_cat_name($dc);
                                }
                                $extra_categories_temp = trim( $cextra . ',' . $extra_categories, ',');
                            }
                            else
                            {
                                $extra_categories_temp = trim(get_cat_name($default_category) . ',' .$extra_categories, ',');
                            }
                        }
                        else
                        {
                            $extra_categories_temp = $extra_categories;
                        }
                        $block_arr = array();
                        $custom_arr = array();
                        if($custom_fields != '')
                        {
                            if(stristr($custom_fields, '=>') != false)
                            {
                                $rule_arr = explode(',', trim($custom_fields));
                                foreach($rule_arr as $rule)
                                {
                                    $my_args = explode('=>', trim($rule));
                                    if(isset($my_args[1]))
                                    {
                                        if ( isset( $shortcode_tags['aicontent'] ) ) {
                                            $aicontent_handler = $shortcode_tags['aicontent'];
                                            unset( $shortcode_tags['aicontent'] );
                                        } else {
                                            $aicontent_handler = null;
                                        }
                                        $my_args[1] = do_shortcode($my_args[1]);
                                        $my_args[0] = do_shortcode($my_args[0]);
                                        if ( $aicontent_handler ) {
                                            $shortcode_tags['aicontent'] = $aicontent_handler;
                                        }
                                        $custom_field_content = trim($my_args[1]);
                                        $custom_field_content = aiomatic_replaceAIPostShortcodes($custom_field_content, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        $custom_field_content = aiomatic_replacetopics($custom_field_content, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                        $custom_field_content = aiomatic_replaceSynergyShortcodes($custom_field_content);
                                        $custom_field_content = $spintax->Parse($custom_field_content, $block_arr);
                                        $custom_field_content = aiomatic_replaceContentShortcodes($custom_field_content, $img_attr, $ai_command);
                                        if(stristr($my_args[1], 'serialize_') !== false)
                                        {
                                            $custom_arr[trim($my_args[0])] = array(str_replace('serialize_', '', $custom_field_content));
                                        }
                                        else
                                        {
                                            if(stristr($my_args[0], '[') !== false && stristr($my_args[0], ']') !== false)
                                            {
                                                preg_match_all('#([^\[\]]*?)\[([^\[\]]*?)\]#', $my_args[0], $cfm);
                                                if(isset($cfm[2][0]))
                                                {
                                                    if(isset($custom_arr[trim($cfm[1][0])]) && is_array($custom_arr[trim($cfm[1][0])]))
                                                    {
                                                        $custom_arr[trim($cfm[1][0])] = array_merge($custom_arr[trim($cfm[1][0])], array(trim($cfm[2][0]) => $custom_field_content));
                                                    }
                                                    else
                                                    {
                                                        $custom_arr[trim($cfm[1][0])] = array(trim($cfm[2][0]) => $custom_field_content);
                                                    }
                                                }
                                                else
                                                {
                                                    $custom_arr[trim($my_args[0])] = $custom_field_content;
                                                }
                                            }
                                            else
                                            {
                                                $custom_arr[trim($my_args[0])] = $custom_field_content;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        $block_arr = array();
                        $custom_arr = array_merge($custom_arr, array('aiomatic_auto_post_spinned' => $already_spinned, 'aiomatic_post_cats' => $extra_categories_temp, 'aiomatic_post_tags' => $post_the_tags));
                        $custom_tax_arr = array();
                        if($custom_tax != '')
                        {
                            if(stristr($custom_tax, '=>') != false)
                            {
                                $rule_arr = explode(';', trim($custom_tax));
                                foreach($rule_arr as $rule)
                                {
                                    $my_args = explode('=>', trim($rule));
                                    if(isset($my_args[1]))
                                    {
                                        $custom_tax_content = trim($my_args[1]);
                                        $custom_tax_content = aiomatic_replaceAIPostShortcodes($custom_tax_content, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        $custom_tax_content = aiomatic_replacetopics($custom_tax_content, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                        $custom_tax_content = aiomatic_replaceSynergyShortcodes($custom_tax_content);
                                        $custom_tax_content = $spintax->Parse($custom_tax_content, $block_arr);
                                        $custom_tax_content = aiomatic_replaceContentShortcodes($custom_tax_content, $img_attr, $ai_command);
                                        if(aiomatic_substr(trim($my_args[0]), 0, 3) === "pa_" && $post_type == 'product' && !empty($custom_tax_content))
                                        {
                                            if(isset($custom_arr['_product_attributes']))
                                            {
                                                $custom_arr['_product_attributes'] = array_merge($custom_arr['_product_attributes'], array(trim($my_args[0]) =>array(
                                                    'name' => trim($my_args[0]),
                                                    'value' => $custom_tax_content,
                                                    'is_visible' => '1',
                                                    'is_taxonomy' => '1'
                                                )));
                                            }
                                            else
                                            {
                                                $custom_arr['_product_attributes'] = array(trim($my_args[0]) =>array(
                                                    'name' => trim($my_args[0]),
                                                    'value' => $custom_tax_content,
                                                    'is_visible' => '1',
                                                    'is_taxonomy' => '1'
                                                ));
                                            }
                                        }
                                        if(isset($custom_tax_arr[trim($my_args[0])]))
                                        {
                                            $custom_tax_arr[trim($my_args[0])] .= ',' . $custom_tax_content;
                                        }
                                        else
                                        {
                                            $custom_tax_arr[trim($my_args[0])] = $custom_tax_content;
                                        }
                                    }
                                }
                            }
                        }
                        if(count($custom_tax_arr) > 0)
                        {
                            $my_post['taxo_input'] = $custom_tax_arr;
                        }
                        $my_post['meta_input'] = $custom_arr;
                        if($parent_id != '')
                        {
                            $my_post['post_parent'] = intval($parent_id);
                        }
                        if ($enable_pingback == '1') {
                            $my_post['ping_status'] = 'open';
                        } else {
                            $my_post['ping_status'] = 'closed';
                        }
                        if($min_time != '' && $max_time != '')
                        {
                            $t1 = strtotime($min_time);
                            $t2 = strtotime($max_time);
                            if($t1 != false && $t2 != false)
                            {
                                $int = wp_rand($t1, $t2);
                                $my_post['post_date'] = date('Y-m-d H:i:s', $int);
                            }
                        }
                        elseif($min_time != '')
                        {
                            $t1 = strtotime($min_time);
                            if($t1 != false)
                            {
                                $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                            }
                        }
                        elseif($max_time != '')
                        {
                            $t1 = strtotime($max_time);
                            if($t1 != false)
                            {
                                $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                            }
                        }
                        if($new_post_excerpt != '')
                        {
                            $my_post['post_excerpt']          = $new_post_excerpt;
                        }
                        $count++;
                    }
                    elseif($posting_mode == 'title')
                    {
                        $headings_arr_copy = $headings_arr;
                        $added_img_list = array();
                        $raw_img_list = array();
                        $full_result_list = array();
                        $added_images = 0;
                        $heading_results = array();
                        if(count($post_title_lines) == 0)
                        {
                            break;
                        }
                        if ($count > intval($max)) {
                            break;
                        }
                        if (!isset($aiomatic_Main_Settings['no_random_titles']) || $aiomatic_Main_Settings['no_random_titles'] != 'on')
                        {
                            $current_index = array_rand($post_title_lines);
                        }
                        else
                        {
                            $current_index = array_key_first($post_title_lines);
                        }
                        $post_title = trim($post_title_lines[$current_index]);
                        if($title_once == '1')
                        {
                            if(array_key_exists($post_title, $posted_items))
                            {
                                aiomatic_log_to_file('Skipping Bulk Post Creator title, already processed: ' . $post_title);
                                unset($post_title_lines[$current_index]);
                                continue;
                            }
                        }
                        $ptlprocessed = explode('!###!', $post_title);
                        if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                        {
                            $post_title = $ptlprocessed[0];
                            $post_title_keywords = $ptlprocessed[1];
                        }
                        if(isset($rss_feeds[$post_title]))
                        {
                            $post_link = $rss_feeds[$post_title]['url'];
                            $user_name = $rss_feeds[$post_title]['author'];
                            $post_cats = $rss_feeds[$post_title]['cats'];
                            $post_excerpt = $rss_feeds[$post_title]['excerpt'];
                            $final_content = $rss_feeds[$post_title]['content'];
                        }
                        $tprepp = $spintax->Parse($post_title);
                        if($tprepp != false && $tprepp != '')
                        {
                            $post_title = $tprepp;
                        }
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                        {
                            aiomatic_log_to_file('Starting processing post title: ' . $post_title);
                        }
                        $old_title = $post_title;
                        $already_spinned = 0;
                        if (filter_var($post_title, FILTER_VALIDATE_URL) === false && stristr($post_title, '%%ai_generated_title%%') === false)
                        {
                            unset($post_title_lines[$current_index]);
                        }
                        $allmodels = aiomatic_get_all_models();
                        if(!empty($global_prepend))
                        {
                            $global_prepend = aiomatic_replaceSynergyShortcodes($global_prepend);
                            $global_prepend = aiomatic_replaceAIPostShortcodes($global_prepend, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', '');     
                        }
                        if(!empty($global_append))
                        {
                            $global_append = aiomatic_replaceSynergyShortcodes($global_append);
                            $global_append = aiomatic_replaceAIPostShortcodes($global_append, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', '');     
                        }
                        if($custom_shortcodes != '')
                        {
                            $custom_shortcodes_arr = preg_split('/\r\n|\r|\n/', $custom_shortcodes);
                            foreach($custom_shortcodes_arr as $my_short)
                            {
                                $name_part = explode('=>', $my_short);
                                if(isset($name_part[1]) && !empty(trim($name_part[1])))
                                {
                                    $shortname = trim($name_part[0]);
                                    if(strstr($post_title, '%%' . $shortname . '%%'))
                                    {
                                        $shortval = '';
                                        $name_part[1] = str_replace('%%post_title%%', $post_title, $name_part[1]);
                                        $ai_part = explode('@@', $name_part[1]);
                                        if(isset($ai_part[1]) && !empty(trim($ai_part[1])))
                                        {
                                            if(!in_array(trim($ai_part[0]), $allmodels))
                                            {
                                                $aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                            }
                                            else
                                            {
                                                $aimodel = trim($ai_part[0]);
                                            }
                                            $zai_command = trim($ai_part[1]);
                                            $zai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $zai_command);
                                            $zai_command = aiomatic_replaceSynergyShortcodes($zai_command);
                                            $zai_command = aiomatic_replaceAIPostShortcodes($zai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', ''); 
                                            foreach($custom_shortcodes_arr as $my_check_short)
                                            {
                                                $check_name_part = explode('=>', $my_check_short);
                                                if(isset($check_name_part[1]) && !empty(trim($check_name_part[1])))
                                                {
                                                    $check_shortname = trim($check_name_part[0]);
                                                    if($shortname !== $check_shortname && strstr($zai_command, '%%' . $check_shortname . '%%') !== false)
                                                    {
                                                        $check_shortval = '';
                                                        $check_ai_part = explode('@@', $check_name_part[1]);
                                                        if(!in_array(trim($check_ai_part[0]), $allmodels))
                                                        {
                                                            $check_aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                                        }
                                                        else
                                                        {
                                                            $check_aimodel = trim($check_ai_part[0]);
                                                        }
                                                        $check_ai_command = trim($check_ai_part[1]);
                                                        $aierror = '';

                                                        $check_ai_command = aiomatic_replaceSynergyShortcodes($check_ai_command);
                                                        $check_ai_command = aiomatic_replaceAIPostShortcodes($check_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', ''); 

                                                        $check_ai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $check_ai_command);
                                                        $check_generated_text = aiomatic_generate_custom_shortcode_content($token, $check_aimodel, $check_ai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                                                        if($check_generated_text === false)
                                                        {
                                                            aiomatic_log_to_file('Custom nested shortcode generator error: ' . $aierror);
                                                        }
                                                        else
                                                        {
                                                            $check_shortval = trim(trim($check_generated_text), '.');
                                                        }
                                                        $zai_command = str_replace('%%' . $check_shortname . '%%', $check_shortval, $zai_command);
                                                    }
                                                }
                                            }
                                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating title based shortcodes'));
                                            $aierror = '';
                                            $generated_text = aiomatic_generate_custom_shortcode_content($token, $aimodel, $zai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                                            if($generated_text === false)
                                            {
                                                aiomatic_log_to_file('Custom shortcode generator error: ' . $aierror);
                                            }
                                            else
                                            {
                                                $shortval = trim(trim($generated_text), '.');
                                            }
                                        }
                                        $post_title = str_replace('%%' . $shortname . '%%', $shortval, $post_title);
                                    }
                                }
                            } 
                        }
                        if(stristr($post_title, '%%ai_generated_title%%') !== false || $title_source == 'ai')
                        {
                            if($orig_ai_command_title == '')
                            {
                                $orig_ai_command_title = $post_title;
                            }
                            if($orig_ai_command_title != '')
                            {
                                $title_ai_command = $orig_ai_command_title;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $title_ai_command = preg_split('/\r\n|\r|\n/', $title_ai_command);
                                    $title_ai_command = array_filter($title_ai_command);
                                    if(count($title_ai_command) > 0)
                                    {
                                        $title_ai_command = $title_ai_command[array_rand($title_ai_command)];
                                    }
                                    else
                                    {
                                        $title_ai_command = '';
                                    }
                                }
                                $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                if(!empty($title_ai_command))
                                {
                                    $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $title_ai_command = trim(strip_tags($post_title));
                                }
                                $title_ai_command = trim($title_ai_command);
                                if (filter_var($title_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($title_ai_command, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($title_ai_command);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $title_ai_command = $txt_content;
                                                $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                                $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($title_ai_command))
                                {
                                    aiomatic_log_to_file('Empty API post title seed expression provided!');
                                }
                                else
                                {
                                    if(aiomatic_strlen($title_ai_command) > $max_seed_tokens * 4)
                                    {
                                        $title_ai_command = aiomatic_substr($title_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                                    }
                                    $title_ai_command = trim($title_ai_command);
                                    if(empty($title_ai_command))
                                    {
                                        aiomatic_log_to_file('Empty API title seed expression provided(2)! ' . print_r($title_ai_command, true));
                                        break;
                                    }
                                    $query_token_count = count(aiomatic_encode($title_ai_command));
                                    $available_tokens = aiomatic_compute_available_tokens($title_model, $max_tokens, $title_ai_command, $query_token_count);
                                    if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                    {
                                        $string_len = aiomatic_strlen($title_ai_command);
                                        $string_len = $string_len / 2;
                                        $string_len = intval(0 - $string_len);
                                        $title_ai_command = aiomatic_substr($title_ai_command, 0, $string_len);
                                        $title_ai_command = trim($title_ai_command);
                                        if(empty($title_ai_command))
                                        {
                                            aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($title_ai_command, true));
                                            break;
                                        }
                                        $query_token_count = count(aiomatic_encode($title_ai_command));
                                        $available_tokens = $max_tokens - $query_token_count;
                                    }
                                    $aierror = '';
                                    $finish_reason = '';
                                    if(!empty($global_prepend))
                                    {
                                        $title_ai_command = $global_prepend . ' ' . $title_ai_command;
                                    }
                                    if(!empty($global_append))
                                    {
                                        $title_ai_command = $title_ai_command . ' ' . $global_append;
                                    }
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = aiomatic_get_api_service($token, $title_model);
                                        aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $title_model . ')(' . $available_tokens . ') for title text: ' . $title_ai_command);
                                    }
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating title'));
                                    $generated_text = aiomatic_generate_text($token, $title_model, $title_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'titleID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                    if($generated_text === false)
                                    {
                                        aiomatic_log_to_file('Title generator error: ' . $aierror);
                                        break;
                                    }
                                    else
                                    {
                                        $ai_title = ucfirst(trim(trim($generated_text), '.'));
                                        if($title_source == 'ai')
                                        {
                                            $post_title = $ai_title;
                                        }
                                        else
                                        {
                                            $post_title = str_ireplace('%%ai_generated_title%%', $ai_title, $post_title);
                                        }
                                    }
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = aiomatic_get_api_service($token, $title_model);
                                        aiomatic_log_to_file('Successfully got API title result from ' . $api_service . ': ' . $post_title);
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI title query entered.');
                            }
                        }
                        else
                        {
                            $post_title = aiomatic_replaceSynergyShortcodes($post_title);
                        }
                        $post_title = apply_filters('aiomatic_replace_aicontent_shortcode', $post_title);
                        if(empty($post_title))
                        {
                            unset($post_title_lines[$current_index]);
                            continue;
                        }
                        if (strpos($post_title, '%%') === false)
                        {
                            if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                            {
                                $xposts = get_posts(
                                    array(
                                        'post_type'              => $post_type,
                                        'title'                  => html_entity_decode($post_title),
                                        'post_status'            => 'any',
                                        'numberposts'            => 1,
                                        'update_post_term_cache' => false,
                                        'update_post_meta_cache' => false,           
                                        'orderby'                => 'post_date ID',
                                        'order'                  => 'ASC',
                                    )
                                );
                                if ( ! empty( $xposts ) ) {
                                    $zap = $xposts[0];
                                } else {
                                    $zap = null;
                                }
                                if($zap !== null)
                                {
                                    if($overwrite_existing)
                                    {
                                        $update_post_id = $zap->ID;
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Post with specified title is already existing, skipping it: ' . $post_title);
                                        unset($post_title_lines[$current_index]);
                                        continue;
                                    }
                                }
                            }
                            $new_post_title = $post_title;
                        }
                        else
                        {
                            $new_post_title = $post_title;
                            $new_post_title = aiomatic_replaceContentShortcodes($new_post_title, $img_attr, $ai_command);
                            if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                            {
                                $xposts = get_posts(
                                    array(
                                        'post_type'              => $post_type,
                                        'title'                  => html_entity_decode($new_post_title),
                                        'post_status'            => 'any',
                                        'numberposts'            => 1,
                                        'update_post_term_cache' => false,
                                        'update_post_meta_cache' => false,           
                                        'orderby'                => 'post_date ID',
                                        'order'                  => 'ASC',
                                    )
                                );
                                if ( ! empty( $xposts ) ) {
                                    $zap = $xposts[0];
                                } else {
                                    $zap = null;
                                }
                                if($zap !== null)
                                {
                                    if($overwrite_existing)
                                    {
                                        $update_post_id = $zap->ID;
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Post with specified title already published, skipping it: ' . $new_post_title);
                                        unset($post_title_lines[$current_index]);
                                        continue;
                                    }
                                }
                            }
                        }
                        $get_img = '';
                        if($royalty_free == '1')
                        {
                            if($enable_ai_images == '1')
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image))
                                    {
                                        aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                    }
                                    else
                                    {
                                        
                                        
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = aiomatic_get_api_service($token, $image_model);
                                            aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                        }
                                        $skip_this_copy = true;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                        {
                                            $skip_this_copy = false;
                                        }
                                        if (isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] == 'on')
                                        {
                                            $skip_this_copy = false;
                                        }
                                        $aierror = '';
                                        $get_img = aiomatic_generate_ai_image($token, 1, $ai_command_image, $image_size, 'featuredImage', $skip_this_copy, 0, $aierror, $image_model, $post_title);
                                        if($get_img !== false)
                                        {
                                            foreach($get_img as $tmpimg)
                                            {
                                                $get_img = $tmpimg;
                                                break;
                                            }
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate AI featured image: ' . $aierror);
                                            $get_img = '';
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty AI featured image query entered.');
                                }
                            }
                            elseif($enable_ai_images == '2')
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image))
                                    {
                                        aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                    }
                                    else
                                    {
                                        
                                        
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = 'Stability.AI';
                                            aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                        }
                                        if($image_size == '256x256')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '512x512')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '1024x1024')
                                        {
                                            $width = '1024';
                                            $height = '1024';
                                        }
                                        else
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        $skip_this_copy = true;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                        {
                                            $skip_this_copy = false;
                                        }
                                        $ierror = '';
                                        $get_img = aiomatic_generate_stability_image($ai_command_image, $height, $width, 'featuredStableImage', 0, false, $ierror, $skip_this_copy, false, '', 0);
                                        if($get_img !== false)
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                aiomatic_log_to_file('AI generated featured image returned: ' . $get_img[1]);
                                            }
                                            if(is_array($get_img) && isset($get_img[1]))
                                            {
                                                $get_img = $get_img[1];
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate Stability.AI featured image: ' . $ierror);
                                            $get_img = '';
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty AI featured image query entered.');
                                }
                            }
                            elseif($enable_ai_images == '7')
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image))
                                    {
                                        aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                    }
                                    else
                                    {
                                        
                                        
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = 'Google';
                                            aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                        }
                                        $skip_this_copy = true;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                        {
                                            $skip_this_copy = false;
                                        }
                                        if (isset($aiomatic_Main_Settings['google_ai_image_model']) && trim($aiomatic_Main_Settings['google_ai_image_model']) != '') 
                                        {
                                            $model = trim($aiomatic_Main_Settings['google_ai_image_model']);
                                        }
                                        else
                                        {
                                            $model = AIMOGEN_GOOGLE_IMAGE_DEFAULT_MODEL;
                                        }
                                        $ierror = '';
                                        $get_img = aiomatic_generate_image_google($ai_command_image, $model, 'featuredGoogleImage', false, $ierror, false);
                                        if($get_img !== false)
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                aiomatic_log_to_file('AI generated featured image returned: ' . $get_img[1]);
                                            }
                                            if(is_array($get_img) && isset($get_img[1]))
                                            {
                                                $get_img = $get_img[1];
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate Stability.AI featured image: ' . $ierror);
                                            $get_img = '';
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty AI featured image query entered.');
                                }
                            }
                            elseif($enable_ai_images == '4')
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image))
                                    {
                                        aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                    }
                                    else
                                    {
                                        
                                        
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = 'Midjourney';
                                            aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                        }
                                        if($image_size == '256x256')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '512x512')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '1024x1024')
                                        {
                                            $width = '1024';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1792x1024')
                                        {
                                            $width = '1792';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1024x1792')
                                        {
                                            $width = '1024';
                                            $height = '1792';
                                        }
                                        else
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        $skip_this_copy = true;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                        {
                                            $skip_this_copy = false;
                                        }
                                        $ierror = '';
                                        $get_img = aiomatic_generate_ai_image_midjourney($ai_command_image, $width, $height, 'featuredMidjourneyImage', $skip_this_copy, $ierror);
                                        if($get_img !== false)
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate Midjourney featured image: ' . $ierror);
                                            $get_img = '';
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty AI featured image query entered.');
                                }
                            }
                            elseif($enable_ai_images == '5')
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image))
                                    {
                                        aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                    }
                                    else
                                    {
                                        
                                        
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = 'Replicate';
                                            aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                        }
                                        if($image_size == '256x256')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '512x512')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '1024x1024')
                                        {
                                            $width = '1024';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1792x1024')
                                        {
                                            $width = '1792';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1024x1792')
                                        {
                                            $width = '1024';
                                            $height = '1792';
                                        }
                                        else
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        $skip_this_copy = true;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                        {
                                            $skip_this_copy = false;
                                        }
                                        $ierror = '';
                                        $get_img = aiomatic_generate_replicate_image($ai_command_image, $width, $height, 'featuredMidjourneyImage', $skip_this_copy, $ierror);
                                        if($get_img !== false)
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate Replicate featured image: ' . $ierror);
                                            $get_img = '';
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty AI featured image query entered.');
                                }
                            }
                            elseif($enable_ai_images == '9')
                            {
                                $random_image = aiomatic_get_random_media_library_image();

                                if ($random_image !== false)
                                {
                                    $get_img = $random_image['url'];

                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging']))
                                    {
                                        aiomatic_log_to_file(
                                            'Random Media Library featured image selected: ' .
                                            $get_img .
                                            ' (ID: ' . $random_image['id'] . ')'
                                        );
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file(
                                        'Failed to find a random image in Media Library for featured image.'
                                    );

                                    $get_img = '';
                                }
                            }
                            elseif($enable_ai_images == '6')
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image))
                                    {
                                        aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                    }
                                    else
                                    {
                                        
                                        
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = 'Ideogram';
                                            aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                        }
                                        if($image_size == '256x256')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '512x512')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '1024x1024')
                                        {
                                            $width = '1024';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1792x1024')
                                        {
                                            $width = '1792';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1024x1792')
                                        {
                                            $width = '1024';
                                            $height = '1792';
                                        }
                                        else
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        $skip_this_copy = true;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                        {
                                            $skip_this_copy = false;
                                        }
                                        $ierror = '';
                                        $get_img = aiomatic_generate_ideogram_image($ai_command_image, $width, $height, 'featuredMidjourneyImage', $skip_this_copy, $ierror);
                                        if($get_img !== false)
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate Ideogram featured image: ' . $ierror);
                                            $get_img = '';
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty AI featured image query entered.');
                                }
                            }
                            elseif($enable_ai_images == '8')
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($ai_command_image))
                                    {
                                        aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                    }
                                    else
                                    {
                                        
                                        
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = 'Cloudflare';
                                            aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                        }
                                        if($image_size == '256x256')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '512x512')
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        elseif($image_size == '1024x1024')
                                        {
                                            $width = '1024';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1792x1024')
                                        {
                                            $width = '1792';
                                            $height = '1024';
                                        }
                                        elseif($image_size == '1024x1792')
                                        {
                                            $width = '1024';
                                            $height = '1792';
                                        }
                                        else
                                        {
                                            $width = '512';
                                            $height = '512';
                                        }
                                        $skip_this_copy = true;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                        {
                                            $skip_this_copy = false;
                                        }
                                        $ierror = '';
                                        $get_img = aiomatic_generate_cloudflare_image($ai_command_image, $width, $height, 'featuredCloudflareImage', $skip_this_copy, $ierror);
                                        if($get_img !== false)
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate Cloudflare featured image: ' . $ierror);
                                            $get_img = '';
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty AI featured image query entered.');
                                }
                            }
                            elseif($enable_ai_images == '3')
                            {
                                $query_words = $post_title;
                                if ($image_url != '') 
                                {
                                    $replacement = str_replace(array('[', ']'), '', $query_words);
                                    $image_url_temp = str_replace('%%item_title%%', $replacement, $image_url);
                                    $image_url_temp = preg_replace_callback('#%%random_image\[([^\]]*?)\](\[\d+\])?%%#', function ($matches) {
                                        if(isset($matches[2]))
                                        {
                                            $chance = trim($matches[2], '[]');
                                        }
                                        else
                                        {
                                            $chance = '';
                                        }
                                        $arv = array();
                                        $my_img = aiomatic_get_random_image_google($matches[1], 0, 0, $chance, $arv);
                                        return $my_img;
                                    }, $image_url_temp);
                                    $img_rulx = $spintax->Parse(trim($image_url_temp));
                                    $selected_img = aiomatic_select_ai_image($post_title, $img_rulx);
                                    if($selected_img === false)
                                    {
                                        $img_rulx = explode(',', $img_rulx);
                                        $img_rulx = trim($img_rulx[array_rand($img_rulx)]);
                                        if($img_rulx != '')
                                        {
                                            $get_img = $img_rulx;
                                        }
                                    }
                                    else
                                    {
                                        $get_img = $selected_img;
                                    }
                                }
                            }
                            else
                            {
                                $image_query_set = false;
                                $query_words = '';
                                $ai_command_image = '';
                                if($orig_ai_command_image == '')
                                {
                                    $orig_ai_command_image = $image_query;
                                }
                                if($orig_ai_command_image != '')
                                {
                                    $ai_command_image = $orig_ai_command_image;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                        $ai_command_image = array_filter($ai_command_image);
                                        if(count($ai_command_image) > 0)
                                        {
                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                        }
                                        else
                                        {
                                            $ai_command_image = '';
                                        }
                                    }
                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                    if(!empty($ai_command_image))
                                    {
                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $ai_command_image = trim(strip_tags($post_title));
                                    }
                                    $ai_command_image = trim($ai_command_image);
                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $ai_command_image = $txt_content;
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                }
                                if($ai_command_image != '')
                                {
                                    $query_words = $ai_command_image;
                                    $image_query = $ai_command_image;
                                    $image_query_set = true;
                                }
                                if(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'textrazor')
                                {
                                    if(isset($aiomatic_Main_Settings['textrazor_key']) && trim($aiomatic_Main_Settings['textrazor_key']) != '')
                                    {
                                        try
                                        {
                                            if(!class_exists('TextRazor'))
                                            {
                                                require_once(dirname(__FILE__) . "/res/TextRazor.php");
                                            }
                                            TextRazorSettings::setApiKey(trim($aiomatic_Main_Settings['textrazor_key']));
                                            $textrazor = new TextRazor();
                                            $textrazor->addExtractor('entities');
                                            $response = $textrazor->analyze($image_query);
                                            if (isset($response['response']['entities'])) 
                                            {
                                                foreach ($response['response']['entities'] as $entity) 
                                                {
                                                    $query_words = '';
                                                    if(isset($entity['entityEnglishId']))
                                                    {
                                                        $query_words = $entity['entityEnglishId'];
                                                    }
                                                    else
                                                    {
                                                        $query_words = $entity['entityId'];
                                                    }
                                                    if($query_words != '')
                                                    {
                                                        $attached_id = '';
                                                        $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                                        if(!empty($attached_id))
                                                        {
                                                            $additional_attachments[] = $attached_id;
                                                        }
                                                        if(!empty($z_img))
                                                        {
                                                            $get_img = $z_img;
                                                            $go_local_image = false;
                                                            if(!function_exists('is_plugin_active'))
                                                            {
                                                                include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                                            }
                                                            if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                                            {
                                                                $go_local_image = true;
                                                            }
                                                            if($go_local_image == true)
                                                            {
                                                                $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, $query_words);
                                                                if(!empty($attached_id))
                                                                {
                                                                    $additional_attachments[] = $attached_id;
                                                                }
                                                                if($localpath !== false)
                                                                {
                                                                    $get_img = $localpath[0];
                                                                }
                                                            }
                                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                                aiomatic_log_to_file('Royalty Free Image Generated with help of TextRazor (kw: "' . $query_words . '"): ' . $z_img);
                                                            }
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        catch(Exception $e)
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                aiomatic_log_to_file('Failed to search for keywords using TextRazor (2): ' . $e->getMessage());
                                            }
                                        }
                                    }
                                }
                                elseif(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'openai')
                                {
                                    if(isset($aiomatic_Main_Settings['keyword_prompts']) && trim($aiomatic_Main_Settings['keyword_prompts']) != '')
                                    {
                                        if(isset($aiomatic_Main_Settings['keyword_model']) && $aiomatic_Main_Settings['keyword_model'] != '')
                                        {
                                            $kw_model = $aiomatic_Main_Settings['keyword_model'];
                                        }
                                        else
                                        {
                                            $kw_model = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                        }
                                        if(isset($aiomatic_Main_Settings['keyword_assistant_id']) && $aiomatic_Main_Settings['keyword_assistant_id'] != '')
                                        {
                                            $keyword_assistant_id = $aiomatic_Main_Settings['keyword_assistant_id'];
                                        }
                                        else
                                        {
                                            $keyword_assistant_id = '';
                                        }
                                        $title_ai_command = trim($aiomatic_Main_Settings['keyword_prompts']);
                                        $title_ai_command = str_replace('%%default_post_cats%%', $default_cat_list, $title_ai_command);
                                        $title_ai_command = str_replace('%%original_post_title%%', $post_title, $title_ai_command);
                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                        {
                                            $title_ai_command = preg_split('/\r\n|\r|\n/', $title_ai_command);
                                            $title_ai_command = array_filter($title_ai_command);
                                            if(count($title_ai_command) > 0)
                                            {
                                                $title_ai_command = $title_ai_command[array_rand($title_ai_command)];
                                            }
                                            else
                                            {
                                                $title_ai_command = '';
                                            }
                                        }
                                        $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                        if(!empty($title_ai_command))
                                        {
                                            $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        }
                                        $title_ai_command = trim($title_ai_command);
                                        if (filter_var($title_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($title_ai_command, '.txt'))
                                        {
                                            $txt_content = aiomatic_get_web_page($title_ai_command);
                                            if ($txt_content !== FALSE) 
                                            {
                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                $txt_content = array_filter($txt_content);
                                                if(count($txt_content) > 0)
                                                {
                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                    if(trim($txt_content) != '') 
                                                    {
                                                        $title_ai_command = $txt_content;
                                                        $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                                        $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                }
                                            }
                                        }
                                        if(empty($title_ai_command))
                                        {
                                            aiomatic_log_to_file('Empty API keyword extractor seed expression provided!');
                                            $title_ai_command = 'Type the most relevant keyword, no other text before or after it, for a blog post titled:  ' . trim(strip_tags($post_title));
                                        } 
                                        if(aiomatic_strlen($title_ai_command) > $max_seed_tokens * 4)
                                        {
                                            $title_ai_command = aiomatic_substr($title_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                                        }
                                        $title_ai_command = trim($title_ai_command);
                                        if(empty($title_ai_command))
                                        {
                                            aiomatic_log_to_file('Empty API title seed expression provided(3)! ' . print_r($title_ai_command, true));
                                        }
                                        else
                                        {
                                            $query_token_count = count(aiomatic_encode($title_ai_command));
                                            $available_tokens = aiomatic_compute_available_tokens($kw_model, $max_tokens, $title_ai_command, $query_token_count);
                                            if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                            {
                                                $string_len = aiomatic_strlen($title_ai_command);
                                                $string_len = $string_len / 2;
                                                $string_len = intval(0 - $string_len);
                                                $title_ai_command = aiomatic_substr($title_ai_command, 0, $string_len);
                                                $title_ai_command = trim($title_ai_command);
                                                $query_token_count = count(aiomatic_encode($title_ai_command));
                                                $available_tokens = $max_tokens - $query_token_count;
                                            }
                                            $aierror = '';
                                            $finish_reason = '';
                                            if(!empty($global_prepend))
                                            {
                                                $title_ai_command = $global_prepend . ' ' . $title_ai_command;
                                            }
                                            if(!empty($global_append))
                                            {
                                                $title_ai_command = $title_ai_command . ' ' . $global_append;
                                            }
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                $api_service = aiomatic_get_api_service($token, $kw_model);
                                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $keyword_assistant_id . '/' . $kw_model . ')(' . $available_tokens . ') for title text: ' . $title_ai_command);
                                            }
                                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating keywords for image search'));
                                            $generated_text = aiomatic_generate_text($token, $kw_model, $title_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'keywordID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $keyword_assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                            if($generated_text === false)
                                            {
                                                aiomatic_log_to_file('Keyword generator error: ' . $aierror);
                                                $ai_title = '';
                                            }
                                            else
                                            {
                                                $ai_title = trim(trim($generated_text), '.');
                                                $ai_titles = explode(',', $ai_title);
                                                foreach($ai_titles as $query_words)
                                                {
                                                    $attached_id = '';
                                                    $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, trim($query_words), $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                                    if(!empty($attached_id))
                                                    {
                                                        $additional_attachments[] = $attached_id;
                                                    }
                                                    if(!empty($z_img))
                                                    {
                                                        $get_img = $z_img;
                                                        $go_local_image = false;
                                                        if(!function_exists('is_plugin_active'))
                                                        {
                                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                                        }
                                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                                        {
                                                            $go_local_image = true;
                                                        }
                                                        if($go_local_image == true)
                                                        {
                                                            $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, $query_words);
                                                            if(!empty($attached_id))
                                                            {
                                                                $additional_attachments[] = $attached_id;
                                                            }
                                                            if($localpath !== false)
                                                            {
                                                                $get_img = $localpath[0];
                                                            }
                                                        }
                                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                            aiomatic_log_to_file('Royalty Free Image Generated with help of AI (kw: "' . $query_words . '"): ' . $z_img);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                $api_service = aiomatic_get_api_service($token, $kw_model);
                                                aiomatic_log_to_file('Successfully got API keyword result from ' . $api_service . ': ' . $ai_title);
                                            }
                                        }
                                    }
                                }
                                if(empty($get_img))
                                {
                                    if($image_query_set == true && !empty($image_query))
                                    {
                                        $attached_id = '';
                                        $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $image_query, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                        if(!empty($attached_id))
                                        {
                                            $additional_attachments[] = $attached_id;
                                        }
                                        if($get_img == '' || $get_img === false)
                                        {
                                            if(isset($aiomatic_Main_Settings['bimage']) && $aiomatic_Main_Settings['bimage'] == 'on')
                                            {
                                                $keyword_class = new Aiomatic_keywords();
                                                $image_query = $keyword_class->keywords($image_query, 1);
                                                $attached_id = '';
                                                $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $image_query, $img_attr, $attached_id, 20, true, $raw_img_list, array(), $full_result_list);
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                            }
                                        }
                                    }
                                    if(empty($get_img))
                                    {
                                        $keyword_class = new Aiomatic_keywords();
                                        $query_words = $keyword_class->keywords($post_title, 2);
                                        $attached_id = '';
                                        $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                        if(!empty($attached_id))
                                        {
                                            $additional_attachments[] = $attached_id;
                                        }
                                        if($get_img == '' || $get_img === false)
                                        {
                                            if(isset($aiomatic_Main_Settings['bimage']) && $aiomatic_Main_Settings['bimage'] == 'on')
                                            {
                                                $query_words = $keyword_class->keywords($post_title, 1);
                                                $attached_id = '';
                                                $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 20, true, $raw_img_list, array(), $full_result_list);
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                                if($get_img == '' || $get_img === false)
                                                {
                                                    if(isset($aiomatic_Main_Settings['no_royalty_skip']) && $aiomatic_Main_Settings['no_royalty_skip'] == 'on')
                                                    {
                                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                            aiomatic_log_to_file('Skipping importing because no royalty free image found.');
                                                        }
                                                        unset($post_title_lines[$current_index]);
                                                        continue;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if(isset($aiomatic_Main_Settings['no_royalty_skip']) && $aiomatic_Main_Settings['no_royalty_skip'] == 'on')
                                                {
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                        aiomatic_log_to_file('Skipping importing because no royalty free image found.');
                                                    }
                                                    unset($post_title_lines[$current_index]);
                                                    continue;
                                                }
                                            }
                                        }
                                    }
                                    if(!empty($get_img))
                                    {
                                        
                                        $go_local_image = false;
                                        if(!function_exists('is_plugin_active'))
                                        {
                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                        }
                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                        {
                                            $go_local_image = true;
                                        }
                                        if($go_local_image == true)
                                        {
                                            $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, '');
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                            if($localpath !== false)
                                            {
                                                $get_img = $localpath[0];
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                        {
                            $already_spinned = '1';
                        }
                        $my_post                              = array();
                        $my_post['aiomatic_post_image']       = $get_img;
                        if($enable_ai_images == '2')
                        {
                            $my_post['aiomatic_local_image']      = '1';
                        }
                        else
                        {
                            $my_post['aiomatic_local_image']      = '0';
                        }
                        $my_post['aiomatic_enable_pingbacks'] = $enable_pingback;
                        $my_post['default_category']          = $default_category;
                        $my_post['post_type']                 = $post_type;
                        $my_post['comment_status']            = $accept_comments;
                        if (isset($aiomatic_Main_Settings['draft_first']) && $aiomatic_Main_Settings['draft_first'] != 'on')
                        {
                            if($post_status == 'publish')
                            {
                                $draft_me = true;
                                $my_post['post_status'] = 'draft';
                            }
                            else
                            {
                                $my_post['post_status']   = $post_status;
                            }
                        }
                        else
                        {
                            $my_post['post_status']               = $post_status;
                        }
                        if($user_name_type == 'rand')
                        {
                            $randid = aiomatic_display_random_user();
                            if($randid === false)
                            {
                                $my_post['post_author']               = aimogen_get_admin_user_id();
                            }
                            else
                            {
                                $my_post['post_author']               = $randid->ID;
                            }
                        }
                        else
                        {
                            $my_post['post_author']               = $post_user_name;
                        }
                        $ai_command = $orig_ai_command;
                        $ai_command = aiomatic_replaceSynergyShortcodes($ai_command);
                        if(!empty($ai_command))
                        {
                            $aicontent = aiomatic_replaceAIPostShortcodes($ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                        }
                        else
                        {
                            $aicontent = trim(strip_tags($post_title));
                        }
                        if (filter_var($aicontent, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($aicontent, '.txt'))
                        {
                            $txt_content = aiomatic_get_web_page($aicontent);
                            if ($txt_content !== FALSE) 
                            {
                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                $txt_content = array_filter($txt_content);
                                if(count($txt_content) > 0)
                                {
                                    $txt_content = $txt_content[array_rand($txt_content)];
                                    if(trim($txt_content) != '') 
                                    {
                                        $aicontent = $txt_content;
                                        $aicontent = aiomatic_replaceSynergyShortcodes($aicontent);
                                        $aicontent = aiomatic_replaceAIPostShortcodes($aicontent, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                }
                            }
                        }
                        $last_char = aiomatic_substr($aicontent, -1, null);
                        if(!ctype_punct($last_char))
                        {
                            $aicontent .= '.';
                        }
                        if(aiomatic_strlen($aicontent) > $max_seed_tokens * 4)
                        {
                            $aicontent = aiomatic_substr($aicontent, 0, (0-($max_seed_tokens * 4)));
                        }
                        $aicontent = trim($aicontent);
                        if(empty($aicontent))
                        {
                            aiomatic_log_to_file('Empty API seed expression provided! ' . print_r($ai_command, true));
                            break;
                        }
                        $query_token_count = count(aiomatic_encode($aicontent));
                        $available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $aicontent, $query_token_count);
                        if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                        {
                            $string_len = aiomatic_strlen($aicontent);
                            $string_len = $string_len / 2;
                            $string_len = intval(0 - $string_len);
                            $aicontent = aiomatic_substr($aicontent, 0, $string_len);
                            $aicontent = trim($aicontent);
                            if(empty($aicontent))
                            {
                                aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($ai_command, true));
                                break;
                            }
                            $query_token_count = count(aiomatic_encode($aicontent));
                            $available_tokens = $max_tokens - $query_token_count;
                        }
                        $aierror = '';
                        $finish_reason = '';
                        if(!empty($global_prepend))
                        {
                            $aicontent = $global_prepend . ' ' . $aicontent;
                        }
                        if(!empty($global_append))
                        {
                            $aicontent = $aicontent . ' ' . $global_append;
                        }
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                        {
                            $api_service = aiomatic_get_api_service($token, $model);
                            aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for text: ' . $aicontent);
                        }
                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating post content'));
                        $generated_text = aiomatic_generate_text($token, $model, $aicontent, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'contentID' . $param, 0, $finish_reason, $aierror, false, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                        if($generated_text === false)
                        {
                            aiomatic_log_to_file($aierror);
                            break;
                        }
                        else
                        {   
                            if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                            {
                                $new_post_content = ucfirst(trim(nl2br(trim($generated_text))));
                            }
                            else
                            {
                                $new_post_content = ucfirst(trim($generated_text));
                            }
                            if($finish_reason == 'length')
                            {
                                $query_token_count = count(aiomatic_encode($new_post_content));
                                $available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $new_post_content, $query_token_count);
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating post content (2)'));
                                $generated_text = aiomatic_generate_text($token, $model, $new_post_content, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'contentID' . $param, 0, $finish_reason, $aierror, false, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                if($generated_text !== false)
                                {
                                    if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                                    {
                                        $new_post_content .= ' ' . ucfirst(trim(nl2br(trim($generated_text))));
                                    }
                                    else
                                    {
                                        $new_post_content .= ' ' . ucfirst(trim($generated_text));
                                    }
                                }
                            }
                        }
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                        {
                            $api_service = aiomatic_get_api_service($token, $model);
                            aiomatic_log_to_file('Successfully got API result from ' . $api_service . '.');
                        }
                        if($min_char == '')
                        {
                            $min_char = 0;
                        }
                        else
                        {
                            $min_char = intval($min_char);
                        }
                        $cnt = 1;
                        $max_fails = 10;
                        $failed_calls = 0;
                        $heading_results = $headings_arr;
                        if($headings != '' && is_numeric($headings))
                        {
                            if(count($heading_results) < $headings)
                            {
                                $heading_results_ai = aiomatic_scrape_related_questions($new_post_title, $headings, $headings_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $headings_ai_command, $assistant_id);
                                $heading_results = array_merge($heading_results, $heading_results_ai);
                            }
                        }
                        $ai_retry = false;
                        if($image_size == '')
                        {
                            $image_size = '256x256';
                        }
                        if(aiomatic_strlen($new_post_content) > $min_char)
                        {
                            $add_my_image = '';
                            $temp_get_img = '';
                            if(count($heading_results) > 0)
                            {
                                $rand_heading = '';
                                $saverand = array_rand($heading_results);
                                $rand_heading = $heading_results[$saverand];
                                unset($heading_results[$saverand]);
                                if(isset($rand_heading['q']))
                                {
                                    $rand_heading['q'] = preg_replace('#^\d+\.([\s\S]*)#i', '$1', $rand_heading['q']);
                                    $heading_val = '<h2>' . $rand_heading['q'] . '</h2>';
                                    if($rand_heading['a'] != '')
                                    {
                                        $heading_val .= '<span>' . $rand_heading['a'] . '</span>';
                                    }
                                    $image_query = $rand_heading['q'];
                                }
                            }
                            if($heading_val == '')
                            {
                                $temp_post = trim($new_post_content);
                            }
                            else
                            {
                                $temp_post = trim($heading_val);
                            }
                            
                            if($images != '' && is_numeric($images) && $images > $added_images)
                            {
                                $query_words = $post_title;
                                if($image_query == '')
                                {
                                    $image_query = $temp_post;
                                }
                                if($enable_ai_images_article == '1')
                                {
                                    if($orig_ai_command_image_article == '')
                                    {
                                        $orig_ai_command_image_article = $image_query;
                                    }
                                    if($orig_ai_command_image_article != '')
                                    {
                                        $ai_command_image_article = $orig_ai_command_image_article;
                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                        {
                                            $ai_command_image_article = preg_split('/\r\n|\r|\n/', $ai_command_image_article);
                                            $ai_command_image_article = array_filter($ai_command_image_article);
                                            if(count($ai_command_image_article) > 0)
                                            {
                                                $ai_command_image_article = $ai_command_image_article[array_rand($ai_command_image_article)];
                                            }
                                            else
                                            {
                                                $ai_command_image_article = '';
                                            }
                                        }
                                        $ai_command_image_article = aiomatic_replaceSynergyShortcodes($ai_command_image_article);
                                        if(!empty($ai_command_image_article))
                                        {
                                            $ai_command_image_article = aiomatic_replaceAIPostShortcodes($ai_command_image_article, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        }
                                        else
                                        {
                                            $ai_command_image_article = trim(strip_tags($post_title));
                                        }
                                        $ai_command_image_article = trim($ai_command_image_article);
                                        if (filter_var($ai_command_image_article, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image_article, '.txt'))
                                        {
                                            $txt_content = aiomatic_get_web_page($ai_command_image_article);
                                            if ($txt_content !== FALSE) 
                                            {
                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                $txt_content = array_filter($txt_content);
                                                if(count($txt_content) > 0)
                                                {
                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                    if(trim($txt_content) != '') 
                                                    {
                                                        $ai_command_image_article = $txt_content;
                                                        $ai_command_image_article = aiomatic_replaceSynergyShortcodes($ai_command_image_article);
                                                        $ai_command_image_article = aiomatic_replaceAIPostShortcodes($ai_command_image_article, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                }
                                            }
                                        }
                                        if(empty($ai_command_image_article))
                                        {
                                            aiomatic_log_to_file('Empty API image seed expression provided!');
                                        }
                                        else
                                        {
                                            if(aiomatic_strlen($ai_command_image_article) > 1000)
                                            {
                                                $ai_command_image_article = aiomatic_substr($ai_command_image_article, 0, 1000);
                                            }
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                $api_service = aiomatic_get_api_service($token, $image_model_article);
                                                aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $ai_command_image_article);
                                            }
                                            $aierror = '';
                                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating AI image'));
                                            $temp_get_imgs = aiomatic_generate_ai_image($token, 1, $ai_command_image_article, $image_size_article, 'contentImage', false, 0, $aierror, $image_model_article, $post_title);
                                            if($temp_get_imgs !== false)
                                            {
                                                foreach($temp_get_imgs as $tmpimg)
                                                {
                                                    $added_images++;
                                                    $added_img_list[] = $tmpimg;
                                                    $temp_get_img = $tmpimg;
                                                }
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    aiomatic_log_to_file('AI generated image returned: ' . $temp_get_img);
                                                }
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to generate AI image: ' . $aierror);
                                                $temp_get_img = '';
                                            }
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Empty AI image query entered.');
                                    }
                                }
                                elseif($enable_ai_images_article == '2')
                                {
                                    if($orig_ai_command_image_article == '')
                                    {
                                        $orig_ai_command_image_article = $image_query;
                                    }
                                    if($orig_ai_command_image_article != '')
                                    {
                                        $ai_command_image = $orig_ai_command_image_article;
                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                        {
                                            $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                            $ai_command_image = array_filter($ai_command_image);
                                            if(count($ai_command_image) > 0)
                                            {
                                                $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                            }
                                            else
                                            {
                                                $ai_command_image = '';
                                            }
                                        }
                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                        if(!empty($ai_command_image))
                                        {
                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        }
                                        else
                                        {
                                            $ai_command_image = trim(strip_tags($post_title));
                                        }
                                        $ai_command_image = trim($ai_command_image);
                                        if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                        {
                                            $txt_content = aiomatic_get_web_page($ai_command_image);
                                            if ($txt_content !== FALSE) 
                                            {
                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                $txt_content = array_filter($txt_content);
                                                if(count($txt_content) > 0)
                                                {
                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                    if(trim($txt_content) != '') 
                                                    {
                                                        $ai_command_image = $txt_content;
                                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                }
                                            }
                                        }
                                        if(empty($ai_command_image))
                                        {
                                            aiomatic_log_to_file('Empty API image seed expression provided!');
                                        }
                                        else
                                        {
                                            
                                            
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                $api_service = 'Stability.AI';
                                                aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $ai_command_image);
                                            }
                                            if($image_size_article == '256x256')
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            elseif($image_size_article == '512x512')
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            elseif($image_size_article == '1024x1024')
                                            {
                                                $width = '1024';
                                                $height = '1024';
                                            }
                                            else
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            $ierror = '';
                                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating AI image (Stable Diffusion)'));
                                            $temp_get_imgs = aiomatic_generate_stability_image($ai_command_image, $height, $width, 'contentStableImage', 0, false, $ierror, false, false, '', 0);
                                            if($temp_get_imgs !== false)
                                            {
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    aiomatic_log_to_file('AI generated image returned: ' . $temp_get_imgs[1]);
                                                }
                                                $added_images++;
                                                $added_img_list[] = $temp_get_imgs[1];
                                                $temp_get_img = $temp_get_imgs[1];
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to generate Stability.AI image: ' . $ierror);
                                                $temp_get_img = '';
                                            }
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Empty AI image query entered.');
                                    }
                                }
                                elseif($enable_ai_images_article == '7')
                                {
                                    if($orig_ai_command_image_article == '')
                                    {
                                        $orig_ai_command_image_article = $image_query;
                                    }
                                    if($orig_ai_command_image_article != '')
                                    {
                                        $ai_command_image = $orig_ai_command_image_article;
                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                        {
                                            $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                            $ai_command_image = array_filter($ai_command_image);
                                            if(count($ai_command_image) > 0)
                                            {
                                                $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                            }
                                            else
                                            {
                                                $ai_command_image = '';
                                            }
                                        }
                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                        if(!empty($ai_command_image))
                                        {
                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        }
                                        else
                                        {
                                            $ai_command_image = trim(strip_tags($post_title));
                                        }
                                        $ai_command_image = trim($ai_command_image);
                                        if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                        {
                                            $txt_content = aiomatic_get_web_page($ai_command_image);
                                            if ($txt_content !== FALSE) 
                                            {
                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                $txt_content = array_filter($txt_content);
                                                if(count($txt_content) > 0)
                                                {
                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                    if(trim($txt_content) != '') 
                                                    {
                                                        $ai_command_image = $txt_content;
                                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                }
                                            }
                                        }
                                        if(empty($ai_command_image))
                                        {
                                            aiomatic_log_to_file('Empty API image seed expression provided!');
                                        }
                                        else
                                        {
                                            
                                            
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                $api_service = 'Google';
                                                aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $ai_command_image);
                                            }
                                            if (isset($aiomatic_Main_Settings['google_ai_image_model']) && trim($aiomatic_Main_Settings['google_ai_image_model']) != '') 
                                            {
                                                $model = trim($aiomatic_Main_Settings['google_ai_image_model']);
                                            }
                                            else
                                            {
                                                $model = AIMOGEN_GOOGLE_IMAGE_DEFAULT_MODEL;
                                            }
                                            $ierror = '';
                                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating AI image (Google)'));
                                            $temp_get_imgs = aiomatic_generate_image_google($ai_command_image, $model, 'contentGoogleImage', false, $ierror, false);
                                            if($temp_get_imgs !== false)
                                            {
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    aiomatic_log_to_file('AI generated image returned: ' . $temp_get_imgs[1]);
                                                }
                                                $added_images++;
                                                $added_img_list[] = $temp_get_imgs[1];
                                                $temp_get_img = $temp_get_imgs[1];
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to generate Stability.AI image: ' . $ierror);
                                                $temp_get_img = '';
                                            }
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Empty AI image query entered.');
                                    }
                                }
                                elseif($enable_ai_images_article == '4')
                                {
                                    if($orig_ai_command_image_article == '')
                                    {
                                        $orig_ai_command_image_article = $image_query;
                                    }
                                    if($orig_ai_command_image_article != '')
                                    {
                                        $ai_command_image = $orig_ai_command_image_article;
                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                        {
                                            $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                            $ai_command_image = array_filter($ai_command_image);
                                            if(count($ai_command_image) > 0)
                                            {
                                                $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                            }
                                            else
                                            {
                                                $ai_command_image = '';
                                            }
                                        }
                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                        if(!empty($ai_command_image))
                                        {
                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        }
                                        else
                                        {
                                            $ai_command_image = trim(strip_tags($post_title));
                                        }
                                        $ai_command_image = trim($ai_command_image);
                                        if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                        {
                                            $txt_content = aiomatic_get_web_page($ai_command_image);
                                            if ($txt_content !== FALSE) 
                                            {
                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                $txt_content = array_filter($txt_content);
                                                if(count($txt_content) > 0)
                                                {
                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                    if(trim($txt_content) != '') 
                                                    {
                                                        $ai_command_image = $txt_content;
                                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                }
                                            }
                                        }
                                        if(empty($ai_command_image))
                                        {
                                            aiomatic_log_to_file('Empty API image seed expression provided!');
                                        }
                                        else
                                        {
                                            
                                            
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                $api_service = 'Midjourney';
                                                aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $ai_command_image);
                                            }
                                            if($image_size_article == '256x256')
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            elseif($image_size_article == '512x512')
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            elseif($image_size_article == '1024x1024')
                                            {
                                                $width = '1024';
                                                $height = '1024';
                                            }
                                            elseif($image_size_article == '1792x1024')
                                            {
                                                $width = '1792';
                                                $height = '1024';
                                            }
                                            elseif($image_size_article == '1024x1792')
                                            {
                                                $width = '1024';
                                                $height = '1792';
                                            }
                                            else
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            $ierror = '';
                                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating AI image (Midjourney)'));
                                            $temp_get_imgs = aiomatic_generate_ai_image_midjourney($ai_command_image, $width, $height, 'contentMidjourneyImage', false, $ierror);
                                            if($temp_get_imgs !== false)
                                            {
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    aiomatic_log_to_file('AI generated image returned: ' . $temp_get_imgs);
                                                }
                                                $added_images++;
                                                $added_img_list[] = $temp_get_imgs;
                                                $temp_get_img = $temp_get_imgs;
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to generate Midjourney image: ' . $ierror);
                                                $temp_get_img = '';
                                            }
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Empty AI image query entered.');
                                    }
                                }
                                elseif($enable_ai_images_article == '5')
                                {
                                    if($orig_ai_command_image_article == '')
                                    {
                                        $orig_ai_command_image_article = $image_query;
                                    }
                                    if($orig_ai_command_image_article != '')
                                    {
                                        $ai_command_image = $orig_ai_command_image_article;
                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                        {
                                            $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                            $ai_command_image = array_filter($ai_command_image);
                                            if(count($ai_command_image) > 0)
                                            {
                                                $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                            }
                                            else
                                            {
                                                $ai_command_image = '';
                                            }
                                        }
                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                        if(!empty($ai_command_image))
                                        {
                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        }
                                        else
                                        {
                                            $ai_command_image = trim(strip_tags($post_title));
                                        }
                                        $ai_command_image = trim($ai_command_image);
                                        if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                        {
                                            $txt_content = aiomatic_get_web_page($ai_command_image);
                                            if ($txt_content !== FALSE) 
                                            {
                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                $txt_content = array_filter($txt_content);
                                                if(count($txt_content) > 0)
                                                {
                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                    if(trim($txt_content) != '') 
                                                    {
                                                        $ai_command_image = $txt_content;
                                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                }
                                            }
                                        }
                                        if(empty($ai_command_image))
                                        {
                                            aiomatic_log_to_file('Empty API image seed expression provided!');
                                        }
                                        else
                                        {
                                            
                                            
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                $api_service = 'Replicate';
                                                aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $ai_command_image);
                                            }
                                            if($image_size_article == '256x256')
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            elseif($image_size_article == '512x512')
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            elseif($image_size_article == '1024x1024')
                                            {
                                                $width = '1024';
                                                $height = '1024';
                                            }
                                            elseif($image_size_article == '1792x1024')
                                            {
                                                $width = '1792';
                                                $height = '1024';
                                            }
                                            elseif($image_size_article == '1024x1792')
                                            {
                                                $width = '1024';
                                                $height = '1792';
                                            }
                                            else
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            $ierror = '';
                                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating AI image (Replicate)'));
                                            $temp_get_imgs = aiomatic_generate_replicate_image($ai_command_image, $width, $height, 'contentReplicateImage', false, $ierror);
                                            if($temp_get_imgs !== false)
                                            {
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    aiomatic_log_to_file('AI generated image returned: ' . $temp_get_imgs);
                                                }
                                                $added_images++;
                                                $added_img_list[] = $temp_get_imgs;
                                                $temp_get_img = $temp_get_imgs;
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to generate Replicate image: ' . $ierror);
                                                $temp_get_img = '';
                                            }
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Empty AI image query entered.');
                                    }
                                }
                                elseif($enable_ai_images_article == '9')
                                {
                                    $random_image = aiomatic_get_random_media_library_image();

                                    if ($random_image !== false)
                                    {
                                        $temp_get_img = $random_image['url'];

                                        $added_images++;
                                        $added_img_list[] = $temp_get_img;

                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging']))
                                        {
                                            aiomatic_log_to_file(
                                                'Random Media Library article image selected: ' .
                                                $temp_get_img .
                                                ' (ID: ' . $random_image['id'] . ')'
                                            );
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file(
                                            'Failed to find a random image in Media Library for article image.'
                                        );

                                        $temp_get_img = '';
                                    }
                                }
                                elseif($enable_ai_images_article == '6')
                                {
                                    if($orig_ai_command_image_article == '')
                                    {
                                        $orig_ai_command_image_article = $image_query;
                                    }
                                    if($orig_ai_command_image_article != '')
                                    {
                                        $ai_command_image = $orig_ai_command_image_article;
                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                        {
                                            $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                            $ai_command_image = array_filter($ai_command_image);
                                            if(count($ai_command_image) > 0)
                                            {
                                                $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                            }
                                            else
                                            {
                                                $ai_command_image = '';
                                            }
                                        }
                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                        if(!empty($ai_command_image))
                                        {
                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        }
                                        else
                                        {
                                            $ai_command_image = trim(strip_tags($post_title));
                                        }
                                        $ai_command_image = trim($ai_command_image);
                                        if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                        {
                                            $txt_content = aiomatic_get_web_page($ai_command_image);
                                            if ($txt_content !== FALSE) 
                                            {
                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                $txt_content = array_filter($txt_content);
                                                if(count($txt_content) > 0)
                                                {
                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                    if(trim($txt_content) != '') 
                                                    {
                                                        $ai_command_image = $txt_content;
                                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                }
                                            }
                                        }
                                        if(empty($ai_command_image))
                                        {
                                            aiomatic_log_to_file('Empty API image seed expression provided!');
                                        }
                                        else
                                        {
                                            
                                            
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                $api_service = 'Ideogram';
                                                aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $ai_command_image);
                                            }
                                            if($image_size_article == '256x256')
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            elseif($image_size_article == '512x512')
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            elseif($image_size_article == '1024x1024')
                                            {
                                                $width = '1024';
                                                $height = '1024';
                                            }
                                            elseif($image_size_article == '1792x1024')
                                            {
                                                $width = '1792';
                                                $height = '1024';
                                            }
                                            elseif($image_size_article == '1024x1792')
                                            {
                                                $width = '1024';
                                                $height = '1792';
                                            }
                                            else
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            $ierror = '';
                                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating AI image (Ideogram)'));
                                            $temp_get_imgs = aiomatic_generate_ideogram_image($ai_command_image, $width, $height, 'contentIdeogramImage', false, $ierror);
                                            if($temp_get_imgs !== false)
                                            {
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    aiomatic_log_to_file('AI generated image returned: ' . $temp_get_imgs);
                                                }
                                                $added_images++;
                                                $added_img_list[] = $temp_get_imgs;
                                                $temp_get_img = $temp_get_imgs;
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to generate Ideogram image: ' . $ierror);
                                                $temp_get_img = '';
                                            }
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Empty AI image query entered.');
                                    }
                                }
                                elseif($enable_ai_images_article == '8')
                                {
                                    if($orig_ai_command_image_article == '')
                                    {
                                        $orig_ai_command_image_article = $image_query;
                                    }
                                    if($orig_ai_command_image_article != '')
                                    {
                                        $ai_command_image = $orig_ai_command_image_article;
                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                        {
                                            $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                            $ai_command_image = array_filter($ai_command_image);
                                            if(count($ai_command_image) > 0)
                                            {
                                                $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                            }
                                            else
                                            {
                                                $ai_command_image = '';
                                            }
                                        }
                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                        if(!empty($ai_command_image))
                                        {
                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        }
                                        else
                                        {
                                            $ai_command_image = trim(strip_tags($post_title));
                                        }
                                        $ai_command_image = trim($ai_command_image);
                                        if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                        {
                                            $txt_content = aiomatic_get_web_page($ai_command_image);
                                            if ($txt_content !== FALSE) 
                                            {
                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                $txt_content = array_filter($txt_content);
                                                if(count($txt_content) > 0)
                                                {
                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                    if(trim($txt_content) != '') 
                                                    {
                                                        $ai_command_image = $txt_content;
                                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                }
                                            }
                                        }
                                        if(empty($ai_command_image))
                                        {
                                            aiomatic_log_to_file('Empty API image seed expression provided!');
                                        }
                                        else
                                        {
                                            
                                            
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                $api_service = 'Cloudflare';
                                                aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $ai_command_image);
                                            }
                                            if($image_size_article == '256x256')
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            elseif($image_size_article == '512x512')
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            elseif($image_size_article == '1024x1024')
                                            {
                                                $width = '1024';
                                                $height = '1024';
                                            }
                                            elseif($image_size_article == '1792x1024')
                                            {
                                                $width = '1792';
                                                $height = '1024';
                                            }
                                            elseif($image_size_article == '1024x1792')
                                            {
                                                $width = '1024';
                                                $height = '1792';
                                            }
                                            else
                                            {
                                                $width = '512';
                                                $height = '512';
                                            }
                                            $ierror = '';
                                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating AI image (Cloudflare)'));
                                            $temp_get_imgs = aiomatic_generate_cloudflare_image($ai_command_image, $width, $height, 'contentCloudflareImage', false, $ierror);
                                            if($temp_get_imgs !== false)
                                            {
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    aiomatic_log_to_file('AI generated image returned: ' . $temp_get_imgs);
                                                }
                                                $added_images++;
                                                $added_img_list[] = $temp_get_imgs;
                                                $temp_get_img = $temp_get_imgs;
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to generate Cloudflare image: ' . $ierror);
                                                $temp_get_img = '';
                                            }
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Empty AI image query entered.');
                                    }
                                }
                                elseif($enable_ai_images_article == '3')
                                {
                                    if ($image_url != '') 
                                    {
                                        $replacement = str_replace(array('[', ']'), '', $query_words);
                                        $image_url_temp = str_replace('%%item_title%%', $replacement, $image_url);
                                        $image_url_temp = preg_replace_callback('#%%random_image\[([^\]]*?)\](\[\d+\])?%%#', function ($matches) {
                                            if(isset($matches[2]))
                                            {
                                                $chance = trim($matches[2], '[]');
                                            }
                                            else
                                            {
                                                $chance = '';
                                            }
                                            $arv = array();
                                            $my_img = aiomatic_get_random_image_google($matches[1], 0, 0, $chance, $arv);
                                            return $my_img;
                                        }, $image_url_temp);
                                        $img_rulx = $spintax->Parse(trim($image_url_temp));
                                        $selected_img = aiomatic_select_ai_image($post_title, $img_rulx);
                                        if($selected_img === false)
                                        {
                                            $img_rulx = explode(',', $img_rulx);
                                            $img_rulx = trim($img_rulx[array_rand($img_rulx)]);
                                            if($img_rulx != '')
                                            {
                                                $added_images++;
                                                $added_img_list[] = $img_rulx;
                                                $temp_get_img = $img_rulx;
                                            }
                                        }
                                        else
                                        {
                                            $added_images++;
                                            $added_img_list[] = $selected_img;
                                            $temp_get_img = $selected_img;
                                        }
                                    }
                                }
                                elseif(count($images_arr) > 0)
                                {
                                    $first_el = array_shift($images_arr);
                                    $first_el = aiomatic_replaceSynergyShortcodes($first_el);
                                    $added_images++;
                                    $added_img_list[] = $first_el;
                                    $temp_get_img = $first_el;
                                }
                                else
                                {
                                    $image_query_set = false;
                                    $query_words = '';
                                    $ai_command_image = '';
                                    if($orig_ai_command_image == '')
                                    {
                                        $orig_ai_command_image = $image_query;
                                    }
                                    if($orig_ai_command_image != '')
                                    {
                                        $ai_command_image = $orig_ai_command_image;
                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                        {
                                            $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                            $ai_command_image = array_filter($ai_command_image);
                                            if(count($ai_command_image) > 0)
                                            {
                                                $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                            }
                                            else
                                            {
                                                $ai_command_image = '';
                                            }
                                        }
                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                        if(!empty($ai_command_image))
                                        {
                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        }
                                        else
                                        {
                                            $ai_command_image = trim(strip_tags($post_title));
                                        }
                                        $ai_command_image = trim($ai_command_image);
                                        if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                        {
                                            $txt_content = aiomatic_get_web_page($ai_command_image);
                                            if ($txt_content !== FALSE) 
                                            {
                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                $txt_content = array_filter($txt_content);
                                                if(count($txt_content) > 0)
                                                {
                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                    if(trim($txt_content) != '') 
                                                    {
                                                        $ai_command_image = $txt_content;
                                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if($ai_command_image != '')
                                    {
                                        $query_words = $ai_command_image;
                                        $image_query = $ai_command_image;
                                        $image_query_set = true;
                                    }
                                    if(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'textrazor')
                                    {
                                        if(isset($aiomatic_Main_Settings['textrazor_key']) && trim($aiomatic_Main_Settings['textrazor_key']) != '')
                                        {
                                            try
                                            {
                                                if(!class_exists('TextRazor'))
                                                {
                                                    require_once(dirname(__FILE__) . "/res/TextRazor.php");
                                                }
                                                TextRazorSettings::setApiKey(trim($aiomatic_Main_Settings['textrazor_key']));
                                                $textrazor = new TextRazor();
                                                $textrazor->addExtractor('entities');
                                                $response = $textrazor->analyze($image_query);
                                                if (isset($response['response']['entities'])) 
                                                {
                                                    foreach ($response['response']['entities'] as $entity) 
                                                    {
                                                        $query_words = '';
                                                        if(isset($entity['entityEnglishId']))
                                                        {
                                                            $query_words = $entity['entityEnglishId'];
                                                        }
                                                        else
                                                        {
                                                            $query_words = $entity['entityId'];
                                                        }
                                                        if($query_words != '')
                                                        {
                                                            $attached_id = '';
                                                            $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, false, $raw_img_list, array(), $full_result_list);
                                                            if(!empty($attached_id))
                                                            {
                                                                $additional_attachments[] = $attached_id;
                                                            }
                                                            if(!empty($z_img))
                                                            {
                                                                $added_images++;
                                                                $added_img_list[] = $z_img;
                                                                $temp_get_img = $z_img;
                                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                                    aiomatic_log_to_file('Royalty Free Image Generated with help of TextRazor (kw: "' . $query_words . '"): ' . $z_img);
                                                                }
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            catch(Exception $e)
                                            {
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                    aiomatic_log_to_file('Failed to search for keywords using TextRazor (2): ' . $e->getMessage());
                                                }
                                            }
                                        }
                                    }
                                    elseif(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'openai')
                                    {
                                        if(isset($aiomatic_Main_Settings['keyword_prompts']) && trim($aiomatic_Main_Settings['keyword_prompts']) != '')
                                        {
                                            if(isset($aiomatic_Main_Settings['keyword_model']) && $aiomatic_Main_Settings['keyword_model'] != '')
                                            {
                                                $kw_model = $aiomatic_Main_Settings['keyword_model'];
                                            }
                                            else
                                            {
                                                $kw_model = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                            }
                                            if(isset($aiomatic_Main_Settings['keyword_assistant_id']) && $aiomatic_Main_Settings['keyword_assistant_id'] != '')
                                            {
                                                $keyword_assistant_id = $aiomatic_Main_Settings['keyword_assistant_id'];
                                            }
                                            else
                                            {
                                                $keyword_assistant_id = '';
                                            }
                                            $title_ai_command = trim($aiomatic_Main_Settings['keyword_prompts']);
                                            $title_ai_command = str_replace('%%default_post_cats%%', $default_cat_list, $title_ai_command);
                                            $title_ai_command = str_replace('%%original_post_title%%', $post_title, $title_ai_command);
                                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                            {
                                                $title_ai_command = preg_split('/\r\n|\r|\n/', $title_ai_command);
                                                $title_ai_command = array_filter($title_ai_command);
                                                if(count($title_ai_command) > 0)
                                                {
                                                    $title_ai_command = $title_ai_command[array_rand($title_ai_command)];
                                                }
                                                else
                                                {
                                                    $title_ai_command = '';
                                                }
                                            }
                                            $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                            if(!empty($title_ai_command))
                                            {
                                                $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                            $title_ai_command = trim($title_ai_command);
                                            if (filter_var($title_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($title_ai_command, '.txt'))
                                            {
                                                $txt_content = aiomatic_get_web_page($title_ai_command);
                                                if ($txt_content !== FALSE) 
                                                {
                                                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                    $txt_content = array_filter($txt_content);
                                                    if(count($txt_content) > 0)
                                                    {
                                                        $txt_content = $txt_content[array_rand($txt_content)];
                                                        if(trim($txt_content) != '') 
                                                        {
                                                            $title_ai_command = $txt_content;
                                                            $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                                            $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                        }
                                                    }
                                                }
                                            }
                                            if(empty($title_ai_command))
                                            {
                                                aiomatic_log_to_file('Empty API keyword extractor seed expression provided!');
                                                $title_ai_command = 'Type the most relevant keyword, no other text before or after it, for a blog post titled:  ' . trim(strip_tags($post_title));
                                            }
                                            if(aiomatic_strlen($title_ai_command) > $max_seed_tokens * 4)
                                            {
                                                $title_ai_command = aiomatic_substr($title_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                                            }
                                            $title_ai_command = trim($title_ai_command);
                                            if(empty($title_ai_command))
                                            {
                                                aiomatic_log_to_file('Empty API title seed expression provided(4)! ' . print_r($title_ai_command, true));
                                            }
                                            else
                                            {
                                                $query_token_count = count(aiomatic_encode($title_ai_command));
                                                $available_tokens = aiomatic_compute_available_tokens($kw_model, $max_tokens, $title_ai_command, $query_token_count);
                                                if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                                {
                                                    $string_len = aiomatic_strlen($title_ai_command);
                                                    $string_len = $string_len / 2;
                                                    $string_len = intval(0 - $string_len);
                                                    $title_ai_command = aiomatic_substr($title_ai_command, 0, $string_len);
                                                    $title_ai_command = trim($title_ai_command);
                                                    $query_token_count = count(aiomatic_encode($title_ai_command));
                                                    $available_tokens = $max_tokens - $query_token_count;
                                                }
                                                $aierror = '';
                                                $finish_reason = '';
                                                if(!empty($global_prepend))
                                                {
                                                    $title_ai_command = $global_prepend . ' ' . $title_ai_command;
                                                }
                                                if(!empty($global_append))
                                                {
                                                    $title_ai_command = $title_ai_command . ' ' . $global_append;
                                                }
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    $api_service = aiomatic_get_api_service($token, $kw_model);
                                                    aiomatic_log_to_file('Calling ' . $api_service . ' for (' . $keyword_assistant_id . '/' . $kw_model . ')(' . $available_tokens . ') title text: ' . $title_ai_command);
                                                }
                                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating keywords for image search'));
                                                $generated_text = aiomatic_generate_text($token, $kw_model, $title_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'keywordID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $keyword_assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                                if($generated_text === false)
                                                {
                                                    aiomatic_log_to_file('Keyword generator error: ' . $aierror);
                                                    $ai_title = '';
                                                }
                                                else
                                                {
                                                    $ai_title = trim(trim($generated_text), '.');
                                                    $ai_titles = explode(',', $ai_title);
                                                    $heading_cnt = 1;
                                                    foreach($ai_titles as $query_words)
                                                    {
                                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating heading images #' . $heading_cnt));
                                                        $heading_cnt++;
                                                        $attached_id = '';
                                                        $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, trim($query_words), $img_attr, $attached_id, 10, false, $raw_img_list, array(), $full_result_list);
                                                        if(!empty($attached_id))
                                                        {
                                                            $additional_attachments[] = $attached_id;
                                                        }
                                                        if(!empty($z_img))
                                                        {
                                                            $added_images++;
                                                            $added_img_list[] = $z_img;
                                                            $temp_get_img = $z_img;
                                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                                aiomatic_log_to_file('Royalty Free Image Generated with help of AI (kw: "' . $query_words . '"): ' . $z_img);
                                                            }
                                                            break;
                                                        }
                                                    }
                                                }
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    $api_service = aiomatic_get_api_service($token, $kw_model);
                                                    aiomatic_log_to_file('Successfully got API keyword result from ' . $api_service . ': ' . $ai_title);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($temp_get_img))
                                    {
                                        $keyword_class = new Aiomatic_keywords();
                                        $query_words = $keyword_class->keywords($image_query, 2);
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating royalty free image'));
                                        $attached_id = '';
                                        $temp_get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, false, $raw_img_list, array(), $full_result_list);
                                        if(!empty($attached_id))
                                        {
                                            $additional_attachments[] = $attached_id;
                                        }
                                        if($temp_get_img == '' || $temp_get_img === false)
                                        {
                                            $query_words = $keyword_class->keywords($image_query, 1);
                                            $attached_id = '';
                                            $temp_get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 20, false, $raw_img_list, array(), $full_result_list);
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                            if($temp_get_img == '' || $temp_get_img === false)
                                            {
                                                $temp_get_img = '';
                                            }
                                            else
                                            {
                                                if(!in_array($temp_get_img, $added_img_list))
                                                {
                                                    $added_images++;
                                                    $added_img_list[] = $temp_get_img;
                                                }
                                                else
                                                {
                                                    $temp_get_img = '';
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if(!in_array($temp_get_img, $added_img_list))
                                            {
                                                $added_images++;
                                                $added_img_list[] = $temp_get_img;
                                            }
                                            else
                                            {
                                                $temp_get_img = '';
                                            }
                                        }
                                    }
                                }
                                if($temp_get_img != '')
                                {
                                    $add_my_image = '<br/><img class="vimage_class" src="' . $temp_get_img . '" alt="' . esc_attr($query_words) . '"><br/>';
                                }
                            }
                            if($heading_val == '')
                            {
                                $new_post_content = $add_my_image . $new_post_content;
                            }
                            else
                            {
                                $new_post_content = $add_my_image . $heading_val . ' ' . $new_post_content;
                            }
                        }
                        else
                        {
                            $ai_continue_title = $post_title;
                            $extend_id = 1;
                            while(aiomatic_strlen(strip_tags($new_post_content)) < $min_char)
                            {
                                if (isset($aiomatic_Main_Settings['max_retry']) && $aiomatic_Main_Settings['max_retry'] != '' && is_numeric($aiomatic_Main_Settings['max_retry']) && intval($aiomatic_Main_Settings['max_retry']) < $cnt)
                                {
                                    break;
                                }
                                $just_set_fallback = false;
                                $image_query = '';
                                $heading_val = '';
                                if(count($heading_results) > 0)
                                {
                                    $rand_heading = '';
                                    $saverand = array_rand($heading_results);
                                    $rand_heading = $heading_results[$saverand];
                                    unset($heading_results[$saverand]);
                                    if(isset($rand_heading['q']))
                                    {
                                        $rand_heading['q'] = preg_replace('#^\d+\.([\s\S]*)#i', '$1', $rand_heading['q']);
                                        $heading_val = '<h2>' . $rand_heading['q'] . '</h2>' . '<span>' . $rand_heading['a'];
                                        $image_query = $rand_heading['q'];
                                    }
                                }
                                
                                if($heading_val == '')
                                {
                                    $temp_post = trim($new_post_content);
                                }
                                else
                                {
                                    $temp_post = trim($heading_val);
                                }
                                if(aiomatic_strlen($temp_post) > $max_continue_tokens * 4)
                                {
                                    $negative_contiue_tokens = 0 - ($max_continue_tokens * 4);
                                    $newaicontent = aiomatic_substr($temp_post, $negative_contiue_tokens, null);
                                }
                                else
                                {
                                    $newaicontent = $temp_post;
                                }
                                $add_me_to_text = '';
                                if($ai_retry == true)
                                {
                                    $just_set_fallback = true;
                                    if(count($headings_arr_copy) == 0)
                                    {
                                        if (isset($aiomatic_Main_Settings['alternate_continue']) && $aiomatic_Main_Settings['alternate_continue'] == 'on')
                                        {
                                            $newaicontent = $newaicontent . ' ' . $ai_continue_title;
                                        }
                                        else
                                        {
                                            $prai = 'Write a People Also Asked question related to "' . $ai_continue_title . '"';
                                            $aierror = '';
                                            $finish_reason = '';
                                            if(!empty($global_prepend))
                                            {
                                                $prai = $global_prepend . ' ' . $prai;
                                            }
                                            if(!empty($global_append))
                                            {
                                                $prai = $prai . ' ' . $global_append;
                                            }
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                            {
                                                $api_service = aiomatic_get_api_service($token, $model);
                                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for PAA question generator: ' . $prai);
                                            }
                                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating PAA questions'));
                                            $generated_text = aiomatic_generate_text($token, $model, $prai, aimogenpro_get_max_tokens($model), $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'headingID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                            if($generated_text === false)
                                            {
                                                aiomatic_log_to_file('Similarity finding failed: ' . $aierror);
                                                $newaicontent = $aicontent;
                                            }
                                            else
                                            {
                                                if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                                                {
                                                    $newaicontent = ucfirst(trim(nl2br(trim($generated_text))));
                                                }
                                                else
                                                {
                                                    $newaicontent = ucfirst(trim($generated_text));
                                                }
                                                
                                                if(empty($newaicontent))
                                                {
                                                    $newaicontent = $aicontent;
                                                }
                                                else
                                                {
                                                    $newaicontent = preg_replace('#^\d+\.([\s\S]*)#i', '$1', $newaicontent);
                                                    $add_me_to_text = '<h3>' . $newaicontent . '</h3> ';
                                                    $ai_continue_title = $newaicontent;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        $randomIndex = array_rand($headings_arr_copy);
                                        $newaicontent = $headings_arr_copy[$randomIndex];
                                        unset($headings_arr_copy[$randomIndex]);
                                        $newaicontent = preg_replace('#^\d+\.([\s\S]*)#i', '$1', $newaicontent);
                                        $add_me_to_text = '<h3>' . $newaicontent . '</h3> ';
                                    }
                                }
                                $ai_retry = false;
                                $newaicontent = trim($newaicontent);
                                $query_token_count = count(aiomatic_encode($newaicontent));
                                $available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $newaicontent, $query_token_count);
                                if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                {
                                    $string_len = aiomatic_strlen($newaicontent);
                                    $string_len = $string_len / 2;
                                    $string_len = intval(0 - $string_len);
                                    $newaicontent = aiomatic_substr($newaicontent, 0, $string_len);
                                    $newaicontent = trim($newaicontent);
                                    if(empty($newaicontent))
                                    {
                                        aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($temp_post, true));
                                        break;
                                    }
                                    $query_token_count = count(aiomatic_encode($newaicontent));
                                    $available_tokens = $max_tokens - $query_token_count;
                                }
                                $aiwriter = '';
                                $aierror = '';
                                $finish_reason = '';
                                if(!empty($global_prepend))
                                {
                                    $newaicontent = $global_prepend . ' ' . $newaicontent;
                                }
                                if(!empty($global_append))
                                {
                                    $newaicontent = $newaicontent . ' ' . $global_append;
                                }
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    $api_service = aiomatic_get_api_service($token, $model);
                                    $rwair = '';
                                    if($just_set_fallback == true)
                                    {
                                        $rwair = '(fallback)';
                                    }
                                    aiomatic_log_to_file('Calling ' . $api_service . ' again (' . $cnt . ')(' . $available_tokens . ')' . $rwair . ', to meet minimum character limit: ' . $min_char . ' - current char count: ' . aiomatic_strlen(strip_tags($new_post_content)));
                                }
                                if (isset($aiomatic_Main_Settings['continue_prepend']) && $aiomatic_Main_Settings['continue_prepend'] != '')
                                {
                                    $newaicontent = $aiomatic_Main_Settings['continue_prepend'] . '\n\n' . $newaicontent;
                                }
                                if (isset($aiomatic_Main_Settings['continue_append']) && $aiomatic_Main_Settings['continue_append'] != '')
                                {
                                    $newaicontent = $newaicontent . '\n\n' . $aiomatic_Main_Settings['continue_append'];
                                }
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating post content extensions #' . $extend_id));
                                $extend_id++;
                                $generated_text = aiomatic_generate_text($token, $model, $newaicontent, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'contentID' . $param, 0, $finish_reason, $aierror, false, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                if($generated_text === false)
                                {
                                    aiomatic_log_to_file($aierror);
                                    break;
                                }
                                else
                                {
                                    if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                                    {
                                        $aiwriter = $add_me_to_text . ucfirst(trim(nl2br(trim($generated_text))));
                                    }
                                    else
                                    {
                                        $aiwriter = $add_me_to_text . ucfirst(trim($generated_text));
                                    }
                                }
                                $add_my_image = '';
                                $temp_get_img = '';
                                if($aiwriter == '')
                                {
                                    $ai_retry = true;
                                    if($just_set_fallback == true)
                                    {
                                        aiomatic_log_to_file('Ending execution, already retried once');
                                        break;
                                    }
                                    unset($post_title_lines[$current_index]);
                                    continue;
                                }
                                if($images != '' && is_numeric($images) && $images > $added_images)
                                {
                                    $image_query_set = false;
                                    $query_words = '';
                                    $ai_command_image = '';
                                    if($orig_ai_command_image == '')
                                    {
                                        $orig_ai_command_image = $image_query;
                                    }
                                    if($orig_ai_command_image != '')
                                    {
                                        $ai_command_image = $orig_ai_command_image;
                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                        {
                                            $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                            $ai_command_image = array_filter($ai_command_image);
                                            if(count($ai_command_image) > 0)
                                            {
                                                $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                            }
                                            else
                                            {
                                                $ai_command_image = '';
                                            }
                                        }
                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                        if(!empty($ai_command_image))
                                        {
                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        }
                                        else
                                        {
                                            $ai_command_image = trim(strip_tags($post_title));
                                        }
                                        $ai_command_image = trim($ai_command_image);
                                        if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                        {
                                            $txt_content = aiomatic_get_web_page($ai_command_image);
                                            if ($txt_content !== FALSE) 
                                            {
                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                $txt_content = array_filter($txt_content);
                                                if(count($txt_content) > 0)
                                                {
                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                    if(trim($txt_content) != '') 
                                                    {
                                                        $ai_command_image = $txt_content;
                                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if($ai_command_image != '')
                                    {
                                        $query_words = $ai_command_image;
                                        $image_query = $ai_command_image;
                                        $image_query_set = true;
                                    }
                                    else
                                    {
                                        $query_words = $post_title;
                                    }
                                    if($image_query == '')
                                    {
                                        $image_query = $temp_post;
                                    }
                                    if($enable_ai_images_article == '1')
                                    {
                                        if($orig_ai_command_image_article == '')
                                        {
                                            $orig_ai_command_image_article = $image_query;
                                        }
                                        if($orig_ai_command_image_article != '')
                                        {
                                            $ai_command_image = $orig_ai_command_image_article;
                                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                            {
                                                $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                                $ai_command_image = array_filter($ai_command_image);
                                                if(count($ai_command_image) > 0)
                                                {
                                                    $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                                }
                                                else
                                                {
                                                    $ai_command_image = '';
                                                }
                                            }
                                            $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                            if(!empty($ai_command_image))
                                            {
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                            else
                                            {
                                                $ai_command_image = trim(strip_tags($post_title));
                                            }
                                            $ai_command_image = trim($ai_command_image);
                                            if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                            {
                                                $txt_content = aiomatic_get_web_page($ai_command_image);
                                                if ($txt_content !== FALSE) 
                                                {
                                                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                    $txt_content = array_filter($txt_content);
                                                    if(count($txt_content) > 0)
                                                    {
                                                        $txt_content = $txt_content[array_rand($txt_content)];
                                                        if(trim($txt_content) != '') 
                                                        {
                                                            $ai_command_image = $txt_content;
                                                            $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                        }
                                                    }
                                                }
                                            }
                                            if(empty($ai_command_image))
                                            {
                                                aiomatic_log_to_file('Empty API image seed expression provided!');
                                            }
                                            else
                                            {
                                                
                                                
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    $api_service = aiomatic_get_api_service($token, $image_model_article);
                                                    aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $ai_command_image);
                                                }
                                                $aierror = '';
                                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating AI image'));
                                                $temp_get_imgs = aiomatic_generate_ai_image($token, 1, $ai_command_image, $image_size_article, 'contentImage', false, 0, $aierror, $image_model_article, $post_title);
                                                if($temp_get_imgs !== false)
                                                {
                                                    foreach($temp_get_imgs as $tmpimg)
                                                    {
                                                        $added_images++;
                                                        $added_img_list[] = $tmpimg;
                                                        $temp_get_img = $tmpimg;
                                                    }
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                    {
                                                        aiomatic_log_to_file('AI generated image returned: ' . $temp_get_img);
                                                    }
                                                }
                                                else
                                                {
                                                    aiomatic_log_to_file('Failed to generate AI image: ' . $aierror);
                                                    $temp_get_img = '';
                                                }
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Empty AI image query entered.');
                                        }
                                    }
                                    elseif($enable_ai_images_article == '2')
                                    {
                                        if($orig_ai_command_image_article == '')
                                        {
                                            $orig_ai_command_image_article = $image_query;
                                        }
                                        if($orig_ai_command_image_article != '')
                                        {
                                            $ai_command_image = $orig_ai_command_image_article;
                                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                            {
                                                $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                                $ai_command_image = array_filter($ai_command_image);
                                                if(count($ai_command_image) > 0)
                                                {
                                                    $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                                }
                                                else
                                                {
                                                    $ai_command_image = '';
                                                }
                                            }
                                            $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                            if(!empty($ai_command_image))
                                            {
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                            else
                                            {
                                                $ai_command_image = trim(strip_tags($post_title));
                                            }
                                            $ai_command_image = trim($ai_command_image);
                                            if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                            {
                                                $txt_content = aiomatic_get_web_page($ai_command_image);
                                                if ($txt_content !== FALSE) 
                                                {
                                                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                    $txt_content = array_filter($txt_content);
                                                    if(count($txt_content) > 0)
                                                    {
                                                        $txt_content = $txt_content[array_rand($txt_content)];
                                                        if(trim($txt_content) != '') 
                                                        {
                                                            $ai_command_image = $txt_content;
                                                            $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                        }
                                                    }
                                                }
                                            }
                                            if(empty($ai_command_image))
                                            {
                                                aiomatic_log_to_file('Empty API image seed expression provided!');
                                            }
                                            else
                                            {
                                                
                                                
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    $api_service = 'Stability.AI';
                                                    aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $ai_command_image);
                                                }
                                                if($image_size_article == '256x256')
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                elseif($image_size_article == '512x512')
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                elseif($image_size_article == '1024x1024')
                                                {
                                                    $width = '1024';
                                                    $height = '1024';
                                                }
                                                else
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                $ierror = '';
                                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Stable Diffusion image'));
                                                $temp_get_imgs = aiomatic_generate_stability_image($ai_command_image, $height, $width, 'contentStableImage', 0, false, $ierror, false, false, '', 0);
                                                if($temp_get_imgs !== false)
                                                {
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                    {
                                                        aiomatic_log_to_file('AI generated image returned: ' . $temp_get_imgs[1]);
                                                    }
                                                    $added_images++;
                                                    $added_img_list[] = $temp_get_imgs[1];
                                                    $temp_get_img = $temp_get_imgs[1];
                                                }
                                                else
                                                {
                                                    aiomatic_log_to_file('Failed to generate Stability.AI image: ' . $ierror);
                                                    $temp_get_img = '';
                                                }
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Empty AI image query entered.');
                                        }
                                    }
                                    elseif($enable_ai_images_article == '7')
                                    {
                                        if($orig_ai_command_image_article == '')
                                        {
                                            $orig_ai_command_image_article = $image_query;
                                        }
                                        if($orig_ai_command_image_article != '')
                                        {
                                            $ai_command_image = $orig_ai_command_image_article;
                                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                            {
                                                $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                                $ai_command_image = array_filter($ai_command_image);
                                                if(count($ai_command_image) > 0)
                                                {
                                                    $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                                }
                                                else
                                                {
                                                    $ai_command_image = '';
                                                }
                                            }
                                            $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                            if(!empty($ai_command_image))
                                            {
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                            else
                                            {
                                                $ai_command_image = trim(strip_tags($post_title));
                                            }
                                            $ai_command_image = trim($ai_command_image);
                                            if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                            {
                                                $txt_content = aiomatic_get_web_page($ai_command_image);
                                                if ($txt_content !== FALSE) 
                                                {
                                                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                    $txt_content = array_filter($txt_content);
                                                    if(count($txt_content) > 0)
                                                    {
                                                        $txt_content = $txt_content[array_rand($txt_content)];
                                                        if(trim($txt_content) != '') 
                                                        {
                                                            $ai_command_image = $txt_content;
                                                            $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                        }
                                                    }
                                                }
                                            }
                                            if(empty($ai_command_image))
                                            {
                                                aiomatic_log_to_file('Empty API image seed expression provided!');
                                            }
                                            else
                                            {
                                                if (isset($aiomatic_Main_Settings['google_ai_image_model']) && trim($aiomatic_Main_Settings['google_ai_image_model']) != '') 
                                                {
                                                    $model = trim($aiomatic_Main_Settings['google_ai_image_model']);
                                                }
                                                else
                                                {
                                                    $model = AIMOGEN_GOOGLE_IMAGE_DEFAULT_MODEL;
                                                }
                                                
                                                
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    $api_service = 'Google';
                                                    aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $ai_command_image);
                                                }
                                                $ierror = '';
                                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Google image'));
                                                $temp_get_imgs = aiomatic_generate_image_google($ai_command_image, $model, 'contentGoogleImage', false, $ierror, false);
                                                if($temp_get_imgs !== false)
                                                {
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                    {
                                                        aiomatic_log_to_file('AI generated image returned: ' . $temp_get_imgs[1]);
                                                    }
                                                    $added_images++;
                                                    $added_img_list[] = $temp_get_imgs[1];
                                                    $temp_get_img = $temp_get_imgs[1];
                                                }
                                                else
                                                {
                                                    aiomatic_log_to_file('Failed to generate Stability.AI image: ' . $ierror);
                                                    $temp_get_img = '';
                                                }
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Empty AI image query entered.');
                                        }
                                    }
                                    elseif($enable_ai_images_article == '9')
                                    {
                                        $random_image = aiomatic_get_random_media_library_image();

                                        if ($random_image !== false)
                                        {
                                            $temp_get_img = $random_image['url'];

                                            $added_images++;
                                            $added_img_list[] = $temp_get_img;

                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging']))
                                            {
                                                aiomatic_log_to_file(
                                                    'Random Media Library article image selected: ' .
                                                    $temp_get_img .
                                                    ' (ID: ' . $random_image['id'] . ')'
                                                );
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file(
                                                'Failed to find a random image in Media Library for article image.'
                                            );

                                            $temp_get_img = '';
                                        }
                                    }
                                    elseif($enable_ai_images_article == '4')
                                    {
                                        if($orig_ai_command_image_article == '')
                                        {
                                            $orig_ai_command_image_article = $image_query;
                                        }
                                        if($orig_ai_command_image_article != '')
                                        {
                                            $ai_command_image = $orig_ai_command_image_article;
                                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                            {
                                                $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                                $ai_command_image = array_filter($ai_command_image);
                                                if(count($ai_command_image) > 0)
                                                {
                                                    $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                                }
                                                else
                                                {
                                                    $ai_command_image = '';
                                                }
                                            }
                                            $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                            if(!empty($ai_command_image))
                                            {
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                            else
                                            {
                                                $ai_command_image = trim(strip_tags($post_title));
                                            }
                                            $ai_command_image = trim($ai_command_image);
                                            if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                            {
                                                $txt_content = aiomatic_get_web_page($ai_command_image);
                                                if ($txt_content !== FALSE) 
                                                {
                                                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                    $txt_content = array_filter($txt_content);
                                                    if(count($txt_content) > 0)
                                                    {
                                                        $txt_content = $txt_content[array_rand($txt_content)];
                                                        if(trim($txt_content) != '') 
                                                        {
                                                            $ai_command_image = $txt_content;
                                                            $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                        }
                                                    }
                                                }
                                            }
                                            if(empty($ai_command_image))
                                            {
                                                aiomatic_log_to_file('Empty API image seed expression provided!');
                                            }
                                            else
                                            {
                                                
                                                
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    $api_service = 'Midjourney';
                                                    aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $ai_command_image);
                                                }
                                                if($image_size_article == '256x256')
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                elseif($image_size_article == '512x512')
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                elseif($image_size_article == '1024x1024')
                                                {
                                                    $width = '1024';
                                                    $height = '1024';
                                                }
                                                elseif($image_size_article == '1792x1024')
                                                {
                                                    $width = '1792';
                                                    $height = '1024';
                                                }
                                                elseif($image_size_article == '1024x1792')
                                                {
                                                    $width = '1024';
                                                    $height = '1792';
                                                }
                                                else
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                $ierror = '';
                                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Midjourney image'));
                                                $temp_get_imgs = aiomatic_generate_ai_image_midjourney($ai_command_image, $width, $height, 'contentMidjourneyImage', false, $ierror);
                                                if($temp_get_imgs !== false)
                                                {
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                    {
                                                        aiomatic_log_to_file('AI generated image returned: ' . $temp_get_imgs);
                                                    }
                                                    $added_images++;
                                                    $added_img_list[] = $temp_get_imgs;
                                                    $temp_get_img = $temp_get_imgs;
                                                }
                                                else
                                                {
                                                    aiomatic_log_to_file('Failed to generate Midjourney image: ' . $ierror);
                                                    $temp_get_img = '';
                                                }
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Empty AI image query entered.');
                                        }
                                    }
                                    elseif($enable_ai_images_article == '5')
                                    {
                                        if($orig_ai_command_image_article == '')
                                        {
                                            $orig_ai_command_image_article = $image_query;
                                        }
                                        if($orig_ai_command_image_article != '')
                                        {
                                            $ai_command_image = $orig_ai_command_image_article;
                                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                            {
                                                $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                                $ai_command_image = array_filter($ai_command_image);
                                                if(count($ai_command_image) > 0)
                                                {
                                                    $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                                }
                                                else
                                                {
                                                    $ai_command_image = '';
                                                }
                                            }
                                            $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                            if(!empty($ai_command_image))
                                            {
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                            else
                                            {
                                                $ai_command_image = trim(strip_tags($post_title));
                                            }
                                            $ai_command_image = trim($ai_command_image);
                                            if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                            {
                                                $txt_content = aiomatic_get_web_page($ai_command_image);
                                                if ($txt_content !== FALSE) 
                                                {
                                                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                    $txt_content = array_filter($txt_content);
                                                    if(count($txt_content) > 0)
                                                    {
                                                        $txt_content = $txt_content[array_rand($txt_content)];
                                                        if(trim($txt_content) != '') 
                                                        {
                                                            $ai_command_image = $txt_content;
                                                            $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                        }
                                                    }
                                                }
                                            }
                                            if(empty($ai_command_image))
                                            {
                                                aiomatic_log_to_file('Empty API image seed expression provided!');
                                            }
                                            else
                                            {
                                                
                                                
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    $api_service = 'Replicate';
                                                    aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $ai_command_image);
                                                }
                                                if($image_size_article == '256x256')
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                elseif($image_size_article == '512x512')
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                elseif($image_size_article == '1024x1024')
                                                {
                                                    $width = '1024';
                                                    $height = '1024';
                                                }
                                                elseif($image_size_article == '1792x1024')
                                                {
                                                    $width = '1792';
                                                    $height = '1024';
                                                }
                                                elseif($image_size_article == '1024x1792')
                                                {
                                                    $width = '1024';
                                                    $height = '1792';
                                                }
                                                else
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                $ierror = '';
                                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Replicate image'));
                                                $det = aiomatic_generate_replicate_image($ai_command_image, $width, $height, 'contentReplicateImage', false, $ierror);
                                                if($temp_get_imgs !== false)
                                                {
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                    {
                                                        aiomatic_log_to_file('AI generated image returned: ' . $temp_get_imgs);
                                                    }
                                                    $added_images++;
                                                    $added_img_list[] = $temp_get_imgs;
                                                    $temp_get_img = $temp_get_imgs;
                                                }
                                                else
                                                {
                                                    aiomatic_log_to_file('Failed to generate Replicate image: ' . $ierror);
                                                    $temp_get_img = '';
                                                }
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Empty AI image query entered.');
                                        }
                                    }
                                    elseif($enable_ai_images_article == '6')
                                    {
                                        if($orig_ai_command_image_article == '')
                                        {
                                            $orig_ai_command_image_article = $image_query;
                                        }
                                        if($orig_ai_command_image_article != '')
                                        {
                                            $ai_command_image = $orig_ai_command_image_article;
                                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                            {
                                                $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                                $ai_command_image = array_filter($ai_command_image);
                                                if(count($ai_command_image) > 0)
                                                {
                                                    $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                                }
                                                else
                                                {
                                                    $ai_command_image = '';
                                                }
                                            }
                                            $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                            if(!empty($ai_command_image))
                                            {
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                            else
                                            {
                                                $ai_command_image = trim(strip_tags($post_title));
                                            }
                                            $ai_command_image = trim($ai_command_image);
                                            if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                            {
                                                $txt_content = aiomatic_get_web_page($ai_command_image);
                                                if ($txt_content !== FALSE) 
                                                {
                                                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                    $txt_content = array_filter($txt_content);
                                                    if(count($txt_content) > 0)
                                                    {
                                                        $txt_content = $txt_content[array_rand($txt_content)];
                                                        if(trim($txt_content) != '') 
                                                        {
                                                            $ai_command_image = $txt_content;
                                                            $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                        }
                                                    }
                                                }
                                            }
                                            if(empty($ai_command_image))
                                            {
                                                aiomatic_log_to_file('Empty API image seed expression provided!');
                                            }
                                            else
                                            {
                                                
                                                
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    $api_service = 'Ideogram';
                                                    aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $ai_command_image);
                                                }
                                                if($image_size_article == '256x256')
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                elseif($image_size_article == '512x512')
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                elseif($image_size_article == '1024x1024')
                                                {
                                                    $width = '1024';
                                                    $height = '1024';
                                                }
                                                elseif($image_size_article == '1792x1024')
                                                {
                                                    $width = '1792';
                                                    $height = '1024';
                                                }
                                                elseif($image_size_article == '1024x1792')
                                                {
                                                    $width = '1024';
                                                    $height = '1792';
                                                }
                                                else
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                $ierror = '';
                                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Ideogram image'));
                                                $det = aiomatic_generate_ideogram_image($ai_command_image, $width, $height, 'contentIdeogramImage', false, $ierror);
                                                if($temp_get_imgs !== false)
                                                {
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                    {
                                                        aiomatic_log_to_file('AI generated image returned: ' . $temp_get_imgs);
                                                    }
                                                    $added_images++;
                                                    $added_img_list[] = $temp_get_imgs;
                                                    $temp_get_img = $temp_get_imgs;
                                                }
                                                else
                                                {
                                                    aiomatic_log_to_file('Failed to generate Ideogram image: ' . $ierror);
                                                    $temp_get_img = '';
                                                }
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Empty AI image query entered.');
                                        }
                                    }
                                    elseif($enable_ai_images_article == '8')
                                    {
                                        if($orig_ai_command_image_article == '')
                                        {
                                            $orig_ai_command_image_article = $image_query;
                                        }
                                        if($orig_ai_command_image_article != '')
                                        {
                                            $ai_command_image = $orig_ai_command_image_article;
                                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                            {
                                                $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                                $ai_command_image = array_filter($ai_command_image);
                                                if(count($ai_command_image) > 0)
                                                {
                                                    $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                                }
                                                else
                                                {
                                                    $ai_command_image = '';
                                                }
                                            }
                                            $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                            if(!empty($ai_command_image))
                                            {
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                            else
                                            {
                                                $ai_command_image = trim(strip_tags($post_title));
                                            }
                                            $ai_command_image = trim($ai_command_image);
                                            if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                            {
                                                $txt_content = aiomatic_get_web_page($ai_command_image);
                                                if ($txt_content !== FALSE) 
                                                {
                                                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                    $txt_content = array_filter($txt_content);
                                                    if(count($txt_content) > 0)
                                                    {
                                                        $txt_content = $txt_content[array_rand($txt_content)];
                                                        if(trim($txt_content) != '') 
                                                        {
                                                            $ai_command_image = $txt_content;
                                                            $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                        }
                                                    }
                                                }
                                            }
                                            if(empty($ai_command_image))
                                            {
                                                aiomatic_log_to_file('Empty API image seed expression provided!');
                                            }
                                            else
                                            {
                                                
                                                
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                {
                                                    $api_service = 'Cloudflare';
                                                    aiomatic_log_to_file('Calling ' . $api_service . ' for image: ' . $ai_command_image);
                                                }
                                                if($image_size_article == '256x256')
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                elseif($image_size_article == '512x512')
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                elseif($image_size_article == '1024x1024')
                                                {
                                                    $width = '1024';
                                                    $height = '1024';
                                                }
                                                elseif($image_size_article == '1792x1024')
                                                {
                                                    $width = '1792';
                                                    $height = '1024';
                                                }
                                                elseif($image_size_article == '1024x1792')
                                                {
                                                    $width = '1024';
                                                    $height = '1792';
                                                }
                                                else
                                                {
                                                    $width = '512';
                                                    $height = '512';
                                                }
                                                $ierror = '';
                                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Cloudflare image'));
                                                $det = aiomatic_generate_cloudflare_image($ai_command_image, $width, $height, 'contentCloudflareImage', false, $ierror);
                                                if($temp_get_imgs !== false)
                                                {
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                    {
                                                        aiomatic_log_to_file('AI generated image returned: ' . $temp_get_imgs);
                                                    }
                                                    $added_images++;
                                                    $added_img_list[] = $temp_get_imgs;
                                                    $temp_get_img = $temp_get_imgs;
                                                }
                                                else
                                                {
                                                    aiomatic_log_to_file('Failed to generate Cloudflare image: ' . $ierror);
                                                    $temp_get_img = '';
                                                }
                                            }
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Empty AI image query entered.');
                                        }
                                    }
                                    elseif($enable_ai_images_article == '3')
                                    {
                                        if ($image_url != '') 
                                        {
                                            $replacement = str_replace(array('[', ']'), '', $query_words);
                                            $image_url_temp = str_replace('%%item_title%%', $replacement, $image_url);
                                            $image_url_temp = preg_replace_callback('#%%random_image\[([^\]]*?)\](\[\d+\])?%%#', function ($matches) {
                                                if(isset($matches[2]))
                                                {
                                                    $chance = trim($matches[2], '[]');
                                                }
                                                else
                                                {
                                                    $chance = '';
                                                }
                                                $arv = array();
                                                $my_img = aiomatic_get_random_image_google($matches[1], 0, 0, $chance, $arv);
                                                return $my_img;
                                            }, $image_url_temp);
                                            $img_rulx = $spintax->Parse(trim($image_url_temp));
                                            $selected_img = aiomatic_select_ai_image($post_title, $img_rulx);
                                            if($selected_img === false)
                                            {
                                                $img_rulx = explode(',', $img_rulx);
                                                $img_rulx = trim($img_rulx[array_rand($img_rulx)]);
                                                if($img_rulx != '')
                                                {
                                                    $added_images++;
                                                    $added_img_list[] = $img_rulx;
                                                    $temp_get_img = $img_rulx;
                                                }
                                            }
                                            else
                                            {
                                                $added_images++;
                                                $added_img_list[] = $selected_img;
                                                $temp_get_img = $selected_img;
                                            }
                                        }
                                    }
                                    elseif(count($images_arr) > 0)
                                    {
                                        $first_el = array_shift($images_arr);
                                        $first_el = aiomatic_replaceSynergyShortcodes($first_el);
                                        $added_images++;
                                        $added_img_list[] = $first_el;
                                        $temp_get_img = $first_el;
                                    }
                                    else
                                    {
                                        $query_words = '';
                                        if(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'textrazor')
                                        {
                                            if(isset($aiomatic_Main_Settings['textrazor_key']) && trim($aiomatic_Main_Settings['textrazor_key']) != '')
                                            {
                                                try
                                                {
                                                    if(!class_exists('TextRazor'))
                                                    {
                                                        require_once(dirname(__FILE__) . "/res/TextRazor.php");
                                                    }
                                                    TextRazorSettings::setApiKey(trim($aiomatic_Main_Settings['textrazor_key']));
                                                    $textrazor = new TextRazor();
                                                    $textrazor->addExtractor('entities');
                                                    $response = $textrazor->analyze($image_query);
                                                    if (isset($response['response']['entities'])) 
                                                    {
                                                        foreach ($response['response']['entities'] as $entity) 
                                                        {
                                                            $query_words = '';
                                                            if(isset($entity['entityEnglishId']))
                                                            {
                                                                $query_words = $entity['entityEnglishId'];
                                                            }
                                                            else
                                                            {
                                                                $query_words = $entity['entityId'];
                                                            }
                                                            if($query_words != '')
                                                            {
                                                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating royalty free image'));
                                                                $attached_id = '';
                                                                $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, false, $raw_img_list, array(), $full_result_list);
                                                                if(!empty($attached_id))
                                                                {
                                                                    $additional_attachments[] = $attached_id;
                                                                }
                                                                if(!empty($z_img))
                                                                {
                                                                    $added_images++;
                                                                    $added_img_list[] = $z_img;
                                                                    $temp_get_img = $z_img;
                                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                                        aiomatic_log_to_file('Royalty Free Image Generated with help of TextRazor (kw: "' . $query_words . '"): ' . $z_img);
                                                                    }
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                catch(Exception $e)
                                                {
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                        aiomatic_log_to_file('Failed to search for keywords using TextRazor (2): ' . $e->getMessage());
                                                    }
                                                }
                                            }
                                        }
                                        elseif(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'openai')
                                        {
                                            if(isset($aiomatic_Main_Settings['keyword_prompts']) && trim($aiomatic_Main_Settings['keyword_prompts']) != '')
                                            {
                                                if(isset($aiomatic_Main_Settings['keyword_model']) && $aiomatic_Main_Settings['keyword_model'] != '')
                                                {
                                                    $kw_model = $aiomatic_Main_Settings['keyword_model'];
                                                }
                                                else
                                                {
                                                    $kw_model = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                                }
                                                if(isset($aiomatic_Main_Settings['keyword_assistant_id']) && $aiomatic_Main_Settings['keyword_assistant_id'] != '')
                                                {
                                                    $keyword_assistant_id = $aiomatic_Main_Settings['keyword_assistant_id'];
                                                }
                                                else
                                                {
                                                    $keyword_assistant_id = '';
                                                }
                                                $title_ai_command = trim($aiomatic_Main_Settings['keyword_prompts']);
                                                $title_ai_command = str_replace('%%default_post_cats%%', $default_cat_list, $title_ai_command);
                                                $title_ai_command = str_replace('%%original_post_title%%', $post_title, $title_ai_command);
                                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                                {
                                                    $title_ai_command = preg_split('/\r\n|\r|\n/', $title_ai_command);
                                                    $title_ai_command = array_filter($title_ai_command);
                                                    if(count($title_ai_command) > 0)
                                                    {
                                                        $title_ai_command = $title_ai_command[array_rand($title_ai_command)];
                                                    }
                                                    else
                                                    {
                                                        $title_ai_command = '';
                                                    }
                                                }
                                                $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                                if(!empty($title_ai_command))
                                                {
                                                    $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                                $title_ai_command = trim($title_ai_command);
                                                if (filter_var($title_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($title_ai_command, '.txt'))
                                                {
                                                    $txt_content = aiomatic_get_web_page($title_ai_command);
                                                    if ($txt_content !== FALSE) 
                                                    {
                                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                        $txt_content = array_filter($txt_content);
                                                        if(count($txt_content) > 0)
                                                        {
                                                            $txt_content = $txt_content[array_rand($txt_content)];
                                                            if(trim($txt_content) != '') 
                                                            {
                                                                $title_ai_command = $txt_content;
                                                                $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                                                $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                            }
                                                        }
                                                    }
                                                }
                                                if(empty($title_ai_command))
                                                {
                                                    aiomatic_log_to_file('Empty API keyword extractor seed expression provided!');
                                                    $title_ai_command = 'Type the most relevant keyword, no other text before or after it, for a blog post titled:  ' . trim(strip_tags($post_title));
                                                }
                                                if(aiomatic_strlen($title_ai_command) > $max_seed_tokens * 4)
                                                {
                                                    $title_ai_command = aiomatic_substr($title_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                                                }
                                                $title_ai_command = trim($title_ai_command);
                                                if(empty($title_ai_command))
                                                {
                                                    aiomatic_log_to_file('Empty API title seed expression provided(5)! ' . print_r($title_ai_command, true));
                                                }
                                                else
                                                {
                                                    $query_token_count = count(aiomatic_encode($title_ai_command));
                                                    $available_tokens = aiomatic_compute_available_tokens($kw_model, $max_tokens, $title_ai_command, $query_token_count);
                                                    if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                                    {
                                                        $string_len = aiomatic_strlen($title_ai_command);
                                                        $string_len = $string_len / 2;
                                                        $string_len = intval(0 - $string_len);
                                                        $title_ai_command = aiomatic_substr($title_ai_command, 0, $string_len);
                                                        $title_ai_command = trim($title_ai_command);
                                                        $query_token_count = count(aiomatic_encode($title_ai_command));
                                                        $available_tokens = $max_tokens - $query_token_count;
                                                    }
                                                    $aierror = '';
                                                    $finish_reason = '';
                                                    if(!empty($global_prepend))
                                                    {
                                                        $title_ai_command = $global_prepend . ' ' . $title_ai_command;
                                                    }
                                                    if(!empty($global_append))
                                                    {
                                                        $title_ai_command = $title_ai_command . ' ' . $global_append;
                                                    }
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                    {
                                                        $api_service = aiomatic_get_api_service($token, $kw_model);
                                                        aiomatic_log_to_file('Calling ' . $api_service . ' (' . $keyword_assistant_id . '/' . $kw_model . ')(' . $available_tokens . ') for title text: ' . $title_ai_command);
                                                    }
                                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating AI image search keywords'));
                                                    $generated_text = aiomatic_generate_text($token, $kw_model, $title_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'keywordID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $keyword_assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                                    if($generated_text === false)
                                                    {
                                                        aiomatic_log_to_file('Keyword generator error: ' . $aierror);
                                                        $ai_title = '';
                                                    }
                                                    else
                                                    {
                                                        $ai_title = trim(trim($generated_text), '.');
                                                        $ai_titles = explode(',', $ai_title);
                                                        foreach($ai_titles as $query_words)
                                                        {
                                                            $attached_id = '';
                                                            $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, trim($query_words), $img_attr, $attached_id, 10, false, $raw_img_list, array(), $full_result_list);
                                                            if(!empty($attached_id))
                                                            {
                                                                $additional_attachments[] = $attached_id;
                                                            }
                                                            if(!empty($z_img))
                                                            {
                                                                $added_images++;
                                                                $added_img_list[] = $z_img;
                                                                $temp_get_img = $z_img;
                                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                                    aiomatic_log_to_file('Royalty Free Image Generated with help of AI (kw: "' . $query_words . '"): ' . $z_img);
                                                                }
                                                                break;
                                                            }
                                                        }
                                                    }
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                                    {
                                                        $api_service = aiomatic_get_api_service($token, $kw_model);
                                                        aiomatic_log_to_file('Successfully got API keyword result from ' . $api_service . ': ' . $ai_title);
                                                    }
                                                }
                                            }
                                        }
                                        if(empty($temp_get_img))
                                        {
                                            $keyword_class = new Aiomatic_keywords();
                                            $query_words = $keyword_class->keywords($image_query, 2);
                                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating royalty free images'));
                                            $temp_get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, false, $raw_img_list, array(), $full_result_list);
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                            if($temp_get_img == '' || $temp_get_img === false)
                                            {
                                                $query_words = $keyword_class->keywords($image_query, 1);
                                                $temp_get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 20, false, $raw_img_list, array(), $full_result_list);
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                                if($temp_get_img == '' || $temp_get_img === false)
                                                {
                                                    $temp_get_img = '';
                                                }
                                                else
                                                {
                                                    if(!in_array($temp_get_img, $added_img_list))
                                                    {
                                                        $added_images++;
                                                        $added_img_list[] = $temp_get_img;
                                                    }
                                                    else
                                                    {
                                                        $temp_get_img = '';
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if(!in_array($temp_get_img, $added_img_list))
                                                {
                                                    $added_images++;
                                                    $added_img_list[] = $temp_get_img;
                                                }
                                                else
                                                {
                                                    $temp_get_img = '';
                                                }
                                            }
                                        }
                                    }
                                    if($temp_get_img != '')
                                    {
                                        $add_my_image = '<br/><img class="ximage_class" src="' . $temp_get_img . '" alt="' . esc_attr($query_words) . '"><br/>';
                                    }
                                }
                                if($heading_val == '')
                                {
                                    if($add_my_image == '')
                                    {
                                        $add_my_image = ' ';
                                    }
                                    if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                                    {
                                        $new_post_content .= $add_my_image . trim(nl2br($aiwriter));
                                    }
                                    else
                                    {
                                        $new_post_content .= $add_my_image . trim($aiwriter);
                                    }
                                }
                                else
                                {
                                    if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                                    {
                                        $new_post_content .= $add_my_image . $heading_val . ' ' . trim(nl2br($aiwriter)) . '</span>';
                                    }
                                    else
                                    {
                                        $new_post_content .= $add_my_image . $heading_val . ' ' . trim($aiwriter) . '</span>';
                                    }
                                }
                                if($enable_ai_images == '0')
                                {
                                    sleep(1);
                                }
                                $cnt++;
                            }
                        }
                        if($strip_title == '1')
                        {
                            $new_post_content = str_replace($post_title, '', $new_post_content);
                            $new_post_content = str_replace('<h2></h2>', '', $new_post_content);
                            $new_post_content = str_replace('<h3></h3>', '', $new_post_content);
                        }
                        if (isset($aiomatic_Main_Settings['swear_filter']) && $aiomatic_Main_Settings['swear_filter'] == 'on') 
                        {
                            require_once(dirname(__FILE__) . "/res/swear.php");
                            $new_post_content = aimogenpro_filterwords($new_post_content);
                        }
                        if(isset($aiomatic_Main_Settings['global_ban_words']) && $aiomatic_Main_Settings['global_ban_words'] != '') {
                            $continue    = false;
                            $aiomatic_Main_Settings['global_ban_words'] = trim(trim(trim($aiomatic_Main_Settings['global_ban_words']), ','));
                            $banned_list = explode(',', $aiomatic_Main_Settings['global_ban_words']);
                            foreach ($banned_list as $banned_word) {
                                if (stripos($new_post_content, trim($banned_word)) !== FALSE) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because it\'s content contains global banned word: ' . $banned_word);
                                    }
                                    $continue = true;
                                    break;
                                }
                                if (stripos($new_post_title, trim($banned_word)) !== FALSE) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because it\'s title contains global banned word: ' . $banned_word);
                                    }
                                    $continue = true;
                                    break;
                                }
                            }
                            if ($continue === true) {
                                unset($post_title_lines[$current_index]);
                                continue;
                            }
                        }
                        if(isset($aiomatic_Main_Settings['global_req_words']) && $aiomatic_Main_Settings['global_req_words'] != '')
                        {
                            if(isset($aiomatic_Main_Settings['require_only_one']) && $aiomatic_Main_Settings['require_only_one'] == 'on')
                            {
                                $continue      = true;
                                $aiomatic_Main_Settings['global_req_words'] = trim(trim(trim($aiomatic_Main_Settings['global_req_words']), ','));
                                $required_list = explode(',', $aiomatic_Main_Settings['global_req_words']);
                                foreach ($required_list as $required_word) {
                                    if (stripos($new_post_content, trim($required_word)) !== FALSE || stripos($new_post_title, trim($required_word)) !== FALSE) {
                                        $continue = false;
                                        break;
                                    }
                                }
                                if ($continue === true) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because it\'s content doesn\'t contain global required words.');
                                    }
                                    unset($post_title_lines[$current_index]);
                                    continue;
                                }
                            }
                            else
                            {
                                $continue      = false;
                                $aiomatic_Main_Settings['global_req_words'] = trim(trim(trim($aiomatic_Main_Settings['global_req_words']), ','));
                                $required_list = explode(',', $aiomatic_Main_Settings['global_req_words']);
                                foreach ($required_list as $required_word) {
                                    if (stripos($new_post_content, trim($required_word)) === FALSE && stripos($new_post_title, trim($required_word)) === FALSE) {
                                        $continue = true;
                                        break;
                                    }
                                }
                                if ($continue === true) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because it\'s content doesn\'t contain global required words.');
                                    }
                                    unset($post_title_lines[$current_index]);
                                    continue;
                                }
                            }
                        }
                        if (isset($aiomatic_Main_Settings['spin_what']) && $aiomatic_Main_Settings['spin_what'] === 'omni') 
                        {
                            $skip_spin = '1';
                        }
                        $arr = aiomatic_spin_and_translate($new_post_title, $new_post_content, '3', $skip_spin, $skip_translate);
                        if($arr[0] != $new_post_title)
                        {
                            $new_post_title = $arr[0];
                            if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                            {
                                $posts = get_posts(
                                    array(
                                        'post_type'              => $post_type,
                                        'title'                  => html_entity_decode($new_post_title),
                                        'post_status'            => 'any',
                                        'numberposts'            => 1,
                                        'update_post_term_cache' => false,
                                        'update_post_meta_cache' => false,           
                                        'orderby'                => 'post_date ID',
                                        'order'                  => 'ASC',
                                    )
                                );
                                if ( ! empty( $posts ) ) {
                                    $zap = $posts[0];
                                } else {
                                    $zap = null;
                                }
                                if($zap !== null)
                                {
                                    if($overwrite_existing)
                                    {
                                        $update_post_id = $zap->ID;
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Post with specified title already existing (after spin/translate), skipping it: ' . $new_post_title);
                                        unset($post_title_lines[$current_index]);
                                        continue;
                                    }
                                }
                            }
                        }
                        $new_post_content            = $arr[1];
                        if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                        {
                            $already_spinned = '1';
                        }
                        if ($auto_categories == 'content') {
                            $extra_categories            = aiomatic_extractKeyWords($new_post_content);
                            $extra_categories            = implode(',', $extra_categories);
                        }
                        elseif ($auto_categories == 'title') {
                            $extra_categories            = aiomatic_extractKeyWords($new_post_title);
                            $extra_categories            = implode(',', $extra_categories);
                        }
                        elseif ($auto_categories == 'both') {
                            $extra_categories            = aiomatic_extractKeyWords($new_post_content);
                            $extra_categories            = implode(',', $extra_categories);
                            $extra_categories2            = aiomatic_extractKeyWords($new_post_title);
                            $extra_categories2            = implode(',', $extra_categories2);
                            if($extra_categories2 != '')
                            {
                                $extra_categories .= ',' . $extra_categories2;
                            }
                        }
                        elseif ($auto_categories == 'ai') 
                        {
                            $category_ai_command = $orig_ai_command_category;
                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                            {
                                $category_ai_command = preg_split('/\r\n|\r|\n/', $category_ai_command);
                                $category_ai_command = array_filter($category_ai_command);
                                if(count($category_ai_command) > 0)
                                {
                                    $category_ai_command = $category_ai_command[array_rand($category_ai_command)];
                                }
                                else
                                {
                                    $category_ai_command = '';
                                }
                            }
                            $category_ai_command = aiomatic_replaceSynergyShortcodes($category_ai_command);
                            if(!empty($category_ai_command))
                            {
                                $category_ai_command = aiomatic_replaceAIPostShortcodes($category_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                $category_ai_command = aiomatic_replacetopics($category_ai_command, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                            }
                            else
                            {
                                $category_ai_command = trim(strip_tags('Write a comma separated list of categories, for the post title: %%post_title%%'));
                            }
                            $category_ai_command = trim($category_ai_command);
                            if (filter_var($category_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($category_ai_command, '.txt'))
                            {
                                $txt_content = aiomatic_get_web_page($category_ai_command);
                                if ($txt_content !== FALSE) 
                                {
                                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                    $txt_content = array_filter($txt_content);
                                    if(count($txt_content) > 0)
                                    {
                                        $txt_content = $txt_content[array_rand($txt_content)];
                                        if(trim($txt_content) != '') 
                                        {
                                            $category_ai_command = $txt_content;
                                            $category_ai_command = aiomatic_replaceSynergyShortcodes($category_ai_command);
                                            $category_ai_command = aiomatic_replaceAIPostShortcodes($category_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            $category_ai_command = aiomatic_replacetopics($category_ai_command, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                        }
                                    }
                                }
                            }
                            if(empty($category_ai_command))
                            {
                                aiomatic_log_to_file('Empty API post category seed expression provided!');
                            }
                            else
                            {
                                if(aiomatic_strlen($category_ai_command) > $max_seed_tokens * 4)
                                {
                                    $category_ai_command = aiomatic_substr($category_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                                }
                                $category_ai_command = trim($category_ai_command);
                                if(empty($category_ai_command))
                                {
                                    aiomatic_log_to_file('Empty API category seed expression provided! ' . print_r($category_ai_command, true));
                                    break;
                                }
                                $query_token_count = count(aiomatic_encode($category_ai_command));
                                $available_tokens = aiomatic_compute_available_tokens($category_model, $max_tokens, $category_ai_command, $query_token_count);
                                if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                {
                                    $string_len = aiomatic_strlen($category_ai_command);
                                    $string_len = $string_len / 2;
                                    $string_len = intval(0 - $string_len);
                                    $category_ai_command = aiomatic_substr($category_ai_command, 0, $string_len);
                                    $category_ai_command = trim($category_ai_command);
                                    if(empty($category_ai_command))
                                    {
                                        aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($category_ai_command, true));
                                        break;
                                    }
                                    $query_token_count = count(aiomatic_encode($category_ai_command));
                                    $available_tokens = $max_tokens - $query_token_count;
                                }
                                $aierror = '';
                                $finish_reason = '';
                                if(!empty($global_prepend))
                                {
                                    $category_ai_command = $global_prepend . ' ' . $category_ai_command;
                                }
                                if(!empty($global_append))
                                {
                                    $category_ai_command = $category_ai_command . ' ' . $global_append;
                                }
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = aiomatic_get_api_service($token, $category_model);
                                    aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $category_model . ')(' . $available_tokens . ') for category generator: ' . $category_ai_command);
                                }
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating categories'));
                                $generated_text = aiomatic_generate_text($token, $category_model, $category_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'categoryID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', false, $store_data, array(), '', '', '');
                                if($generated_text === false)
                                {
                                    aiomatic_log_to_file('Category generator error: ' . $aierror);
                                    break;
                                }
                                else
                                {
                                    $extra_categories = $generated_text;
                                }
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = aiomatic_get_api_service($token, $category_model);
                                    aiomatic_log_to_file('Successfully got API category result from ' . $api_service . ': ' . $generated_text);
                                }
                            }
                        }
                        else
                        {
                            $extra_categories = '';
                        }
                        $my_post['extra_categories'] = $extra_categories;
                        
                        $item_tags                   = aiomatic_extractKeyWords($new_post_content, 3);
                        $item_tags                   = implode(',', $item_tags);
                        $title_tags                   = aiomatic_extractKeyWords($new_post_title, 3);
                        $title_tags                   = implode(',', $title_tags);
                        $item_create_tag_sp = $spintax->Parse($item_create_tag);
                        if ($can_create_tag == 'content') {
                            $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $item_tags;
                            $my_post['extra_tags']       = $item_tags;
                        } else if ($can_create_tag == 'title') {
                            $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $title_tags;
                            $my_post['extra_tags']       = $title_tags;
                        } else if ($can_create_tag == 'both') {
                            $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . ($item_tags != '' ? $item_tags . ',' : '') . $title_tags;
                            $my_post['extra_tags']       = ($item_tags != '' ? $item_tags . ',' : '') . $title_tags;
                        } else if ($can_create_tag == 'ai') {
                            $ai_tags = '';
                            $tag_ai_command = $orig_ai_command_tag;
                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                            {
                                $tag_ai_command = preg_split('/\r\n|\r|\n/', $tag_ai_command);
                                $tag_ai_command = array_filter($tag_ai_command);
                                if(count($tag_ai_command) > 0)
                                {
                                    $tag_ai_command = $tag_ai_command[array_rand($tag_ai_command)];
                                }
                                else
                                {
                                    $tag_ai_command = '';
                                }
                            }
                            $tag_ai_command = aiomatic_replaceSynergyShortcodes($tag_ai_command);
                            if(!empty($tag_ai_command))
                            {
                                $tag_ai_command = aiomatic_replaceAIPostShortcodes($tag_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                $tag_ai_command = aiomatic_replacetopics($tag_ai_command, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                            }
                            else
                            {
                                $tag_ai_command = trim(strip_tags('Write a comma separated list of tags, for the post title: %%post_title%%'));
                            }
                            $tag_ai_command = trim($tag_ai_command);
                            if (filter_var($tag_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($tag_ai_command, '.txt'))
                            {
                                $txt_content = aiomatic_get_web_page($tag_ai_command);
                                if ($txt_content !== FALSE) 
                                {
                                    $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                    $txt_content = array_filter($txt_content);
                                    if(count($txt_content) > 0)
                                    {
                                        $txt_content = $txt_content[array_rand($txt_content)];
                                        if(trim($txt_content) != '') 
                                        {
                                            $tag_ai_command = $txt_content;
                                            $tag_ai_command = aiomatic_replaceSynergyShortcodes($tag_ai_command);
                                            $tag_ai_command = aiomatic_replaceAIPostShortcodes($tag_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            $tag_ai_command = aiomatic_replacetopics($tag_ai_command, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                        }
                                    }
                                }
                            }
                            if(empty($tag_ai_command))
                            {
                                aiomatic_log_to_file('Empty API post tag seed expression provided!');
                            }
                            else
                            {
                                if(aiomatic_strlen($tag_ai_command) > $max_seed_tokens * 4)
                                {
                                    $tag_ai_command = aiomatic_substr($tag_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                                }
                                $tag_ai_command = trim($tag_ai_command);
                                if(empty($tag_ai_command))
                                {
                                    aiomatic_log_to_file('Empty API tag seed expression provided! ' . print_r($tag_ai_command, true));
                                    break;
                                }
                                $query_token_count = count(aiomatic_encode($tag_ai_command));
                                $available_tokens = aiomatic_compute_available_tokens($tag_model, $max_tokens, $tag_ai_command, $query_token_count);
                                if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                {
                                    $string_len = aiomatic_strlen($tag_ai_command);
                                    $string_len = $string_len / 2;
                                    $string_len = intval(0 - $string_len);
                                    $tag_ai_command = aiomatic_substr($tag_ai_command, 0, $string_len);
                                    $tag_ai_command = trim($tag_ai_command);
                                    if(empty($tag_ai_command))
                                    {
                                        aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($tag_ai_command, true));
                                        break;
                                    }
                                    $query_token_count = count(aiomatic_encode($tag_ai_command));
                                    $available_tokens = $max_tokens - $query_token_count;
                                }
                                $aierror = '';
                                $finish_reason = '';
                                if(!empty($global_prepend))
                                {
                                    $tag_ai_command = $global_prepend . ' ' . $tag_ai_command;
                                }
                                if(!empty($global_append))
                                {
                                    $tag_ai_command = $tag_ai_command . ' ' . $global_append;
                                }
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = aiomatic_get_api_service($token, $tag_model);
                                    aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $tag_model . ')(' . $available_tokens . ') for tag generator: ' . $tag_ai_command);
                                }
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating tags'));
                                $generated_text = aiomatic_generate_text($token, $tag_model, $tag_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'tagID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', false, $store_data, array(), '', '', '');
                                if($generated_text === false)
                                {
                                    aiomatic_log_to_file('Tag generator error: ' . $aierror);
                                    break;
                                }
                                else
                                {
                                    $ai_tags = $generated_text;
                                }
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = aiomatic_get_api_service($token, $tag_model);
                                    aiomatic_log_to_file('Successfully got API tag result from ' . $api_service . ': ' . $generated_text);
                                }
                            }
                            $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $ai_tags;
                            $my_post['extra_tags']       = $ai_tags;
                        } else {
                            $post_the_tags = $item_create_tag_sp;
                            $my_post['extra_tags']       = '';
                        }
                        $my_post['tags_input'] = $post_the_tags;
                        $new_post_content = aimogen_bulk_polish_article_content($new_post_content, array('title' => isset($new_post_title) ? $new_post_title : '', 'topic' => isset($post_topic) ? $post_topic : '', 'language' => isset($content_language) ? $content_language : '', 'model' => (isset($topic_content_model) && $topic_content_model !== '') ? $topic_content_model : (isset($model) ? $model : ''), 'token' => isset($token) ? $token : '', 'temperature' => isset($temperature) ? $temperature : '', 'top_p' => isset($top_p) ? $top_p : '', 'presence_penalty' => isset($presence_penalty) ? $presence_penalty : '', 'frequency_penalty' => isset($frequency_penalty) ? $frequency_penalty : '', 'rule_id' => isset($rule_unique_id) ? $rule_unique_id : '', 'global_prepend' => isset($global_prepend) ? $global_prepend : '', 'global_append' => isset($global_append) ? $global_append : '', 'assistant_id' => isset($assistant_id) ? $assistant_id : '', 'thread_id' => isset($thread_id) ? $thread_id : '', 'store_data' => isset($store_data) ? $store_data : 'off'));
                    $new_post_content        = html_entity_decode($new_post_content);
                        $new_post_content = str_replace('</ iframe>', '</iframe>', $new_post_content);
                        if ($videos == '1')
                        {
                            if(isset($aiomatic_Main_Settings['social_list']) && !empty($aiomatic_Main_Settings['social_list']) && is_array($aiomatic_Main_Settings['social_list']))
                            {
                                $social_list = $aiomatic_Main_Settings['social_list'];
                            }
                            else
                            {
                                $social_list = array();
                            }
                            $new_vid = aiomatic_get_video($new_post_title, '', $social_list);
                            if($new_vid !== false)
                            {
                                $new_post_content .= $new_vid;
                            }
                        }
                        if ($strip_by_regex !== '')
                        {
                            $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex);
                            $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex);
                            $xcnt = 0;
                            foreach($xstrip_by_regex as $sbr)
                            {
                                if(isset($xreplace_regex[$xcnt]))
                                {
                                    $repreg = $xreplace_regex[$xcnt];
                                }
                                else
                                {
                                    $repreg = '';
                                }
                                $xcnt++;
                                $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $new_post_content);
                                if($temp_cont !== NULL)
                                {
                                    $new_post_content = $temp_cont;
                                }
                            }
                        }
                        $post_prepender = aiomatic_replaceAIPostShortcodes($post_prepend, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                        $post_prepender = aiomatic_replacetopics($post_prepender, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                        $post_appender = aiomatic_replaceAIPostShortcodes($post_append, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                        $post_appender = aiomatic_replacetopics($post_appender, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                        $post_appender = aiomatic_replaceSynergyShortcodes($post_appender);
                        $post_prepender = aiomatic_replaceSynergyShortcodes($post_prepender);
                        if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                        {
                            if($new_post_content === strip_tags($new_post_content)) 
                            {
                                if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                                {
                                    $new_post_content = nl2br($new_post_content);
                                }
                            }
                        }
                        if (!isset($aiomatic_Main_Settings['no_undetectibility']) || $aiomatic_Main_Settings['no_undetectibility'] != 'on') 
                        {
                            if (!isset($aiomatic_Main_Settings['no_undetectibility_bulk']) || $aiomatic_Main_Settings['no_undetectibility_bulk'] != 'on') 
                            {
                                if(!isset($xchars))
                                {
                                    $xchars = array();
                                }
                                $rand_percentage = wp_rand(10, 20);
                                $new_post_content = aiomatic_make_unique($new_post_content, $xchars, $rand_percentage);
                            }
                        }
                        $zlang = 'en_US';
                        if (isset($aiomatic_Main_Settings['kw_lang']) && !empty($aiomatic_Main_Settings['kw_lang'])) {
                            $zlang = $aiomatic_Main_Settings['kw_lang'];
                        }
                        $rel_search = array('post_title', 'post_content');
                        if (isset($aiomatic_Main_Settings['rel_search']) && is_array($aiomatic_Main_Settings['rel_search'])) {
                            $rel_search = $aiomatic_Main_Settings['rel_search'];
                        }
                        if($max_links !== '' && $inboundlinker !== null && $link_type != 'disabled')
                        {
                            try
                            {
                                $new_post_content = $inboundlinker->add_inbound_links($new_post_content, $max_links, $link_post_types, $zlang, $rel_search, null, $link_type, $link_list, $link_nofollow, '', '', array());
                            }
                            catch(Exception $ex)
                            {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Failed to add inbound links to content: ' . $ex->getMessage());
                                }
                            }
                        }
                        if($ret_content == 1)
                        {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('Returning AI generated content, finished.');
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Finished processing'));
                            return array($post_prepender . ' ' . $new_post_content . ' ' . $post_appender, $new_post_title);
                        }
                        $the_final_cont = $post_prepender . ' ' . $new_post_content . ' ' . $post_appender;
                        $trunchi_content = aiomatic_truncate_content($the_final_cont, 16777215);
                        if (isset($aiomatic_Main_Settings['convert_gutenberg']) && trim($aiomatic_Main_Settings['convert_gutenberg']) == 'on')
                        {
                            $my_post['post_content'] = aiomatic_convert_html_to_gutenberg_blocks($trunchi_content);
                        }
                        else
                        {
                            $my_post['post_content'] = $trunchi_content;
                        }
                        if(stristr($my_post['post_content'], '<pre><code>&lt;') !== false)
                        {
                            if (!isset($aiomatic_Main_Settings['pre_code_off']) || trim($aiomatic_Main_Settings['pre_code_off']) != 'on')
                            {
                                $my_post['post_content'] = aiomatic_parse_pre_code_entities($my_post['post_content']);
                            }
                        }
                        $my_post['post_content'] = aimogen_bulk_finalize_prose($my_post['post_content']);
                        $my_post['post_title']           = aiomatic_truncate_title($new_post_title);
                        $my_post['aiomatic_source_title']   = $old_title;
                        $my_post['aiomatic_timestamp']   = aiomatic_get_date_now();
                        $my_post['aiomatic_post_format'] = $post_format;
                        if (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678') 
                        {
                            if(is_array($default_category))
                            {
                                $cextra = '';
                                foreach($default_category as $dc)
                                {
                                    $cextra .= ',' . get_cat_name($dc);
                                }
                                $extra_categories_temp = trim( $cextra . ',' . $extra_categories, ',');
                            }
                            else
                            {
                                $extra_categories_temp = trim(get_cat_name($default_category) . ',' .$extra_categories, ',');
                            }
                        }
                        else
                        {
                            $extra_categories_temp = $extra_categories;
                        }
                        $block_arr = array();
                        $custom_arr = array();
                        if($custom_fields != '')
                        {
                            if(stristr($custom_fields, '=>') != false)
                            {
                                $rule_arr = explode(',', trim($custom_fields));
                                foreach($rule_arr as $rule)
                                {
                                    $my_args = explode('=>', trim($rule));
                                    if(isset($my_args[1]))
                                    {
                                        if ( isset( $shortcode_tags['aicontent'] ) ) {
                                            $aicontent_handler = $shortcode_tags['aicontent'];
                                            unset( $shortcode_tags['aicontent'] );
                                        } else {
                                            $aicontent_handler = null;
                                        }
                                        $my_args[1] = do_shortcode($my_args[1]);
                                        $my_args[0] = do_shortcode($my_args[0]);
                                        if ( $aicontent_handler ) {
                                            $shortcode_tags['aicontent'] = $aicontent_handler;
                                        }
                                        $custom_field_content = trim($my_args[1]);
                                        $custom_field_content = aiomatic_replaceAIPostShortcodes($custom_field_content, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        $custom_field_content = aiomatic_replacetopics($custom_field_content, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                        $custom_field_content = aiomatic_replaceSynergyShortcodes($custom_field_content);
                                        $custom_field_content = $spintax->Parse($custom_field_content, $block_arr);
                                        $custom_field_content = aiomatic_replaceContentShortcodes($custom_field_content, $img_attr, $ai_command);
                                        if(stristr($my_args[1], 'serialize_') !== false)
                                        {
                                            $custom_arr[trim($my_args[0])] = array(str_replace('serialize_', '', $custom_field_content));
                                        }
                                        else
                                        {
                                            if(stristr($my_args[0], '[') !== false && stristr($my_args[0], ']') !== false)
                                            {
                                                preg_match_all('#([^\[\]]*?)\[([^\[\]]*?)\]#', $my_args[0], $cfm);
                                                if(isset($cfm[2][0]))
                                                {
                                                    if(isset($custom_arr[trim($cfm[1][0])]) && is_array($custom_arr[trim($cfm[1][0])]))
                                                    {
                                                        $custom_arr[trim($cfm[1][0])] = array_merge($custom_arr[trim($cfm[1][0])], array(trim($cfm[2][0]) => $custom_field_content));
                                                    }
                                                    else
                                                    {
                                                        $custom_arr[trim($cfm[1][0])] = array(trim($cfm[2][0]) => $custom_field_content);
                                                    }
                                                }
                                                else
                                                {
                                                    $custom_arr[trim($my_args[0])] = $custom_field_content;
                                                }
                                            }
                                            else
                                            {
                                                $custom_arr[trim($my_args[0])] = $custom_field_content;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        $block_arr = array();
                        $custom_arr = array_merge($custom_arr, array('aiomatic_auto_post_spinned' => $already_spinned, 'aiomatic_post_cats' => $extra_categories_temp, 'aiomatic_post_tags' => $post_the_tags));
                        $custom_tax_arr = array();
                        if($custom_tax != '')
                        {
                            if(stristr($custom_tax, '=>') != false)
                            {
                                $rule_arr = explode(';', trim($custom_tax));
                                foreach($rule_arr as $rule)
                                {
                                    $my_args = explode('=>', trim($rule));
                                    if(isset($my_args[1]))
                                    {
                                        $custom_tax_content = trim($my_args[1]);
                                        $custom_tax_content = aiomatic_replaceAIPostShortcodes($custom_tax_content, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        $custom_tax_content = aiomatic_replacetopics($custom_tax_content, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                        $custom_tax_content = aiomatic_replaceSynergyShortcodes($custom_tax_content);
                                        $custom_tax_content = $spintax->Parse($custom_tax_content, $block_arr);
                                        $custom_tax_content = aiomatic_replaceContentShortcodes($custom_tax_content, $img_attr, $ai_command);
                                        if(aiomatic_substr(trim($my_args[0]), 0, 3) === "pa_" && $post_type == 'product' && !empty($custom_tax_content))
                                        {
                                            if(isset($custom_arr['_product_attributes']))
                                            {
                                                $custom_arr['_product_attributes'] = array_merge($custom_arr['_product_attributes'], array(trim($my_args[0]) =>array(
                                                    'name' => trim($my_args[0]),
                                                    'value' => $custom_tax_content,
                                                    'is_visible' => '1',
                                                    'is_taxonomy' => '1'
                                                )));
                                            }
                                            else
                                            {
                                                $custom_arr['_product_attributes'] = array(trim($my_args[0]) =>array(
                                                    'name' => trim($my_args[0]),
                                                    'value' => $custom_tax_content,
                                                    'is_visible' => '1',
                                                    'is_taxonomy' => '1'
                                                ));
                                            }
                                        }
                                        if(isset($custom_tax_arr[trim($my_args[0])]))
                                        {
                                            $custom_tax_arr[trim($my_args[0])] .= ',' . $custom_tax_content;
                                        }
                                        else
                                        {
                                            $custom_tax_arr[trim($my_args[0])] = $custom_tax_content;
                                        }
                                    }
                                }
                            }
                        }
                        if(count($custom_tax_arr) > 0)
                        {
                            $my_post['taxo_input'] = $custom_tax_arr;
                        }
                        $my_post['meta_input'] = $custom_arr;
                        if($parent_id != '')
                        {
                            $my_post['post_parent'] = intval($parent_id);
                        }
                        if ($enable_pingback == '1') {
                            $my_post['ping_status'] = 'open';
                        } else {
                            $my_post['ping_status'] = 'closed';
                        }
                        if($min_time != '' && $max_time != '')
                        {
                            $t1 = strtotime($min_time);
                            $t2 = strtotime($max_time);
                            if($t1 != false && $t2 != false)
                            {
                                $int = wp_rand($t1, $t2);
                                $my_post['post_date'] = date('Y-m-d H:i:s', $int);
                            }
                        }
                        elseif($min_time != '')
                        {
                            $t1 = strtotime($min_time);
                            if($t1 != false)
                            {
                                $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                            }
                        }
                        elseif($max_time != '')
                        {
                            $t1 = strtotime($max_time);
                            if($t1 != false)
                            {
                                $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                            }
                        }
                        $count++;
                    }
                    else
                    {
                        aiomatic_log_to_file('Unknown posting mode submitted: ' . $posting_mode . '!');
                        if($auto == 1)
                        {
                            aiomatic_clearFromList($param, $type);
                        }
                        return 'fail';
                    }
                    if($update_post_id != '')
                    {
                        $my_post['ID'] = $update_post_id;
                    }
                    remove_filter('content_save_pre', 'wp_filter_post_kses');
                    remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                    try
                    {
                        $my_post['post_content'] = str_replace('\r\n', '', $my_post['post_content']);
                        $post_id = wp_insert_post($my_post, true);
                        if (is_wp_error($post_id)) 
                        {
                            aiomatic_log_to_file('Trying publishing again');
                            if (aiomatic_strlen($my_post['post_content']) > 16777215) {
                                $my_post['post_content'] = aiomatic_substr($my_post['post_content'], 0, 16777215);
                            }
                            $my_post['post_content'] = wp_kses_post($my_post['post_content']);
                            $my_post['post_content'] = mb_convert_encoding($my_post['post_content'], 'UTF-8', 'UTF-8');
                            $my_post['post_content'] = str_replace('\r\n', '', $my_post['post_content']);
                            $post_id = wp_insert_post($my_post, true);
                        }
                    }
                    catch(Exception $e)
                    {
                        aiomatic_log_to_file('Exception in publishing post (this is coming from another plugin, so we ignore it): ' . $e->getMessage());
                    }
                    add_filter('content_save_pre', 'wp_filter_post_kses');
                    add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                    if (!is_wp_error($post_id)) {
                        if($post_id === 0)
                        {
                            aiomatic_log_to_file('An error occurred while inserting post into wp database! Title:' . $my_post['post_title']);
                            continue;
                        }
                        $words = str_word_count(wp_strip_all_tags($my_post['post_content']));
                        aiomatic_increment_publishing_stats($words);
                        aimogen_bulk_on_post_created($post_id, $my_post['post_title'], isset($new_post_excerpt) ? $new_post_excerpt : '', isset($post_topic) ? $post_topic : (isset($post_title) ? $post_title : ''));
                        aiomatic_set_last_activity(
                            'article',
                            ['post_id' => $post_id]
                        );
                        $posts_inserted++;
                        if($wpml_lang != '' && function_exists('pll_set_post_language'))
                        {
                            pll_set_post_language($post_id, $wpml_lang);
                        }
                        if(!empty($additional_attachments))
                        {
                            foreach($additional_attachments as $add_att)
                            {
                                wp_update_post([
                                    'ID' => $add_att,
                                    'post_parent' => $post_id,
                                ]);
                            }
                        }
                        $default_categories = array();
                        if($remove_default == '1' && ($auto_categories != 'disabled' || (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678')))
                        {
                            $default_categories = wp_get_post_categories($post_id);
                        }
                        if(isset($my_post['taxo_input']))
                        {
                            foreach($my_post['taxo_input'] as $taxn => $taxval)
                            {
                                $taxn = trim($taxn);
                                $taxval = trim($taxval);
                                if(is_taxonomy_hierarchical($taxn))
                                {
                                    $taxval = array_map('trim', explode(',', $taxval));
                                    for($ii = 0; $ii < count($taxval); $ii++)
                                    {
                                        if(!is_numeric($taxval[$ii]))
                                        {
                                            $term_ids = [];
                                            $parent_id = 0;
                                            $hierarchy_parts = array_map('trim', explode('>', $taxval[$ii]));
                                            foreach($hierarchy_parts as $hp)
                                            {
                                                if(!is_numeric($hp))
                                                {
                                                    $xtermid = get_term_by('name', $hp, $taxn);
                                                    if($xtermid !== false)
                                                    {
                                                        $parent_id = $xtermid->term_id;
                                                        if(!is_numeric($taxval[$ii]))
                                                        {
                                                            $taxval[$ii] = intval($xtermid->term_id);
                                                        }
                                                        else
                                                        {
                                                            $taxval[] = intval($xtermid->term_id);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        wp_insert_term( $hp, $taxn, ['parent' => $parent_id]);
                                                        $xtermid = get_term_by('name', $hp, $taxn);
                                                        if($xtermid !== false)
                                                        {
                                                            $parent_id = $xtermid->term_id;
                                                            if($wpml_lang != '' && function_exists('pll_set_term_language'))
                                                            {
                                                                pll_set_term_language($xtermid->term_id, $wpml_lang); 
                                                            }
                                                            elseif($wpml_lang != '' && has_filter('wpml_object_id'))
                                                            {
                                                                $wpml_element_type = apply_filters( 'wpml_element_type', $taxn );
                                                                $pars['element_id'] = $xtermid->term_id;
                                                                $pars['element_type'] = $wpml_element_type;
                                                                $pars['language_code'] = $wpml_lang;
                                                                $pars['trid'] = FALSE;
                                                                $pars['source_language_code'] = NULL;
                                                                do_action('wpml_set_element_language_details', $pars);
                                                            }
                                                            if(!is_numeric($taxval[$ii]))
                                                            {
                                                                $taxval[$ii] = intval($xtermid->term_id);
                                                            }
                                                            else
                                                            {
                                                                $taxval[] = intval($xtermid->term_id);
                                                            }
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    if(!is_numeric($taxval[$ii]))
                                                    {
                                                        $taxval[$ii] = intval($hp);
                                                    }
                                                    else
                                                    {
                                                        $taxval[] = intval($hp);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    wp_set_post_terms($post_id, $taxval, $taxn, true);
                                }
                                else
                                {
                                    $jterms = array_map('trim', explode(',', $taxval));
                                    wp_set_post_terms($post_id, $jterms, $taxn, true);
                                }
                            }
                        }
                        if (isset($my_post['aiomatic_post_format']) && $my_post['aiomatic_post_format'] != '' && $my_post['aiomatic_post_format'] != 'post-format-standard') {
                            wp_set_post_terms($post_id, $my_post['aiomatic_post_format'], 'post_format', true);
                        }
                        $featured_path = '';
                        $get_img = $my_post['aiomatic_post_image'];
                        if ($get_img != '') {
                            if($my_post['aiomatic_local_image'] == '1')
                            {
                                $local_get_img = $get_img[0];
                                if (!aiomatic_assign_featured_image_path($local_get_img, $post_id)) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('aiomatic_assign_featured_image_path failed for ' . $local_get_img);
                                    }
                                } else {
                                    $featured_path = $get_img[1];
                                }
                            }
                            else
                            {
                                if(is_numeric($get_img))
                                {
                                    $featured_path = aiomatic_assign_featured_image($get_img, $post_id);
                                }
                                else
                                {
                                    if (!aiomatic_generate_featured_image($get_img, $post_id)) {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('aiomatic_generate_featured_image failed for ' . $get_img);
                                        }
                                    } else {
                                        $featured_path = $get_img;
                                    }
                                }
                            }
                        }
                        if($featured_path == '')
                        {
                            if ($image_url != '') {
                                $replacement = str_replace(array('[', ']'), '', $my_post['post_title']);
                                $image_url_temp = str_replace('%%item_title%%', $replacement, $image_url);
                                $image_url_temp = preg_replace_callback('#%%random_image\[([^\]]*?)\](\[\d+\])?%%#', function ($matches) {
                                    if(isset($matches[2]))
                                    {
                                        $chance = trim($matches[2], '[]');
                                    }
                                    else
                                    {
                                        $chance = '';
                                    }
                                    $arv = array();
                                    $my_img = aiomatic_get_random_image_google($matches[1], 0, 0, $chance, $arv);
                                    return $my_img;
                                }, $image_url_temp);
                                $img_rulx = $spintax->Parse(trim($image_url_temp));
                                $selected_img = aiomatic_select_ai_image($my_post['post_title'], $img_rulx);
                                if($selected_img === false)
                                {
                                    $img_rulx = explode(',', $img_rulx);
                                    $img_rulx = trim($img_rulx[array_rand($img_rulx)]);
                                }
                                else
                                {
                                    $img_rulx = $selected_img;
                                }
                                if(is_numeric($img_rulx))
                                {
                                    $featured_path = aiomatic_assign_featured_image($img_rulx, $post_id);
                                }
                                else
                                {
                                    if($img_rulx != '')
                                    {
                                        if (!aiomatic_generate_featured_image($img_rulx, $post_id)) {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                aiomatic_log_to_file('aiomatic_generate_featured_image failed to default value: ' . $img_rulx . '!');
                                            }
                                        } else {
                                            $featured_path = $img_rulx;
                                        }
                                    }
                                }
                            }
                        }
                        if ($auto_categories != 'disabled') {
                            if ($my_post['extra_categories'] != '') {
                                $extra_cats = explode(',', $my_post['extra_categories']);
                                if($post_type == 'product')
                                {
                                    $product_tax = 'product_cat';
                                }
                                else
                                {
                                    $product_tax = 'category';
                                }
                                foreach($extra_cats as $extra_cat)
                                {
                                    $extra_cat = trim($extra_cat);
                                    $extra_cat = strip_tags($extra_cat);
                                    $extra_cat = preg_replace('#^\d+\.\s*#', '', $extra_cat);
                                    if(empty($extra_cat))
                                    {
                                        continue;
                                    }
                                    if ($skip_inexist == '1') 
                                    {
                                        if(!term_exists($extra_cat, $product_tax))
                                        {
                                            continue;
                                        }
                                    }
                                    $termid = aiomatic_create_terms($product_tax, null, trim($extra_cat));
                                    wp_set_post_terms($post_id, $termid, $product_tax, true);
                                    if($wpml_lang != '' && function_exists('pll_set_term_language'))
                                    {
                                        foreach($termid as $tx)
                                        {
                                            pll_set_term_language($tx, $wpml_lang); 
                                        }
                                    }
                                    elseif($wpml_lang != '' && has_filter('wpml_object_id'))
                                    {
                                        $wpml_element_type = apply_filters( 'wpml_element_type', 'product_cat' );
                                        foreach($termid as $tx)
                                        {
                                            $pars['element_id'] = $tx;
                                            $pars['element_type'] = $wpml_element_type;
                                            $pars['language_code'] = $wpml_lang;
                                            $pars['trid'] = FALSE;
                                            $pars['source_language_code'] = NULL;
                                            do_action('wpml_set_element_language_details', $pars);
                                        }
                                    }
                                }
                            }
                        }
                        if (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678') {
                            $cats   = array();
                            if(is_array($default_category))
                            {
                                foreach($default_category as $dc)
                                {
                                    $cats[] = $dc;
                                }
                            }
                            else
                            {
                                $cats[] = $default_category;
                            }
                            global $sitepress;
                            if($wpml_lang != '' && has_filter('wpml_current_language') && $sitepress != null)
                            {
                                $current_language = apply_filters( 'wpml_current_language', NULL );
                                $sitepress->switch_lang($wpml_lang);
                            }
                            $target_cat = 'category';
                            if($post_type == 'product')
                            {
                                $target_cat = 'product_cat';
                            }
                            wp_set_object_terms($post_id, array_map( 'intval', $cats ), $target_cat, true);
                            if($wpml_lang != '' && function_exists('pll_set_term_language'))
                            {
                                foreach($cats as $cc)
                                {
                                    pll_set_term_language($cc, $wpml_lang);
                                }
                            }
                            elseif($wpml_lang != '' && has_filter('wpml_current_language') && $sitepress != null)
                            {
                                $sitepress->switch_lang($current_language);
                            }
                        }
                        if (isset($my_post['tags_input']) && $my_post['tags_input'] != '')
                        {
                            if($post_type == 'product')
                            {
                                wp_set_post_terms($post_id, $my_post['tags_input'], 'product_tag', true);
                            }
                        }
                        $tax_rez = wp_set_object_terms( $post_id, 'aiomatic_' . $type . '_' . $param, 'coderevolution_post_source', true);
                        if (is_wp_error($tax_rez)) {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('wp_set_object_terms failed for: ' . $post_id . '!');
                            }
                        }
                        if($post_type == 'topic' && $parent_id != '')
                        {
                            update_post_meta($post_id, '_bbp_forum_id', $parent_id);
                            update_post_meta($post_id, '_bbp_topic_id', $post_id);
                            update_post_meta($post_id, '_bbp_voice_count', '0');
                            update_post_meta($post_id, '_bbp_reply_count', '0');
                            update_post_meta($post_id, '_bbp_reply_count_hidden', '0');
                            update_post_meta($post_id, '_bbp_last_reply_id', '0');
                            update_post_meta($post_id, '_bbp_last_active_id', $post_id);
                            update_post_meta($post_id, '_bbp_last_active_time', get_post_field( 'post_date', $topic_id, 'db' ));
                            do_action( 'bbp_insert_topic', (int) $post_id, (int) $parent_id );
                        }
                        if($post_type == 'reply' && $parent_id != '')
                        {
                            if(function_exists('bbp_get_topic_forum_id'))
                            {
                                $forum_aidi = bbp_get_topic_forum_id($parent_id);
                                if(empty($forum_aidi))
                                {
                                    $forum_aidi = 0;
                                }
                            }
                            else
                            {
                                $forum_aidi = 0;
                            }
                            do_action( 'bbp_insert_reply', (int) $post_id, (int) $parent_id, (int) $forum_aidi );
                        }
                        if($remove_default == '1' && ($auto_categories != 'disabled' || (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678')))
                        {
                            $new_categories = wp_get_post_categories($post_id);
                            $removed_cat = false;
                            if(isset($default_categories) && !($default_categories == $new_categories))
                            {
                                foreach($default_categories as $dc)
                                {
                                    $rem_cat = get_category( $dc );
                                    wp_remove_object_terms( $post_id, $rem_cat->slug, 'category' );
                                    $removed_cat = true;
                                }
                            }
                            if($removed_cat == false)
                            {
                                wp_remove_object_terms( $post_id, 'uncategorized', 'category' );
                            }
                        }
                        aiomatic_addPostMeta($post_id, $my_post, $param, $type, $featured_path, $post_topic, $rule_unique_id, $post_link);
                        if($wpml_lang != '' && (class_exists('SitePress') || function_exists('wpml_object_id')))
                        {
                            $wpml_element_type = apply_filters( 'wpml_element_type', $post_type );
                            $pars['element_id'] = $post_id;
                            $pars['element_type'] = $wpml_element_type;
                            $pars['language_code'] = $wpml_lang;
                            $pars['source_language_code'] = NULL;
                            do_action('wpml_set_element_language_details', $pars);

                            global $wp_filesystem;
                            if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
                                include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() );
                                wp_filesystem($creds);
                            }
                            if($wp_filesystem->exists(WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php'))
                            {
                                include_once( WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php' );
                            }
                            $wpml_lang = trim($wpml_lang);
                            if(function_exists('wpml_update_translatable_content'))
                            {
                                wpml_update_translatable_content('post_' . $post_type, $post_id, $wpml_lang);
                                if($my_post['post_title'] != '')
                                {
                                    global $sitepress;
                                    global $wpdb;
                                    $keyid = md5($my_post['post_title']);
                                    $keyName = $keyid . '_wpml';
                                    $rezxxxa = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}postmeta WHERE `meta_key` = '$keyName' limit 1", ARRAY_A );
                                    if(count($rezxxxa) != 0)
                                    {
                                        $metaRow = $rezxxxa[0];
                                        $metaValue = $metaRow['meta_value'];
                                        $metaParts = explode('_', $metaValue);
                                        $sitepress->set_element_language_details($post_id, 'post_'.$my_post['post_type'] , $metaParts[0], $wpml_lang, $metaParts[1] ); 
                                    }
                                    else
                                    {
                                        $ptrid = $sitepress->get_element_trid($post_id);
                                        update_post_meta($post_id, $keyid.'_wpml', $ptrid.'_'.$wpml_lang );
                                    }
                                }
                                
                            }
                        }
                        if (isset($aiomatic_Main_Settings['draft_first']) && $aiomatic_Main_Settings['draft_first'] == 'on' && $draft_me == true)
                        {
                            aiomatic_change_post_status($post_id, 'publish');
                        }
                    } else {
                        aiomatic_log_to_file('Failed to insert post into wp database(1)! Title:' . $my_post['post_title'] . '! Error: ' . $post_id->get_error_message() . ' Error code: ' . $post_id->get_error_code() . ' Error data: ' . $post_id->get_error_data());
                        continue;
                    }
                }
            }
            elseif($type == '1')
            {
                if($default_lang != '')
                {
                    $default_lang = explode(',', $default_lang);
                    $default_lang = array_map( 'trim', $default_lang );
                }
                else
                {
                    $default_lang = array();
                }
                $url_list_lines = array();
                if($url_list != '')
                {
                    $url_list_lines = preg_split('/\r\n|\r|\n/', $url_list);
                }
                else
                {
                    aiomatic_log_to_file('You need to enter a YouTube video URL to use this feature!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
                $additional_kws = array();
                $post_link = '';
                $user_name        = '';
                $featured_image   = '';
                $post_cats = '';
                $post_tagz = '';
                $post_excerpt = '';
                $final_content = '';
                $postID = '';
                $heading_val = '';
                $image_query = '';
                $temp_post = '';
                $cntx = count($url_list_lines);
                $rss_feeds = array();
                for($ji = 0; $ji < $cntx; $ji++)
                {
                    if (filter_var($url_list_lines[$ji], FILTER_VALIDATE_URL) !== false && stristr($url_list_lines[$ji], 'youtu') === false) 
                    {
                        if(aiomatic_endsWith($url_list_lines[$ji], '.txt'))
                        {
                            $txt_content = aiomatic_get_web_page($url_list_lines[$ji]);
                            if ($txt_content === FALSE) 
                            {
                                aiomatic_log_to_file('Failed to read text file: ' . $url_list_lines[$ji]);
                                unset($url_list_lines[$ji]);
                                if($auto == 1)
                                {
                                    aiomatic_log_to_file($param);
                                }
                                continue;
                            }
                            unset($url_list_lines[$ji]);
                            $additional_kws = preg_split('/\r\n|\r|\n/', $txt_content);
                        }
                        else
                        {
                            aiomatic_log_to_file('Trying to parse RSS feed items(3): ' . $url_list_lines[$ji]);
                            try
                            {
                                if(!class_exists('SimplePie_Autoloader', false))
                                {
                                    require_once(dirname(__FILE__) . "/res/simplepie/autoloader.php");
                                }
                            }
                            catch(Exception $e) 
                            {
                                unset($url_list_lines[$ji]);
                                aiomatic_log_to_file('Exception thrown in SimplePie autoloader: ' . $e->getMessage());
                                if($auto == 1)
                                {
                                    aiomatic_log_to_file($param);
                                }
                                continue;
                            }
                            $feed = new SimplePie();
                            $feed->set_timeout(120);
                            $feed->set_feed_url($url_list_lines[$ji]);
                            $feed->enable_cache(false);
                            $feed->strip_htmltags(false);
                            $feed->init();
                            $feed->handle_content_type();
                            if ($feed->error()) 
                            {
                                aiomatic_log_to_file('Error in parsing RSS feed: ' . $feed->error() . ' for ' . $url_list_lines[$ji]);
                                unset($url_list_lines[$ji]);
                                if($auto == 1)
                                {
                                    aiomatic_clearFromList($param, $type);
                                }
                                continue;
                            }
                            $items = $feed->get_items();
                            $zero = true;
                            foreach($items as $itemx)
                            {
                                if($zero == true)
                                {
                                    $post_link = trim($itemx->get_permalink());
                                    if(isset($rss_items[$post_link]))
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Skipping RSS title because it was already processed before: ' . $itemx->get_title());
                                        }
                                        continue;
                                    }
                                    if ($fauthor = $itemx->get_author()) 
                                    {
                                        $user_name = $fauthor->get_name();
                                    }
                                    else
                                    {
                                        $user_name = '';
                                    }
                                    $feed_cats = array();
                                    $varx = $itemx->get_categories();
                                    if(is_array($varx))
                                    {
                                        foreach ($varx as $xcategory)
                                        {
                                            $feed_cats[] = $xcategory->get_label();
                                        }
                                    }
                                    $post_cats = implode(',', $feed_cats);
                                    $post_excerpt = $itemx->get_description();
                                    $final_content = $itemx->get_content();
                                    $rss_feeds[$itemx->get_title()] = array('url' => $post_link, 'author' => $user_name,  'cats' => $post_cats, 'excerpt' => $post_excerpt, 'content' => $final_content );
                                }
                                else
                                {
                                    $post_link_temp = trim($itemx->get_permalink());
                                    if(isset($rss_items[$post_link_temp]))
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Skipping RSS title because it was already processed before: ' . $itemx->get_title());
                                        }
                                        continue;
                                    }
                                    if ($fauthor = $itemx->get_author()) 
                                    {
                                        $user_name_temp = $fauthor->get_name();
                                    }
                                    else
                                    {
                                        $user_name_temp = '';
                                    }
                                    $feed_cats = array();
                                    $varx = $itemx->get_categories();
                                    if(is_array($varx))
                                    {
                                        foreach ($varx as $xcategory)
                                        {
                                            $feed_cats[] = $xcategory->get_label();
                                        }
                                    }
                                    $post_cats_temp = implode(',', $feed_cats);
                                    $post_excerpt_temp = $itemx->get_description();
                                    $final_content_temp = $itemx->get_content();
                                    $rss_feeds[$itemx->get_title()] = array('url' => $post_link_temp, 'author' => $user_name_temp,  'cats' => $post_cats_temp, 'excerpt' => $post_excerpt_temp, 'content' => $final_content_temp );
                                }
                                $additional_kws[] = $itemx->get_permalink();
                                $zero = false;
                            }
                            unset($url_list_lines[$ji]);
                        }
                    }
                }
                if(count($additional_kws) > 0)
                {
                    $url_list_lines = array_merge($url_list_lines, $additional_kws);
                }
                $url_list_lines = array_unique($url_list_lines);
                foreach($url_list_lines as $zindedx => $urlline)
                {
                    preg_match_all('#https:\/\/(?:www\.)?youtube\.com\/@([^\/\n\s]+)#i', $urlline, $hmatches);
                    if(isset($hmatches[1][0]))
                    {
                        $videos_ok = false;
                        if (isset($aiomatic_Main_Settings['yt_app_id']) && trim($aiomatic_Main_Settings['yt_app_id']) != '') 
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Getting videos from channel'));
                            $channel_id = '';
                            $za_app = explode(',', $aiomatic_Main_Settings['yt_app_id']);
                            $za_app = trim($za_app[array_rand($za_app)]);
                            $chfound = false;
                            $channel_link="https://www.googleapis.com/youtube/v3/search?part=snippet&type=channel&maxResults=1&q=" . trim(trim($hmatches[1][0]), '@') . "&key=" . $za_app;
                            $chid      = aiomatic_get_web_page($channel_link);
                            if (stristr($chid, 'items')) {
                                $ch_json = json_decode($chid);
                                $channels      = $ch_json->items;
                                foreach ($channels as $channel) 
                                {
                                    if(isset($channel->id->channelId))
                                    {
                                        $channel_id = $channel->id->channelId;
                                        $chfound = true;
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to find YouTube channel ID: ' . $hmatches[1][0]);
                            }
                            if($chfound == true)
                            {
                                $feed_uri = 'https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&videoEmbeddable=true&key=' . $za_app;
                                $feed_uri .= '&maxResults=50';
                                $feed_uri .= '&channelId=' . $channel_id;
                                $feed_uri .= '&order=date';
                                $chid   = aiomatic_get_web_page($feed_uri);
                                $ytjson = json_decode($chid);
                                if($ytjson === null)
                                {
                                    aiomatic_log_to_file('Failed to get video info for channel: ' . $channel_id); 
                                }
                                else
                                {
                                    if(isset($ytjson->items))
                                    {
                                        $zitems = $ytjson->items;
                                        foreach ($zitems as $zitem) 
                                        {
                                            $url_list_lines[] = 'https://www.youtube.com/watch?v=' . $zitem->id->videoId;
                                            $videos_ok = true;
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to decode channel results: ' . print_r($ytjson, true)); 
                                    }
                                }
                            }
                        }
                        if($videos_ok === false)
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Getting videos from channel using direct method'));
                            $chch  = curl_init();
                            if ($chch !== FALSE) 
                            {
                                if (isset($aiomatic_Main_Settings['proxy_url']) && $aiomatic_Main_Settings['proxy_url'] != '' && $aiomatic_Main_Settings['proxy_url'] != 'disable' && $aiomatic_Main_Settings['proxy_url'] != 'disabled') {
                                    $prx = explode(',', $aiomatic_Main_Settings['proxy_url']);
                                    $randomness = array_rand($prx);
                                    curl_setopt( $chch, CURLOPT_PROXY, trim($prx[$randomness]));
                                    if (isset($aiomatic_Main_Settings['proxy_auth']) && $aiomatic_Main_Settings['proxy_auth'] != '') 
                                    {
                                        $prx_auth = explode(',', $aiomatic_Main_Settings['proxy_auth']);
                                        if(isset($prx_auth[$randomness]) && trim($prx_auth[$randomness]) != '')
                                        {
                                            curl_setopt( $chch, CURLOPT_PROXYUSERPWD, trim($prx_auth[$randomness]));
                                        }
                                    }
                                }
                                curl_setopt($chch, CURLOPT_CONNECTTIMEOUT, 10);
                                if (isset($aiomatic_Main_Settings['max_timeout']) && $aiomatic_Main_Settings['max_timeout'] != '')
                                {
                                    $ztime = intval($aiomatic_Main_Settings['max_timeout']);
                                }
                                else
                                {
                                    $ztime = 300;
                                }
                                curl_setopt($chch, CURLOPT_TIMEOUT, $ztime);
                                curl_setopt($chch, CURLOPT_HTTPGET, 1);
                                curl_setopt($chch, CURLOPT_REFERER, get_site_url());
                                curl_setopt($chch, CURLOPT_URL, 'https://www.youtube.com/@' . $hmatches[1][0] . '/');
                                curl_setopt($chch, CURLOPT_RETURNTRANSFER, 1);
                                curl_setopt($chch, CURLOPT_SSL_VERIFYHOST, 0);
                                curl_setopt($chch, CURLOPT_SSL_VERIFYPEER, 0);
                                $za_video_page = curl_exec($chch);
                                if($za_video_page === false)
                                {
                                    aiomatic_log_to_file('Failed to download channel listing: ' . $urlline);
                                }
                                else
                                {
                                    preg_match_all('#"videoIds":\["([^"]*?)"\]#i', $za_video_page, $hmatches);
                                    if(isset($hmatches[1][0]))
                                    {
                                        $vms = array_unique($hmatches[1]);
                                        $vms = array_reverse($vms);
                                        foreach($vms as $vma)
                                        {   
                                            $url_list_lines[] = 'https://www.youtube.com/watch?v=' . $vma;
                                        }
                                    }
                                }
                                curl_close($chch);
                                $rand_sleep = wp_rand(400, 700);
                                usleep($rand_sleep * 1000);
                            }
                            else
                            {
                                aiomatic_log_to_file('Failed to init curl in channel listing: ' . $urlline);
                            }
                        }
                        unset($url_list_lines[$zindedx]);
                    }
                    if(stristr($urlline, 'list=') !== false)
                    {
                        $playlist_id = aiomatic_getPlaylistIdFromUrl(trim($urlline));
                        if(!empty($playlist_id))
                        {
                            $videos_ok = false;
                            if (isset($aiomatic_Main_Settings['yt_app_id']) && trim($aiomatic_Main_Settings['yt_app_id']) != '') 
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Getting videos from playlist'));
                                $channel_id = '';
                                $za_app = explode(',', $aiomatic_Main_Settings['yt_app_id']);
                                $za_app = trim($za_app[array_rand($za_app)]);
                                $chfound = false;
                                $channel_link='https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&key=' . $za_app . '&maxResults=50&playlistId=' . trim($playlist_id);
                                $chid      = aiomatic_get_web_page($channel_link);
                                if (stristr($chid, 'items')) {
                                    $ch_json = json_decode($chid);
                                    if(isset($ch_json->items))
                                    {
                                        $items = $ch_json->items;
                                        foreach ($items as $zitem) 
                                        {
                                            $url_list_lines[] = 'https://www.youtube.com/watch?v=' . $zitem->snippet->resourceId->videoId;
                                            $videos_ok = true;
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to find YouTube playlist ID: ' . $playlist_id);
                                }
                            }
                            if($videos_ok === false)
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Getting videos from playlist using direct method'));
                                $chch  = curl_init();
                                if ($chch !== FALSE) 
                                {
                                    if (isset($aiomatic_Main_Settings['proxy_url']) && $aiomatic_Main_Settings['proxy_url'] != '' && $aiomatic_Main_Settings['proxy_url'] != 'disable' && $aiomatic_Main_Settings['proxy_url'] != 'disabled') {
                                        $prx = explode(',', $aiomatic_Main_Settings['proxy_url']);
                                        $randomness = array_rand($prx);
                                        curl_setopt( $chch, CURLOPT_PROXY, trim($prx[$randomness]));
                                        if (isset($aiomatic_Main_Settings['proxy_auth']) && $aiomatic_Main_Settings['proxy_auth'] != '') 
                                        {
                                            $prx_auth = explode(',', $aiomatic_Main_Settings['proxy_auth']);
                                            if(isset($prx_auth[$randomness]) && trim($prx_auth[$randomness]) != '')
                                            {
                                                curl_setopt( $chch, CURLOPT_PROXYUSERPWD, trim($prx_auth[$randomness]));
                                            }
                                        }
                                    }
                                    curl_setopt($chch, CURLOPT_CONNECTTIMEOUT, 10);
                                    if (isset($aiomatic_Main_Settings['max_timeout']) && $aiomatic_Main_Settings['max_timeout'] != '')
                                    {
                                        $ztime = intval($aiomatic_Main_Settings['max_timeout']);
                                    }
                                    else
                                    {
                                        $ztime = 300;
                                    }
                                    curl_setopt($chch, CURLOPT_TIMEOUT, $ztime);
                                    curl_setopt($chch, CURLOPT_HTTPGET, 1);
                                    curl_setopt($chch, CURLOPT_REFERER, get_site_url());
                                    curl_setopt($chch, CURLOPT_URL, 'https://www.youtube.com/playlist?list=' . $playlist_id);
                                    curl_setopt($chch, CURLOPT_RETURNTRANSFER, 1);
                                    curl_setopt($chch, CURLOPT_SSL_VERIFYHOST, 0);
                                    curl_setopt($chch, CURLOPT_SSL_VERIFYPEER, 0);
                                    $za_video_page = curl_exec($chch);
                                    if($za_video_page === false)
                                    {
                                        aiomatic_log_to_file('Failed to download playlist listing: ' . $urlline);
                                    }
                                    else
                                    {
                                        preg_match_all('#"videoIds":\["([^"]*?)"\]#i', $za_video_page, $hmatches);
                                        if(isset($hmatches[1][0]))
                                        {
                                            $vms = array_unique($hmatches[1]);
                                            $vms = array_reverse($vms);
                                            foreach($vms as $vma)
                                            {   
                                                $url_list_lines[] = 'https://www.youtube.com/watch?v=' . $vma;
                                            }
                                        }
                                    }
                                    curl_close($chch);
                                    $rand_sleep = wp_rand(400, 700);
                                    usleep($rand_sleep * 1000);
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to init curl in playlist listing: ' . $urlline);
                                }
                            }
                            unset($url_list_lines[$zindedx]);
                        }
                    }
                }
                if($overwrite_existing == '1')
                {
                    $url_list_lines_processed = array();
                    foreach($url_list_lines as $indx => $ptl)
                    {
                        $ptlprocessed = explode('!###!', $ptl);
                        if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                        {
                            $url_list_lines_processed[$indx] = $ptlprocessed[0];
                        }
                        else
                        {
                            $url_list_lines_processed[$indx] = $ptl;
                        }
                    }
                    foreach($posted_items as $ptit => $pid)
                    {
                        if (($key = array_search($ptit, $url_list_lines_processed)) !== false) {
                            $update_post_id = $pid;
                            break;
                        }
                    }
                }
                if($title_once == '1')
                {
                    $skipt = 0;
                    $url_list_lines_processed = array();
                    foreach($url_list_lines as $indx => $ptl)
                    {
                        $ptlprocessed = explode('!###!', $ptl);
                        if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                        {
                            $url_list_lines_processed[$indx] = $ptlprocessed[0];
                        }
                        else
                        {
                            $url_list_lines_processed[$indx] = $ptl;
                        }
                    }
                    foreach($posted_items as $ptit => $pid)
                    {
                        if (($key = array_search($ptit, $url_list_lines_processed)) !== false) {
                            aiomatic_log_to_file('Skipping YouTube title, already processed: ' . $ptit);
                            unset($url_list_lines[$key]);
                            unset($url_list_lines_processed[$key]);
                            $skipt++;
                        }
                    }
                    if(count($url_list_lines) == 0 && $skipt > 0)
                    {
                        if (isset($aiomatic_Main_Settings['email_notification']) && $aiomatic_Main_Settings['email_notification'] != '')
                        {
                            if($count === 1)
                            {
                                $email_list = explode(',', $aiomatic_Main_Settings['email_notification']);
                                foreach($email_list as $thisaddr)
                                {
                                    $thisaddr = trim($thisaddr);
                                    try
                                    {
                                        $admin_mail = get_option('admin_email');
                                        $to        = $thisaddr;
                                        $subject   = '[Aimogen] YouTube URLs depleted rule ID ' . $param . ' - ' . aiomatic_get_date_now();
                                        $message   = 'YouTube Rule ID ' . esc_html($param) . ' (' . $rule_description . ') depleted its YouTube URLs list, no new posts publised! Website URL: ' . get_site_url();
                                        $headers[] = 'From: Aimogen Plugin <' . $admin_mail . '>';
                                        $headers[] = 'Reply-To: ' . $admin_mail;
                                        $headers[] = 'X-Mailer: PHP/' . phpversion();
                                        $headers[] = 'Content-Type: text/html';
                                        $headers[] = 'Charset: ' . get_option('blog_charset', 'UTF-8');
                                        wp_mail($to, $subject, $message, $headers);
                                    }
                                    catch (Exception $e) {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Failed to send mail: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                        }
                                    }
                                }
                            }
                        }
                        aiomatic_log_to_file('All YouTube URLs already processed, nothing to do.');
                        if($auto == 1)
                        {
                            aiomatic_clearFromList($param, $type);
                        }
                        return 'nochange';
                    }
                }
                $spintax = new Aiomatic_Spintax();
                $orig_ai_command = $ai_command;
                $orig_ai_command_title = $title_ai_command;
                $orig_ai_command_category = $category_ai_command;
                $orig_ai_command_tag = $tag_ai_command;
                $orig_ai_command_image = $ai_command_image;
                $already_spinned = 0;
                if(isset($aiomatic_Main_Settings['attr_text']) && $aiomatic_Main_Settings['attr_text'] != '')
                {
                    $img_attr = $aiomatic_Main_Settings['attr_text'];
                }
                else
                {
                    $img_attr = '';
                }
                $headings_arr = array();
                if($images_list != '')
                {
                    $images_arr = preg_split('/\r\n|\r|\n/', $images_list);
                    $images_arr = array_map('trim', $images_arr);
                }
                else
                {
                    $images_arr = array();
                }
                while(true) 
                {
                    $thread_id = '';
                    $my_title_outro = '';
                    if ($count > intval($max)) {
                        break;
                    }
                    $heading_image_loc = $heading_img_location;
                    if($heading_image_loc == 'random')
                    {
                        $xwords = array('top', 'heading', 'bottom');
                        $randomWord = $xwords[array_rand($xwords)];
                        $heading_image_loc = $randomWord;
                    }
                    $update_post_id  = '';
                    $current_section = '';
                    $post_sections = '';
                    $post_topic = '';
                    $post_title_keywords = '';
                    $headings_arr_copy = $headings_arr;
                    $added_img_list = array();
                    $raw_img_list = array();
                    $full_result_list = array();
                    $added_images = 0;
                    $heading_results = array();
                    $returned_caption = '';
                    if(count($url_list_lines) == 0)
                    {
                        break;
                    }
                    if ($count > intval($max)) {
                        break;
                    }
                    if($no_random == '1')
                    {
                        $current_index = array_key_first($url_list_lines);
                    }
                    else
                    {
                        if (!isset($aiomatic_Main_Settings['no_random_titles']) || $aiomatic_Main_Settings['no_random_titles'] != 'on')
                        {
                            $current_index = array_rand($url_list_lines);
                        }
                        else
                        {
                            $current_index = array_key_first($url_list_lines);
                        }
                    }
                    $video_url = trim($url_list_lines[$current_index]);
                    if($title_once == '1')
                    {
                        unset($url_list_lines[$current_index]);
                    }
                    $ptlprocessed = explode('!###!', $video_url);
                    if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                    {
                        $video_url = $ptlprocessed[0];
                        $post_title_keywords = $ptlprocessed[1];
                    }
                    if(isset($rss_feeds[$video_url]))
                    {
                        $post_link = $rss_feeds[$video_url]['url'];
                        $user_name = $rss_feeds[$video_url]['author'];
                        $post_cats = $rss_feeds[$video_url]['cats'];
                        $post_excerpt = $rss_feeds[$video_url]['excerpt'];
                        $final_content = $rss_feeds[$video_url]['content'];
                    }
                    $tprepp = $spintax->Parse($video_url);
                    if($tprepp != false && $tprepp != '')
                    {
                        $video_url = $tprepp;
                    }
                    $video_url = aiomatic_replaceSynergyShortcodes($video_url);
                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                    {
                        aiomatic_log_to_file('Starting processing YouTube data: ' . $video_url);
                    }
                    $old_title = $video_url;
                    $already_spinned = 0;
                    if (!stristr($video_url, 'youtu') && !stristr($video_url, 'http'))
                    {
                        if (isset($aiomatic_Main_Settings['yt_app_id']) && trim($aiomatic_Main_Settings['yt_app_id']) != '') 
                        {
                            $za_app = explode(',', $aiomatic_Main_Settings['yt_app_id']);
                            $za_app = trim($za_app[array_rand($za_app)]);
                            $feed_uri = 'https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&videoEmbeddable=true&key=' . $za_app;
                            $feed_uri .= '&maxResults=50';
                            $feed_uri .= '&q='.urlencode(trim(stripslashes(str_replace('&quot;', '"', $video_url))));
                            $feed_uri .= '&order=date';
                            $chid   = aiomatic_get_web_page($feed_uri);
                            $ytjson = json_decode($chid);
                            if($ytjson === null)
                            {
                                aiomatic_log_to_file('Failed to get video info for youtube keyword: ' . $video_url); 
                                unset($url_list_lines[$current_index]);
                                break;
                            }
                            else
                            {
                                if(isset($ytjson->items))
                                {
                                    $zitems = $ytjson->items;
                                    foreach ($zitems as $zitem) 
                                    {
                                        $video_url = 'https://www.youtube.com/watch?v=' . $zitem->id->videoId;
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to decode video search results: ' . print_r($ytjson, true)); 
                                    unset($url_list_lines[$current_index]);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            aiomatic_log_to_file('Only YouTube URLs are supported, this does not seem to be a YouTube video URL: ' . $video_url);
                            unset($url_list_lines[$current_index]);
                            break;
                        }
                    }
                    $allmodels = aiomatic_get_all_models();
                    if($custom_shortcodes != '')
                    {
                        $custom_shortcodes_arr = preg_split('/\r\n|\r|\n/', $custom_shortcodes);
                        foreach($custom_shortcodes_arr as $my_short)
                        {
                            $name_part = explode('=>', $my_short);
                            if(isset($name_part[1]) && !empty(trim($name_part[1])))
                            {
                                $shortname = trim($name_part[0]);
                                if(strstr($video_url, '%%' . $shortname . '%%'))
                                {
                                    $shortval = '';
                                    $name_part[1] = str_replace('%%video_url%%', $video_url, $name_part[1]);
                                    $ai_part = explode('@@', $name_part[1]);
                                    if(isset($ai_part[1]) && !empty(trim($ai_part[1])))
                                    {
                                        if(!in_array(trim($ai_part[0]), $allmodels))
                                        {
                                            $aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                        }
                                        else
                                        {
                                            $aimodel = trim($ai_part[0]);
                                        }
                                        $zai_command = trim($ai_part[1]);
                                        $zai_command = aiomatic_replaceSynergyShortcodes($zai_command);
                                        $zai_command = aiomatic_replaceAIPostShortcodes($zai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', '');     
                                        $zai_command = aiomatic_replace_youtube($zai_command, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                                        $zai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $zai_command);
                                        foreach($custom_shortcodes_arr as $my_check_short)
                                        {
                                            $check_name_part = explode('=>', $my_check_short);
                                            if(isset($check_name_part[1]) && !empty(trim($check_name_part[1])))
                                            {
                                                $check_shortname = trim($check_name_part[0]);
                                                if($shortname !== $check_shortname && strstr($zai_command, '%%' . $check_shortname . '%%') !== false)
                                                {
                                                    $check_shortval = '';
                                                    $check_ai_part = explode('@@', $check_name_part[1]);
                                                    if(!in_array(trim($check_ai_part[0]), $allmodels))
                                                    {
                                                        $check_aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                                    }
                                                    else
                                                    {
                                                        $check_aimodel = trim($check_ai_part[0]);
                                                    }
                                                    $check_ai_command = trim($check_ai_part[1]);
                                                    $aierror = '';
                                                    $check_ai_command = aiomatic_replaceSynergyShortcodes($check_ai_command);
                                                    $check_ai_command = aiomatic_replaceAIPostShortcodes($check_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', '');     
                                                    $check_ai_command = aiomatic_replace_youtube($check_ai_command, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                                                    $check_ai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $check_ai_command);
                                                    $check_generated_text = aiomatic_generate_custom_shortcode_content($token, $check_aimodel, $check_ai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                                                    if($check_generated_text === false)
                                                    {
                                                        aiomatic_log_to_file('Custom nested shortcode generator error: ' . $aierror);
                                                    }
                                                    else
                                                    {
                                                        $check_shortval = trim(trim($check_generated_text), '.');
                                                    }
                                                    $zai_command = str_replace('%%' . $check_shortname . '%%', $check_shortval, $zai_command);
                                                }
                                            }
                                        }
                                        $aierror = '';
                                        $generated_text = aiomatic_generate_custom_shortcode_content($token, $aimodel, $zai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                                        if($generated_text === false)
                                        {
                                            aiomatic_log_to_file('Custom shortcode generator error: ' . $aierror);
                                        }
                                        else
                                        {
                                            $shortval = trim(trim($generated_text), '.');
                                        }
                                    }
                                    $video_url = str_replace('%%' . $shortname . '%%', $shortval, $video_url);
                                }
                            }
                        } 
                    }
                    if(!empty($global_prepend))
                    {
                        $global_prepend = aiomatic_replaceSynergyShortcodes($global_prepend);
                        $global_prepend = aiomatic_replaceAIPostShortcodes($global_prepend, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', '');     
                        $global_prepend = aiomatic_replace_youtube($global_prepend, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                    }
                    if(!empty($global_append))
                    {
                        $global_append = aiomatic_replaceSynergyShortcodes($global_append);
                        $global_append = aiomatic_replace_youtube($global_append, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                        $global_append = aiomatic_replaceAIPostShortcodes($global_append, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', '');     
                    }
                    $video_url = aiomatic_replaceSynergyShortcodes($video_url);
                    $video_url = apply_filters('aiomatic_replace_aicontent_shortcode', $video_url);
                    $video_url = aiomatic_extractYouTubeVideoId($video_url);
                    if(empty($video_url))
                    {
                        aiomatic_log_to_file('Empty Video URL Submitted: ' . $video_url);
                        unset($url_list_lines[$current_index]);
                        break;
                    }
                    
                    $za_video_page = '';
                    $returned_caption = '';
                    $ch  = curl_init();
                    if ($ch !== FALSE) 
                    {
                        if (isset($aiomatic_Main_Settings['proxy_url']) && $aiomatic_Main_Settings['proxy_url'] != '' && $aiomatic_Main_Settings['proxy_url'] != 'disable' && $aiomatic_Main_Settings['proxy_url'] != 'disabled') {
                            $prx = explode(',', $aiomatic_Main_Settings['proxy_url']);
                            $randomness = array_rand($prx);
                            curl_setopt( $ch, CURLOPT_PROXY, trim($prx[$randomness]));
                            if (isset($aiomatic_Main_Settings['proxy_auth']) && $aiomatic_Main_Settings['proxy_auth'] != '') 
                            {
                                $prx_auth = explode(',', $aiomatic_Main_Settings['proxy_auth']);
                                if(isset($prx_auth[$randomness]) && trim($prx_auth[$randomness]) != '')
                                {
                                    curl_setopt( $ch, CURLOPT_PROXYUSERPWD, trim($prx_auth[$randomness]));
                                }
                            }
                        }
                        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                        if (isset($aiomatic_Main_Settings['max_timeout']) && $aiomatic_Main_Settings['max_timeout'] != '')
                        {
                            $ztime = intval($aiomatic_Main_Settings['max_timeout']);
                        }
                        else
                        {
                            $ztime = 300;
                        }
                        if (isset($aiomatic_Main_Settings['youtube_cookies']) && $aiomatic_Main_Settings['youtube_cookies'] != '')
                        {
                            curl_setopt($ch, CURLOPT_COOKIE, $aiomatic_Main_Settings['youtube_cookies']);
                        }
                        curl_setopt($ch, CURLOPT_TIMEOUT, $ztime);
                        curl_setopt($ch, CURLOPT_HTTPGET, 1);
                        curl_setopt($ch, CURLOPT_REFERER, get_site_url());
                        curl_setopt($ch, CURLOPT_URL, $video_url);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                        $za_video_page = curl_exec($ch);
                        if($za_video_page === false)
                        {
                            aiomatic_log_to_file('Failed to download video URL: ' . $video_url);
                        }
                        curl_close($ch);
                    }
                    else
                    {
                        aiomatic_log_to_file('Failed to init curl in video listing: ' . $video_url);
                    }
                    $post_title = '';
                    $post_desc = '';
                    if($za_video_page !== false)
                    {
                        preg_match_all('#<meta name="title" content="([^"]*?)">#i', $za_video_page, $zmatches);
                        if(isset($zmatches[1][0]))
                        {
                            $post_title = $zmatches[1][0];
                        }
                        else
                        {
                            preg_match_all('#<title>([^"]*?) - YouTube<\/title>#i', $za_video_page, $zmatches);
                            if(isset($zmatches[1][0]))
                            {
                                $post_title = $zmatches[1][0];
                            }
                            else
                            {
                                preg_match_all('#<meta property="og:title" content="([^"]*?)">#i', $za_video_page, $zmatches);
                                if(isset($zmatches[1][0]))
                                {
                                    $post_title = $zmatches[1][0];
                                }
                                else
                                {
                                    preg_match_all('#<meta property="twitter:title" content="([^"]*?)">#i', $za_video_page, $zmatches);
                                    if(isset($zmatches[1][0]))
                                    {
                                        $post_title = $zmatches[1][0];
                                    }
                                    else
                                    {
                                        preg_match_all('#<meta itemprop="name" content="([^"]*?)">#i', $za_video_page, $zmatches);
                                        if(isset($zmatches[1][0]))
                                        {
                                            $post_title = $zmatches[1][0];
                                        }
                                    }
                                }
                            }
                        }
                        preg_match_all('#"description":{"simpleText":"([^"]*?)"#i', $za_video_page, $zmatches);
                        if(isset($zmatches[1][0]))
                        {
                            $post_desc = $zmatches[1][0];
                        }
                        else
                        {
                            preg_match_all('#"attributedDescription":{"content":"([^"]*?)"#i', $za_video_page, $zmatches);
                            if(isset($zmatches[1][0]))
                            {
                                $post_desc = $zmatches[1][0];
                            }
                            else
                            {
                                preg_match_all('#"attributedDescriptionBodyText":{"content":"([^"]*?)"#i', $za_video_page, $zmatches);
                                if(isset($zmatches[1][0]))
                                {
                                    $post_desc = $zmatches[1][0];
                                }
                                else
                                {
                                    preg_match_all('#"shortDescription":"([^"]*?)"#i', $za_video_page, $zmatches);
                                    if(isset($zmatches[1][0]))
                                    {
                                        $post_desc = $zmatches[1][0];
                                    }
                                }
                            }
                        }
                        $video_id = '';
                        preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user|shorts)\/))([^\?&\"'>]+)/", $video_url, $amatches);
                        if(isset($amatches[1]))
                        {
                            $video_id = $amatches[1];
                        }
                        $caprez = false;
                        if(!empty($video_id))
                        {
                            try
                            {
                                $caprez = aiomatic_get_video_transcript($video_id);
                            }
                            catch(Exception $e)
                            {
                                try 
                                {
                                    $caprez = aiomatic_get_video_transcript_2($video_id);
                                } 
                                catch (Exception $e) 
                                {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('Failed to get transcript for video ID ' . $video_id . ': ' . $e->getMessage());
                                    }
                                }
                            }
                        }
                        if(is_array($caprez) && isset($caprez['text']))
                        {
                            $returned_caption = $caprez['text'];
                        }
                    }
                    if(empty($returned_caption))
                    {
                        aiomatic_log_to_file('[WARNING] Failed to find subtitles for video URL: ' . $video_url);
                        break;
                    }
                    if($max_caption != '')
                    {
                        $max_caption = intval($max_caption);
                        $returned_caption = aiomatic_substr($returned_caption, 0, $max_caption);
                    }
                    $youtube_thumb = '';
                    preg_match_all('#<link rel="image_src" href="([^"]*?)">#i', $za_video_page, $zmatches);
                    if(isset($zmatches[1][0]))
                    {
                        $youtube_thumb = $zmatches[1][0];
                    }
                    else
                    {
                        preg_match_all('#<meta property="og:image" content="([^"]*?)">#i', $za_video_page, $zmatches);
                        if(isset($zmatches[1][0]))
                        {
                            $youtube_thumb = $zmatches[1][0];
                        }
                        else
                        {
                            preg_match_all('#<meta name="twitter:image" content="([^"]*?)">#i', $za_video_page, $zmatches);
                            if(isset($zmatches[1][0]))
                            {
                                $youtube_thumb = $zmatches[1][0];
                            }
                            else
                            {
                                preg_match_all('#<link itemprop="thumbnailUrl" href="([^"]*?)">#i', $za_video_page, $zmatches);
                                if(isset($zmatches[1][0]))
                                {
                                    $youtube_thumb = $zmatches[1][0];
                                }
                            }
                        }
                    }
                    if($ai_titles == '1')
                    {
                        if($title_prompt != '')
                        {
                            if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                            {
                                $title_prompt_arr = preg_split('/\r\n|\r|\n/', $title_prompt);
                                $my_title_prompt = $title_prompt_arr[array_rand($title_prompt_arr)];
                            }
                            else
                            {
                                $my_title_prompt = $title_prompt;
                            }
                            $zatitle_prompt = aiomatic_replace_youtube($my_title_prompt, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                            if(stristr($run_regex_on, 'title') !== false)
                            {
                                if ($strip_by_regex_prompts !== '')
                                {
                                    $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                    $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                    $xcnt = 0;
                                    foreach($xstrip_by_regex as $sbr)
                                    {
                                        if(isset($xreplace_regex[$xcnt]))
                                        {
                                            $repreg = $xreplace_regex[$xcnt];
                                        }
                                        else
                                        {
                                            $repreg = '';
                                        }
                                        $xcnt++;
                                        $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $zatitle_prompt);
                                        if($temp_cont !== NULL)
                                        {
                                            $zatitle_prompt = $temp_cont;
                                        }
                                    }
                                }
                            }
                            if($zatitle_prompt != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating title based on YouTube video'));
                                $written = aiomatic_write_content($zatitle_prompt, $topic_title_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, true, false, 'title', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate title!');
                                    if($auto == 1)
                                    {
                                        aiomatic_clearFromList($param, $type);
                                    }
                                    return 'fail';
                                }
                                else
                                {
                                    $written = ucfirst(trim(trim($written), '.'));
                                    $post_title = $written;
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed title prompt. Nothing to do.');
                                if($auto == 1)
                                {
                                    aiomatic_clearFromList($param, $type);
                                }
                                return 'fail';
                            }
                        }
                    }
                    if (strpos($post_title, '%%') === false)
                    {
                        if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                        {
                            $xposts = get_posts(
                                array(
                                    'post_type'              => $post_type,
                                    'title'                  => html_entity_decode($post_title),
                                    'post_status'            => 'any',
                                    'numberposts'            => 1,
                                    'update_post_term_cache' => false,
                                    'update_post_meta_cache' => false,           
                                    'orderby'                => 'post_date ID',
                                    'order'                  => 'ASC',
                                )
                            );
                            if ( ! empty( $xposts ) ) {
                                $zap = $xposts[0];
                            } else {
                                $zap = null;
                            }
                            if($zap !== null)
                            {
                                if($overwrite_existing)
                                {
                                    $update_post_id = $zap->ID;
                                }
                                else
                                {
                                    aiomatic_log_to_file('Post with specified title found to be existing, skipping it: ' . $post_title);
                                    unset($url_list_lines[$current_index]);
                                    continue;
                                }
                            }
                        }
                        $new_post_title = $post_title;
                    }
                    else
                    {
                        $new_post_title = $post_title;
                        $new_post_title = aiomatic_replaceContentShortcodes($new_post_title, $img_attr, $ai_command);
                        if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                        {
                            $xposts = get_posts(
                                array(
                                    'post_type'              => $post_type,
                                    'title'                  => html_entity_decode($new_post_title),
                                    'post_status'            => 'any',
                                    'numberposts'            => 1,
                                    'update_post_term_cache' => false,
                                    'update_post_meta_cache' => false,           
                                    'orderby'                => 'post_date ID',
                                    'order'                  => 'ASC',
                                )
                            );
                            if ( ! empty( $xposts ) ) {
                                $zap = $xposts[0];
                            } else {
                                $zap = null;
                            }
                            if($zap !== null)
                            {
                                if($overwrite_existing)
                                {
                                    $update_post_id = $zap->ID;
                                }
                                else
                                {
                                    aiomatic_log_to_file('Post with specified title already published, skipping it: ' . $new_post_title);
                                    unset($url_list_lines[$current_index]);
                                    continue;
                                }
                            }
                        }
                    }
                    $post_sections = '';
                    $current_section = '';
                    $headings_arr_copy = $headings_arr;
                    $added_img_list = array();
                    $raw_img_list = array();
                    $full_result_list = array();
                    $added_vid_list = array();
                    $added_images = 0;
                    $added_videos = 0;
                    $heading_results = array();
                    if(empty($post_title))
                    {
                        aiomatic_log_to_file('Empty post title submitted, nothing to do!');
                        continue;
                    }
                    if(stristr($run_regex_on, 'sections') !== false)
                    {
                        if ($strip_by_regex_prompts !== '')
                        {
                            $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                            $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                            $xcnt = 0;
                            foreach($xstrip_by_regex as $sbr)
                            {
                                if(isset($xreplace_regex[$xcnt]))
                                {
                                    $repreg = $xreplace_regex[$xcnt];
                                }
                                else
                                {
                                    $repreg = '';
                                }
                                $xcnt++;
                                $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $sections_prompt);
                                if($temp_cont !== NULL)
                                {
                                    $sections_prompt = $temp_cont;
                                }
                            }
                        }
                    }
                    if($sections_prompt != '' && $post_sections_list == '')
                    {
                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                        {
                            $sections_prompt_arr = preg_split('/\r\n|\r|\n/', $sections_prompt);
                            $my_post_section = $sections_prompt_arr[array_rand($sections_prompt_arr)];
                        }
                        else
                        {
                            $my_post_section = $sections_prompt;
                        }
                        $my_post_section = aiomatic_replace_youtube($my_post_section, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                        if($my_post_section != '')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating tags'));
                            $written = aiomatic_write_content($my_post_section, $topic_sections_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, true, false, 'sections', 'user', $assistant_id, $thread_id, $store_data);
                            if($written === false)
                            {
                                aiomatic_log_to_file('Failed to generate sections!');
                                if($auto == 1)
                                {
                                    aiomatic_clearFromList($param, $type);
                                }
                                return 'fail';
                            }
                            else
                            {
                                $post_sections = $written;
                            }
                        }
                        else
                        {
                            aiomatic_log_to_file('Empty processed sections prompt. Nothing to do.');
                            if($auto == 1)
                            {
                                aiomatic_clearFromList($param, $type);
                            }
                            return 'fail';
                        }
                    }
                    else
                    {
                        if($post_sections_list != '')
                        {
                            $post_sections = $spintax->Parse($post_sections_list);
                        }
                    }
                    $post_sections = aiomatic_filter_sections($post_sections);
                    $new_post_content = '';
                    if(stristr($run_regex_on, 'intro') !== false)
                    {
                        if ($strip_by_regex_prompts !== '')
                        {
                            $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                            $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                            $xcnt = 0;
                            foreach($xstrip_by_regex as $sbr)
                            {
                                if(isset($xreplace_regex[$xcnt]))
                                {
                                    $repreg = $xreplace_regex[$xcnt];
                                }
                                else
                                {
                                    $repreg = '';
                                }
                                $xcnt++;
                                $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $intro_prompt);
                                if($temp_cont !== NULL)
                                {
                                    $intro_prompt = $temp_cont;
                                }
                            }
                        }
                    }
                    if($intro_prompt != '')
                    {
                        $my_intro_prompt = $intro_prompt;
                        $my_intro_prompt = aiomatic_replace_youtube($my_intro_prompt, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                        if($my_intro_prompt != '')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating YouTube based intro'));
                            $written = aiomatic_write_content($my_intro_prompt, $topic_intro_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'intro', 'user', $assistant_id, $thread_id, $store_data);
                            if($written === false)
                            {
                                aiomatic_log_to_file('Failed to generate intro for section: ' . $current_section);
                                continue;
                            }
                            else
                            {
                                if($new_post_content != '')
                                {
                                    $new_post_content .= ' ';
                                }
                                $new_post_content .= $written;
                            }
                        }
                        else
                        {
                            aiomatic_log_to_file('Empty processed intro prompt. Nothing to do.');
                        }
                    }
                    if(stristr($topic_images_bck, '-') !== false)
                    {
                        preg_match('/\s*(\d+)\s*-\s*(\d+)\s*/', $topic_images_bck, $matches);
                        if(isset($matches[2]) && $matches[2] != '' && isset($matches[1]) && $matches[1] != '')
                        {
                            $txmin = intval($matches[1]);
                            $txmax = intval($matches[2]);
                            $topic_images = mt_rand($txmin, $txmax);
                        }
                        else
                        {
                            $topic_images = $topic_images_bck;
                        }
                    }
                    if($heading_image_loc != 'top')
                    {
                        if(!isset($aiomatic_Main_Settings['no_intro_image']) || trim($aiomatic_Main_Settings['no_intro_image']) != 'on')
                        {
                            if($topic_images != '' && is_numeric($topic_images) && $topic_images > $added_images)
                            {
                                if($new_post_content !== '')
                                {
                                    $the_image_prompt = $post_title;
                                    if($enable_ai_images != '0' && $enable_ai_images != '3')
                                    {
                                        $ai_command_image = $orig_ai_command_image;
                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                        {
                                            $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                            $ai_command_image = array_filter($ai_command_image);
                                            if(count($ai_command_image) > 0)
                                            {
                                                $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                            }
                                            else
                                            {
                                                $ai_command_image = '';
                                            }
                                        }
                                        $za_post_title = aiomatic_replaceContentShortcodes($the_image_prompt, $img_attr, $ai_command);
                                        $ai_command_image = aiomatic_replacetopics($ai_command_image, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                        if(!empty($ai_command_image))
                                        {
                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        }
                                        else
                                        {
                                            $ai_command_image = trim(strip_tags($the_image_prompt));
                                        }
                                        $ai_command_image = trim($ai_command_image);
                                        if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                        {
                                            $txt_content = aiomatic_get_web_page($ai_command_image);
                                            if ($txt_content !== FALSE) 
                                            {
                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                $txt_content = array_filter($txt_content);
                                                if(count($txt_content) > 0)
                                                {
                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                    if(trim($txt_content) != '') 
                                                    {
                                                        $ai_command_image = $txt_content;
                                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                }
                                            }
                                        }
                                        if(empty($ai_command_image))
                                        {
                                            aiomatic_log_to_file('Empty API image seed expression provided!');
                                        }
                                        else
                                        {
                                            
                                            
                                            $the_image_prompt = $ai_command_image;
                                        }
                                    }
                                    $new_img = aiomatic_get_royalty_free_image($the_image_prompt, $enable_ai_images, $image_size, $images_arr, $token, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $custom_shortcodes, $global_prepend, $global_append, $image_url, $attached_id, $raw_img_list, $default_cat_list, $image_model);
                                    if(!empty($attached_id))
                                    {
                                        $additional_attachments[] = $attached_id;
                                    }
                                    if($new_img !== false && !in_array($new_img, $added_img_list))
                                    {
                                        $new_post_content .= '<br/><img class="yimage_class" src="' . $new_img . '" alt="' . esc_attr($post_title) . '"><br/>';
                                        $added_img_list[] = $new_img;
                                        $added_images++;
                                    }
                                }
                            }
                        }
                    }
                    if($title_outro != '')
                    {
                        $my_title_outro = $title_outro;
                        $my_title_outro = aiomatic_replace_youtube($my_title_outro, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                        $my_title_outro = $spintax->Parse(trim($my_title_outro));     
                    }
                    if(!empty($title_toc))
                    {
                        $my_title_toc = $title_toc;
                        $my_title_toc = aiomatic_replace_youtube($my_title_toc, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                        $my_title_toc = $spintax->Parse(trim($my_title_toc));
                    }
                    if($title_qa != '')
                    {
                        $my_title_qa = $title_qa;
                        $my_title_qa = aiomatic_replace_youtube($my_title_qa, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                        $my_title_qa = $spintax->Parse(trim($my_title_qa));
                    }
                    if($content_prompt != '')
                    {
                        if($single_content_call == '1')
                        {
                            $last_section_content = '';
                            $current_section = $post_sections;
                            $my_post_content = $content_prompt;
                            $my_post_content = aiomatic_replace_youtube($my_post_content, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                            $my_post_content = str_replace('%%article_so_far%%', $new_post_content, $my_post_content);
                            $my_post_content = str_replace('%%last_section_content%%', $last_section_content, $my_post_content);
                            if(stristr($run_regex_on, 'content') !== false)
                            {
                                if ($strip_by_regex_prompts !== '')
                                {
                                    $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                    $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                    $xcnt = 0;
                                    foreach($xstrip_by_regex as $sbr)
                                    {
                                        if(isset($xreplace_regex[$xcnt]))
                                        {
                                            $repreg = $xreplace_regex[$xcnt];
                                        }
                                        else
                                        {
                                            $repreg = '';
                                        }
                                        $xcnt++;
                                        $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_post_content);
                                        if($temp_cont !== NULL)
                                        {
                                            $my_post_content = $temp_cont;
                                        }
                                    }
                                }
                            }
                            if($my_post_content != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating YouTube based topic list'));
                                $written = aiomatic_write_content($my_post_content, $topic_content_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'content', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate topic list for section: ' . $current_section);
                                    continue;
                                }
                                else
                                {
                                    if($new_post_content != '')
                                    {
                                        $new_post_content .= ' ';
                                    }
                                    $new_img_arr = array();
                                    if($topic_images != '' && is_numeric($topic_images) && intval($topic_images) - 2 > $added_images)
                                    {
                                        $howmore = intval($topic_images) - 2;
                                        for($cont = 0; $cont < $howmore; $cont++)
                                        {
                                            if($search_query_repetition == '1')
                                            {
                                                $the_image_prompt = $post_title;
                                            }
                                            else
                                            {
                                                $the_image_prompt = $current_section;
                                            }
                                            if($enable_ai_images != '0' && $enable_ai_images != '3')
                                            {
                                                $ai_command_image = $orig_ai_command_image;
                                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                                {
                                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                                    $ai_command_image = array_filter($ai_command_image);
                                                    if(count($ai_command_image) > 0)
                                                    {
                                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                                    }
                                                    else
                                                    {
                                                        $ai_command_image = '';
                                                    }
                                                }
                                                $za_post_title = aiomatic_replaceContentShortcodes($the_image_prompt, $img_attr, $ai_command);
                                                $ai_command_image = aiomatic_replacetopics($ai_command_image, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                if(!empty($ai_command_image))
                                                {
                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                                else
                                                {
                                                    $ai_command_image = trim(strip_tags($the_image_prompt));
                                                }
                                                $ai_command_image = trim($ai_command_image);
                                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                                {
                                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                                    if ($txt_content !== FALSE) 
                                                    {
                                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                        $txt_content = array_filter($txt_content);
                                                        if(count($txt_content) > 0)
                                                        {
                                                            $txt_content = $txt_content[array_rand($txt_content)];
                                                            if(trim($txt_content) != '') 
                                                            {
                                                                $ai_command_image = $txt_content;
                                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                            }
                                                        }
                                                    }
                                                }
                                                if(empty($ai_command_image))
                                                {
                                                    aiomatic_log_to_file('Empty API image seed expression provided!');
                                                }
                                                else
                                                {
                                                    
                                                    
                                                    $the_image_prompt = $ai_command_image;
                                                }
                                            }
                                            $new_img = aiomatic_get_royalty_free_image($the_image_prompt, $enable_ai_images, $image_size, $images_arr, $token, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $custom_shortcodes, $global_prepend, $global_append, $image_url, $attached_id, $raw_img_list, $default_cat_list, $image_model);
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                            if($new_img !== false && !in_array($new_img, $added_img_list))
                                            {
                                                $new_post_content .= '<br/><img class="zimage_class" src="' . $new_img . '" alt="' . esc_attr($current_section) . '"><br/>';
                                                $added_img_list[] = $new_img;
                                                $new_img_arr[] = $new_img;
                                                $added_images++;
                                            }
                                        } 
                                    }
                                    if(count($new_img_arr) > 0)
                                    {
                                        $written_arr = preg_split("/\r\n|\n|\r/", $written);
                                        if(count($written_arr) > 1)
                                        {
                                            foreach($new_img_arr as $new_img_x)
                                            {
                                                array_splice($written_arr, wp_rand(0, count($written_arr)), 0, '<br/><img src="' . $new_img_x . '">');
                                            }
                                            $written = implode('\r\n', $written_arr);
                                        }
                                    }
                                    $new_vid_arr = array();
                                    $new_post_content .= $written;
                                    if($topic_videos == '1')
                                    {
                                        preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user|shorts)\/))([^\?&\"'>]+)/", $video_url, $amatches);
                                        if(isset($amatches[1]))
                                        {
                                            $video_id = $amatches[1];
                                            if (isset($aiomatic_Main_Settings['player_width']) && $aiomatic_Main_Settings['player_width'] !== '') {
                                                $vwidth = esc_attr($aiomatic_Main_Settings['player_width']);
                                            }
                                            else
                                            {
                                                $vwidth = 580;
                                            }
                                            if (isset($aiomatic_Main_Settings['player_height']) && $aiomatic_Main_Settings['player_height'] !== '') {
                                                $vheight = esc_attr($aiomatic_Main_Settings['player_height']);
                                            }
                                            else
                                            {
                                                $vheight = 380;
                                            }
                                            $new_post_content .= '<br/><br/><div class="automaticx-video-container"><iframe allow="autoplay" width="' . $vwidth . '" height="' . $vheight . '" src="https://www.youtube.com/embed/' . $video_id . '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>';
                                            $added_vid_list[] = $video_id;
                                            $new_vid_arr[] = $new_img;
                                            $added_videos++;
                                        }
                                    }
                                    if(count($new_vid_arr) > 0)
                                    {
                                        $written_arr = preg_split("/\r\n|\n|\r/", $written);
                                        if(count($written_arr) > 1)
                                        {
                                            foreach($new_vid_arr as $new_img_x)
                                            {
                                                array_splice($written_arr, wp_rand(0, count($written_arr)), 0, '<br/><img src="' . $new_img_x . '">');
                                            }
                                            $written = implode('\r\n', $written_arr);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed topic prompt. Nothing to do.');
                            }
                        }
                        else
                        {
                            if($post_sections != '')
                            {
                                $post_sections_arr = preg_split('/\r\n|\r|\n/', $post_sections);
                            }
                            else
                            {
                                $post_sections_arr = array();
                            }
                            $toc = '';
                            if($enable_toc == '1')
                            {
                                if(!empty($title_toc))
                                {
                                    if($my_title_toc != '')
                                    {
                                        $toc .= '<h2>' . $my_title_toc . '</h2>';
                                    }
                                }
                                $toc .= '<ul class="toc-class">';
                                foreach($post_sections_arr as $current_section)
                                {
                                    if(!empty($current_section))
                                    {
                                        $toc .= '<li><a href="#' . sanitize_title($current_section) . '">' . $current_section . '</a></li>';
                                    }
                                }
                                if($title_qa != '')
                                {
                                    if($my_title_qa != '')
                                    {
                                        if($qa_prompt != '' && $enable_qa == '1')
                                        {
                                            $toc .= '<li><a href="#qa">' . $my_title_qa . '</a></li>';
                                        }
                                    }
                                }
                                if($title_outro != '')
                                {
                                    if($my_title_outro != '')
                                    {
                                        if($outro_prompt != '')
                                        {
                                            $toc .= '<li><a href="#outro">' . $my_title_outro . '</a></li>';
                                        }
                                    }
                                }
                                $toc .= '</ul>';
                                $new_post_content .= '<br/>' . $toc . '<br/>';
                            }
                            $section_id = 1;
                            $last_section_content = '';
                            foreach($post_sections_arr as $current_section)
                            {
                                $current_section = trim($current_section);
                                $current_section = trim($current_section, '.;');
                                if(empty($current_section))
                                {
                                    continue;
                                }
                                $my_post_content = $content_prompt;
                                $my_post_content = aiomatic_replace_youtube($my_post_content, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                                $my_post_content = str_replace('%%article_so_far%%', $new_post_content, $my_post_content);
                                $my_post_content = str_replace('%%last_section_content%%', $last_section_content, $my_post_content);
                                if(stristr($run_regex_on, 'content') !== false)
                                {
                                    if ($strip_by_regex_prompts !== '')
                                    {
                                        $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                        $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                        $xcnt = 0;
                                        foreach($xstrip_by_regex as $sbr)
                                        {
                                            if(isset($xreplace_regex[$xcnt]))
                                            {
                                                $repreg = $xreplace_regex[$xcnt];
                                            }
                                            else
                                            {
                                                $repreg = '';
                                            }
                                            $xcnt++;
                                            $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_post_content);
                                            if($temp_cont !== NULL)
                                            {
                                                $my_post_content = $temp_cont;
                                            }
                                        }
                                    }
                                }
                                if($my_post_content != '')
                                {
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating YouTube based content for section ID #' . $section_id));
                                    $section_id++;
                                    $written = aiomatic_write_content($my_post_content, $topic_content_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'content', 'user', $assistant_id, $thread_id, $store_data);
                                    if($written === false)
                                    {
                                        aiomatic_log_to_file('Failed to generate content for section: ' . $current_section);
                                        continue;
                                    }
                                    else
                                    {
                                        if($heading_image_loc == 'top')
                                        {
                                            if($img_all_headings == '1' || ($topic_images != '' && is_numeric($topic_images) && $topic_images > $added_images))
                                            {
                                                if($new_post_content !== '')
                                                {
                                                    if($search_query_repetition == '1')
                                                    {
                                                        $the_image_prompt = $post_title;
                                                    }
                                                    else
                                                    {
                                                        $the_image_prompt = $current_section;
                                                    }
                                                    if($enable_ai_images != '0' && $enable_ai_images != '3')
                                                    {
                                                        $ai_command_image = $orig_ai_command_image;
                                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                                        {
                                                            $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                                            $ai_command_image = array_filter($ai_command_image);
                                                            if(count($ai_command_image) > 0)
                                                            {
                                                                $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                                            }
                                                            else
                                                            {
                                                                $ai_command_image = '';
                                                            }
                                                        }
                                                        $za_post_title = aiomatic_replaceContentShortcodes($the_image_prompt, $img_attr, $ai_command);
                                                        $ai_command_image = aiomatic_replacetopics($ai_command_image, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                        if(!empty($ai_command_image))
                                                        {
                                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                        }
                                                        else
                                                        {
                                                            $ai_command_image = trim(strip_tags($the_image_prompt));
                                                        }
                                                        $ai_command_image = trim($ai_command_image);
                                                        if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                                        {
                                                            $txt_content = aiomatic_get_web_page($ai_command_image);
                                                            if ($txt_content !== FALSE) 
                                                            {
                                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                                $txt_content = array_filter($txt_content);
                                                                if(count($txt_content) > 0)
                                                                {
                                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                                    if(trim($txt_content) != '') 
                                                                    {
                                                                        $ai_command_image = $txt_content;
                                                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        if(empty($ai_command_image))
                                                        {
                                                            aiomatic_log_to_file('Empty API image seed expression provided!');
                                                        }
                                                        else
                                                        {
                                                            
                                                            
                                                            $the_image_prompt = $ai_command_image;
                                                        }
                                                    }
                                                    $new_img = aiomatic_get_royalty_free_image($the_image_prompt, $enable_ai_images, $image_size, $images_arr, $token, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $custom_shortcodes, $global_prepend, $global_append, $image_url, $attached_id, $raw_img_list, $default_cat_list, $image_model);
                                                    if(!empty($attached_id))
                                                    {
                                                        $additional_attachments[] = $attached_id;
                                                    }
                                                    if($new_img !== false && !in_array($new_img, $added_img_list))
                                                    {
                                                        $new_post_content .= '<br/><img class="qimage_class" src="' . $new_img . '" alt="' . esc_attr($current_section) . '"><br/>';
                                                        $added_img_list[] = $new_img;
                                                        $added_images++;
                                                    }
                                                }
                                            }
                                        }
                                        $written = str_ireplace($current_section, '', $written);
                                        preg_match_all('#\d+\.\s*([\s\S]*)#', $current_section, $mxatches);
                                        if(isset($mxatches[1][0]))
                                        {
                                            $written = str_ireplace(trim($mxatches[1][0]), '', $written);
                                            $written = str_ireplace(str_replace(['"', '\''], '', $mxatches[1][0]), '', $written);
                                        }
                                        $written = str_ireplace('<h2></h2>', '', $written);
                                        $written = str_ireplace('<h3></h3>', '', $written);
                                        if($sections_role == 'h2')
                                        {
                                            $new_post_content .= '<h2 id="' . sanitize_title($current_section) . '">' . $current_section . '</h2>';
                                        }
                                        elseif($sections_role == 'h3')
                                        {
                                            $new_post_content .= '<h3 id="' . sanitize_title($current_section) . '">' . $current_section . '</h3>';
                                        }
                                        elseif($sections_role == 'b')
                                        {
                                            $new_post_content .= '<b id="' . sanitize_title($current_section) . '">' . $current_section . '</b>';
                                        }
                                        elseif($sections_role == 'i')
                                        {
                                            $new_post_content .= '<i id="' . sanitize_title($current_section) . '">' . $current_section . '</i>';
                                        }
                                        elseif($sections_role == 'bi')
                                        {
                                            $new_post_content .= '<b><i id="' . sanitize_title($current_section) . '">' . $current_section . '</i></b>';
                                        }
                                        elseif($sections_role == 'p')
                                        {
                                            $new_post_content .= '<p id="' . sanitize_title($current_section) . '">' . $current_section . '</p>';
                                        }
                                        elseif($sections_role == 'x')
                                        {
                                            $new_post_content .= '<br/><span id="' . sanitize_title($current_section) . '">' . $current_section . '</span><br/>';
                                        }
                                        if($heading_image_loc == 'heading')
                                        {
                                            if($img_all_headings == '1' || ($topic_images != '' && is_numeric($topic_images) && $topic_images > $added_images))
                                            {
                                                if($new_post_content !== '')
                                                {
                                                    if($search_query_repetition == '1')
                                                    {
                                                        $the_image_prompt = $post_title;
                                                    }
                                                    else
                                                    {
                                                        $the_image_prompt = $current_section;
                                                    }
                                                    if($enable_ai_images != '0' && $enable_ai_images != '3')
                                                    {
                                                        $ai_command_image = $orig_ai_command_image;
                                                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                                        {
                                                            $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                                            $ai_command_image = array_filter($ai_command_image);
                                                            if(count($ai_command_image) > 0)
                                                            {
                                                                $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                                            }
                                                            else
                                                            {
                                                                $ai_command_image = '';
                                                            }
                                                        }
                                                        $za_post_title = aiomatic_replaceContentShortcodes($the_image_prompt, $img_attr, $ai_command);
                                                        $ai_command_image = aiomatic_replacetopics($ai_command_image, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                        if(!empty($ai_command_image))
                                                        {
                                                            $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                        }
                                                        else
                                                        {
                                                            $ai_command_image = trim(strip_tags($the_image_prompt));
                                                        }
                                                        $ai_command_image = trim($ai_command_image);
                                                        if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                                        {
                                                            $txt_content = aiomatic_get_web_page($ai_command_image);
                                                            if ($txt_content !== FALSE) 
                                                            {
                                                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                                $txt_content = array_filter($txt_content);
                                                                if(count($txt_content) > 0)
                                                                {
                                                                    $txt_content = $txt_content[array_rand($txt_content)];
                                                                    if(trim($txt_content) != '') 
                                                                    {
                                                                        $ai_command_image = $txt_content;
                                                                        $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        if(empty($ai_command_image))
                                                        {
                                                            aiomatic_log_to_file('Empty API image seed expression provided!');
                                                        }
                                                        else
                                                        {
                                                            
                                                            
                                                            $the_image_prompt = $ai_command_image;
                                                        }
                                                    }
                                                    $new_img = aiomatic_get_royalty_free_image($the_image_prompt, $enable_ai_images, $image_size, $images_arr, $token, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $custom_shortcodes, $global_prepend, $global_append, $image_url, $attached_id, $raw_img_list, $default_cat_list, $image_model);
                                                    if(!empty($attached_id))
                                                    {
                                                        $additional_attachments[] = $attached_id;
                                                    }
                                                    if($new_img !== false && !in_array($new_img, $added_img_list))
                                                    {
                                                        $new_post_content .= '<br/><img class="qimage_class" src="' . $new_img . '" alt="' . esc_attr($current_section) . '"><br/>';
                                                        $added_img_list[] = $new_img;
                                                        $added_images++;
                                                    }
                                                }
                                            }
                                        }
                                        $last_section_content = $written;
                                        $new_post_content .= $written;
                                    }
                                    if($heading_image_loc == 'bottom')
                                    {
                                        if($img_all_headings == '1' || ($topic_images != '' && is_numeric($topic_images) && $topic_images > $added_images))
                                        {
                                            if($new_post_content !== '')
                                            {
                                                if($search_query_repetition == '1')
                                                {
                                                    $the_image_prompt = $post_title;
                                                }
                                                else
                                                {
                                                    $the_image_prompt = $current_section;
                                                }
                                                if($enable_ai_images != '0' && $enable_ai_images != '3')
                                                {
                                                    $ai_command_image = $orig_ai_command_image;
                                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                                    {
                                                        $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                                        $ai_command_image = array_filter($ai_command_image);
                                                        if(count($ai_command_image) > 0)
                                                        {
                                                            $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                                        }
                                                        else
                                                        {
                                                            $ai_command_image = '';
                                                        }
                                                    }
                                                    $za_post_title = aiomatic_replaceContentShortcodes($the_image_prompt, $img_attr, $ai_command);
                                                    $ai_command_image = aiomatic_replacetopics($ai_command_image, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                    if(!empty($ai_command_image))
                                                    {
                                                        $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                    }
                                                    else
                                                    {
                                                        $ai_command_image = trim(strip_tags($the_image_prompt));
                                                    }
                                                    $ai_command_image = trim($ai_command_image);
                                                    if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                                    {
                                                        $txt_content = aiomatic_get_web_page($ai_command_image);
                                                        if ($txt_content !== FALSE) 
                                                        {
                                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                                            $txt_content = array_filter($txt_content);
                                                            if(count($txt_content) > 0)
                                                            {
                                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                                if(trim($txt_content) != '') 
                                                                {
                                                                    $ai_command_image = $txt_content;
                                                                    $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                                }
                                                            }
                                                        }
                                                    }
                                                    if(empty($ai_command_image))
                                                    {
                                                        aiomatic_log_to_file('Empty API image seed expression provided!');
                                                    }
                                                    else
                                                    {
                                                        
                                                        
                                                        $the_image_prompt = $ai_command_image;
                                                    }
                                                }
                                                $new_img = aiomatic_get_royalty_free_image($the_image_prompt, $enable_ai_images, $image_size, $images_arr, $token, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $custom_shortcodes, $global_prepend, $global_append, $image_url, $attached_id, $raw_img_list, $default_cat_list, $image_model);
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                                if($new_img !== false && !in_array($new_img, $added_img_list))
                                                {
                                                    $new_post_content .= '<br/><img class="qimage_class" src="' . $new_img . '" alt="' . esc_attr($current_section) . '"><br/>';
                                                    $added_img_list[] = $new_img;
                                                    $added_images++;
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty processed content prompt. Nothing to do.');
                                }
                            }
                        }
                    }
                    if($enable_qa == '1')
                    {
                        if($qa_prompt != '')
                        {
                            $my_qa_prompt = $qa_prompt;
                            $my_qa_prompt = aiomatic_replace_youtube($my_qa_prompt, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                            if(stristr($run_regex_on, 'qa') !== false)
                            {
                                if ($strip_by_regex_prompts !== '')
                                {
                                    $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                    $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                    $xcnt = 0;
                                    foreach($xstrip_by_regex as $sbr)
                                    {
                                        if(isset($xreplace_regex[$xcnt]))
                                        {
                                            $repreg = $xreplace_regex[$xcnt];
                                        }
                                        else
                                        {
                                            $repreg = '';
                                        }
                                        $xcnt++;
                                        $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_qa_prompt);
                                        if($temp_cont !== NULL)
                                        {
                                            $my_qa_prompt = $temp_cont;
                                        }
                                    }
                                }
                            }
                            if($my_qa_prompt != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating YouTube based qa'));
                                $written = aiomatic_write_content($my_qa_prompt, $topic_qa_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'qa', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate Q&A for topic: ' . $current_section);
                                    continue;
                                }
                                else
                                {
                                    if($new_post_content != '')
                                    {
                                        $new_post_content .= ' ';
                                    }
                                    if($my_title_qa !== '')
                                    {
                                        if($sections_role == 'h2')
                                        {
                                            $new_post_content .= '<h2 id="qa">' . $my_title_qa . '</h2>';
                                        }
                                        elseif($sections_role == 'h3')
                                        {
                                            $new_post_content .= '<h3 id="qa">' . $my_title_qa . '</h3>';
                                        }
                                        elseif($sections_role == 'b')
                                        {
                                            $new_post_content .= '<b id="qa">' . $my_title_qa . '</b>';
                                        }
                                        elseif($sections_role == 'i')
                                        {
                                            $new_post_content .= '<i id="qa">' . $my_title_qa . '</i>';
                                        }
                                        elseif($sections_role == 'bi')
                                        {
                                            $new_post_content .= '<b><i id="qa">' . $my_title_qa . '</i></b>';
                                        }
                                        elseif($sections_role == 'p')
                                        {
                                            $new_post_content .= '<p id="qa">' . $my_title_qa . '</p>';
                                        }
                                        elseif($sections_role == 'x')
                                        {
                                            $new_post_content .= '<br/><span id="qa">' . $my_title_qa . '</span><br/>';
                                        }
                                        else
                                        {
                                            $new_post_content .= '<br/>' . $my_title_qa . '<br/>';
                                        }
                                    }
                                    $new_post_content .= $written;
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed Q&A prompt. Nothing to do.');
                            }
                        }
                    }
                    if($outro_prompt != '')
                    {
                        $my_outro_prompt = $outro_prompt;
                        $my_outro_prompt = aiomatic_replace_youtube($my_outro_prompt, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                        if(stristr($run_regex_on, 'outro') !== false)
                        {
                            if ($strip_by_regex_prompts !== '')
                            {
                                $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                $xcnt = 0;
                                foreach($xstrip_by_regex as $sbr)
                                {
                                    if(isset($xreplace_regex[$xcnt]))
                                    {
                                        $repreg = $xreplace_regex[$xcnt];
                                    }
                                    else
                                    {
                                        $repreg = '';
                                    }
                                    $xcnt++;
                                    $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_outro_prompt);
                                    if($temp_cont !== NULL)
                                    {
                                        $my_outro_prompt = $temp_cont;
                                    }
                                }
                            }
                        }
                        if($my_outro_prompt != '')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating YouTube based outro'));
                            $written = aiomatic_write_content($my_outro_prompt, $topic_outro_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'outro', 'user', $assistant_id, $thread_id, $store_data);
                            if($written === false)
                            {
                                aiomatic_log_to_file('Failed to generate outro for section: ' . $current_section);
                                continue;
                            }
                            else
                            {
                                if($new_post_content != '')
                                {
                                    $new_post_content .= ' ';
                                }
                                if($title_outro !== '')
                                {
                                    if($my_title_outro != '')
                                    {
                                        if($sections_role == 'h2')
                                        {
                                            $new_post_content .= '<h2 id="outro">' . $my_title_outro . '</h2>';
                                        }
                                        elseif($sections_role == 'h3')
                                        {
                                            $new_post_content .= '<h3 id="outro">' . $my_title_outro . '</h3>';
                                        }
                                        elseif($sections_role == 'b')
                                        {
                                            $new_post_content .= '<b id="outro">' . $my_title_outro . '</b>';
                                        }
                                        elseif($sections_role == 'i')
                                        {
                                            $new_post_content .= '<i id="outro">' . $my_title_outro . '</i>';
                                        }
                                        elseif($sections_role == 'bi')
                                        {
                                            $new_post_content .= '<b><i id="outro">' . $my_title_outro . '</i></b>';
                                        }
                                        elseif($sections_role == 'p')
                                        {
                                            $new_post_content .= '<p id="outro">' . $my_title_outro . '</p>';
                                        }
                                        elseif($sections_role == 'x')
                                        {
                                            $new_post_content .= '<br/><span id="outro">' . $my_title_outro . '</span><br/>';
                                        }
                                        else
                                        {
                                            $new_post_content .= '<br/>' . $my_title_outro . '<br/>';
                                        }
                                    }
                                }
                                else
                                {
                                    $new_post_content .= '<br/><br/>';
                                }
                                $new_post_content .= $written;
                            }
                        }
                        else
                        {
                            aiomatic_log_to_file('Empty processed outro prompt. Nothing to do.');
                        }
                    }
                    if($topic_images != '' && is_numeric($topic_images) && $topic_images > $added_images)
                    {
                        if($new_post_content !== '')
                        {
                            $the_image_prompt = $post_title;
                            if($enable_ai_images != '0' && $enable_ai_images != '3')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $za_post_title = aiomatic_replaceContentShortcodes($the_image_prompt, $img_attr, $ai_command);
                                $ai_command_image = aiomatic_replacetopics($ai_command_image, $za_post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($the_image_prompt));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $the_image_prompt, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    $the_image_prompt = $ai_command_image;
                                }
                            }
                            $new_img = aiomatic_get_royalty_free_image($the_image_prompt, $enable_ai_images, $image_size, $images_arr, $token, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $custom_shortcodes, $global_prepend, $global_append, $image_url, $attached_id, $raw_img_list, $default_cat_list, $image_model);
                            if(!empty($attached_id))
                            {
                                $additional_attachments[] = $attached_id;
                            }
                            if($new_img !== false && !in_array($new_img, $added_img_list))
                            {
                                $new_post_content .= '<br/><img class="wimage_class" src="' . $new_img . '" alt="' . esc_attr($post_title) . '"><br/>';
                                $added_img_list[] = $new_img;
                                $added_images++;
                            }
                        }
                    }
                    if($topic_videos == '1')
                    {
                        preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user|shorts)\/))([^\?&\"'>]+)/", $video_url, $amatches);
                        if(isset($amatches[1]))
                        {
                            $video_id = $amatches[1];
                            if (isset($aiomatic_Main_Settings['player_width']) && $aiomatic_Main_Settings['player_width'] !== '') {
                                $vwidth = esc_attr($aiomatic_Main_Settings['player_width']);
                            }
                            else
                            {
                                $vwidth = 580;
                            }
                            if (isset($aiomatic_Main_Settings['player_height']) && $aiomatic_Main_Settings['player_height'] !== '') {
                                $vheight = esc_attr($aiomatic_Main_Settings['player_height']);
                            }
                            else
                            {
                                $vheight = 380;
                            }
                            $new_post_content .= '<br/><br/><div class="automaticx-video-container"><iframe allow="autoplay" width="' . $vwidth . '" height="' . $vheight . '" src="https://www.youtube.com/embed/' . $video_id . '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>';
                            $added_vid_list[] = $video_id;
                            $new_vid_arr[] = $new_img;
                            $added_videos++;
                        }
                    }
                    if($new_post_content == '')
                    {
                        aiomatic_log_to_file("Warning, empty post content because of empty content prompt!");
                    }

                    $new_post_excerpt = '';
                    $current_section = $post_sections;
                    if($excerpt_prompt != '')
                    {
                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                        {
                            $excerpt_prompt_arr = preg_split('/\r\n|\r|\n/', $excerpt_prompt);
                            $my_post_excerpt = $excerpt_prompt_arr[array_rand($excerpt_prompt_arr)];
                        }
                        else
                        {
                            $my_post_excerpt = $excerpt_prompt;
                        }
                        $my_post_excerpt = aiomatic_replace_youtube($my_post_excerpt, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                        if(stristr($run_regex_on, 'excerpt') !== false)
                        {
                            if ($strip_by_regex_prompts !== '')
                            {
                                $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                $xcnt = 0;
                                foreach($xstrip_by_regex as $sbr)
                                {
                                    if(isset($xreplace_regex[$xcnt]))
                                    {
                                        $repreg = $xreplace_regex[$xcnt];
                                    }
                                    else
                                    {
                                        $repreg = '';
                                    }
                                    $xcnt++;
                                    $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_post_excerpt);
                                    if($temp_cont !== NULL)
                                    {
                                        $my_post_excerpt = $temp_cont;
                                    }
                                }
                            }
                        }
                        if($my_post_excerpt != '')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating YouTube based excerpt'));
                            $written = aiomatic_write_content($my_post_excerpt, $topic_excerpt_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, true, false, 'excerpt', 'user', $assistant_id, $thread_id, $store_data);
                            if($written === false)
                            {
                                aiomatic_log_to_file('Failed to generate excerpt!');
                            }
                            else
                            {
                                $new_post_excerpt = $written;
                            }
                        }
                        else
                        {
                            aiomatic_log_to_file('Empty processed excerpt prompt. Nothing to do.');
                        }
                    }

                    $get_img = '';
                    if($royalty_free == '1')
                    {
                        if($enable_ai_images == '1')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = aiomatic_get_api_service($token, $image_model);
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    if (isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] == 'on')
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $aierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating AI image'));
                                    $get_img = aiomatic_generate_ai_image($token, 1, $ai_command_image, $image_size, 'featuredImage', $skip_this_copy, 0, $aierror, $image_model, $post_title);
                                    if($get_img !== false)
                                    {
                                        foreach($get_img as $tmpimg)
                                        {
                                            $get_img = $tmpimg;
                                            break;
                                        }
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate AI featured image: ' . $aierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '2')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Stability.AI';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating YouTube based Stable Diffusion image'));
                                    $get_img = aiomatic_generate_stability_image($ai_command_image, $height, $width, 'featuredStableImage', 0, false, $ierror, $skip_this_copy, false, '', 0);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img[1]);
                                        }
                                        if(is_array($get_img) && isset($get_img[1]))
                                        {
                                            $get_img = $get_img[1];
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Stability.AI featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '7')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Google';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    if (isset($aiomatic_Main_Settings['google_ai_image_model']) && trim($aiomatic_Main_Settings['google_ai_image_model']) != '') 
                                    {
                                        $model = trim($aiomatic_Main_Settings['google_ai_image_model']);
                                    }
                                    else
                                    {
                                        $model = AIMOGEN_GOOGLE_IMAGE_DEFAULT_MODEL;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating YouTube based Google image'));
                                    $get_img = aiomatic_generate_image_google($ai_command_image, $model, 'featuredGoogleImage', false, $ierror, false);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img[1]);
                                        }
                                        if(is_array($get_img) && isset($get_img[1]))
                                        {
                                            $get_img = $get_img[1];
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Google featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '4')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Midjourney';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1792x1024')
                                    {
                                        $width = '1792';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1024x1792')
                                    {
                                        $width = '1024';
                                        $height = '1792';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating YouTube based Midjourney image'));
                                    $get_img = aiomatic_generate_ai_image_midjourney($ai_command_image, $width, $height, 'featuredMidjourneyImage', $skip_this_copy, $ierror);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Midjourney featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '5')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Replicate';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1792x1024')
                                    {
                                        $width = '1792';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1024x1792')
                                    {
                                        $width = '1024';
                                        $height = '1792';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating YouTube based Replicate image'));
                                    $get_img = aiomatic_generate_replicate_image($ai_command_image, $width, $height, 'featuredReplicateImage', $skip_this_copy, $ierror);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Replicate featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '9')
                        {
                            $random_image = aiomatic_get_random_media_library_image();

                            if ($random_image !== false)
                            {
                                $get_img = $random_image['url'];

                                if (isset($aiomatic_Main_Settings['enable_detailed_logging']))
                                {
                                    aiomatic_log_to_file(
                                        'Random Media Library featured image selected for YouTube post: ' .
                                        $get_img .
                                        ' (ID: ' . $random_image['id'] . ')'
                                    );
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file(
                                    'Failed to find a random image in Media Library for YouTube featured image.'
                                );

                                $get_img = '';
                            }
                        }
                        elseif($enable_ai_images == '6')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Ideogram';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1792x1024')
                                    {
                                        $width = '1792';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1024x1792')
                                    {
                                        $width = '1024';
                                        $height = '1792';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating YouTube based Ideogram image'));
                                    $get_img = aiomatic_generate_ideogram_image($ai_command_image, $width, $height, 'featuredIdeogramImage', $skip_this_copy, $ierror);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Ideogram featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '8')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Cloudflare';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1792x1024')
                                    {
                                        $width = '1792';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1024x1792')
                                    {
                                        $width = '1024';
                                        $height = '1792';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating YouTube based Cloudflare image'));
                                    $get_img = aiomatic_generate_cloudflare_image($ai_command_image, $width, $height, 'featuredCloudflareImage', $skip_this_copy, $ierror);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Cloudflare featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '3')
                        {
                            if ($image_url != '') 
                            {
                                $replacement = str_replace(array('[', ']'), '', $query_words);
                                $image_url_temp = str_replace('%%item_title%%', $replacement, $image_url);
                                $image_url_temp = preg_replace_callback('#%%random_image\[([^\]]*?)\](\[\d+\])?%%#', function ($matches) {
                                    if(isset($matches[2]))
                                    {
                                        $chance = trim($matches[2], '[]');
                                    }
                                    else
                                    {
                                        $chance = '';
                                    }
                                    $arv = array();
                                    $my_img = aiomatic_get_random_image_google($matches[1], 0, 0, $chance, $arv);
                                    return $my_img;
                                }, $image_url_temp);
                                $img_rulx = $spintax->Parse(trim($image_url_temp));
                                $selected_img = aiomatic_select_ai_image($post_title, $img_rulx);
                                if($selected_img === false)
                                {
                                    $img_rulx = explode(',', $img_rulx);
                                    $img_rulx = trim($img_rulx[array_rand($img_rulx)]);
                                    if($img_rulx != '')
                                    {
                                        $get_img = $img_rulx;
                                    }
                                }
                                else
                                {
                                    $get_img = $selected_img;
                                }
                            }
                        }
                        else
                        {
                            $image_query_set = false;
                            $query_words = '';
                            $ai_command_image = '';
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                            }
                            if($ai_command_image != '')
                            {
                                $query_words = $ai_command_image;
                                $image_query = $ai_command_image;
                                $image_query_set = true;
                            }
                            if(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'textrazor')
                            {
                                if(isset($aiomatic_Main_Settings['textrazor_key']) && trim($aiomatic_Main_Settings['textrazor_key']) != '')
                                {
                                    try
                                    {
                                        if(!class_exists('TextRazor'))
                                        {
                                            require_once(dirname(__FILE__) . "/res/TextRazor.php");
                                        }
                                        TextRazorSettings::setApiKey(trim($aiomatic_Main_Settings['textrazor_key']));
                                        $textrazor = new TextRazor();
                                        $textrazor->addExtractor('entities');
                                        $response = $textrazor->analyze($image_query);
                                        if (isset($response['response']['entities'])) 
                                        {
                                            foreach ($response['response']['entities'] as $entity) 
                                            {
                                                $query_words = '';
                                                if(isset($entity['entityEnglishId']))
                                                {
                                                    $query_words = $entity['entityEnglishId'];
                                                }
                                                else
                                                {
                                                    $query_words = $entity['entityId'];
                                                }
                                                if($query_words != '')
                                                {
                                                    $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                                    if(!empty($attached_id))
                                                    {
                                                        $additional_attachments[] = $attached_id;
                                                    }
                                                    if(!empty($z_img))
                                                    {
                                                        $get_img = $z_img;
                                                        $go_local_image = false;
                                                        if(!function_exists('is_plugin_active'))
                                                        {
                                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                                        }
                                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                                        {
                                                            $go_local_image = true;
                                                        }
                                                        if($go_local_image == true)
                                                        {
                                                            $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, $query_words);
                                                            if(!empty($attached_id))
                                                            {
                                                                $additional_attachments[] = $attached_id;
                                                            }
                                                            if($localpath !== false)
                                                            {
                                                                $get_img = $localpath[0];
                                                            }
                                                        }
                                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                            aiomatic_log_to_file('Royalty Free Image Generated with help of TextRazor (kw: "' . $query_words . '"): ' . $z_img);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch(Exception $e)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Failed to search for keywords using TextRazor (2): ' . $e->getMessage());
                                        }
                                    }
                                }
                            }
                            elseif(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'openai')
                            {
                                if(isset($aiomatic_Main_Settings['keyword_prompts']) && trim($aiomatic_Main_Settings['keyword_prompts']) != '')
                                {
                                    if(isset($aiomatic_Main_Settings['keyword_model']) && $aiomatic_Main_Settings['keyword_model'] != '')
                                    {
                                        $kw_model = $aiomatic_Main_Settings['keyword_model'];
                                    }
                                    else
                                    {
                                        $kw_model = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                    }
                                    if(isset($aiomatic_Main_Settings['keyword_assistant_id']) && $aiomatic_Main_Settings['keyword_assistant_id'] != '')
                                    {
                                        $keyword_assistant_id = $aiomatic_Main_Settings['keyword_assistant_id'];
                                    }
                                    else
                                    {
                                        $keyword_assistant_id = '';
                                    }
                                    $title_ai_command = trim($aiomatic_Main_Settings['keyword_prompts']);
                                    $title_ai_command = str_replace('%%default_post_cats%%', $default_cat_list, $title_ai_command);
                                    $title_ai_command = str_replace('%%original_post_title%%', $post_title, $title_ai_command);
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $title_ai_command = preg_split('/\r\n|\r|\n/', $title_ai_command);
                                        $title_ai_command = array_filter($title_ai_command);
                                        if(count($title_ai_command) > 0)
                                        {
                                            $title_ai_command = $title_ai_command[array_rand($title_ai_command)];
                                        }
                                        else
                                        {
                                            $title_ai_command = '';
                                        }
                                    }
                                    $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                    if(!empty($title_ai_command))
                                    {
                                        $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    $title_ai_command = trim($title_ai_command);
                                    if (filter_var($title_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($title_ai_command, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($title_ai_command);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $title_ai_command = $txt_content;
                                                    $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                                    $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($title_ai_command))
                                    {
                                        aiomatic_log_to_file('Empty API keyword extractor seed expression provided!');
                                        $title_ai_command = 'Type the most relevant keyword, no other text before or after it, for a blog post titled:  ' . trim(strip_tags($post_title));
                                    }
                                    if(aiomatic_strlen($title_ai_command) > $max_seed_tokens * 4)
                                    {
                                        $title_ai_command = aiomatic_substr($title_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                                    }
                                    $title_ai_command = trim($title_ai_command);
                                    if(empty($title_ai_command))
                                    {
                                        aiomatic_log_to_file('Empty API title seed expression provided(3)! ' . print_r($title_ai_command, true));
                                    }
                                    else
                                    {
                                        $query_token_count = count(aiomatic_encode($title_ai_command));
                                        $available_tokens = aiomatic_compute_available_tokens($kw_model, $max_tokens, $title_ai_command, $query_token_count);
                                        if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                        {
                                            $string_len = aiomatic_strlen($title_ai_command);
                                            $string_len = $string_len / 2;
                                            $string_len = intval(0 - $string_len);
                                            $title_ai_command = aiomatic_substr($title_ai_command, 0, $string_len);
                                            $title_ai_command = trim($title_ai_command);
                                            $query_token_count = count(aiomatic_encode($title_ai_command));
                                            $available_tokens = $max_tokens - $query_token_count;
                                        }
                                        $aierror = '';
                                        $finish_reason = '';
                                        if(!empty($global_prepend))
                                        {
                                            $title_ai_command = $global_prepend . ' ' . $title_ai_command;
                                        }
                                        if(!empty($global_append))
                                        {
                                            $title_ai_command = $title_ai_command . ' ' . $global_append;
                                        }
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = aiomatic_get_api_service($token, $kw_model);
                                            aiomatic_log_to_file('Calling ' . $api_service . ' (' . $keyword_assistant_id . '/' . $kw_model . ')(' . $available_tokens . ') for title text: ' . $title_ai_command);
                                        }
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating keywords for image search'));
                                        $generated_text = aiomatic_generate_text($token, $kw_model, $title_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'keywordID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $keyword_assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                        if($generated_text === false)
                                        {
                                            aiomatic_log_to_file('Keyword generator error: ' . $aierror);
                                            $ai_title = '';
                                        }
                                        else
                                        {
                                            $ai_title = trim(trim($generated_text), '.');
                                            $xai_titles = explode(',', $ai_title);
                                            foreach($xai_titles as $query_words)
                                            {
                                                $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, trim($query_words), $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                                if(!empty($z_img))
                                                {
                                                    $get_img = $z_img;
                                                    $go_local_image = false;
                                                    if(!function_exists('is_plugin_active'))
                                                    {
                                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                                    }
                                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                                    {
                                                        $go_local_image = true;
                                                    }
                                                    if($go_local_image == true)
                                                    {
                                                        $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, $query_words);
                                                        if(!empty($attached_id))
                                                        {
                                                            $additional_attachments[] = $attached_id;
                                                        }
                                                        if($localpath !== false)
                                                        {
                                                            $get_img = $localpath[0];
                                                        }
                                                    }
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                        aiomatic_log_to_file('Royalty Free Image Generated with help of AI (kw: "' . $query_words . '"): ' . $z_img);
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = aiomatic_get_api_service($token, $kw_model);
                                            aiomatic_log_to_file('Successfully got API keyword result from ' . $api_service . ': ' . $ai_title);
                                        }
                                    }
                                }
                            }
                            if(empty($get_img))
                            {
                                if($image_query_set == true && !empty($image_query))
                                {
                                    $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $image_query, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                    if(!empty($attached_id))
                                    {
                                        $additional_attachments[] = $attached_id;
                                    }
                                    if($get_img == '' || $get_img === false)
                                    {
                                        if(isset($aiomatic_Main_Settings['bimage']) && $aiomatic_Main_Settings['bimage'] == 'on')
                                        {
                                            $keyword_class = new Aiomatic_keywords();
                                            $image_query = $keyword_class->keywords($image_query, 1);
                                            $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $image_query, $img_attr, $attached_id, 20, true, $raw_img_list, array(), $full_result_list);
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                        }
                                    }
                                }
                                if(empty($get_img))
                                {
                                    $keyword_class = new Aiomatic_keywords();
                                    $query_words = $keyword_class->keywords($post_title, 2);
                                    $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                    if(!empty($attached_id))
                                    {
                                        $additional_attachments[] = $attached_id;
                                    }
                                    if($get_img == '' || $get_img === false)
                                    {
                                        if(isset($aiomatic_Main_Settings['bimage']) && $aiomatic_Main_Settings['bimage'] == 'on')
                                        {
                                            $query_words = $keyword_class->keywords($post_title, 1);
                                            $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 20, true, $raw_img_list, array(), $full_result_list);
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                            if($get_img == '' || $get_img === false)
                                            {
                                                if(isset($aiomatic_Main_Settings['no_royalty_skip']) && $aiomatic_Main_Settings['no_royalty_skip'] == 'on')
                                                {
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                        aiomatic_log_to_file('Skipping importing because no royalty free image found.');
                                                    }
                                                    unset($post_title_lines[$current_index]);
                                                    continue;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if(isset($aiomatic_Main_Settings['no_royalty_skip']) && $aiomatic_Main_Settings['no_royalty_skip'] == 'on')
                                            {
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                    aiomatic_log_to_file('Skipping importing because no royalty free image found.');
                                                }
                                                unset($post_title_lines[$current_index]);
                                                continue;
                                            }
                                        }
                                    }
                                }
                                if(!empty($get_img))
                                {
                                    $go_local_image = false;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                    {
                                        $go_local_image = true;
                                    }
                                    if($go_local_image == true)
                                    {
                                        $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, '');
                                        if(!empty($attached_id))
                                        {
                                            $additional_attachments[] = $attached_id;
                                        }
                                        if($localpath !== false)
                                        {
                                            $get_img = $localpath[0];
                                        }
                                    }
                                }
                            }
                        }
                    }
                    elseif($royalty_free == '2')
                    {
                        $get_img = $youtube_thumb;
                    }
                    if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                    {
                        $already_spinned = '1';
                    }
                    $my_post                              = array();
                    $my_post['aiomatic_post_image']       = $get_img;
                    if($enable_ai_images == '2')
                    {
                        $my_post['aiomatic_local_image']      = '1';
                    }
                    else
                    {
                        $my_post['aiomatic_local_image']      = '0';
                    }
                    $my_post['aiomatic_enable_pingbacks'] = $enable_pingback;
                    $my_post['default_category']          = $default_category;
                    $my_post['post_type']                 = $post_type;
                    $my_post['comment_status']            = $accept_comments;
                    if (isset($aiomatic_Main_Settings['draft_first']) && $aiomatic_Main_Settings['draft_first'] != 'on')
                    {
                        if($post_status == 'publish')
                        {
                            $draft_me = true;
                            $my_post['post_status'] = 'draft';
                        }
                        else
                        {
                            $my_post['post_status']   = $post_status;
                        }
                    }
                    else
                    {
                        $my_post['post_status']               = $post_status;
                    }
                    if($user_name_type == 'rand')
                    {
                        $randid = aiomatic_display_random_user();
                        if($randid === false)
                        {
                            $my_post['post_author']               = aimogen_get_admin_user_id();
                        }
                        else
                        {
                            $my_post['post_author']               = $randid->ID;
                        }
                    }
                    else
                    {
                        $my_post['post_author']               = $post_user_name;
                    }
                    if($strip_title == '1')
                    {
                        $new_post_content = str_replace($post_title, '', $new_post_content);
                        $new_post_content = str_replace('<h2></h2>', '', $new_post_content);
                        $new_post_content = str_replace('<h3></h3>', '', $new_post_content);
                    }
                    if (isset($aiomatic_Main_Settings['swear_filter']) && $aiomatic_Main_Settings['swear_filter'] == 'on') 
                    {
                        require_once(dirname(__FILE__) . "/res/swear.php");
                        $new_post_content = aimogenpro_filterwords($new_post_content);
                    }
                    if(isset($aiomatic_Main_Settings['global_ban_words']) && $aiomatic_Main_Settings['global_ban_words'] != '') {
                        $continue    = false;
                        $aiomatic_Main_Settings['global_ban_words'] = trim(trim(trim($aiomatic_Main_Settings['global_ban_words']), ','));
                        $banned_list = explode(',', $aiomatic_Main_Settings['global_ban_words']);
                        foreach ($banned_list as $banned_word) {
                            if (stripos($new_post_content, trim($banned_word)) !== FALSE) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s content contains global banned word: ' . $banned_word);
                                }
                                $continue = true;
                                break;
                            }
                            if (stripos($post_title, trim($banned_word)) !== FALSE) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s title contains global banned word: ' . $banned_word);
                                }
                                $continue = true;
                                break;
                            }
                        }
                        if ($continue === true) {
                            continue;
                        }
                    }
                    if(isset($aiomatic_Main_Settings['global_req_words']) && $aiomatic_Main_Settings['global_req_words'] != '')
                    {
                        if(isset($aiomatic_Main_Settings['require_only_one']) && $aiomatic_Main_Settings['require_only_one'] == 'on')
                        {
                            $continue      = true;
                            $aiomatic_Main_Settings['global_req_words'] = trim(trim(trim($aiomatic_Main_Settings['global_req_words']), ','));
                            $required_list = explode(',', $aiomatic_Main_Settings['global_req_words']);
                            foreach ($required_list as $required_word) {
                                if (stripos($new_post_content, trim($required_word)) !== FALSE || stripos($post_title, trim($required_word)) !== FALSE) {
                                    $continue = false;
                                    break;
                                }
                            }
                            if ($continue === true) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s content doesn\'t contain global required words.');
                                }
                                continue;
                            }
                        }
                        else
                        {
                            $continue      = false;
                            $aiomatic_Main_Settings['global_req_words'] = trim(trim(trim($aiomatic_Main_Settings['global_req_words']), ','));
                            $required_list = explode(',', $aiomatic_Main_Settings['global_req_words']);
                            foreach ($required_list as $required_word) {
                                if (stripos($new_post_content, trim($required_word)) === FALSE && stripos($post_title, trim($required_word)) === FALSE) {
                                    $continue = true;
                                    break;
                                }
                            }
                            if ($continue === true) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s content doesn\'t contain global required words.');
                                }
                                continue;
                            }
                        }
                    }
                    $new_post_title = $post_title;
                    if (isset($aiomatic_Main_Settings['spin_what']) && $aiomatic_Main_Settings['spin_what'] === 'omni') 
                    {
                        $skip_spin = '1';
                    }
                    $arr = aiomatic_spin_and_translate($new_post_title, $new_post_content, '3', $skip_spin, $skip_translate);
                    if($arr[0] != $new_post_title)
                    {
                        $new_post_title = $arr[0];
                        if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                        {
                            $posts = get_posts(
                                array(
                                    'post_type'              => $post_type,
                                    'title'                  => html_entity_decode($new_post_title),
                                    'post_status'            => 'any',
                                    'numberposts'            => 1,
                                    'update_post_term_cache' => false,
                                    'update_post_meta_cache' => false,           
                                    'orderby'                => 'post_date ID',
                                    'order'                  => 'ASC',
                                )
                            );
                            if ( ! empty( $posts ) ) {
                                $zap = $posts[0];
                            } else {
                                $zap = null;
                            }
                            if($zap !== null)
                            {
                                if($overwrite_existing)
                                {
                                    $update_post_id = $zap->ID;
                                }
                                else
                                {
                                    aiomatic_log_to_file('Post with specified title already existing (after spin/translate), skipping it: ' . $new_post_title);
                                    unset($post_title_lines[$current_index]);
                                    continue;
                                }
                            }
                        }
                    }
                    $new_post_content            = $arr[1];
                    if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                    {
                        $already_spinned = '1';
                    }
                    if ($auto_categories == 'content') {
                        $extra_categories            = aiomatic_extractKeyWords($new_post_content);
                        $extra_categories            = implode(',', $extra_categories);
                    }
                    elseif ($auto_categories == 'title') {
                        $extra_categories            = aiomatic_extractKeyWords($new_post_title);
                        $extra_categories            = implode(',', $extra_categories);
                    }
                    elseif ($auto_categories == 'both') {
                        $extra_categories            = aiomatic_extractKeyWords($new_post_content);
                        $extra_categories            = implode(',', $extra_categories);
                        $extra_categories2            = aiomatic_extractKeyWords($new_post_title);
                        $extra_categories2            = implode(',', $extra_categories2);
                        if($extra_categories2 != '')
                        {
                            $extra_categories .= ',' . $extra_categories2;
                        }
                    }
                    elseif ($auto_categories == 'ai') 
                    {
                        $category_ai_command = $orig_ai_command_category;
                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                        {
                            $category_ai_command = preg_split('/\r\n|\r|\n/', $category_ai_command);
                            $category_ai_command = array_filter($category_ai_command);
                            if(count($category_ai_command) > 0)
                            {
                                $category_ai_command = $category_ai_command[array_rand($category_ai_command)];
                            }
                            else
                            {
                                $category_ai_command = '';
                            }
                        }
                        $category_ai_command = aiomatic_replaceSynergyShortcodes($category_ai_command);
                        if(!empty($category_ai_command))
                        {
                            $category_ai_command = aiomatic_replaceAIPostShortcodes($category_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                            $category_ai_command = aiomatic_replace_youtube($category_ai_command, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                        }
                        else
                        {
                            $category_ai_command = trim(strip_tags('Write a comma separated list of categories, for the post title: %%post_title%%'));
                        }
                        $category_ai_command = trim($category_ai_command);
                        if (filter_var($category_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($category_ai_command, '.txt'))
                        {
                            $txt_content = aiomatic_get_web_page($category_ai_command);
                            if ($txt_content !== FALSE) 
                            {
                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                $txt_content = array_filter($txt_content);
                                if(count($txt_content) > 0)
                                {
                                    $txt_content = $txt_content[array_rand($txt_content)];
                                    if(trim($txt_content) != '') 
                                    {
                                        $category_ai_command = $txt_content;
                                        $category_ai_command = aiomatic_replaceSynergyShortcodes($category_ai_command);
                                        $category_ai_command = aiomatic_replaceAIPostShortcodes($category_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        $category_ai_command = aiomatic_replace_youtube($category_ai_command, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                                    }
                                }
                            }
                        }
                        if(empty($category_ai_command))
                        {
                            aiomatic_log_to_file('Empty API post category seed expression provided!');
                        }
                        else
                        {
                            if(aiomatic_strlen($category_ai_command) > $max_seed_tokens * 4)
                            {
                                $category_ai_command = aiomatic_substr($category_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                            }
                            $category_ai_command = trim($category_ai_command);
                            if(empty($category_ai_command))
                            {
                                aiomatic_log_to_file('Empty API category seed expression provided! ' . print_r($category_ai_command, true));
                                break;
                            }
                            $query_token_count = count(aiomatic_encode($category_ai_command));
                            $available_tokens = aiomatic_compute_available_tokens($category_model, $max_tokens, $category_ai_command, $query_token_count);
                            if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                            {
                                $string_len = aiomatic_strlen($category_ai_command);
                                $string_len = $string_len / 2;
                                $string_len = intval(0 - $string_len);
                                $category_ai_command = aiomatic_substr($category_ai_command, 0, $string_len);
                                $category_ai_command = trim($category_ai_command);
                                if(empty($category_ai_command))
                                {
                                    aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($category_ai_command, true));
                                    break;
                                }
                                $query_token_count = count(aiomatic_encode($category_ai_command));
                                $available_tokens = $max_tokens - $query_token_count;
                            }
                            $aierror = '';
                            $finish_reason = '';
                            if(!empty($global_prepend))
                            {
                                $category_ai_command = $global_prepend . ' ' . $category_ai_command;
                            }
                            if(!empty($global_append))
                            {
                                $category_ai_command = $category_ai_command . ' ' . $global_append;
                            }
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $category_model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $category_model . ')(' . $available_tokens . ') for category generator: ' . $category_ai_command);
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating categories'));
                            $generated_text = aiomatic_generate_text($token, $category_model, $category_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'categoryID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', false, $store_data, array(), '', '', '');
                            if($generated_text === false)
                            {
                                aiomatic_log_to_file('Category generator error: ' . $aierror);
                                break;
                            }
                            else
                            {
                                $extra_categories = $generated_text;
                            }
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $category_model);
                                aiomatic_log_to_file('Successfully got API category result from ' . $api_service . ': ' . $generated_text);
                            }
                        }
                    }
                    else
                    {
                        $extra_categories = '';
                    }
                    $my_post['extra_categories'] = $extra_categories;
                    
                    $item_tags                   = aiomatic_extractKeyWords($new_post_content, 3);
                    $item_tags                   = implode(',', $item_tags);
                    $title_tags                   = aiomatic_extractKeyWords($new_post_title, 3);
                    $title_tags                   = implode(',', $title_tags);
                    $item_create_tag_sp = $spintax->Parse($item_create_tag);
                    if ($can_create_tag == 'content') {
                        $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $item_tags;
                        $my_post['extra_tags']       = $item_tags;
                    } else if ($can_create_tag == 'title') {
                        $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $title_tags;
                        $my_post['extra_tags']       = $title_tags;
                    } else if ($can_create_tag == 'both') {
                        $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . ($item_tags != '' ? $item_tags . ',' : '') . $title_tags;
                        $my_post['extra_tags']       = ($item_tags != '' ? $item_tags . ',' : '') . $title_tags;
                    } else if ($can_create_tag == 'ai') {
                        $ai_tags = '';
                        $tag_ai_command = $orig_ai_command_tag;
                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                        {
                            $tag_ai_command = preg_split('/\r\n|\r|\n/', $tag_ai_command);
                            $tag_ai_command = array_filter($tag_ai_command);
                            if(count($tag_ai_command) > 0)
                            {
                                $tag_ai_command = $tag_ai_command[array_rand($tag_ai_command)];
                            }
                            else
                            {
                                $tag_ai_command = '';
                            }
                        }
                        $tag_ai_command = aiomatic_replaceSynergyShortcodes($tag_ai_command);
                        if(!empty($tag_ai_command))
                        {
                            $tag_ai_command = aiomatic_replaceAIPostShortcodes($tag_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                            $tag_ai_command = aiomatic_replace_youtube($tag_ai_command, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                        }
                        else
                        {
                            $tag_ai_command = trim(strip_tags('Write a comma separated list of tags, for the post title: %%post_title%%'));
                        }
                        $tag_ai_command = trim($tag_ai_command);
                        if (filter_var($tag_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($tag_ai_command, '.txt'))
                        {
                            $txt_content = aiomatic_get_web_page($tag_ai_command);
                            if ($txt_content !== FALSE) 
                            {
                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                $txt_content = array_filter($txt_content);
                                if(count($txt_content) > 0)
                                {
                                    $txt_content = $txt_content[array_rand($txt_content)];
                                    if(trim($txt_content) != '') 
                                    {
                                        $tag_ai_command = $txt_content;
                                        $tag_ai_command = aiomatic_replaceSynergyShortcodes($tag_ai_command);
                                        $tag_ai_command = aiomatic_replaceAIPostShortcodes($tag_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        $tag_ai_command = aiomatic_replace_youtube($tag_ai_command, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                                    }
                                }
                            }
                        }
                        if(empty($tag_ai_command))
                        {
                            aiomatic_log_to_file('Empty API post tag seed expression provided!');
                        }
                        else
                        {
                            if(aiomatic_strlen($tag_ai_command) > $max_seed_tokens * 4)
                            {
                                $tag_ai_command = aiomatic_substr($tag_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                            }
                            $tag_ai_command = trim($tag_ai_command);
                            if(empty($tag_ai_command))
                            {
                                aiomatic_log_to_file('Empty API tag seed expression provided! ' . print_r($tag_ai_command, true));
                                break;
                            }
                            $query_token_count = count(aiomatic_encode($tag_ai_command));
                            $available_tokens = aiomatic_compute_available_tokens($tag_model, $max_tokens, $tag_ai_command, $query_token_count);
                            if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                            {
                                $string_len = aiomatic_strlen($tag_ai_command);
                                $string_len = $string_len / 2;
                                $string_len = intval(0 - $string_len);
                                $tag_ai_command = aiomatic_substr($tag_ai_command, 0, $string_len);
                                $tag_ai_command = trim($tag_ai_command);
                                if(empty($tag_ai_command))
                                {
                                    aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($tag_ai_command, true));
                                    break;
                                }
                                $query_token_count = count(aiomatic_encode($tag_ai_command));
                                $available_tokens = $max_tokens - $query_token_count;
                            }
                            $aierror = '';
                            $finish_reason = '';
                            if(!empty($global_prepend))
                            {
                                $tag_ai_command = $global_prepend . ' ' . $tag_ai_command;
                            }
                            if(!empty($global_append))
                            {
                                $tag_ai_command = $tag_ai_command . ' ' . $global_append;
                            }
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $tag_model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $tag_model . ')(' . $available_tokens . ') for tag generator: ' . $tag_ai_command);
                            }
                            
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating tags'));
                            $generated_text = aiomatic_generate_text($token, $tag_model, $tag_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'tagID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', false, $store_data, array(), '', '', '');
                            if($generated_text === false)
                            {
                                aiomatic_log_to_file('Tag generator error: ' . $aierror);
                                break;
                            }
                            else
                            {
                                $ai_tags = $generated_text;
                            }
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $tag_model);
                                aiomatic_log_to_file('Successfully got API tag result from ' . $api_service . ': ' . $generated_text);
                            }
                        }
                        $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $ai_tags;
                        $my_post['extra_tags']       = $ai_tags;
                    } else {
                        $post_the_tags = $item_create_tag_sp;
                        $my_post['extra_tags']       = '';
                    }
                    $my_post['tags_input'] = $post_the_tags;
                    $new_post_content = aimogen_bulk_polish_article_content($new_post_content, array('title' => isset($new_post_title) ? $new_post_title : '', 'topic' => isset($post_topic) ? $post_topic : '', 'language' => isset($content_language) ? $content_language : '', 'model' => (isset($topic_content_model) && $topic_content_model !== '') ? $topic_content_model : (isset($model) ? $model : ''), 'token' => isset($token) ? $token : '', 'temperature' => isset($temperature) ? $temperature : '', 'top_p' => isset($top_p) ? $top_p : '', 'presence_penalty' => isset($presence_penalty) ? $presence_penalty : '', 'frequency_penalty' => isset($frequency_penalty) ? $frequency_penalty : '', 'rule_id' => isset($rule_unique_id) ? $rule_unique_id : '', 'global_prepend' => isset($global_prepend) ? $global_prepend : '', 'global_append' => isset($global_append) ? $global_append : '', 'assistant_id' => isset($assistant_id) ? $assistant_id : '', 'thread_id' => isset($thread_id) ? $thread_id : '', 'store_data' => isset($store_data) ? $store_data : 'off'));
                    $new_post_content        = html_entity_decode($new_post_content);
                    $new_post_content = str_replace('</ iframe>', '</iframe>', $new_post_content);
                    if ($strip_by_regex !== '')
                    {
                        $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex);
                        $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex);
                        $xcnt = 0;
                        foreach($xstrip_by_regex as $sbr)
                        {
                            if(isset($xreplace_regex[$xcnt]))
                            {
                                $repreg = $xreplace_regex[$xcnt];
                            }
                            else
                            {
                                $repreg = '';
                            }
                            $xcnt++;
                            $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $new_post_content);
                            if($temp_cont !== NULL)
                            {
                                $new_post_content = $temp_cont;
                            }
                        }
                    }
                    $post_prepender = aiomatic_replaceAIPostShortcodes($post_prepend, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                    $post_prepender = aiomatic_replace_youtube($post_prepender, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                    $post_appender = aiomatic_replaceAIPostShortcodes($post_append, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                    $post_appender = aiomatic_replace_youtube($post_appender, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                    $post_appender = aiomatic_replaceSynergyShortcodes($post_appender);
                    $post_prepender = aiomatic_replaceSynergyShortcodes($post_prepender);
                    $zlang = 'en_US';
                    if (isset($aiomatic_Main_Settings['kw_lang']) && !empty($aiomatic_Main_Settings['kw_lang'])) {
                        $zlang = $aiomatic_Main_Settings['kw_lang'];
                    }
                    $rel_search = array('post_title', 'post_content');
                    if (isset($aiomatic_Main_Settings['rel_search']) && is_array($aiomatic_Main_Settings['rel_search'])) {
                        $rel_search = $aiomatic_Main_Settings['rel_search'];
                    }
                    if($max_links !== '' && $inboundlinker !== null && $link_type != 'disabled')
                    {
                        try
                        {
                            $new_post_content = $inboundlinker->add_inbound_links($new_post_content, $max_links, $link_post_types, $zlang, $rel_search, null, $link_type, $link_list, $link_nofollow, '', '', array());
                        }
                        catch(Exception $ex)
                        {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('Failed to add new inbound links to content: ' . $ex->getMessage());
                            }
                        }
                    }
                    if($topic_videos == '1' && count($added_vid_list) == 0)
                    {
                        preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user|shorts)\/))([^\?&\"'>]+)/", $video_url, $amatches);
                        if(isset($amatches[1]))
                        {
                            $video_id = $amatches[1];
                            if (isset($aiomatic_Main_Settings['player_width']) && $aiomatic_Main_Settings['player_width'] !== '') {
                                $vwidth = esc_attr($aiomatic_Main_Settings['player_width']);
                            }
                            else
                            {
                                $vwidth = 580;
                            }
                            if (isset($aiomatic_Main_Settings['player_height']) && $aiomatic_Main_Settings['player_height'] !== '') {
                                $vheight = esc_attr($aiomatic_Main_Settings['player_height']);
                            }
                            else
                            {
                                $vheight = 380;
                            }
                            $new_post_content .= '<br/><br/><div class="automaticx-video-container"><iframe title="' . str_replace('"', "'", $new_post_title) . '" allow="autoplay" width="' . $vwidth . '" height="' . $vheight . '" src="https://www.youtube.com/embed/' . $video_id . '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>';
                            $added_vid_list[] = $video_id;
                            $new_vid_arr[] = $video_id;
                            $added_videos++;
                        }
                    }
                    if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                    {
                        if($new_post_content === strip_tags($new_post_content)) 
                        {
                            $new_post_content = nl2br($new_post_content);
                        }
                    }
                    if (!isset($aiomatic_Main_Settings['no_undetectibility']) || $aiomatic_Main_Settings['no_undetectibility'] != 'on') 
                    {
                        if (!isset($aiomatic_Main_Settings['no_undetectibility_bulk']) || $aiomatic_Main_Settings['no_undetectibility_bulk'] != 'on') 
                        {
                            if(!isset($xchars))
                            {
                                $xchars = array();
                            }
                            $rand_percentage = wp_rand(10, 20);
                            $new_post_content = aiomatic_make_unique($new_post_content, $xchars, $rand_percentage);
                        }
                    }
                    if($ret_content == 1)
                    {
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                            aiomatic_log_to_file('Returning AI generated content, finished.');
                        }
                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Finished processing'));
                        return array($post_prepender . ' ' . $new_post_content . ' ' . $post_appender, $new_post_title);
                    }
                    $the_final_cont = $post_prepender . ' ' . $new_post_content . ' ' . $post_appender;
                    $trunchi_content = aiomatic_truncate_content($the_final_cont, 16777215);
                    if (isset($aiomatic_Main_Settings['convert_gutenberg']) && trim($aiomatic_Main_Settings['convert_gutenberg']) == 'on')
                    {
                        $my_post['post_content'] = aiomatic_convert_html_to_gutenberg_blocks($trunchi_content);
                    }
                    else
                    {
                        $my_post['post_content'] = $trunchi_content;
                    }
                    if(stristr($my_post['post_content'], '<pre><code>&lt;') !== false)
                    {
                        if (!isset($aiomatic_Main_Settings['pre_code_off']) || trim($aiomatic_Main_Settings['pre_code_off']) != 'on')
                        {
                            $my_post['post_content'] = aiomatic_parse_pre_code_entities($my_post['post_content']);
                        }
                    }
                    $my_post['post_content'] = aimogen_bulk_finalize_prose($my_post['post_content']);
                    $my_post['post_title']           = aiomatic_truncate_title($new_post_title);
                    $my_post['aiomatic_source_title']   = $video_url;
                    $my_post['aiomatic_timestamp']   = aiomatic_get_date_now();
                    $my_post['aiomatic_post_format'] = $post_format;
                    if (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678') 
                    {
                        if(is_array($default_category))
                        {
                            $cextra = '';
                            foreach($default_category as $dc)
                            {
                                $cextra .= ',' . get_cat_name($dc);
                            }
                            $extra_categories_temp = trim( $cextra . ',' . $extra_categories, ',');
                        }
                        else
                        {
                            $extra_categories_temp = trim(get_cat_name($default_category) . ',' .$extra_categories, ',');
                        }
                    }
                    else
                    {
                        $extra_categories_temp = $extra_categories;
                    }
                    $block_arr = array();
                    $custom_arr = array();
                    if($custom_fields != '')
                    {
                        if(stristr($custom_fields, '=>') != false)
                        {
                            $rule_arr = explode(',', trim($custom_fields));
                            foreach($rule_arr as $rule)
                            {
                                $my_args = explode('=>', trim($rule));
                                if(isset($my_args[1]))
                                {
                                    if ( isset( $shortcode_tags['aicontent'] ) ) {
                                        $aicontent_handler = $shortcode_tags['aicontent'];
                                        unset( $shortcode_tags['aicontent'] );
                                    } else {
                                        $aicontent_handler = null;
                                    }
                                    $my_args[1] = do_shortcode($my_args[1]);
                                    $my_args[0] = do_shortcode($my_args[0]);
                                    if ( $aicontent_handler ) {
                                        $shortcode_tags['aicontent'] = $aicontent_handler;
                                    }
                                    $custom_field_content = trim($my_args[1]);
                                    $custom_field_content = aiomatic_replaceAIPostShortcodes($custom_field_content, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    $custom_field_content = aiomatic_replace_youtube($custom_field_content, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                                    $custom_field_content = aiomatic_replaceSynergyShortcodes($custom_field_content);
                                    $custom_field_content = $spintax->Parse($custom_field_content, $block_arr);
                                    $custom_field_content = aiomatic_replaceContentShortcodes($custom_field_content, $img_attr, $ai_command);
                                    if(stristr($my_args[1], 'serialize_') !== false)
                                    {
                                        $custom_arr[trim($my_args[0])] = array(str_replace('serialize_', '', $custom_field_content));
                                    }
                                    else
                                    {
                                        if(stristr($my_args[0], '[') !== false && stristr($my_args[0], ']') !== false)
                                        {
                                            preg_match_all('#([^\[\]]*?)\[([^\[\]]*?)\]#', $my_args[0], $cfm);
                                            if(isset($cfm[2][0]))
                                            {
                                                if(isset($custom_arr[trim($cfm[1][0])]) && is_array($custom_arr[trim($cfm[1][0])]))
                                                {
                                                    $custom_arr[trim($cfm[1][0])] = array_merge($custom_arr[trim($cfm[1][0])], array(trim($cfm[2][0]) => $custom_field_content));
                                                }
                                                else
                                                {
                                                    $custom_arr[trim($cfm[1][0])] = array(trim($cfm[2][0]) => $custom_field_content);
                                                }
                                            }
                                            else
                                            {
                                                $custom_arr[trim($my_args[0])] = $custom_field_content;
                                            }
                                        }
                                        else
                                        {
                                            $custom_arr[trim($my_args[0])] = $custom_field_content;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $block_arr = array();
                    $custom_arr = array_merge($custom_arr, array('aiomatic_auto_post_spinned' => $already_spinned, 'aiomatic_post_cats' => $extra_categories_temp, 'aiomatic_post_tags' => $post_the_tags));
                    $custom_tax_arr = array();
                    if($custom_tax != '')
                    {
                        if(stristr($custom_tax, '=>') != false)
                        {
                            $rule_arr = explode(';', trim($custom_tax));
                            foreach($rule_arr as $rule)
                            {
                                $my_args = explode('=>', trim($rule));
                                if(isset($my_args[1]))
                                {
                                    $custom_tax_content = trim($my_args[1]);
                                    $custom_tax_content = aiomatic_replaceAIPostShortcodes($custom_tax_content, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    $custom_tax_content = aiomatic_replace_youtube($custom_tax_content, $post_title, $post_desc, $video_url, $returned_caption, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list);
                                    $custom_tax_content = aiomatic_replaceSynergyShortcodes($custom_tax_content);
                                    $custom_tax_content = $spintax->Parse($custom_tax_content, $block_arr);
                                    $custom_tax_content = aiomatic_replaceContentShortcodes($custom_tax_content, $img_attr, $ai_command);
                                    if(aiomatic_substr(trim($my_args[0]), 0, 3) === "pa_" && $post_type == 'product' && !empty($custom_tax_content))
                                    {
                                        if(isset($custom_arr['_product_attributes']))
                                        {
                                            $custom_arr['_product_attributes'] = array_merge($custom_arr['_product_attributes'], array(trim($my_args[0]) =>array(
                                                'name' => trim($my_args[0]),
                                                'value' => $custom_tax_content,
                                                'is_visible' => '1',
                                                'is_taxonomy' => '1'
                                            )));
                                        }
                                        else
                                        {
                                            $custom_arr['_product_attributes'] = array(trim($my_args[0]) =>array(
                                                'name' => trim($my_args[0]),
                                                'value' => $custom_tax_content,
                                                'is_visible' => '1',
                                                'is_taxonomy' => '1'
                                            ));
                                        }
                                    }
                                    if(isset($custom_tax_arr[trim($my_args[0])]))
                                    {
                                        $custom_tax_arr[trim($my_args[0])] .= ',' . $custom_tax_content;
                                    }
                                    else
                                    {
                                        $custom_tax_arr[trim($my_args[0])] = $custom_tax_content;
                                    }
                                }
                            }
                        }
                    }
                    if(count($custom_tax_arr) > 0)
                    {
                        $my_post['taxo_input'] = $custom_tax_arr;
                    }
                    $my_post['meta_input'] = $custom_arr;
                    if($parent_id != '')
                    {
                        $my_post['post_parent'] = intval($parent_id);
                    }
                    if ($enable_pingback == '1') {
                        $my_post['ping_status'] = 'open';
                    } else {
                        $my_post['ping_status'] = 'closed';
                    }
                    if($min_time != '' && $max_time != '')
                    {
                        $t1 = strtotime($min_time);
                        $t2 = strtotime($max_time);
                        if($t1 != false && $t2 != false)
                        {
                            $int = wp_rand($t1, $t2);
                            $my_post['post_date'] = date('Y-m-d H:i:s', $int);
                        }
                    }
                    elseif($min_time != '')
                    {
                        $t1 = strtotime($min_time);
                        if($t1 != false)
                        {
                            $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                        }
                    }
                    elseif($max_time != '')
                    {
                        $t1 = strtotime($max_time);
                        if($t1 != false)
                        {
                            $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                        }
                    }
                    if($new_post_excerpt != '')
                    {
                        $my_post['post_excerpt']          = $new_post_excerpt;
                    }
                    $count++;
                    if($update_post_id != '')
                    {
                        $my_post['ID'] = $update_post_id;
                    }
                    remove_filter('content_save_pre', 'wp_filter_post_kses');
                    remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                    try
                    {
                        $my_post['post_content'] = str_replace('\r\n', '', $my_post['post_content']);
                        $post_id = wp_insert_post($my_post, true);
                        if (is_wp_error($post_id)) 
                        {
                            aiomatic_log_to_file('Trying publishing again');
                            if (aiomatic_strlen($my_post['post_content']) > 16777215) {
                                $my_post['post_content'] = aiomatic_substr($my_post['post_content'], 0, 16777215);
                            }
                            $my_post['post_content'] = wp_kses_post($my_post['post_content']);
                            $my_post['post_content'] = str_replace('\r\n', '', $my_post['post_content']);
                            $post_id = wp_insert_post($my_post, true);
                        }
                    }
                    catch(Exception $e)
                    {
                        aiomatic_log_to_file('Exception in publishing post (this is coming from another plugin, so we ignore it): ' . $e->getMessage());
                    }
                    add_filter('content_save_pre', 'wp_filter_post_kses');
                    add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                    if (!is_wp_error($post_id)) {
                        if($post_id === 0)
                        {
                            aiomatic_log_to_file('An error occurred while inserting post into wp database! Title:' . $my_post['post_title']);
                            continue;
                        }
                        $words = str_word_count(wp_strip_all_tags($my_post['post_content']));
                        aiomatic_increment_publishing_stats($words);
                        aimogen_bulk_on_post_created($post_id, $my_post['post_title'], isset($new_post_excerpt) ? $new_post_excerpt : '', isset($post_topic) ? $post_topic : (isset($post_title) ? $post_title : ''));
                        aiomatic_set_last_activity(
                            'article',
                            ['post_id' => $post_id]
                        );
                        $posts_inserted++;
                        if($wpml_lang != '' && function_exists('pll_set_post_language'))
                        {
                            pll_set_post_language($post_id, $wpml_lang);
                        }
                        if(!empty($additional_attachments))
                        {
                            foreach($additional_attachments as $add_att)
                            {
                                wp_update_post([
                                    'ID' => $add_att,
                                    'post_parent' => $post_id,
                                ]);
                            }
                        }
                        $default_categories = array();
                        if($remove_default == '1' && ($auto_categories != 'disabled' || (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678')))
                        {
                            $default_categories = wp_get_post_categories($post_id);
                        }
                        if(isset($my_post['taxo_input']))
                        {
                            foreach($my_post['taxo_input'] as $taxn => $taxval)
                            {
                                $taxn = trim($taxn);
                                $taxval = trim($taxval);
                                if(is_taxonomy_hierarchical($taxn))
                                {
                                    $taxval = array_map('trim', explode(',', $taxval));
                                    for($ii = 0; $ii < count($taxval); $ii++)
                                    {
                                        $term_ids = [];
                                        $parent_id = 0;
                                        $hierarchy_parts = array_map('trim', explode('>', $taxval[$ii]));
                                        foreach($hierarchy_parts as $hp)
                                        {
                                            if(!is_numeric($hp))
                                            {
                                                $xtermid = get_term_by('name', $hp, $taxn);
                                                if($xtermid !== false)
                                                {
                                                    $parent_id = $xtermid->term_id;
                                                    if(!is_numeric($taxval[$ii]))
                                                    {
                                                        $taxval[$ii] = intval($xtermid->term_id);
                                                    }
                                                    else
                                                    {
                                                        $taxval[] = intval($xtermid->term_id);
                                                    }
                                                }
                                                else
                                                {
                                                    wp_insert_term( $hp, $taxn, ['parent' => $parent_id]);
                                                    $xtermid = get_term_by('name', $hp, $taxn);
                                                    if($xtermid !== false)
                                                    {
                                                        $parent_id = $xtermid->term_id;
                                                        if($wpml_lang != '' && function_exists('pll_set_term_language'))
                                                        {
                                                            pll_set_term_language($xtermid->term_id, $wpml_lang); 
                                                        }
                                                        elseif($wpml_lang != '' && has_filter('wpml_object_id'))
                                                        {
                                                            $wpml_element_type = apply_filters( 'wpml_element_type', $taxn );
                                                            $pars['element_id'] = $xtermid->term_id;
                                                            $pars['element_type'] = $wpml_element_type;
                                                            $pars['language_code'] = $wpml_lang;
                                                            $pars['trid'] = FALSE;
                                                            $pars['source_language_code'] = NULL;
                                                            do_action('wpml_set_element_language_details', $pars);
                                                        }
                                                        if(!is_numeric($taxval[$ii]))
                                                        {
                                                            $taxval[$ii] = intval($xtermid->term_id);
                                                        }
                                                        else
                                                        {
                                                            $taxval[] = intval($xtermid->term_id);
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if(!is_numeric($taxval[$ii]))
                                                {
                                                    $taxval[$ii] = intval($hp);
                                                }
                                                else
                                                {
                                                    $taxval[] = intval($hp);
                                                }
                                            }
                                        }
                                    }
                                    wp_set_post_terms($post_id, $taxval, $taxn, true);
                                }
                                else
                                {
                                    $jterms = array_map('trim', explode(',', $taxval));
                                    wp_set_post_terms($post_id, $jterms, $taxn, true);
                                }
                            }
                        }
                        if (isset($my_post['aiomatic_post_format']) && $my_post['aiomatic_post_format'] != '' && $my_post['aiomatic_post_format'] != 'post-format-standard') {
                            wp_set_post_terms($post_id, $my_post['aiomatic_post_format'], 'post_format', true);
                        }
                        $featured_path = '';
                        $get_img = $my_post['aiomatic_post_image'];
                        if ($get_img != '') {
                            if($my_post['aiomatic_local_image'] == '1')
                            {
                                $local_get_img = $get_img[0];
                                if (!aiomatic_assign_featured_image_path($local_get_img, $post_id)) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('aiomatic_assign_featured_image_path failed for ' . $local_get_img);
                                    }
                                } else {
                                    $featured_path = $get_img[1];
                                }
                            }
                            else
                            {
                                if(is_numeric($get_img))
                                {
                                    $featured_path = aiomatic_assign_featured_image($get_img, $post_id);
                                }
                                else
                                {
                                    if (!aiomatic_generate_featured_image($get_img, $post_id)) {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('aiomatic_generate_featured_image failed for ' . $get_img);
                                        }
                                    } else {
                                        $featured_path = $get_img;
                                    }
                                }
                            }
                        }
                        if($featured_path == '')
                        {
                            if ($image_url != '') {
                                $replacement = str_replace(array('[', ']'), '', $my_post['post_title']);
                                $image_url_temp = str_replace('%%item_title%%', $replacement, $image_url);
                                $image_url_temp = preg_replace_callback('#%%random_image\[([^\]]*?)\](\[\d+\])?%%#', function ($matches) {
                                    if(isset($matches[2]))
                                    {
                                        $chance = trim($matches[2], '[]');
                                    }
                                    else
                                    {
                                        $chance = '';
                                    }
                                    $arv = array();
                                    $my_img = aiomatic_get_random_image_google($matches[1], 0, 0, $chance, $arv);
                                    return $my_img;
                                }, $image_url_temp);
                                $img_rulx = $spintax->Parse(trim($image_url_temp));
                                $selected_img = aiomatic_select_ai_image($my_post['post_title'], $img_rulx);
                                if($selected_img === false)
                                {
                                    $img_rulx = explode(',', $img_rulx);
                                    $img_rulx = trim($img_rulx[array_rand($img_rulx)]);
                                }
                                else
                                {
                                    $img_rulx = $selected_img;
                                }
                                if(is_numeric($img_rulx))
                                {
                                    $featured_path = aiomatic_assign_featured_image($img_rulx, $post_id);
                                }
                                else
                                {
                                    if($img_rulx != '')
                                    {
                                        if (!aiomatic_generate_featured_image($img_rulx, $post_id)) {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                aiomatic_log_to_file('aiomatic_generate_featured_image failed to default value: ' . $img_rulx . '!');
                                            }
                                        } else {
                                            $featured_path = $img_rulx;
                                        }
                                    }
                                }
                            }
                        }
                        if ($auto_categories != 'disabled') {
                            if ($my_post['extra_categories'] != '') {
                                $extra_cats = explode(',', $my_post['extra_categories']);
                                if($post_type == 'product')
                                {
                                    $product_tax = 'product_cat';
                                }
                                else
                                {
                                    $product_tax = 'category';
                                }
                                foreach($extra_cats as $extra_cat)
                                {
                                    $extra_cat = trim($extra_cat);
                                    $extra_cat = strip_tags($extra_cat);
                                    $extra_cat = preg_replace('#^\d+\.\s*#', '', $extra_cat);
                                    if(empty($extra_cat))
                                    {
                                        continue;
                                    }
                                    if ($skip_inexist == '1') 
                                    {
                                        if(!term_exists($extra_cat, $product_tax))
                                        {
                                            continue;
                                        }
                                    }
                                    $termid = aiomatic_create_terms($product_tax, null, trim($extra_cat));
                                    wp_set_post_terms($post_id, $termid, $product_tax, true);
                                    if($wpml_lang != '' && function_exists('pll_set_term_language'))
                                    {
                                        foreach($termid as $tx)
                                        {
                                            pll_set_term_language($tx, $wpml_lang); 
                                        }
                                    }
                                    elseif($wpml_lang != '' && has_filter('wpml_object_id'))
                                    {
                                        $wpml_element_type = apply_filters( 'wpml_element_type', 'product_cat' );
                                        foreach($termid as $tx)
                                        {
                                            $pars['element_id'] = $tx;
                                            $pars['element_type'] = $wpml_element_type;
                                            $pars['language_code'] = $wpml_lang;
                                            $pars['trid'] = FALSE;
                                            $pars['source_language_code'] = NULL;
                                            do_action('wpml_set_element_language_details', $pars);
                                        }
                                    }
                                }
                            }
                        }
                        if (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678') {
                            $cats   = array();
                            if(is_array($default_category))
                            {
                                foreach($default_category as $dc)
                                {
                                    $cats[] = $dc;
                                }
                            }
                            else
                            {
                                $cats[] = $default_category;
                            }
                            global $sitepress;
                            if($wpml_lang != '' && has_filter('wpml_current_language') && $sitepress != null)
                            {
                                $current_language = apply_filters( 'wpml_current_language', NULL );
                                $sitepress->switch_lang($wpml_lang);
                            }
                            $target_cat = 'category';
                            if($post_type == 'product')
                            {
                                $target_cat = 'product_cat';
                            }
                            wp_set_object_terms($post_id, array_map( 'intval', $cats ), $target_cat, true);
                            if($wpml_lang != '' && function_exists('pll_set_term_language'))
                            {
                                foreach($cats as $cc)
                                {
                                    pll_set_term_language($cc, $wpml_lang);
                                }
                            }
                            elseif($wpml_lang != '' && has_filter('wpml_current_language') && $sitepress != null)
                            {
                                $sitepress->switch_lang($current_language);
                            }
                        }
                        if (isset($my_post['tags_input']) && $my_post['tags_input'] != '')
                        {
                            if($post_type == 'product')
                            {
                                wp_set_post_terms($post_id, $my_post['tags_input'], 'product_tag', true);
                            }
                        }
                        $tax_rez = wp_set_object_terms( $post_id, 'aiomatic_' . $type . '_' . $param, 'coderevolution_post_source', true);
                        if (is_wp_error($tax_rez)) {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('wp_set_object_terms failed for: ' . $post_id . '!');
                            }
                        }
                        if($post_type == 'topic' && $parent_id != '')
                        {
                            update_post_meta($post_id, '_bbp_forum_id', $parent_id);
                            update_post_meta($post_id, '_bbp_topic_id', $post_id);
                            update_post_meta($post_id, '_bbp_voice_count', '0');
                            update_post_meta($post_id, '_bbp_reply_count', '0');
                            update_post_meta($post_id, '_bbp_reply_count_hidden', '0');
                            update_post_meta($post_id, '_bbp_last_reply_id', '0');
                            update_post_meta($post_id, '_bbp_last_active_id', $post_id);
                            update_post_meta($post_id, '_bbp_last_active_time', get_post_field( 'post_date', $topic_id, 'db' ));
                            do_action( 'bbp_insert_topic', (int) $post_id, (int) $parent_id );
                        }
                        if($post_type == 'reply' && $parent_id != '')
                        {
                            if(function_exists('bbp_get_topic_forum_id'))
                            {
                                $forum_aidi = bbp_get_topic_forum_id($parent_id);
                                if(empty($forum_aidi))
                                {
                                    $forum_aidi = 0;
                                }
                            }
                            else
                            {
                                $forum_aidi = 0;
                            }
                            do_action( 'bbp_insert_reply', (int) $post_id, (int) $parent_id, (int) $forum_aidi );
                        }
                        if($remove_default == '1' && ($auto_categories != 'disabled' || (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678')))
                        {
                            $new_categories = wp_get_post_categories($post_id);
                            $removed_cat = false;
                            if(isset($default_categories) && !($default_categories == $new_categories))
                            {
                                foreach($default_categories as $dc)
                                {
                                    $rem_cat = get_category( $dc );
                                    wp_remove_object_terms( $post_id, $rem_cat->slug, 'category' );
                                    $removed_cat = true;
                                }
                            }
                            if($removed_cat == false)
                            {
                                wp_remove_object_terms( $post_id, 'uncategorized', 'category' );
                            }
                        }
                        aiomatic_addPostMeta($post_id, $my_post, $param, $type, $featured_path, $post_topic, $rule_unique_id, $post_link);
                        if($wpml_lang != '' && (class_exists('SitePress') || function_exists('wpml_object_id')))
                        {
                            $wpml_element_type = apply_filters( 'wpml_element_type', $post_type );
                            $pars['element_id'] = $post_id;
                            $pars['element_type'] = $wpml_element_type;
                            $pars['language_code'] = $wpml_lang;
                            $pars['source_language_code'] = NULL;
                            do_action('wpml_set_element_language_details', $pars);

                            global $wp_filesystem;
                            if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
                                include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() );
                                wp_filesystem($creds);
                            }
                            if($wp_filesystem->exists(WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php'))
                            {
                                include_once( WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php' );
                            }
                            $wpml_lang = trim($wpml_lang);
                            if(function_exists('wpml_update_translatable_content'))
                            {
                                wpml_update_translatable_content('post_' . $post_type, $post_id, $wpml_lang);
                                if($my_post['post_title'] != '')
                                {
                                    global $sitepress;
                                    global $wpdb;
                                    $keyid = md5($my_post['post_title']);
                                    $keyName = $keyid . '_wpml';
                                    $rezxxxa = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}postmeta WHERE `meta_key` = '$keyName' limit 1", ARRAY_A );
                                    if(count($rezxxxa) != 0)
                                    {
                                        $metaRow = $rezxxxa[0];
                                        $metaValue = $metaRow['meta_value'];
                                        $metaParts = explode('_', $metaValue);
                                        $sitepress->set_element_language_details($post_id, 'post_'.$my_post['post_type'] , $metaParts[0], $wpml_lang, $metaParts[1] ); 
                                    }
                                    else
                                    {
                                        $ptrid = $sitepress->get_element_trid($post_id);
                                        update_post_meta($post_id, $keyid.'_wpml', $ptrid.'_'.$wpml_lang );
                                    }
                                }
                                
                            }
                        }
                        if (isset($aiomatic_Main_Settings['draft_first']) && $aiomatic_Main_Settings['draft_first'] == 'on' && $draft_me == true)
                        {
                            aiomatic_change_post_status($post_id, 'publish');
                        }
                    } else {
                        aiomatic_log_to_file('Failed to insert post into wp database(2)! Title:' . $my_post['post_title'] . '! Error: ' . $post_id->get_error_message() . ' Error code: ' . $post_id->get_error_code() . ' Error data: ' . $post_id->get_error_data());
                        continue;
                    }
                }
            }
            elseif($type == '2')
            {
                $amazon_keyword = str_replace(',', '|', $amazon_keyword);
                $amazon_keyword_lines = array();
                if($amazon_keyword != '')
                {
                    $amazon_keyword_lines = preg_split('/\r\n|\r|\n/', $amazon_keyword);
                }
                else
                {
                    aiomatic_log_to_file('You need to enter an Amazon product search keyword to use this feature!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
                $additional_kws = array();
                $post_link = '';
                $user_name        = '';
                $featured_image   = '';
                $post_cats = '';
                $post_tagz = '';
                $post_excerpt = '';
                $final_content = '';
                $postID = '';
                $heading_val = '';
                $image_query = '';
                $temp_post = '';
                $cntx = count($amazon_keyword_lines);
                $rss_feeds = array();
                for($ji = 0; $ji < $cntx; $ji++)
                {
                    if (filter_var($amazon_keyword_lines[$ji], FILTER_VALIDATE_URL) !== false && stristr($amazon_keyword_lines[$ji], 'youtu') === false) 
                    {
                        if(aiomatic_endsWith($amazon_keyword_lines[$ji], '.txt'))
                        {
                            $txt_content = aiomatic_get_web_page($amazon_keyword_lines[$ji]);
                            if ($txt_content === FALSE) 
                            {
                                aiomatic_log_to_file('Failed to read text file: ' . $amazon_keyword_lines[$ji]);
                                unset($amazon_keyword_lines[$ji]);
                                if($auto == 1)
                                {
                                    aiomatic_log_to_file($param);
                                }
                                continue;
                            }
                            unset($amazon_keyword_lines[$ji]);
                            $additional_kws = preg_split('/\r\n|\r|\n/', $txt_content);
                        }
                        else
                        {
                            aiomatic_log_to_file('Trying to parse RSS feed items(4): ' . $amazon_keyword_lines[$ji]);
                            try
                            {
                                if(!class_exists('SimplePie_Autoloader', false))
                                {
                                    require_once(dirname(__FILE__) . "/res/simplepie/autoloader.php");
                                }
                            }
                            catch(Exception $e) 
                            {
                                unset($amazon_keyword_lines[$ji]);
                                aiomatic_log_to_file('Exception thrown in SimplePie autoloader: ' . $e->getMessage());
                                if($auto == 1)
                                {
                                    aiomatic_log_to_file($param);
                                }
                                continue;
                            }
                            $feed = new SimplePie();
                            $feed->set_timeout(120);
                            $feed->set_feed_url($amazon_keyword_lines[$ji]);
                            $feed->enable_cache(false);
                            $feed->strip_htmltags(false);
                            $feed->init();
                            $feed->handle_content_type();
                            if ($feed->error()) 
                            {
                                aiomatic_log_to_file('Error in parsing RSS feed: ' . $feed->error() . ' for ' . $amazon_keyword_lines[$ji]);
                                unset($amazon_keyword_lines[$ji]);
                                if($auto == 1)
                                {
                                    aiomatic_clearFromList($param, $type);
                                }
                                continue;
                            }
                            $items = $feed->get_items();
                            $zero = true;
                            foreach($items as $itemx)
                            {
                                if($zero == true)
                                {
                                    $post_link = trim($itemx->get_permalink());
                                    if(isset($rss_items[$post_link]))
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Skipping RSS title because it was already processed before: ' . $itemx->get_title());
                                        }
                                        continue;
                                    }
                                    if ($fauthor = $itemx->get_author()) 
                                    {
                                        $user_name = $fauthor->get_name();
                                    }
                                    else
                                    {
                                        $user_name = '';
                                    }
                                    $feed_cats = array();
                                    $varx = $itemx->get_categories();
                                    if(is_array($varx))
                                    {
                                        foreach ($varx as $xcategory)
                                        {
                                            $feed_cats[] = $xcategory->get_label();
                                        }
                                    }
                                    $post_cats = implode(',', $feed_cats);
                                    $post_excerpt = $itemx->get_description();
                                    $final_content = $itemx->get_content();
                                    $rss_feeds[$itemx->get_title()] = array('url' => $post_link, 'author' => $user_name,  'cats' => $post_cats, 'excerpt' => $post_excerpt, 'content' => $final_content );
                                }
                                else
                                {
                                    $post_link_temp = trim($itemx->get_permalink());
                                    if(isset($rss_items[$post_link_temp]))
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Skipping RSS title because it was already processed before: ' . $itemx->get_title());
                                        }
                                        continue;
                                    }
                                    if ($fauthor = $itemx->get_author()) 
                                    {
                                        $user_name_temp = $fauthor->get_name();
                                    }
                                    else
                                    {
                                        $user_name_temp = '';
                                    }
                                    $feed_cats = array();
                                    $varx = $itemx->get_categories();
                                    if(is_array($varx))
                                    {
                                        foreach ($varx as $xcategory)
                                        {
                                            $feed_cats[] = $xcategory->get_label();
                                        }
                                    }
                                    $post_cats_temp = implode(',', $feed_cats);
                                    $post_excerpt_temp = $itemx->get_description();
                                    $final_content_temp = $itemx->get_content();
                                    $rss_feeds[$itemx->get_title()] = array('url' => $post_link_temp, 'author' => $user_name_temp,  'cats' => $post_cats_temp, 'excerpt' => $post_excerpt_temp, 'content' => $final_content_temp );
                                }
                                $additional_kws[] = $itemx->get_title();
                                $zero = false;
                            }
                            unset($amazon_keyword_lines[$ji]);
                        }
                    }
                }
                if(count($additional_kws) > 0)
                {
                    $amazon_keyword_lines = array_merge($amazon_keyword_lines, $additional_kws);
                }
                $amazon_keyword_lines = array_unique($amazon_keyword_lines);
                if($overwrite_existing == '1')
                {
                    $amazon_keyword_lines_processed = array();
                    foreach($amazon_keyword_lines as $zind => $ptl)
                    {
                        $ptlprocessed = explode('!###!', $ptl);
                        if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                        {
                            $amazon_keyword_lines_processed[$zind] = $ptlprocessed[0];
                        }
                        else
                        {
                            $amazon_keyword_lines_processed[$zind] = $ptl;
                        }
                    }
                    foreach($posted_items as $ptit => $pid)
                    {
                        if (($key = array_search($ptit, $amazon_keyword_lines_processed)) !== false) {
                            $update_post_id = $pid;
                            break;
                        }
                    }
                }
                if($title_once == '1')
                {
                    $skipt = 0;
                    $amazon_keyword_lines_processed = array();
                    foreach($amazon_keyword_lines as $zind => $ptl)
                    {
                        $ptlprocessed = explode('!###!', $ptl);
                        if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                        {
                            $amazon_keyword_lines_processed[$zind] = $ptlprocessed[0];
                        }
                        else
                        {
                            $amazon_keyword_lines_processed[$zind] = $ptl;
                        }
                    }
                    foreach($posted_items as $ptit => $pid)
                    {
                        if (($key = array_search($ptit, $amazon_keyword_lines_processed)) !== false) {
                            aiomatic_log_to_file('Skipping Amazon title, already processed: ' . $ptit);
                            unset($amazon_keyword_lines[$key]);
                            unset($amazon_keyword_lines_processed[$key]);
                            $skipt++;
                        }
                    }
                    if(count($amazon_keyword_lines) == 0 && $skipt > 0)
                    {
                        if (isset($aiomatic_Main_Settings['email_notification']) && $aiomatic_Main_Settings['email_notification'] != '')
                        {
                            if($count === 1)
                            {
                                $email_list = explode(',', $aiomatic_Main_Settings['email_notification']);
                                foreach($email_list as $thisaddr)
                                {
                                    $thisaddr = trim($thisaddr);
                                    try
                                    {
                                        $admin_mail = get_option('admin_email');
                                        $to        = $thisaddr;
                                        $subject   = '[Aimogen] Amazon Keywords depleted rule ID ' . $param . ' - ' . aiomatic_get_date_now();
                                        $message   = 'Amazon Rule ID ' . esc_html($param) . ' (' . $rule_description . ') depleted its Amazon keywords list, no new posts publised! Website URL: ' . get_site_url();
                                        $headers[] = 'From: Aimogen Plugin <' . $admin_mail . '>';
                                        $headers[] = 'Reply-To: ' . $admin_mail;
                                        $headers[] = 'X-Mailer: PHP/' . phpversion();
                                        $headers[] = 'Content-Type: text/html';
                                        $headers[] = 'Charset: ' . get_option('blog_charset', 'UTF-8');
                                        wp_mail($to, $subject, $message, $headers);
                                    }
                                    catch (Exception $e) {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Failed to send mail: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                        }
                                    }
                                }
                            }
                        }
                        aiomatic_log_to_file('All Amazon keywords already processed, nothing to do.');
                        if($auto == 1)
                        {
                            aiomatic_clearFromList($param, $type);
                        }
                        return 'nochange';
                    }
                }
                $spintax = new Aiomatic_Spintax();
                $orig_ai_command = $ai_command;
                $orig_ai_command_title = $title_ai_command;
                $orig_ai_command_category = $category_ai_command;
                $orig_ai_command_tag = $tag_ai_command;
                $orig_ai_command_image = $ai_command_image;
                $already_spinned = 0;
                if(isset($aiomatic_Main_Settings['attr_text']) && $aiomatic_Main_Settings['attr_text'] != '')
                {
                    $img_attr = $aiomatic_Main_Settings['attr_text'];
                }
                else
                {
                    $img_attr = '';
                }
                $headings_arr = array();
                if($images_list != '')
                {
                    $images_arr = preg_split('/\r\n|\r|\n/', $images_list);
                    $images_arr = array_map('trim', $images_arr);
                }
                else
                {
                    $images_arr = array();
                }
                require_once(__DIR__ . '/res/amazon-direct.php');
                while(true) 
                {
                    $thread_id = '';
                    $my_title_outro = '';
                    if ($count > intval($max)) {
                        break;
                    }
                    $update_post_id  = '';
                    $product_description = '';
                    $current_section = '';
                    $post_sections = array();
                    $post_topic = '';
                    $post_title_keywords = '';
                    $headings_arr_copy = $headings_arr;
                    $added_img_list = array();
                    $raw_img_list = array();
                    $full_result_list = array();
                    $added_images = 0;
                    $heading_results = array();
                    if(count($amazon_keyword_lines) == 0)
                    {
                        break;
                    }
                    if ($count > intval($max)) {
                        break;
                    }
                    if (!isset($aiomatic_Main_Settings['no_random_titles']) || $aiomatic_Main_Settings['no_random_titles'] != 'on')
                    {
                        $current_index = array_rand($amazon_keyword_lines);
                    }
                    else
                    {
                        $current_index = array_key_first($amazon_keyword_lines);
                    }
                    $amazon_kw = trim($amazon_keyword_lines[$current_index]);
                    if($title_once == '1')
                    {
                        unset($amazon_keyword_lines[$current_index]);
                    }
                    $ptlprocessed = explode('!###!', $amazon_kw);
                    if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                    {
                        $amazon_kw = $ptlprocessed[0];
                        $post_title_keywords = $ptlprocessed[1];
                    }
                    if(isset($rss_feeds[$amazon_kw]))
                    {
                        $post_link = $rss_feeds[$amazon_kw]['url'];
                        $user_name = $rss_feeds[$amazon_kw]['author'];
                        $post_cats = $rss_feeds[$amazon_kw]['cats'];
                        $post_excerpt = $rss_feeds[$amazon_kw]['excerpt'];
                        $final_content = $rss_feeds[$amazon_kw]['content'];
                    }
                    $tprepp = $spintax->Parse($amazon_kw);
                    if($tprepp != false && $tprepp != '')
                    {
                        $amazon_kw = $tprepp;
                    }
                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                    {
                        aiomatic_log_to_file('Starting processing Product Roundup keyword: ' . $amazon_kw);
                    }
                    $old_title = $amazon_kw;
                    $already_spinned = 0;
                    $allmodels = aiomatic_get_all_models();
                    if($custom_shortcodes != '')
                    {
                        $custom_shortcodes_arr = preg_split('/\r\n|\r|\n/', $custom_shortcodes);
                        foreach($custom_shortcodes_arr as $my_short)
                        {
                            $name_part = explode('=>', $my_short);
                            if(isset($name_part[1]) && !empty(trim($name_part[1])))
                            {
                                $shortname = trim($name_part[0]);
                                if(strstr($amazon_kw, '%%' . $shortname . '%%'))
                                {
                                    $shortval = '';
                                    $name_part[1] = str_replace('%%search_keywords%%', $amazon_kw, $name_part[1]);
                                    $ai_part = explode('@@', $name_part[1]);
                                    if(isset($ai_part[1]) && !empty(trim($ai_part[1])))
                                    {
                                        if(!in_array(trim($ai_part[0]), $allmodels))
                                        {
                                            $aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                        }
                                        else
                                        {
                                            $aimodel = trim($ai_part[0]);
                                        }
                                        $zai_command = trim($ai_part[1]);
                                        $zai_command = aiomatic_replaceSynergyShortcodes($zai_command);
                                        $zai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $zai_command);
                                        foreach($custom_shortcodes_arr as $my_check_short)
                                        {
                                            $check_name_part = explode('=>', $my_check_short);
                                            if(isset($check_name_part[1]) && !empty(trim($check_name_part[1])))
                                            {
                                                $check_shortname = trim($check_name_part[0]);
                                                if($shortname !== $check_shortname && strstr($zai_command, '%%' . $check_shortname . '%%') !== false)
                                                {
                                                    $check_shortval = '';
                                                    $check_ai_part = explode('@@', $check_name_part[1]);
                                                    if(!in_array(trim($check_ai_part[0]), $allmodels))
                                                    {
                                                        $check_aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                                    }
                                                    else
                                                    {
                                                        $check_aimodel = trim($check_ai_part[0]);
                                                    }
                                                    $check_ai_command = trim($check_ai_part[1]);
                                                    $aierror = '';
                                                    $check_ai_command = aiomatic_replaceSynergyShortcodes($check_ai_command);
                                                    $check_ai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $check_ai_command);
                                                    $check_generated_text = aiomatic_generate_custom_shortcode_content($token, $check_aimodel, $check_ai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                                                    if($check_generated_text === false)
                                                    {
                                                        aiomatic_log_to_file('Custom nested shortcode generator error: ' . $aierror);
                                                    }
                                                    else
                                                    {
                                                        $check_shortval = trim(trim($check_generated_text), '.');
                                                    }
                                                    $zai_command = str_replace('%%' . $check_shortname . '%%', $check_shortval, $zai_command);
                                                }
                                            }
                                        }
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating custom shortcodes'));
                                        $aierror = '';
                                        $generated_text = aiomatic_generate_custom_shortcode_content($token, $aimodel, $zai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                                        if($generated_text === false)
                                        {
                                            aiomatic_log_to_file('Custom shortcode generator error: ' . $aierror);
                                        }
                                        else
                                        {
                                            $shortval = trim(trim($generated_text), '.');
                                        }
                                    }
                                    $amazon_kw = str_replace('%%' . $shortname . '%%', $shortval, $amazon_kw);
                                }
                            }
                        } 
                    }
                    $amazon_kw = aiomatic_replaceSynergyShortcodes($amazon_kw);
                    $amazon_kw = apply_filters('aiomatic_replace_aicontent_shortcode', $amazon_kw);
                    if(empty($amazon_kw))
                    {
                        aiomatic_log_to_file('Empty Amazon Keyword Submitted: ' . $amazon_kw);
                        unset($amazon_keyword_lines[$current_index]);
                        continue;
                    }
                    if($product_source == 'clickbank')
                    {
                        if(stristr($max_products_cb, '-') !== false)
                        {
                            preg_match('/\s*(\d+)\s*-\s*(\d+)\s*/', $max_products_cb, $matches);
                            if(isset($matches[2]) && $matches[2] != '' && isset($matches[1]) && $matches[1] != '')
                            {
                                $rmin = intval($matches[1]);
                                $rmax = intval($matches[2]);
                                $max_prod = mt_rand($rmin, $rmax);
                            }
                            else
                            {
                                $max_prod = $max_products_cb;
                            }
                        }
                        else
                        {
                            if(empty($max_products_cb))
                            {
                                $max_products_cb = '3';
                            }
                            $max_prod = $max_products_cb;
                        }
                        $max_prod = intval($max_prod);
                        $amazresult = aiomatic_clickbank_get_post($cb_affiliate_id, $amazon_kw, $neg_keywords, $item_category, $shipable_only, $pitch_plus, $one_time, $recurring, $affiliate_tools, $spotlight, $mobile_hoplink, $item_language, $activation, $item_gravity, $dollar_sale, $dollar_sale_av, $rebill_total, $per_sale, $per_rebill, $sort_results_cb, $max_prod);
                        if(is_array($amazresult) && isset($amazresult['status']) && $amazresult['status'] == 'nothing')
                        {
                            aiomatic_log_to_file('No results found for ClickBank keyword search: ' . $amazon_kw);
                            unset($amazon_keyword_lines[$current_index]);
                            continue;
                        }
                        if(!is_array($amazresult))
                        {
                            aiomatic_log_to_file('Empty response from ClickBank: ' . $amazon_kw);
                            unset($amazon_keyword_lines[$current_index]);
                            continue;
                        }
                        if(is_array($amazresult) && count($amazresult) == 0)
                        {
                            aiomatic_log_to_file('Empty results found for ClickBank keyword search: ' . $amazon_kw);
                            unset($amazon_keyword_lines[$current_index]);
                            continue;
                        }
                    }
                    else
                    {
                        if(stristr($max_products, '-') !== false)
                        {
                            preg_match('/\s*(\d+)\s*-\s*(\d+)\s*/', $max_products, $matches);
                            if(isset($matches[2]) && $matches[2] != '' && isset($matches[1]) && $matches[1] != '')
                            {
                                $rmin = intval($matches[1]);
                                $rmax = intval($matches[2]);
                                $max_prod = mt_rand($rmin, $rmax);
                            }
                            else
                            {
                                $max_prod = $max_products;
                            }
                        }
                        else
                        {
                            if(empty($max_products))
                            {
                                $max_products = '3';
                            }
                            $max_prod = $max_products;
                        }
                        $max_prod = intval($max_prod);
                        $amazresult = aiomatic_amazon_get_post($amazon_kw, trim($affiliate_id), $target_country, $min_price, $max_price, $sort_results, $max_prod, '1', array());
                        if(is_array($amazresult) && isset($amazresult['status']) && $amazresult['status'] == 'nothing')
                        {
                            aiomatic_log_to_file('No results found for keyword search: ' . $amazon_kw);
                            unset($amazon_keyword_lines[$current_index]);
                            continue;
                        }
                        if(!is_array($amazresult))
                        {
                            aiomatic_log_to_file('Empty response from Amazon: ' . $amazon_kw);
                            unset($amazon_keyword_lines[$current_index]);
                            continue;
                        }
                        if(is_array($amazresult) && count($amazresult) == 0)
                        {
                            aiomatic_log_to_file('Empty results found for keyword search: ' . $amazon_kw);
                            unset($amazon_keyword_lines[$current_index]);
                            continue;
                        }
                    }
                    if($shuffle_products == '1')
                    {
                        shuffle($amazresult);
                    }
                    $product_titles = '';
                    foreach($amazresult as $amr)
                    {
                        $product_titles .= '"' . $amr->offer_title . '",';
                    }
                    $product_titles = rtrim($product_titles, ',');
                    $post_title = '';
                    $amazon_thumb = $amazresult[array_rand($amazresult)]->product_img;
                    $product_title = '';
                    $product_reviews = '';
                    $aff_url = '';
                    $product_author = '';
                    $product_brand = '';
                    $product_isbn = '';
                    $product_upc = '';
                    $offer_price = '';
                    $product_price = '';
                    $product_list_price = '';
                    $price_numeric = '';
                    $price_currency = '';
                    $product_asin = '';
                    $cart_url = '';
                    $list_price_numeric = '';
                    $product_imgs = '';
                    //new
                    $item_score = '';
                    $edition = '';
                    $language = '';
                    $pages_count = '';
                    $publication_date = '';
                    $contributors = '';
                    $manufacturer = '';
                    $binding = '';
                    $product_group = '';
                    $rating = '';
                    $eans = '';
                    $part_no = '';
                    $model = '';
                    $warranty = '';
                    $color = '';
                    $is_adult = '';
                    $dimensions = '';
                    $date = '';
                    $size = '';
                    $unit_count = '';
                    if(!empty($global_prepend))
                    {
                        $global_prepend = aiomatic_replaceSynergyShortcodes($global_prepend);
                        $global_prepend = aiomatic_replaceAIPostShortcodes($global_prepend, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', '');     
                        $global_prepend = aiomatic_replace_amazon($global_prepend, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                        }
                    if(!empty($global_append))
                    {
                        $global_append = aiomatic_replaceSynergyShortcodes($global_append);
                        $global_append = aiomatic_replace_amazon($global_append, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                        $global_append = aiomatic_replaceAIPostShortcodes($global_append, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', '');     
                    }
                    if($title_prompt != '')
                    {
                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                        {
                            $title_prompt_arr = preg_split('/\r\n|\r|\n/', $title_prompt);
                            $my_title_prompt = $title_prompt_arr[array_rand($title_prompt_arr)];
                        }
                        else
                        {
                            $my_title_prompt = $title_prompt;
                        }
                        $zatitle_prompt = aiomatic_replace_amazon($my_title_prompt, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                        if(stristr($run_regex_on, 'title') !== false)
                        {
                            if ($strip_by_regex_prompts !== '')
                            {
                                $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                $xcnt = 0;
                                foreach($xstrip_by_regex as $sbr)
                                {
                                    if(isset($xreplace_regex[$xcnt]))
                                    {
                                        $repreg = $xreplace_regex[$xcnt];
                                    }
                                    else
                                    {
                                        $repreg = '';
                                    }
                                    $xcnt++;
                                    $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $zatitle_prompt);
                                    if($temp_cont !== NULL)
                                    {
                                        $zatitle_prompt = $temp_cont;
                                    }
                                }
                            }
                        }
                        if($zatitle_prompt != '')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon title'));
                            $written = aiomatic_write_content($zatitle_prompt, $topic_title_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, true, false, 'title', 'user', $assistant_id, $thread_id, $store_data);
                            if($written === false)
                            {
                                aiomatic_log_to_file('Failed to generate title!');
                                if($auto == 1)
                                {
                                    aiomatic_clearFromList($param, $type);
                                }
                                return 'fail';
                            }
                            else
                            {
                                $written = ucfirst(trim(trim($written), '.'));
                                $post_title = $written;
                            }
                        }
                        else
                        {
                            aiomatic_log_to_file('Empty processed title prompt. Nothing to do.');
                            if($auto == 1)
                            {
                                aiomatic_clearFromList($param, $type);
                            }
                            return 'fail';
                        }
                    }
                    if(empty($post_title))
                    {
                        aiomatic_log_to_file('Failed to automatically generate Amazon product roundup title!');
                        if($auto == 1)
                        {
                            aiomatic_clearFromList($param, $type);
                        }
                        return 'fail';
                    }
                    if (strpos($post_title, '%%') === false)
                    {
                        if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                        {
                            $xposts = get_posts(
                                array(
                                    'post_type'              => $post_type,
                                    'title'                  => html_entity_decode($post_title),
                                    'post_status'            => 'any',
                                    'numberposts'            => 1,
                                    'update_post_term_cache' => false,
                                    'update_post_meta_cache' => false,           
                                    'orderby'                => 'post_date ID',
                                    'order'                  => 'ASC',
                                )
                            );
                            if ( ! empty( $xposts ) ) {
                                $zap = $xposts[0];
                            } else {
                                $zap = null;
                            }
                            if($zap !== null)
                            {
                                if($overwrite_existing)
                                {
                                    $update_post_id = $zap->ID;
                                }
                                else
                                {
                                    aiomatic_log_to_file('Post with specified title already existing, skipping it: ' . $post_title);
                                    unset($amazon_keyword_lines[$current_index]);
                                    continue;
                                }
                            }
                        }
                        $new_post_title = $post_title;
                    }
                    else
                    {
                        $new_post_title = $post_title;
                        $new_post_title = aiomatic_replaceContentShortcodes($new_post_title, $img_attr, $ai_command);
                        if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                        {
                            $xposts = get_posts(
                                array(
                                    'post_type'              => $post_type,
                                    'title'                  => html_entity_decode($new_post_title),
                                    'post_status'            => 'any',
                                    'numberposts'            => 1,
                                    'update_post_term_cache' => false,
                                    'update_post_meta_cache' => false,           
                                    'orderby'                => 'post_date ID',
                                    'order'                  => 'ASC',
                                )
                            );
                            if ( ! empty( $xposts ) ) {
                                $zap = $xposts[0];
                            } else {
                                $zap = null;
                            }
                            if($zap !== null)
                            {
                                if($overwrite_existing)
                                {
                                    $update_post_id = $zap->ID;
                                }
                                else
                                {
                                    aiomatic_log_to_file('Post with specified title already published, skipping it: ' . $new_post_title);
                                    unset($amazon_keyword_lines[$current_index]);
                                    continue;
                                }
                            }
                        }
                    }
                    $current_section = '';
                    $headings_arr_copy = $headings_arr;
                    $added_img_list = array();
                    $raw_img_list = array();
                    $full_result_list = array();
                    $added_vid_list = array();
                    $added_images = 0;
                    $added_videos = 0;
                    $heading_results = array();
                    if(empty($post_title))
                    {
                        aiomatic_log_to_file('Empty post title submitted, nothing to do!');
                        continue;
                    }
                    $post_sections = array();
                    foreach($amazresult as $amr)
                    {
                        $post_sections[] = $amr->offer_title;
                    }
                    $new_post_content = '';
                    if(stristr($run_regex_on, 'intro') !== false)
                    {
                        if ($strip_by_regex_prompts !== '')
                        {
                            $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                            $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                            $xcnt = 0;
                            foreach($xstrip_by_regex as $sbr)
                            {
                                if(isset($xreplace_regex[$xcnt]))
                                {
                                    $repreg = $xreplace_regex[$xcnt];
                                }
                                else
                                {
                                    $repreg = '';
                                }
                                $xcnt++;
                                $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $intro_prompt);
                                if($temp_cont !== NULL)
                                {
                                    $intro_prompt = $temp_cont;
                                }
                            }
                        }
                    }
                    if($intro_prompt != '')
                    {
                        $my_intro_prompt = $intro_prompt;
                        $my_intro_prompt = aiomatic_replace_amazon($my_intro_prompt, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                        if($my_intro_prompt != '')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon intro'));
                            $written = aiomatic_write_content($my_intro_prompt, $topic_intro_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'intro', 'user', $assistant_id, $thread_id, $store_data);
                            if($written === false)
                            {
                                aiomatic_log_to_file('Failed to generate intro for section: ' . $current_section);
                                continue;
                            }
                            else
                            {
                                if($new_post_content != '')
                                {
                                    $new_post_content .= ' ';
                                }
                                $new_post_content .= $written;
                            }
                        }
                        else
                        {
                            aiomatic_log_to_file('Empty processed intro prompt. Nothing to do.');
                        }
                    }
                    if($title_outro != '')
                    {
                        $my_title_outro = $title_outro;
                        $my_title_outro = aiomatic_replace_amazon($my_title_outro, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                        $my_title_outro = $spintax->Parse(trim($my_title_outro));
                    }
                    if(!empty($title_toc))
                    {
                        $my_title_toc = $title_toc;
                        $my_title_toc = aiomatic_replace_amazon($my_title_toc, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                        $my_title_toc = $spintax->Parse(trim($my_title_toc));
                    }
                    if($title_qa != '')
                    {
                        $my_title_qa = $title_qa;
                        $my_title_qa = aiomatic_replace_amazon($my_title_qa, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                        $my_title_qa = $spintax->Parse(trim($my_title_qa));
                    }
                    if($content_prompt != '')
                    { 
                        $post_sections_arr = $amazresult;
                        $toc = '';
                        if($enable_toc == '1')
                        {
                            if(!empty($title_toc))
                            {
                                if($my_title_toc != '')
                                {
                                    $toc .= '<h2>' . $my_title_toc . '</h2>';
                                }
                            }
                            $toc .= '<ul class="toc-class">';
                            foreach($post_sections_arr as $the_current_section)
                            {
                                if(!empty($current_section))
                                {
                                    $toc .= '<li><a href="#' . sanitize_title($the_current_section->offer_title) . '">' . $the_current_section->offer_title . '</a></li>';
                                }
                            }
                            if($title_qa != '')
                            {
                                if($my_title_qa != '')
                                {
                                    if($qa_prompt != '' && $enable_qa == '1')
                                    {
                                        $toc .= '<li><a href="#qa">' . $my_title_qa . '</a></li>';
                                    }
                                }
                            }
                            if($title_outro != '')
                            {
                                if($my_title_outro != '')
                                {
                                    if($outro_prompt != '')
                                    {
                                        $toc .= '<li><a href="#outro">' . $my_title_outro . '</a></li>';
                                    }
                                }
                            }
                            $toc .= '</ul>';
                            $new_post_content .= '<br/>' . $toc . '<br/>';
                        }
                        $topic_count = 1;
                        $last_section_content = '';
                        foreach($post_sections_arr as $the_current_section)
                        {
                            if(trim($affiliate_id) != '')
                            {
                                $aff_url = $the_current_section->offer_url;
                            }
                            else
                            {
                                $aff_url = $the_current_section->source_link;
                            }
                            $current_section = trim($the_current_section->offer_title);
                            $current_section = trim($current_section, '.;');
                            $product_title = $current_section;
                            if(empty($current_section))
                            {
                                continue;
                            }
                            $my_post_content = $content_prompt;
                            $product_description = $the_current_section->offer_desc;
                            $product_reviews = implode('<br><br>', $the_current_section->item_reviews);
                            $product_author = $the_current_section->product_author;
                            $product_brand = $the_current_section->product_brand;
                            $product_isbn = $the_current_section->product_isbn;
                            $product_upc = $the_current_section->product_upc;
                            $offer_price = $the_current_section->offer_price;
                            $product_price = $the_current_section->product_price;
                            $product_list_price = $the_current_section->product_list_price;
                            $price_numeric = $the_current_section->price_numeric;
                            $price_currency = $the_current_section->price_currency;
                            $product_asin = $the_current_section->product_asin;
                            $cart_url = $the_current_section->cart_url;
                            $list_price_numeric = $the_current_section->list_price_numeric;
                            $product_imgs = $the_current_section->product_imgs;
                            //new
                            $item_score = $the_current_section->item_score; 
                            $language = $the_current_section->language; 
                            $edition = $the_current_section->edition; 
                            $pages_count = $the_current_section->pages_count; 
                            $publication_date = $the_current_section->publication_date; 
                            $contributors = $the_current_section->contributors; 
                            $manufacturer = $the_current_section->manufacturer; 
                            $binding = $the_current_section->binding; 
                            $product_group = $the_current_section->product_group; 
                            $rating = $the_current_section->rating; 
                            $eans = $the_current_section->eans; 
                            $part_no = $the_current_section->part_no; 
                            $model = $the_current_section->model; 
                            $warranty = $the_current_section->warranty; 
                            $color = $the_current_section->color; 
                            $is_adult = $the_current_section->is_adult; 
                            $dimensions = $the_current_section->dimensions; 
                            $date = $the_current_section->date; 
                            $size = $the_current_section->size; 
                            $unit_count = $the_current_section->unit_count; 

                            $my_post_content = aiomatic_replace_amazon($my_post_content, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                            $my_post_content = str_replace('%%article_so_far%%', $new_post_content, $my_post_content);
                            $my_post_content = str_replace('%%last_section_content%%', $last_section_content, $my_post_content);
                            if(stristr($run_regex_on, 'content') !== false)
                            {
                                if ($strip_by_regex_prompts !== '')
                                {
                                    $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                    $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                    $xcnt = 0;
                                    foreach($xstrip_by_regex as $sbr)
                                    {
                                        if(isset($xreplace_regex[$xcnt]))
                                        {
                                            $repreg = $xreplace_regex[$xcnt];
                                        }
                                        else
                                        {
                                            $repreg = '';
                                        }
                                        $xcnt++;
                                        $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_post_content);
                                        if($temp_cont !== NULL)
                                        {
                                            $my_post_content = $temp_cont;
                                        }
                                    }
                                }
                            }
                            if($first_hand == '1')
                            {
                                $my_post_content = str_replace('%%first_hand_experience_prompt%%', 'Write as if you had first-hand experience with the product you are describing.', $my_post_content);
                            }
                            else
                            {
                                $my_post_content = str_replace('%%first_hand_experience_prompt%%', '', $my_post_content);
                            }
                            $my_post_content = str_replace('%%product_author%%', $the_current_section->product_author, $my_post_content);
                            $my_post_content = str_replace('%%product_brand%%', $the_current_section->product_brand, $my_post_content);
                            $my_post_content = str_replace('%%product_isbn%%', $the_current_section->product_isbn, $my_post_content);
                            $my_post_content = str_replace('%%product_upc%%', $the_current_section->product_upc, $my_post_content);
                            $my_post_content = str_replace('%%offer_url%%', $the_current_section->offer_url, $my_post_content);
                            $my_post_content = str_replace('%%offer_price%%', $the_current_section->offer_price, $my_post_content);
                            $my_post_content = str_replace('%%product_list_price%%', $the_current_section->product_list_price, $my_post_content);
                            $my_post_content = str_replace('%%offer_img%%', $the_current_section->offer_img, $my_post_content);
                            $my_post_content = str_replace('%%price_numeric%%', $the_current_section->price_numeric, $my_post_content);
                            $my_post_content = str_replace('%%price_currency%%', $the_current_section->price_currency, $my_post_content);
                            $my_post_content = str_replace('%%review_link%%', $the_current_section->review_link, $my_post_content);
                            $my_post_content = str_replace('%%product_asin%%', $the_current_section->product_asin, $my_post_content);
                            $my_post_content = str_replace('%%cart_url%%', $the_current_section->cart_url, $my_post_content);
                            $my_post_content = str_replace('%%list_price_numeric%%', $the_current_section->list_price_numeric, $my_post_content);
                            $my_post_content = str_replace('%%product_imgs%%', $the_current_section->product_imgs, $my_post_content);
                            $my_post_content = str_replace('%%product_imgs_html%%', $the_current_section->product_imgs_html, $my_post_content);
                            $my_post_content = str_replace('%%price_with_discount_fixed%%', $the_current_section->price_with_discount_fixed, $my_post_content);
                            if($my_post_content != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon topic content #' . $topic_count));
                                $topic_count++;
                                $written = aiomatic_write_content($my_post_content, $topic_content_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'content', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate content for section: ' . $current_section);
                                    continue;
                                }
                                else
                                {
                                    $written = str_ireplace($current_section, '', $written);
                                    preg_match_all('#\d+\.\s*([\s\S]*)#', $current_section, $mxatches);
                                    if(isset($mxatches[1][0]))
                                    {
                                        $written = str_ireplace(trim($mxatches[1][0]), '', $written);
                                        $written = str_ireplace(str_replace(['"', '\''], '', $mxatches[1][0]), '', $written);
                                    }
                                    $written = str_ireplace('<h2></h2>', '', $written);
                                    $written = str_ireplace('<h3></h3>', '', $written);
                                    $link_to_source = $current_section;
                                    if($no_headlink != '1')
                                    {
                                        $link_to_source = '<a target="_blank" rel="nofollow sponsored noopener" href="' . $aff_url . '">' . $current_section . '</a>';
                                    }
                                    if($sections_role == 'h2')
                                    {
                                        $new_post_content .= '<h2 id="' . sanitize_title($current_section) . '">' . $link_to_source . '</h2>';
                                    }
                                    elseif($sections_role == 'h3')
                                    {
                                        $new_post_content .= '<h3 id="' . sanitize_title($current_section) . '">' . $link_to_source . '</h3>';
                                    }
                                    elseif($sections_role == 'b')
                                    {
                                        $new_post_content .= '<b id="' . sanitize_title($current_section) . '">' . $link_to_source . '</b>';
                                    }
                                    elseif($sections_role == 'i')
                                    {
                                        $new_post_content .= '<i id="' . sanitize_title($current_section) . '">' . $link_to_source . '</i>';
                                    }
                                    elseif($sections_role == 'bi')
                                    {
                                        $new_post_content .= '<b><i id="' . sanitize_title($current_section) . '">' . $link_to_source . '</i></b>';
                                    }
                                    elseif($sections_role == 'p')
                                    {
                                        $new_post_content .= '<p id="' . sanitize_title($current_section) . '">' . $link_to_source . '</p>';
                                    }
                                    elseif($sections_role == 'x')
                                    {
                                        $new_post_content .= '<br/><span id="' . sanitize_title($current_section) . '">' . $link_to_source . '</span><br/>';
                                    }
                                    else
                                    {
                                        $new_post_content .= '<br/>' . $link_to_source . '<br/>';
                                    }
                                    if($topic_images == '1')
                                    {
                                        $show_url = $the_current_section->product_img;
                                        if(isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled')
                                        {
                                            $localpath = aiomatic_copy_image_locally($show_url, $attached_id, '', false, '');
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                            if($localpath !== false)
                                            {
                                                $show_url = $localpath[0];
                                            }
                                        }
                                        $new_post_content .= '<br/><img class="rimage_class" src="' . $show_url . '" alt="' . esc_attr($post_title) . '"><br/>';
                                        $added_img_list[] = $show_url;
                                        $added_images++;
                                    }
                                    $last_section_content = $written;
                                    $new_post_content .= $written;
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed content prompt. Nothing to do.');
                            }
                        }
                    }
                    if($enable_qa == '1')
                    {
                        if($qa_prompt != '')
                        {
                            $my_qa_prompt = $qa_prompt;
                            $my_qa_prompt = aiomatic_replace_amazon($my_qa_prompt, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                            if(stristr($run_regex_on, 'qa') !== false)
                            {
                                if ($strip_by_regex_prompts !== '')
                                {
                                    $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                    $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                    $xcnt = 0;
                                    foreach($xstrip_by_regex as $sbr)
                                    {
                                        if(isset($xreplace_regex[$xcnt]))
                                        {
                                            $repreg = $xreplace_regex[$xcnt];
                                        }
                                        else
                                        {
                                            $repreg = '';
                                        }
                                        $xcnt++;
                                        $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_qa_prompt);
                                        if($temp_cont !== NULL)
                                        {
                                            $my_qa_prompt = $temp_cont;
                                        }
                                    }
                                }
                            }
                            if($my_qa_prompt != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon qa'));
                                $written = aiomatic_write_content($my_qa_prompt, $topic_qa_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'qa', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate Q&A for topic: ' . $my_qa_prompt);
                                    continue;
                                }
                                else
                                {
                                    if($new_post_content != '')
                                    {
                                        $new_post_content .= ' ';
                                    }
                                    if($my_title_qa !== '')
                                    {
                                        if($sections_role == 'h2')
                                        {
                                            $new_post_content .= '<h2 id="qa">' . $my_title_qa . '</h2>';
                                        }
                                        elseif($sections_role == 'h3')
                                        {
                                            $new_post_content .= '<h3 id="qa">' . $my_title_qa . '</h3>';
                                        }
                                        elseif($sections_role == 'b')
                                        {
                                            $new_post_content .= '<b id="qa">' . $my_title_qa . '</b>';
                                        }
                                        elseif($sections_role == 'i')
                                        {
                                            $new_post_content .= '<i id="qa">' . $my_title_qa . '</i>';
                                        }
                                        elseif($sections_role == 'bi')
                                        {
                                            $new_post_content .= '<b><i id="qa">' . $my_title_qa . '</i></b>';
                                        }
                                        elseif($sections_role == 'p')
                                        {
                                            $new_post_content .= '<p id="qa">' . $my_title_qa . '</p>';
                                        }
                                        elseif($sections_role == 'x')
                                        {
                                            $new_post_content .= '<br/><span id="qa">' . $my_title_qa . '</span><br/>';
                                        }
                                        else
                                        {
                                            $new_post_content .= '<br/>' . $my_title_qa . '<br/>';
                                        }
                                    }
                                    $new_post_content .= $written;
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed Q&A prompt. Nothing to do.');
                            }
                        }
                    }
                    if($enable_table == '1')
                    {
                        if($table_prompt != '')
                        {
                            $my_table_prompt = $table_prompt;
                            $my_table_prompt = aiomatic_replace_amazon($my_table_prompt, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                            if(stristr($run_regex_on, 'table') !== false)
                            {
                                if ($strip_by_regex_prompts !== '')
                                {
                                    $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                    $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                    $xcnt = 0;
                                    foreach($xstrip_by_regex as $sbr)
                                    {
                                        if(isset($xreplace_regex[$xcnt]))
                                        {
                                            $repreg = $xreplace_regex[$xcnt];
                                        }
                                        else
                                        {
                                            $repreg = '';
                                        }
                                        $xcnt++;
                                        $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_table_prompt);
                                        if($temp_cont !== NULL)
                                        {
                                            $my_table_prompt = $temp_cont;
                                        }
                                    }
                                }
                            }
                            if($my_table_prompt != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon table'));
                                $written = aiomatic_write_content($my_table_prompt, $topic_table_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'qa', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate Comparison Table for topic: ' . $my_table_prompt);
                                    continue;
                                }
                                else
                                {
                                    if($new_post_content != '')
                                    {
                                        $new_post_content .= ' ';
                                    }
                                    $new_post_content .= $written;
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed Comparison Table prompt. Nothing to do.');
                            }
                        }
                    }
                    if($outro_prompt != '')
                    {
                        $my_outro_prompt = $outro_prompt;
                        $my_outro_prompt = aiomatic_replace_amazon($my_outro_prompt, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                        if(stristr($run_regex_on, 'outro') !== false)
                        {
                            if ($strip_by_regex_prompts !== '')
                            {
                                $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                $xcnt = 0;
                                foreach($xstrip_by_regex as $sbr)
                                {
                                    if(isset($xreplace_regex[$xcnt]))
                                    {
                                        $repreg = $xreplace_regex[$xcnt];
                                    }
                                    else
                                    {
                                        $repreg = '';
                                    }
                                    $xcnt++;
                                    $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_outro_prompt);
                                    if($temp_cont !== NULL)
                                    {
                                        $my_outro_prompt = $temp_cont;
                                    }
                                }
                            }
                        }
                        if($my_outro_prompt != '')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon outro'));
                            $written = aiomatic_write_content($my_outro_prompt, $topic_outro_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, true, false, 'outro', 'user', $assistant_id, $thread_id, $store_data);
                            if($written === false)
                            {
                                aiomatic_log_to_file('Failed to generate outro for section: ' . $current_section);
                                continue;
                            }
                            else
                            {
                                if($new_post_content != '')
                                {
                                    $new_post_content .= ' ';
                                }
                                if($title_outro !== '')
                                {
                                    if($my_title_outro != '')
                                    {
                                        if($sections_role == 'h2')
                                        {
                                            $new_post_content .= '<h2 id="outro">' . $my_title_outro . '</h2>';
                                        }
                                        elseif($sections_role == 'h3')
                                        {
                                            $new_post_content .= '<h3 id="outro">' . $my_title_outro . '</h3>';
                                        }
                                        elseif($sections_role == 'b')
                                        {
                                            $new_post_content .= '<b id="outro">' . $my_title_outro . '</b>';
                                        }
                                        elseif($sections_role == 'i')
                                        {
                                            $new_post_content .= '<i id="outro">' . $my_title_outro . '</i>';
                                        }
                                        elseif($sections_role == 'bi')
                                        {
                                            $new_post_content .= '<b><i id="outro">' . $my_title_outro . '</i></b>';
                                        }
                                        elseif($sections_role == 'p')
                                        {
                                            $new_post_content .= '<p id="outro">' . $my_title_outro . '</p>';
                                        }
                                        elseif($sections_role == 'x')
                                        {
                                            $new_post_content .= '<br/><span id="outro">' . $my_title_outro . '</span><br/>';
                                        }
                                        else
                                        {
                                            $new_post_content .= '<br/>' . $my_title_outro . '<br/>';
                                        }
                                    }
                                }
                                else
                                {
                                    $new_post_content .= '<br/><br/>';
                                }
                                $new_post_content .= $written;
                            }
                        }
                        else
                        {
                            aiomatic_log_to_file('Empty processed outro prompt. Nothing to do.');
                        }
                    }
                    if($new_post_content == '')
                    {
                        aiomatic_log_to_file("Warning, empty post content because of empty content prompt!");
                    }

                    $new_post_excerpt = '';
                    $current_section = implode(',', $post_sections);
                    if($excerpt_prompt != '')
                    {
                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                        {
                            $excerpt_prompt_arr = preg_split('/\r\n|\r|\n/', $excerpt_prompt);
                            $my_post_excerpt = $excerpt_prompt_arr[array_rand($excerpt_prompt_arr)];
                        }
                        else
                        {
                            $my_post_excerpt = $excerpt_prompt;
                        }
                        $my_post_excerpt = aiomatic_replace_amazon($my_post_excerpt, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                        if(stristr($run_regex_on, 'excerpt') !== false)
                        {
                            if ($strip_by_regex_prompts !== '')
                            {
                                $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                $xcnt = 0;
                                foreach($xstrip_by_regex as $sbr)
                                {
                                    if(isset($xreplace_regex[$xcnt]))
                                    {
                                        $repreg = $xreplace_regex[$xcnt];
                                    }
                                    else
                                    {
                                        $repreg = '';
                                    }
                                    $xcnt++;
                                    $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_post_excerpt);
                                    if($temp_cont !== NULL)
                                    {
                                        $my_post_excerpt = $temp_cont;
                                    }
                                }
                            }
                        }
                        if($my_post_excerpt != '')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon excerpt'));
                            $written = aiomatic_write_content($my_post_excerpt, $topic_excerpt_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, true, false, 'excerpt', 'user', $assistant_id, $thread_id, $store_data);
                            if($written === false)
                            {
                                aiomatic_log_to_file('Failed to generate excerpt!');
                            }
                            else
                            {
                                $new_post_excerpt = $written;
                            }
                        }
                        else
                        {
                            aiomatic_log_to_file('Empty processed excerpt prompt. Nothing to do.');
                        }
                    }

                    $get_img = '';
                    if($royalty_free == '1')
                    {
                        if($enable_ai_images == '1')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = aiomatic_get_api_service($token, $image_model);
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    if (isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] == 'on')
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $aierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating AI image'));
                                    $get_img = aiomatic_generate_ai_image($token, 1, $ai_command_image, $image_size, 'featuredImage', $skip_this_copy, 0, $aierror, $image_model, $post_title);
                                    if($get_img !== false)
                                    {
                                        foreach($get_img as $tmpimg)
                                        {
                                            $get_img = $tmpimg;
                                            break;
                                        }
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate AI featured image: ' . $aierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '2')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Stability.AI';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Stable Diffusion image'));
                                    $get_img = aiomatic_generate_stability_image($ai_command_image, $height, $width, 'featuredStableImage', 0, false, $ierror, $skip_this_copy, false, '', 0);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img[1]);
                                        }
                                        if(is_array($get_img) && isset($get_img[1]))
                                        {
                                            $get_img = $get_img[1];
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Stability.AI featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '7')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Google';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    if (isset($aiomatic_Main_Settings['google_ai_image_model']) && trim($aiomatic_Main_Settings['google_ai_image_model']) != '') 
                                    {
                                        $model = trim($aiomatic_Main_Settings['google_ai_image_model']);
                                    }
                                    else
                                    {
                                        $model = AIMOGEN_GOOGLE_IMAGE_DEFAULT_MODEL;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Google image'));
                                    $get_img = aiomatic_generate_image_google($ai_command_image, $model, 'featuredGoogleImage', false, $ierror, false);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img[1]);
                                        }
                                        if(is_array($get_img) && isset($get_img[1]))
                                        {
                                            $get_img = $get_img[1];
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Stability.AI featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '4')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Midjourney';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1792x1024')
                                    {
                                        $width = '1792';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1024x1792')
                                    {
                                        $width = '1024';
                                        $height = '1792';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Midjourney image'));
                                    $get_img = aiomatic_generate_ai_image_midjourney($ai_command_image, $width, $height, 'featuredMidjourneyImage', $skip_this_copy, $ierror);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Midjourney featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '5')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Replicate';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1792x1024')
                                    {
                                        $width = '1792';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1024x1792')
                                    {
                                        $width = '1024';
                                        $height = '1792';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Replicate image'));
                                    $get_img = aiomatic_generate_replicate_image($ai_command_image, $width, $height, 'featuredReplicateImage', $skip_this_copy, $ierror);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Replicate featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '6')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Ideogram';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1792x1024')
                                    {
                                        $width = '1792';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1024x1792')
                                    {
                                        $width = '1024';
                                        $height = '1792';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Ideogram image'));
                                    $get_img = aiomatic_generate_ideogram_image($ai_command_image, $width, $height, 'featuredIdeogramImage', $skip_this_copy, $ierror);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Ideogram featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '8')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Cloudflare';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1792x1024')
                                    {
                                        $width = '1792';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1024x1792')
                                    {
                                        $width = '1024';
                                        $height = '1792';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Cloudflare image'));
                                    $get_img = aiomatic_generate_cloudflare_image($ai_command_image, $width, $height, 'featuredCloudflareImage', $skip_this_copy, $ierror);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Cloudflare featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '9')
                        {
                            $random_image = aiomatic_get_random_media_library_image();

                            if ($random_image !== false)
                            {
                                $get_img = $random_image['url'];

                                if (isset($aiomatic_Main_Settings['enable_detailed_logging']))
                                {
                                    aiomatic_log_to_file(
                                        'Random Media Library featured image selected: ' .
                                        $get_img .
                                        ' (ID: ' . $random_image['id'] . ')'
                                    );
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file(
                                    'Failed to find a random image in Media Library for featured image.'
                                );

                                $get_img = '';
                            }
                        }
                        elseif($enable_ai_images == '3')
                        {
                            if ($image_url != '') 
                            {
                                $replacement = str_replace(array('[', ']'), '', $query_words);
                                $image_url_temp = str_replace('%%item_title%%', $replacement, $image_url);
                                $image_url_temp = preg_replace_callback('#%%random_image\[([^\]]*?)\](\[\d+\])?%%#', function ($matches) {
                                    if(isset($matches[2]))
                                    {
                                        $chance = trim($matches[2], '[]');
                                    }
                                    else
                                    {
                                        $chance = '';
                                    }
                                    $arv = array();
                                    $my_img = aiomatic_get_random_image_google($matches[1], 0, 0, $chance, $arv);
                                    return $my_img;
                                }, $image_url_temp);
                                $img_rulx = $spintax->Parse(trim($image_url_temp));
                                $selected_img = aiomatic_select_ai_image($post_title, $img_rulx);
                                if($selected_img === false)
                                {
                                    $img_rulx = explode(',', $img_rulx);
                                    $img_rulx = trim($img_rulx[array_rand($img_rulx)]);
                                    if($img_rulx != '')
                                    {
                                        $get_img = $img_rulx;
                                    }
                                }
                                else
                                {
                                    $get_img = $selected_img;
                                }
                            }
                        }
                        else
                        {
                            $image_query_set = false;
                            $query_words = '';
                            $ai_command_image = '';
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                            }
                            if($ai_command_image != '')
                            {
                                $query_words = $ai_command_image;
                                $image_query = $ai_command_image;
                                $image_query_set = true;
                            }
                            if(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'textrazor')
                            {
                                if(isset($aiomatic_Main_Settings['textrazor_key']) && trim($aiomatic_Main_Settings['textrazor_key']) != '')
                                {
                                    try
                                    {
                                        if(!class_exists('TextRazor'))
                                        {
                                            require_once(dirname(__FILE__) . "/res/TextRazor.php");
                                        }
                                        TextRazorSettings::setApiKey(trim($aiomatic_Main_Settings['textrazor_key']));
                                        $textrazor = new TextRazor();
                                        $textrazor->addExtractor('entities');
                                        $response = $textrazor->analyze($image_query);
                                        if (isset($response['response']['entities'])) 
                                        {
                                            foreach ($response['response']['entities'] as $entity) 
                                            {
                                                $query_words = '';
                                                if(isset($entity['entityEnglishId']))
                                                {
                                                    $query_words = $entity['entityEnglishId'];
                                                }
                                                else
                                                {
                                                    $query_words = $entity['entityId'];
                                                }
                                                if($query_words != '')
                                                {
                                                    $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                                    if(!empty($attached_id))
                                                    {
                                                        $additional_attachments[] = $attached_id;
                                                    }
                                                    if(!empty($z_img))
                                                    {
                                                        $get_img = $z_img;
                                                        $go_local_image = false;
                                                        if(!function_exists('is_plugin_active'))
                                                        {
                                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                                        }
                                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                                        {
                                                            $go_local_image = true;
                                                        }
                                                        if($go_local_image == true)
                                                        {
                                                            $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, $query_words);
                                                            if(!empty($attached_id))
                                                            {
                                                                $additional_attachments[] = $attached_id;
                                                            }
                                                            if($localpath !== false)
                                                            {
                                                                $get_img = $localpath[0];
                                                            }
                                                        }
                                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                            aiomatic_log_to_file('Royalty Free Image Generated with help of TextRazor (kw: "' . $query_words . '"): ' . $z_img);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch(Exception $e)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Failed to search for keywords using TextRazor (2): ' . $e->getMessage());
                                        }
                                    }
                                }
                            }
                            elseif(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'openai')
                            {
                                if(isset($aiomatic_Main_Settings['keyword_prompts']) && trim($aiomatic_Main_Settings['keyword_prompts']) != '')
                                {
                                    if(isset($aiomatic_Main_Settings['keyword_model']) && $aiomatic_Main_Settings['keyword_model'] != '')
                                    {
                                        $kw_model = $aiomatic_Main_Settings['keyword_model'];
                                    }
                                    else
                                    {
                                        $kw_model = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                    }
                                    if(isset($aiomatic_Main_Settings['keyword_assistant_id']) && $aiomatic_Main_Settings['keyword_assistant_id'] != '')
                                    {
                                        $keyword_assistant_id = $aiomatic_Main_Settings['keyword_assistant_id'];
                                    }
                                    else
                                    {
                                        $keyword_assistant_id = '';
                                    }
                                    $title_ai_command = trim($aiomatic_Main_Settings['keyword_prompts']);
                                    $title_ai_command = str_replace('%%default_post_cats%%', $default_cat_list, $title_ai_command);
                                    $title_ai_command = str_replace('%%original_post_title%%', $post_title, $title_ai_command);
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $title_ai_command = preg_split('/\r\n|\r|\n/', $title_ai_command);
                                        $title_ai_command = array_filter($title_ai_command);
                                        if(count($title_ai_command) > 0)
                                        {
                                            $title_ai_command = $title_ai_command[array_rand($title_ai_command)];
                                        }
                                        else
                                        {
                                            $title_ai_command = '';
                                        }
                                    }
                                    $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                    if(!empty($title_ai_command))
                                    {
                                        $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    $title_ai_command = trim($title_ai_command);
                                    if (filter_var($title_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($title_ai_command, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($title_ai_command);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $title_ai_command = $txt_content;
                                                    $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                                    $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($title_ai_command))
                                    {
                                        aiomatic_log_to_file('Empty API keyword extractor seed expression provided!');
                                        $title_ai_command = 'Type the most relevant keyword, no other text before or after it, for a blog post titled:  ' . trim(strip_tags($post_title));
                                    }
                                    if(aiomatic_strlen($title_ai_command) > $max_seed_tokens * 4)
                                    {
                                        $title_ai_command = aiomatic_substr($title_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                                    }
                                    $title_ai_command = trim($title_ai_command);
                                    if(empty($title_ai_command))
                                    {
                                        aiomatic_log_to_file('Empty API title seed expression provided(3)! ' . print_r($title_ai_command, true));
                                    }
                                    else
                                    {
                                        $query_token_count = count(aiomatic_encode($title_ai_command));
                                        $available_tokens = aiomatic_compute_available_tokens($kw_model, $max_tokens, $title_ai_command, $query_token_count);
                                        if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                        {
                                            $string_len = aiomatic_strlen($title_ai_command);
                                            $string_len = $string_len / 2;
                                            $string_len = intval(0 - $string_len);
                                            $title_ai_command = aiomatic_substr($title_ai_command, 0, $string_len);
                                            $title_ai_command = trim($title_ai_command);
                                            $query_token_count = count(aiomatic_encode($title_ai_command));
                                            $available_tokens = $max_tokens - $query_token_count;
                                        }
                                        $aierror = '';
                                        $finish_reason = '';
                                        if(!empty($global_prepend))
                                        {
                                            $title_ai_command = $global_prepend . ' ' . $title_ai_command;
                                        }
                                        if(!empty($global_append))
                                        {
                                            $title_ai_command = $title_ai_command . ' ' . $global_append;
                                        }
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = aiomatic_get_api_service($token, $kw_model);
                                            aiomatic_log_to_file('Calling ' . $api_service . ' (' . $keyword_assistant_id . '/' . $kw_model . ')(' . $available_tokens . ') for title text: ' . $title_ai_command);
                                        }
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating royalty free keywords'));
                                        $generated_text = aiomatic_generate_text($token, $kw_model, $title_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'keywordID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $keyword_assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                        if($generated_text === false)
                                        {
                                            aiomatic_log_to_file('Keyword generator error: ' . $aierror);
                                            $ai_title = '';
                                        }
                                        else
                                        {
                                            $ai_title = trim(trim($generated_text), '.');
                                            $ai_titles = explode(',', $ai_title);
                                            foreach($ai_titles as $query_words)
                                            {
                                                $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, trim($query_words), $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                                if(!empty($z_img))
                                                {
                                                    $get_img = $z_img;
                                                    $go_local_image = false;
                                                    if(!function_exists('is_plugin_active'))
                                                    {
                                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                                    }
                                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                                    {
                                                        $go_local_image = true;
                                                    }
                                                    if($go_local_image == true)
                                                    {
                                                        $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, $query_words);
                                                        if(!empty($attached_id))
                                                        {
                                                            $additional_attachments[] = $attached_id;
                                                        }
                                                        if($localpath !== false)
                                                        {
                                                            $get_img = $localpath[0];
                                                        }
                                                    }
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                        aiomatic_log_to_file('Royalty Free Image Generated with help of AI (kw: "' . $query_words . '"): ' . $z_img);
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = aiomatic_get_api_service($token, $kw_model);
                                            aiomatic_log_to_file('Successfully got API keyword result from ' . $api_service . ': ' . $ai_title);
                                        }
                                    }
                                }
                            }
                            if(empty($get_img))
                            {
                                if($image_query_set == true && !empty($image_query))
                                {
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating royalty free image'));
                                    $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $image_query, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                    if(!empty($attached_id))
                                    {
                                        $additional_attachments[] = $attached_id;
                                    }
                                    if($get_img == '' || $get_img === false)
                                    {
                                        if(isset($aiomatic_Main_Settings['bimage']) && $aiomatic_Main_Settings['bimage'] == 'on')
                                        {
                                            $keyword_class = new Aiomatic_keywords();
                                            $image_query = $keyword_class->keywords($image_query, 1);
                                            $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $image_query, $img_attr, $attached_id, 20, true, $raw_img_list, array(), $full_result_list);
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                        }
                                    }
                                }
                                if(empty($get_img))
                                {
                                    $keyword_class = new Aiomatic_keywords();
                                    $query_words = $keyword_class->keywords($post_title, 2);
                                    $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                    if(!empty($attached_id))
                                    {
                                        $additional_attachments[] = $attached_id;
                                    }
                                    if($get_img == '' || $get_img === false)
                                    {
                                        if(isset($aiomatic_Main_Settings['bimage']) && $aiomatic_Main_Settings['bimage'] == 'on')
                                        {
                                            $query_words = $keyword_class->keywords($post_title, 1);
                                            $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 20, true, $raw_img_list, array(), $full_result_list);
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                            if($get_img == '' || $get_img === false)
                                            {
                                                if(isset($aiomatic_Main_Settings['no_royalty_skip']) && $aiomatic_Main_Settings['no_royalty_skip'] == 'on')
                                                {
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                        aiomatic_log_to_file('Skipping importing because no royalty free image found.');
                                                    }
                                                    unset($post_title_lines[$current_index]);
                                                    continue;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if(isset($aiomatic_Main_Settings['no_royalty_skip']) && $aiomatic_Main_Settings['no_royalty_skip'] == 'on')
                                            {
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                    aiomatic_log_to_file('Skipping importing because no royalty free image found.');
                                                }
                                                unset($post_title_lines[$current_index]);
                                                continue;
                                            }
                                        }
                                    }
                                }
                                if(!empty($get_img))
                                {
                                    $go_local_image = false;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                    {
                                        $go_local_image = true;
                                    }
                                    if($go_local_image == true)
                                    {
                                        $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, '');
                                        if(!empty($attached_id))
                                        {
                                            $additional_attachments[] = $attached_id;
                                        }
                                        if($localpath !== false)
                                        {
                                            $get_img = $localpath[0];
                                        }
                                    }
                                }
                            }
                        }
                    }
                    elseif($royalty_free == '2')
                    {
                        $get_img = $amazon_thumb;
                    }
                    if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                    {
                        $already_spinned = '1';
                    }
                    $my_post                              = array();
                    $my_post['aiomatic_post_image']       = $get_img;
                    if($enable_ai_images == '2')
                    {
                        $my_post['aiomatic_local_image']      = '1';
                    }
                    else
                    {
                        $my_post['aiomatic_local_image']      = '0';
                    }
                    $my_post['aiomatic_enable_pingbacks'] = $enable_pingback;
                    $my_post['default_category']          = $default_category;
                    $my_post['post_type']                 = $post_type;
                    $my_post['comment_status']            = $accept_comments;
                    if (isset($aiomatic_Main_Settings['draft_first']) && $aiomatic_Main_Settings['draft_first'] != 'on')
                    {
                        if($post_status == 'publish')
                        {
                            $draft_me = true;
                            $my_post['post_status'] = 'draft';
                        }
                        else
                        {
                            $my_post['post_status']   = $post_status;
                        }
                    }
                    else
                    {
                        $my_post['post_status']               = $post_status;
                    }
                    if($user_name_type == 'rand')
                    {
                        $randid = aiomatic_display_random_user();
                        if($randid === false)
                        {
                            $my_post['post_author']               = aimogen_get_admin_user_id();
                        }
                        else
                        {
                            $my_post['post_author']               = $randid->ID;
                        }
                    }
                    else
                    {
                        $my_post['post_author']               = $post_user_name;
                    }
                    if($strip_title == '1')
                    {
                        $new_post_content = str_replace($post_title, '', $new_post_content);
                        $new_post_content = str_replace('<h2></h2>', '', $new_post_content);
                        $new_post_content = str_replace('<h3></h3>', '', $new_post_content);
                    }
                    if (isset($aiomatic_Main_Settings['swear_filter']) && $aiomatic_Main_Settings['swear_filter'] == 'on') 
                    {
                        require_once(dirname(__FILE__) . "/res/swear.php");
                        $new_post_content = aimogenpro_filterwords($new_post_content);
                    }
                    if(isset($aiomatic_Main_Settings['global_ban_words']) && $aiomatic_Main_Settings['global_ban_words'] != '') {
                        $continue    = false;
                        $aiomatic_Main_Settings['global_ban_words'] = trim(trim(trim($aiomatic_Main_Settings['global_ban_words']), ','));
                        $banned_list = explode(',', $aiomatic_Main_Settings['global_ban_words']);
                        foreach ($banned_list as $banned_word) {
                            if (stripos($new_post_content, trim($banned_word)) !== FALSE) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s content contains global banned word: ' . $banned_word);
                                }
                                $continue = true;
                                break;
                            }
                            if (stripos($post_title, trim($banned_word)) !== FALSE) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s title contains global banned word: ' . $banned_word);
                                }
                                $continue = true;
                                break;
                            }
                        }
                        if ($continue === true) {
                            continue;
                        }
                    }
                    if(isset($aiomatic_Main_Settings['global_req_words']) && $aiomatic_Main_Settings['global_req_words'] != '')
                    {
                        if(isset($aiomatic_Main_Settings['require_only_one']) && $aiomatic_Main_Settings['require_only_one'] == 'on')
                        {
                            $continue      = true;
                            $aiomatic_Main_Settings['global_req_words'] = trim(trim(trim($aiomatic_Main_Settings['global_req_words']), ','));
                            $required_list = explode(',', $aiomatic_Main_Settings['global_req_words']);
                            foreach ($required_list as $required_word) {
                                if (stripos($new_post_content, trim($required_word)) !== FALSE || stripos($post_title, trim($required_word)) !== FALSE) {
                                    $continue = false;
                                    break;
                                }
                            }
                            if ($continue === true) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s content doesn\'t contain global required words.');
                                }
                                continue;
                            }
                        }
                        else
                        {
                            $continue      = false;
                            $aiomatic_Main_Settings['global_req_words'] = trim(trim(trim($aiomatic_Main_Settings['global_req_words']), ','));
                            $required_list = explode(',', $aiomatic_Main_Settings['global_req_words']);
                            foreach ($required_list as $required_word) {
                                if (stripos($new_post_content, trim($required_word)) === FALSE && stripos($post_title, trim($required_word)) === FALSE) {
                                    $continue = true;
                                    break;
                                }
                            }
                            if ($continue === true) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s content doesn\'t contain global required words.');
                                }
                                continue;
                            }
                        }
                    }
                    $new_post_title = $post_title;
                    if (isset($aiomatic_Main_Settings['spin_what']) && $aiomatic_Main_Settings['spin_what'] === 'omni') 
                    {
                        $skip_spin = '1';
                    }
                    $arr = aiomatic_spin_and_translate($new_post_title, $new_post_content, '3', $skip_spin, $skip_translate);
                    if($arr[0] != $new_post_title)
                    {
                        $new_post_title = $arr[0];
                        if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                        {
                            $posts = get_posts(
                                array(
                                    'post_type'              => $post_type,
                                    'title'                  => html_entity_decode($new_post_title),
                                    'post_status'            => 'any',
                                    'numberposts'            => 1,
                                    'update_post_term_cache' => false,
                                    'update_post_meta_cache' => false,           
                                    'orderby'                => 'post_date ID',
                                    'order'                  => 'ASC',
                                )
                            );
                            if ( ! empty( $posts ) ) {
                                $zap = $posts[0];
                            } else {
                                $zap = null;
                            }
                            if($zap !== null)
                            {
                                if($overwrite_existing)
                                {
                                    $update_post_id = $zap->ID;
                                }
                                else
                                {
                                    aiomatic_log_to_file('Post with specified title already existing (after spin/translate), skipping it: ' . $new_post_title);
                                    unset($post_title_lines[$current_index]);
                                    continue;
                                }
                            }
                        }
                    }
                    $new_post_content            = $arr[1];
                    if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                    {
                        $already_spinned = '1';
                    }
                    if ($auto_categories == 'content') {
                        $extra_categories            = aiomatic_extractKeyWords($new_post_content);
                        $extra_categories            = implode(',', $extra_categories);
                    }
                    elseif ($auto_categories == 'title') {
                        $extra_categories            = aiomatic_extractKeyWords($new_post_title);
                        $extra_categories            = implode(',', $extra_categories);
                    }
                    elseif ($auto_categories == 'both') {
                        $extra_categories            = aiomatic_extractKeyWords($new_post_content);
                        $extra_categories            = implode(',', $extra_categories);
                        $extra_categories2            = aiomatic_extractKeyWords($new_post_title);
                        $extra_categories2            = implode(',', $extra_categories2);
                        if($extra_categories2 != '')
                        {
                            $extra_categories .= ',' . $extra_categories2;
                        }
                    }
                    elseif ($auto_categories == 'ai') 
                    {
                        $category_ai_command = $orig_ai_command_category;
                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                        {
                            $category_ai_command = preg_split('/\r\n|\r|\n/', $category_ai_command);
                            $category_ai_command = array_filter($category_ai_command);
                            if(count($category_ai_command) > 0)
                            {
                                $category_ai_command = $category_ai_command[array_rand($category_ai_command)];
                            }
                            else
                            {
                                $category_ai_command = '';
                            }
                        }
                        $category_ai_command = aiomatic_replaceSynergyShortcodes($category_ai_command);
                        if(!empty($category_ai_command))
                        {
                            $category_ai_command = aiomatic_replaceAIPostShortcodes($category_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                            $category_ai_command = aiomatic_replace_amazon($category_ai_command, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                        }
                        else
                        {
                            $category_ai_command = trim(strip_tags('Write a comma separated list of categories, for the post title: %%post_title%%'));
                        }
                        $category_ai_command = trim($category_ai_command);
                        if (filter_var($category_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($category_ai_command, '.txt'))
                        {
                            $txt_content = aiomatic_get_web_page($category_ai_command);
                            if ($txt_content !== FALSE) 
                            {
                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                $txt_content = array_filter($txt_content);
                                if(count($txt_content) > 0)
                                {
                                    $txt_content = $txt_content[array_rand($txt_content)];
                                    if(trim($txt_content) != '') 
                                    {
                                        $category_ai_command = $txt_content;
                                        $category_ai_command = aiomatic_replaceSynergyShortcodes($category_ai_command);
                                        $category_ai_command = aiomatic_replaceAIPostShortcodes($category_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        $category_ai_command = aiomatic_replace_amazon($category_ai_command, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                                    }
                                }
                            }
                        }
                        if(empty($category_ai_command))
                        {
                            aiomatic_log_to_file('Empty API post category seed expression provided!');
                        }
                        else
                        {
                            if(aiomatic_strlen($category_ai_command) > $max_seed_tokens * 4)
                            {
                                $category_ai_command = aiomatic_substr($category_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                            }
                            $category_ai_command = trim($category_ai_command);
                            if(empty($category_ai_command))
                            {
                                aiomatic_log_to_file('Empty API category seed expression provided! ' . print_r($category_ai_command, true));
                                break;
                            }
                            $query_token_count = count(aiomatic_encode($category_ai_command));
                            $available_tokens = aiomatic_compute_available_tokens($category_model, $max_tokens, $category_ai_command, $query_token_count);
                            if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                            {
                                $string_len = aiomatic_strlen($category_ai_command);
                                $string_len = $string_len / 2;
                                $string_len = intval(0 - $string_len);
                                $category_ai_command = aiomatic_substr($category_ai_command, 0, $string_len);
                                $category_ai_command = trim($category_ai_command);
                                if(empty($category_ai_command))
                                {
                                    aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($category_ai_command, true));
                                    break;
                                }
                                $query_token_count = count(aiomatic_encode($category_ai_command));
                                $available_tokens = $max_tokens - $query_token_count;
                            }
                            $aierror = '';
                            $finish_reason = '';
                            if(!empty($global_prepend))
                            {
                                $category_ai_command = $global_prepend . ' ' . $category_ai_command;
                            }
                            if(!empty($global_append))
                            {
                                $category_ai_command = $category_ai_command . ' ' . $global_append;
                            }
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $category_model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $category_model . ')(' . $available_tokens . ') for category generator: ' . $category_ai_command);
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating categories'));
                            $generated_text = aiomatic_generate_text($token, $category_model, $category_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'categoryID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', false, $store_data, array(), '', '', '');
                            if($generated_text === false)
                            {
                                aiomatic_log_to_file('Category generator error: ' . $aierror);
                                break;
                            }
                            else
                            {
                                $extra_categories = $generated_text;
                            }
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $category_model);
                                aiomatic_log_to_file('Successfully got API category result from ' . $api_service . ': ' . $generated_text);
                            }
                        }
                    }
                    else
                    {
                        $extra_categories = '';
                    }
                    $my_post['extra_categories'] = $extra_categories;
                    
                    $item_tags                   = aiomatic_extractKeyWords($new_post_content, 3);
                    $item_tags                   = implode(',', $item_tags);
                    $title_tags                   = aiomatic_extractKeyWords($new_post_title, 3);
                    $title_tags                   = implode(',', $title_tags);
                    $item_create_tag_sp = $spintax->Parse($item_create_tag);
                    if ($can_create_tag == 'content') {
                        $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $item_tags;
                        $my_post['extra_tags']       = $item_tags;
                    } else if ($can_create_tag == 'title') {
                        $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $title_tags;
                        $my_post['extra_tags']       = $title_tags;
                    } else if ($can_create_tag == 'both') {
                        $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . ($item_tags != '' ? $item_tags . ',' : '') . $title_tags;
                        $my_post['extra_tags']       = ($item_tags != '' ? $item_tags . ',' : '') . $title_tags;
                    } else if ($can_create_tag == 'ai') {
                        $ai_tags = '';
                        $tag_ai_command = $orig_ai_command_tag;
                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                        {
                            $tag_ai_command = preg_split('/\r\n|\r|\n/', $tag_ai_command);
                            $tag_ai_command = array_filter($tag_ai_command);
                            if(count($tag_ai_command) > 0)
                            {
                                $tag_ai_command = $tag_ai_command[array_rand($tag_ai_command)];
                            }
                            else
                            {
                                $tag_ai_command = '';
                            }
                        }
                        $tag_ai_command = aiomatic_replaceSynergyShortcodes($tag_ai_command);
                        if(!empty($tag_ai_command))
                        {
                            $tag_ai_command = aiomatic_replaceAIPostShortcodes($tag_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                            $tag_ai_command = aiomatic_replace_amazon($tag_ai_command, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                        }
                        else
                        {
                            $tag_ai_command = trim(strip_tags('Write a comma separated list of tags, for the post title: %%post_title%%'));
                        }
                        $tag_ai_command = trim($tag_ai_command);
                        if (filter_var($tag_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($tag_ai_command, '.txt'))
                        {
                            $txt_content = aiomatic_get_web_page($tag_ai_command);
                            if ($txt_content !== FALSE) 
                            {
                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                $txt_content = array_filter($txt_content);
                                if(count($txt_content) > 0)
                                {
                                    $txt_content = $txt_content[array_rand($txt_content)];
                                    if(trim($txt_content) != '') 
                                    {
                                        $tag_ai_command = $txt_content;
                                        $tag_ai_command = aiomatic_replaceSynergyShortcodes($tag_ai_command);
                                        $tag_ai_command = aiomatic_replaceAIPostShortcodes($tag_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        $tag_ai_command = aiomatic_replace_amazon($tag_ai_command, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                                    }
                                }
                            }
                        }
                        if(empty($tag_ai_command))
                        {
                            aiomatic_log_to_file('Empty API post tag seed expression provided!');
                        }
                        else
                        {
                            if(aiomatic_strlen($tag_ai_command) > $max_seed_tokens * 4)
                            {
                                $tag_ai_command = aiomatic_substr($tag_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                            }
                            $tag_ai_command = trim($tag_ai_command);
                            if(empty($tag_ai_command))
                            {
                                aiomatic_log_to_file('Empty API tag seed expression provided! ' . print_r($tag_ai_command, true));
                                break;
                            }
                            $query_token_count = count(aiomatic_encode($tag_ai_command));
                            $available_tokens = aiomatic_compute_available_tokens($tag_model, $max_tokens, $tag_ai_command, $query_token_count);
                            if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                            {
                                $string_len = aiomatic_strlen($tag_ai_command);
                                $string_len = $string_len / 2;
                                $string_len = intval(0 - $string_len);
                                $tag_ai_command = aiomatic_substr($tag_ai_command, 0, $string_len);
                                $tag_ai_command = trim($tag_ai_command);
                                if(empty($tag_ai_command))
                                {
                                    aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($tag_ai_command, true));
                                    break;
                                }
                                $query_token_count = count(aiomatic_encode($tag_ai_command));
                                $available_tokens = $max_tokens - $query_token_count;
                            }
                            $aierror = '';
                            $finish_reason = '';
                            if(!empty($global_prepend))
                            {
                                $tag_ai_command = $global_prepend . ' ' . $tag_ai_command;
                            }
                            if(!empty($global_append))
                            {
                                $tag_ai_command = $tag_ai_command . ' ' . $global_append;
                            }
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $tag_model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $tag_model . ')(' . $available_tokens . ') for tag generator: ' . $tag_ai_command);
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating tags'));
                            $generated_text = aiomatic_generate_text($token, $tag_model, $tag_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'tagID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', false, $store_data, array(), '', '', '');
                            if($generated_text === false)
                            {
                                aiomatic_log_to_file('Tag generator error: ' . $aierror);
                                break;
                            }
                            else
                            {
                                $ai_tags = $generated_text;
                            }
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $tag_model);
                                aiomatic_log_to_file('Successfully got API tag result from ' . $api_service . ': ' . $generated_text);
                            }
                        }
                        $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $ai_tags;
                        $my_post['extra_tags']       = $ai_tags;
                    } else {
                        $post_the_tags = $item_create_tag_sp;
                        $my_post['extra_tags']       = '';
                    }
                    $my_post['tags_input'] = $post_the_tags;
                    $new_post_content = aimogen_bulk_polish_article_content($new_post_content, array('title' => isset($new_post_title) ? $new_post_title : '', 'topic' => isset($post_topic) ? $post_topic : '', 'language' => isset($content_language) ? $content_language : '', 'model' => (isset($topic_content_model) && $topic_content_model !== '') ? $topic_content_model : (isset($model) ? $model : ''), 'token' => isset($token) ? $token : '', 'temperature' => isset($temperature) ? $temperature : '', 'top_p' => isset($top_p) ? $top_p : '', 'presence_penalty' => isset($presence_penalty) ? $presence_penalty : '', 'frequency_penalty' => isset($frequency_penalty) ? $frequency_penalty : '', 'rule_id' => isset($rule_unique_id) ? $rule_unique_id : '', 'global_prepend' => isset($global_prepend) ? $global_prepend : '', 'global_append' => isset($global_append) ? $global_append : '', 'assistant_id' => isset($assistant_id) ? $assistant_id : '', 'thread_id' => isset($thread_id) ? $thread_id : '', 'store_data' => isset($store_data) ? $store_data : 'off'));
                    $new_post_content        = html_entity_decode($new_post_content);
                    $new_post_content = str_replace('</ iframe>', '</iframe>', $new_post_content);
                    if ($strip_by_regex !== '')
                    {
                        $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex);
                        $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex);
                        $xcnt = 0;
                        foreach($xstrip_by_regex as $sbr)
                        {
                            if(isset($xreplace_regex[$xcnt]))
                            {
                                $repreg = $xreplace_regex[$xcnt];
                            }
                            else
                            {
                                $repreg = '';
                            }
                            $xcnt++;
                            $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $new_post_content);
                            if($temp_cont !== NULL)
                            {
                                $new_post_content = $temp_cont;
                            }
                        }
                    }
                    $post_prepender = aiomatic_replaceAIPostShortcodes($post_prepend, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                    $post_prepender = aiomatic_replace_amazon($post_prepender, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                    $post_appender = aiomatic_replaceAIPostShortcodes($post_append, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                    $post_appender = aiomatic_replace_amazon($post_appender, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                    $post_appender = aiomatic_replaceSynergyShortcodes($post_appender);
                    $post_prepender = aiomatic_replaceSynergyShortcodes($post_prepender);
                    if($topic_videos == '1' && count($added_vid_list) == 0)
                    {
                        if(isset($aiomatic_Main_Settings['social_list']) && !empty($aiomatic_Main_Settings['social_list']) && is_array($aiomatic_Main_Settings['social_list']))
                        {
                            $social_list = $aiomatic_Main_Settings['social_list'];
                        }
                        else
                        {
                            $social_list = array();
                        }
                        $new_vid = aiomatic_get_video($amazon_kw, '', $social_list);
                        if($new_vid !== false && !in_array($new_vid, $added_vid_list))
                        {
                            $new_post_content .= $new_vid;
                            $added_vid_list[] = $new_vid;
                            $new_vid_arr[] = $new_vid;
                            $added_videos++;
                        }
                    }
                    $zlang = 'en_US';
                    if (isset($aiomatic_Main_Settings['kw_lang']) && !empty($aiomatic_Main_Settings['kw_lang'])) {
                        $zlang = $aiomatic_Main_Settings['kw_lang'];
                    }
                    $rel_search = array('post_title', 'post_content');
                    if (isset($aiomatic_Main_Settings['rel_search']) && is_array($aiomatic_Main_Settings['rel_search'])) {
                        $rel_search = $aiomatic_Main_Settings['rel_search'];
                    }
                    if($max_links !== '' && $inboundlinker !== null && $link_type != 'disabled')
                    {
                        try
                        {
                            $new_post_content = $inboundlinker->add_inbound_links($new_post_content, $max_links, $link_post_types, $zlang, $rel_search, null, $link_type, $link_list, $link_nofollow, '', '', array());
                        }
                        catch(Exception $ex)
                        {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('Failed to add new inbound links to content: ' . $ex->getMessage());
                            }
                        }
                    }
                    if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                    {
                        if($new_post_content === strip_tags($new_post_content)) 
                        {
                            $new_post_content = nl2br($new_post_content);
                        }
                    }
                    if (!isset($aiomatic_Main_Settings['no_undetectibility']) || $aiomatic_Main_Settings['no_undetectibility'] != 'on') 
                    {
                        if (!isset($aiomatic_Main_Settings['no_undetectibility_bulk']) || $aiomatic_Main_Settings['no_undetectibility_bulk'] != 'on') 
                        {
                            if(!isset($xchars))
                            {
                                $xchars = array();
                            }
                            $rand_percentage = wp_rand(10, 20);
                            $new_post_content = aiomatic_make_unique($new_post_content, $xchars, $rand_percentage);
                        }
                    }
                    if($ret_content == 1)
                    {
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                            aiomatic_log_to_file('Returning AI generated content, finished.');
                        }
                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Finished processing'));
                        return array($post_prepender . ' ' . $new_post_content . ' ' . $post_appender, $new_post_title);
                    }
                    $the_final_cont = $post_prepender . ' ' . $new_post_content . ' ' . $post_appender;
                    $trunchi_content = aiomatic_truncate_content($the_final_cont, 16777215);
                    if (isset($aiomatic_Main_Settings['convert_gutenberg']) && trim($aiomatic_Main_Settings['convert_gutenberg']) == 'on')
                    {
                        $my_post['post_content'] = aiomatic_convert_html_to_gutenberg_blocks($trunchi_content);
                    }
                    else
                    {
                        $my_post['post_content'] = $trunchi_content;
                    }
                    if(stristr($my_post['post_content'], '<pre><code>&lt;') !== false)
                    {
                        if (!isset($aiomatic_Main_Settings['pre_code_off']) || trim($aiomatic_Main_Settings['pre_code_off']) != 'on')
                        {
                            $my_post['post_content'] = aiomatic_parse_pre_code_entities($my_post['post_content']);
                        }
                    }
                    $my_post['post_content'] = aimogen_bulk_finalize_prose($my_post['post_content']);
                    $my_post['post_title']           = aiomatic_truncate_title($new_post_title);
                    $my_post['aiomatic_source_title']   = $amazon_kw;
                    $my_post['aiomatic_timestamp']   = aiomatic_get_date_now();
                    $my_post['aiomatic_post_format'] = $post_format;
                    if (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678') 
                    {
                        if(is_array($default_category))
                        {
                            $cextra = '';
                            foreach($default_category as $dc)
                            {
                                $cextra .= ',' . get_cat_name($dc);
                            }
                            $extra_categories_temp = trim( $cextra . ',' . $extra_categories, ',');
                        }
                        else
                        {
                            $extra_categories_temp = trim(get_cat_name($default_category) . ',' .$extra_categories, ',');
                        }
                    }
                    else
                    {
                        $extra_categories_temp = $extra_categories;
                    }
                    $block_arr = array();
                    $custom_arr = array();
                    if($custom_fields != '')
                    {
                        if(stristr($custom_fields, '=>') != false)
                        {
                            $rule_arr = explode(',', trim($custom_fields));
                            foreach($rule_arr as $rule)
                            {
                                $my_args = explode('=>', trim($rule));
                                if(isset($my_args[1]))
                                {
                                    if ( isset( $shortcode_tags['aicontent'] ) ) {
                                        $aicontent_handler = $shortcode_tags['aicontent'];
                                        unset( $shortcode_tags['aicontent'] );
                                    } else {
                                        $aicontent_handler = null;
                                    }
                                    $my_args[1] = do_shortcode($my_args[1]);
                                    $my_args[0] = do_shortcode($my_args[0]);
                                    if ( $aicontent_handler ) {
                                        $shortcode_tags['aicontent'] = $aicontent_handler;
                                    }
                                    $custom_field_content = trim($my_args[1]);
                                    $custom_field_content = aiomatic_replaceAIPostShortcodes($custom_field_content, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    $custom_field_content = aiomatic_replace_amazon($custom_field_content, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                                    $custom_field_content = aiomatic_replaceSynergyShortcodes($custom_field_content);
                                    $custom_field_content = $spintax->Parse($custom_field_content, $block_arr);
                                    $custom_field_content = aiomatic_replaceContentShortcodes($custom_field_content, $img_attr, $ai_command);
                                    if(stristr($my_args[1], 'serialize_') !== false)
                                    {
                                        $custom_arr[trim($my_args[0])] = array(str_replace('serialize_', '', $custom_field_content));
                                    }
                                    else
                                    {
                                        if(stristr($my_args[0], '[') !== false && stristr($my_args[0], ']') !== false)
                                        {
                                            preg_match_all('#([^\[\]]*?)\[([^\[\]]*?)\]#', $my_args[0], $cfm);
                                            if(isset($cfm[2][0]))
                                            {
                                                if(isset($custom_arr[trim($cfm[1][0])]) && is_array($custom_arr[trim($cfm[1][0])]))
                                                {
                                                    $custom_arr[trim($cfm[1][0])] = array_merge($custom_arr[trim($cfm[1][0])], array(trim($cfm[2][0]) => $custom_field_content));
                                                }
                                                else
                                                {
                                                    $custom_arr[trim($cfm[1][0])] = array(trim($cfm[2][0]) => $custom_field_content);
                                                }
                                            }
                                            else
                                            {
                                                $custom_arr[trim($my_args[0])] = $custom_field_content;
                                            }
                                        }
                                        else
                                        {
                                            $custom_arr[trim($my_args[0])] = $custom_field_content;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $block_arr = array();
                    $custom_arr = array_merge($custom_arr, array('aiomatic_auto_post_spinned' => $already_spinned, 'aiomatic_post_cats' => $extra_categories_temp, 'aiomatic_post_tags' => $post_the_tags));
                    $custom_tax_arr = array();
                    if($custom_tax != '')
                    {
                        if(stristr($custom_tax, '=>') != false)
                        {
                            $rule_arr = explode(';', trim($custom_tax));
                            foreach($rule_arr as $rule)
                            {
                                $my_args = explode('=>', trim($rule));
                                if(isset($my_args[1]))
                                {
                                    $custom_tax_content = trim($my_args[1]);
                                    $custom_tax_content = aiomatic_replaceAIPostShortcodes($custom_tax_content, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    $custom_tax_content = aiomatic_replace_amazon($custom_tax_content, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, implode(',' , $post_sections), $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count, $amazresult);
                                    $custom_tax_content = aiomatic_replaceSynergyShortcodes($custom_tax_content);
                                    $custom_tax_content = $spintax->Parse($custom_tax_content, $block_arr);
                                    $custom_tax_content = aiomatic_replaceContentShortcodes($custom_tax_content, $img_attr, $ai_command);
                                    if(aiomatic_substr(trim($my_args[0]), 0, 3) === "pa_" && $post_type == 'product' && !empty($custom_tax_content))
                                    {
                                        if(isset($custom_arr['_product_attributes']))
                                        {
                                            $custom_arr['_product_attributes'] = array_merge($custom_arr['_product_attributes'], array(trim($my_args[0]) =>array(
                                                'name' => trim($my_args[0]),
                                                'value' => $custom_tax_content,
                                                'is_visible' => '1',
                                                'is_taxonomy' => '1'
                                            )));
                                        }
                                        else
                                        {
                                            $custom_arr['_product_attributes'] = array(trim($my_args[0]) =>array(
                                                'name' => trim($my_args[0]),
                                                'value' => $custom_tax_content,
                                                'is_visible' => '1',
                                                'is_taxonomy' => '1'
                                            ));
                                        }
                                    }
                                    if(isset($custom_tax_arr[trim($my_args[0])]))
                                    {
                                        $custom_tax_arr[trim($my_args[0])] .= ',' . $custom_tax_content;
                                    }
                                    else
                                    {
                                        $custom_tax_arr[trim($my_args[0])] = $custom_tax_content;
                                    }
                                }
                            }
                        }
                    }
                    if(count($custom_tax_arr) > 0)
                    {
                        $my_post['taxo_input'] = $custom_tax_arr;
                    }
                    $my_post['meta_input'] = $custom_arr;
                    if($parent_id != '')
                    {
                        $my_post['post_parent'] = intval($parent_id);
                    }
                    if ($enable_pingback == '1') {
                        $my_post['ping_status'] = 'open';
                    } else {
                        $my_post['ping_status'] = 'closed';
                    }
                    if($min_time != '' && $max_time != '')
                    {
                        $t1 = strtotime($min_time);
                        $t2 = strtotime($max_time);
                        if($t1 != false && $t2 != false)
                        {
                            $int = wp_rand($t1, $t2);
                            $my_post['post_date'] = date('Y-m-d H:i:s', $int);
                        }
                    }
                    elseif($min_time != '')
                    {
                        $t1 = strtotime($min_time);
                        if($t1 != false)
                        {
                            $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                        }
                    }
                    elseif($max_time != '')
                    {
                        $t1 = strtotime($max_time);
                        if($t1 != false)
                        {
                            $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                        }
                    }
                    if($new_post_excerpt != '')
                    {
                        $my_post['post_excerpt']          = $new_post_excerpt;
                    }
                    $count++;
                    if($update_post_id != '')
                    {
                        $my_post['ID'] = $update_post_id;
                    }
                    remove_filter('content_save_pre', 'wp_filter_post_kses');
                    remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                    try
                    {
                        $post_id = wp_insert_post($my_post, true);
                        $my_post['post_content'] = str_replace('\r\n', '', $my_post['post_content']);
                        if (is_wp_error($post_id)) 
                        {
                            aiomatic_log_to_file('Trying publishing again');
                            if (aiomatic_strlen($my_post['post_content']) > 16777215) {
                                $my_post['post_content'] = aiomatic_substr($my_post['post_content'], 0, 16777215);
                            }
                            $my_post['post_content'] = wp_kses_post($my_post['post_content']);
                            $my_post['post_content'] = str_replace('\r\n', '', $my_post['post_content']);
                            $post_id = wp_insert_post($my_post, true);
                        }
                    }
                    catch(Exception $e)
                    {
                        aiomatic_log_to_file('Exception in publishing post (this is coming from another plugin, so we ignore it): ' . $e->getMessage());
                    }
                    add_filter('content_save_pre', 'wp_filter_post_kses');
                    add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                    if (!is_wp_error($post_id)) {
                        if($post_id === 0)
                        {
                            aiomatic_log_to_file('An error occurred while inserting post into wp database! Title:' . $my_post['post_title']);
                            continue;
                        }
                        $words = str_word_count(wp_strip_all_tags($my_post['post_content']));
                        aiomatic_increment_publishing_stats($words);
                        aimogen_bulk_on_post_created($post_id, $my_post['post_title'], isset($new_post_excerpt) ? $new_post_excerpt : '', isset($post_topic) ? $post_topic : (isset($post_title) ? $post_title : ''));
                        aiomatic_set_last_activity(
                            'article',
                            ['post_id' => $post_id]
                        );
                        $posts_inserted++;
                        if($wpml_lang != '' && function_exists('pll_set_post_language'))
                        {
                            pll_set_post_language($post_id, $wpml_lang);
                        }
                        if(!empty($additional_attachments))
                        {
                            foreach($additional_attachments as $add_att)
                            {
                                wp_update_post([
                                    'ID' => $add_att,
                                    'post_parent' => $post_id,
                                ]);
                            }
                        }
                        $default_categories = array();
                        if($remove_default == '1' && ($auto_categories != 'disabled' || (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678')))
                        {
                            $default_categories = wp_get_post_categories($post_id);
                        }
                        if(isset($my_post['taxo_input']))
                        {
                            foreach($my_post['taxo_input'] as $taxn => $taxval)
                            {
                                $taxn = trim($taxn);
                                $taxval = trim($taxval);
                                if(is_taxonomy_hierarchical($taxn))
                                {
                                    $taxval = array_map('trim', explode(',', $taxval));
                                    for($ii = 0; $ii < count($taxval); $ii++)
                                    {
                                        if(!is_numeric($taxval[$ii]))
                                        {
                                            $term_ids = [];
                                            $parent_id = 0;
                                            $hierarchy_parts = array_map('trim', explode('>', $taxval[$ii]));
                                            foreach($hierarchy_parts as $hp)
                                            {
                                                if(!is_numeric($hp))
                                                {
                                                    $xtermid = get_term_by('name', $hp, $taxn);
                                                    if($xtermid !== false)
                                                    {
                                                        $parent_id = $xtermid->term_id;
                                                        if(!is_numeric($taxval[$ii]))
                                                        {
                                                            $taxval[$ii] = intval($xtermid->term_id);
                                                        }
                                                        else
                                                        {
                                                            $taxval[] = intval($xtermid->term_id);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        wp_insert_term( $hp, $taxn, ['parent' => $parent_id]);
                                                        $xtermid = get_term_by('name', $hp, $taxn);
                                                        if($xtermid !== false)
                                                        {
                                                            $parent_id = $xtermid->term_id;
                                                            if($wpml_lang != '' && function_exists('pll_set_term_language'))
                                                            {
                                                                pll_set_term_language($xtermid->term_id, $wpml_lang); 
                                                            }
                                                            elseif($wpml_lang != '' && has_filter('wpml_object_id'))
                                                            {
                                                                $wpml_element_type = apply_filters( 'wpml_element_type', $taxn );
                                                                $pars['element_id'] = $xtermid->term_id;
                                                                $pars['element_type'] = $wpml_element_type;
                                                                $pars['language_code'] = $wpml_lang;
                                                                $pars['trid'] = FALSE;
                                                                $pars['source_language_code'] = NULL;
                                                                do_action('wpml_set_element_language_details', $pars);
                                                            }
                                                            if(!is_numeric($taxval[$ii]))
                                                            {
                                                                $taxval[$ii] = intval($xtermid->term_id);
                                                            }
                                                            else
                                                            {
                                                                $taxval[] = intval($xtermid->term_id);
                                                            }
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    if(!is_numeric($taxval[$ii]))
                                                    {
                                                        $taxval[$ii] = intval($hp);
                                                    }
                                                    else
                                                    {
                                                        $taxval[] = intval($hp);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    wp_set_post_terms($post_id, $taxval, $taxn, true);
                                }
                                else
                                {
                                    $jterms = array_map('trim', explode(',', $taxval));
                                    wp_set_post_terms($post_id, $jterms, $taxn, true);
                                }
                            }
                        }
                        if (isset($my_post['aiomatic_post_format']) && $my_post['aiomatic_post_format'] != '' && $my_post['aiomatic_post_format'] != 'post-format-standard') {
                            wp_set_post_terms($post_id, $my_post['aiomatic_post_format'], 'post_format', true);
                        }
                        $featured_path = '';
                        $get_img = $my_post['aiomatic_post_image'];
                        if ($get_img != '') {
                            if($my_post['aiomatic_local_image'] == '1')
                            {
                                $local_get_img = $get_img[0];
                                if (!aiomatic_assign_featured_image_path($local_get_img, $post_id)) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('aiomatic_assign_featured_image_path failed for ' . $local_get_img);
                                    }
                                } else {
                                    $featured_path = $get_img[1];
                                }
                            }
                            else
                            {
                                if(is_numeric($get_img))
                                {
                                    $featured_path = aiomatic_assign_featured_image($get_img, $post_id);
                                }
                                else
                                {
                                    if (!aiomatic_generate_featured_image($get_img, $post_id)) {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('aiomatic_generate_featured_image failed for ' . $get_img);
                                        }
                                    } else {
                                        $featured_path = $get_img;
                                    }
                                }
                            }
                        }
                        if($featured_path == '')
                        {
                            if ($image_url != '') {
                                $replacement = str_replace(array('[', ']'), '', $my_post['post_title']);
                                $image_url_temp = str_replace('%%item_title%%', $replacement, $image_url);
                                $image_url_temp = preg_replace_callback('#%%random_image\[([^\]]*?)\](\[\d+\])?%%#', function ($matches) {
                                    if(isset($matches[2]))
                                    {
                                        $chance = trim($matches[2], '[]');
                                    }
                                    else
                                    {
                                        $chance = '';
                                    }
                                    $arv = array();
                                    $my_img = aiomatic_get_random_image_google($matches[1], 0, 0, $chance, $arv);
                                    return $my_img;
                                }, $image_url_temp);
                                $img_rulx = $spintax->Parse(trim($image_url_temp));
                                $selected_img = aiomatic_select_ai_image($my_post['post_title'], $img_rulx);
                                if($selected_img === false)
                                {
                                    $img_rulx = explode(',', $img_rulx);
                                    $img_rulx = trim($img_rulx[array_rand($img_rulx)]);
                                }
                                else
                                {
                                    $img_rulx = $selected_img;
                                }
                                if(is_numeric($img_rulx))
                                {
                                    $featured_path = aiomatic_assign_featured_image($img_rulx, $post_id);
                                }
                                else
                                {
                                    if($img_rulx != '')
                                    {
                                        if (!aiomatic_generate_featured_image($img_rulx, $post_id)) {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                aiomatic_log_to_file('aiomatic_generate_featured_image failed to default value: ' . $img_rulx . '!');
                                            }
                                        } else {
                                            $featured_path = $img_rulx;
                                        }
                                    }
                                }
                            }
                        }
                        if ($auto_categories != 'disabled') {
                            if ($my_post['extra_categories'] != '') {
                                $extra_cats = explode(',', $my_post['extra_categories']);
                                if($post_type == 'product')
                                {
                                    $product_tax = 'product_cat';
                                }
                                else
                                {
                                    $product_tax = 'category';
                                }
                                foreach($extra_cats as $extra_cat)
                                {
                                    $extra_cat = trim($extra_cat);
                                    $extra_cat = strip_tags($extra_cat);
                                    $extra_cat = preg_replace('#^\d+\.\s*#', '', $extra_cat);
                                    if(empty($extra_cat))
                                    {
                                        continue;
                                    }
                                    if ($skip_inexist == '1') 
                                    {
                                        if(!term_exists($extra_cat, $product_tax))
                                        {
                                            continue;
                                        }
                                    }
                                    $termid = aiomatic_create_terms($product_tax, null, trim($extra_cat));
                                    wp_set_post_terms($post_id, $termid, $product_tax, true);
                                    if($wpml_lang != '' && function_exists('pll_set_term_language'))
                                    {
                                        foreach($termid as $tx)
                                        {
                                            pll_set_term_language($tx, $wpml_lang); 
                                        }
                                    }
                                    elseif($wpml_lang != '' && has_filter('wpml_object_id'))
                                    {
                                        $wpml_element_type = apply_filters( 'wpml_element_type', 'product_cat' );
                                        foreach($termid as $tx)
                                        {
                                            $pars['element_id'] = $tx;
                                            $pars['element_type'] = $wpml_element_type;
                                            $pars['language_code'] = $wpml_lang;
                                            $pars['trid'] = FALSE;
                                            $pars['source_language_code'] = NULL;
                                            do_action('wpml_set_element_language_details', $pars);
                                        }
                                    }
                                }
                            }
                        }
                        if (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678') {
                            $cats   = array();
                            if(is_array($default_category))
                            {
                                foreach($default_category as $dc)
                                {
                                    $cats[] = $dc;
                                }
                            }
                            else
                            {
                                $cats[] = $default_category;
                            }
                            global $sitepress;
                            if($wpml_lang != '' && has_filter('wpml_current_language') && $sitepress != null)
                            {
                                $current_language = apply_filters( 'wpml_current_language', NULL );
                                $sitepress->switch_lang($wpml_lang);
                            }
                            $target_cat = 'category';
                            if($post_type == 'product')
                            {
                                $target_cat = 'product_cat';
                            }
                            wp_set_object_terms($post_id, array_map( 'intval', $cats ), $target_cat, true);
                            if($wpml_lang != '' && function_exists('pll_set_term_language'))
                            {
                                foreach($cats as $cc)
                                {
                                    pll_set_term_language($cc, $wpml_lang);
                                }
                            }
                            elseif($wpml_lang != '' && has_filter('wpml_current_language') && $sitepress != null)
                            {
                                $sitepress->switch_lang($current_language);
                            }
                        }
                        if (isset($my_post['tags_input']) && $my_post['tags_input'] != '')
                        {
                            if($post_type == 'product')
                            {
                                wp_set_post_terms($post_id, $my_post['tags_input'], 'product_tag', true);
                            }
                        }
                        $tax_rez = wp_set_object_terms( $post_id, 'aiomatic_' . $type . '_' . $param, 'coderevolution_post_source', true);
                        if (is_wp_error($tax_rez)) {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('wp_set_object_terms failed for: ' . $post_id . '!');
                            }
                        }
                        if($post_type == 'topic' && $parent_id != '')
                        {
                            update_post_meta($post_id, '_bbp_forum_id', $parent_id);
                            update_post_meta($post_id, '_bbp_topic_id', $post_id);
                            update_post_meta($post_id, '_bbp_voice_count', '0');
                            update_post_meta($post_id, '_bbp_reply_count', '0');
                            update_post_meta($post_id, '_bbp_reply_count_hidden', '0');
                            update_post_meta($post_id, '_bbp_last_reply_id', '0');
                            update_post_meta($post_id, '_bbp_last_active_id', $post_id);
                            update_post_meta($post_id, '_bbp_last_active_time', get_post_field( 'post_date', $topic_id, 'db' ));
                            do_action( 'bbp_insert_topic', (int) $post_id, (int) $parent_id );
                        }
                        if($post_type == 'reply' && $parent_id != '')
                        {
                            if(function_exists('bbp_get_topic_forum_id'))
                            {
                                $forum_aidi = bbp_get_topic_forum_id($parent_id);
                                if(empty($forum_aidi))
                                {
                                    $forum_aidi = 0;
                                }
                            }
                            else
                            {
                                $forum_aidi = 0;
                            }
                            do_action( 'bbp_insert_reply', (int) $post_id, (int) $parent_id, (int) $forum_aidi );
                        }
                        if($remove_default == '1' && ($auto_categories != 'disabled' || (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678')))
                        {
                            $new_categories = wp_get_post_categories($post_id);
                            $removed_cat = false;
                            if(isset($default_categories) && !($default_categories == $new_categories))
                            {
                                foreach($default_categories as $dc)
                                {
                                    $rem_cat = get_category( $dc );
                                    wp_remove_object_terms( $post_id, $rem_cat->slug, 'category' );
                                    $removed_cat = true;
                                }
                            }
                            if($removed_cat == false)
                            {
                                wp_remove_object_terms( $post_id, 'uncategorized', 'category' );
                            }
                        }
                        aiomatic_addPostMeta($post_id, $my_post, $param, $type, $featured_path, $post_topic, $rule_unique_id, $post_link);
                        if($wpml_lang != '' && (class_exists('SitePress') || function_exists('wpml_object_id')))
                        {
                            $wpml_element_type = apply_filters( 'wpml_element_type', $post_type );
                            $pars['element_id'] = $post_id;
                            $pars['element_type'] = $wpml_element_type;
                            $pars['language_code'] = $wpml_lang;
                            $pars['source_language_code'] = NULL;
                            do_action('wpml_set_element_language_details', $pars);

                            global $wp_filesystem;
                            if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
                                include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() );
                                wp_filesystem($creds);
                            }
                            if($wp_filesystem->exists(WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php'))
                            {
                                include_once( WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php' );
                            }
                            $wpml_lang = trim($wpml_lang);
                            if(function_exists('wpml_update_translatable_content'))
                            {
                                wpml_update_translatable_content('post_' . $post_type, $post_id, $wpml_lang);
                                if($my_post['post_title'] != '')
                                {
                                    global $sitepress;
                                    global $wpdb;
                                    $keyid = md5($my_post['post_title']);
                                    $keyName = $keyid . '_wpml';
                                    $sql = $wpdb->prepare(
                                        "SELECT * FROM {$wpdb->prefix}postmeta WHERE meta_key = %s LIMIT 1",
                                        $keyName
                                    );
                                    $rezxxxa = $wpdb->get_results($sql, ARRAY_A);
                                    if(count($rezxxxa) != 0)
                                    {
                                        $metaRow = $rezxxxa[0];
                                        $metaValue = $metaRow['meta_value'];
                                        $metaParts = explode('_', $metaValue);
                                        $sitepress->set_element_language_details($post_id, 'post_'.$my_post['post_type'] , $metaParts[0], $wpml_lang, $metaParts[1] ); 
                                    }
                                    else
                                    {
                                        $ptrid = $sitepress->get_element_trid($post_id);
                                        update_post_meta($post_id, $keyid.'_wpml', $ptrid.'_'.$wpml_lang );
                                    }
                                }
                                
                            }
                        }
                        if (isset($aiomatic_Main_Settings['draft_first']) && $aiomatic_Main_Settings['draft_first'] == 'on' && $draft_me == true)
                        {
                            aiomatic_change_post_status($post_id, 'publish');
                        }
                    } else {
                        aiomatic_log_to_file('Failed to insert post into wp database(3)! Title:' . $my_post['post_title'] . '! Error: ' . $post_id->get_error_message() . ' Error code: ' . $post_id->get_error_code() . ' Error data: ' . $post_id->get_error_data());
                        continue;
                    }
                }
            }
            elseif($type == '3')
            {
                $amazon_keyword = str_replace(',', '|', $amazon_keyword);
                $amazon_keyword_lines = array();
                if($amazon_keyword != '')
                {
                    $amazon_keyword_lines = preg_split('/\r\n|\r|\n/', $amazon_keyword);
                }
                else
                {
                    aiomatic_log_to_file('You need to enter an Amazon product search ASIN to use this feature!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
                $additional_kws = array();
                $post_link = '';
                $user_name        = '';
                $featured_image   = '';
                $post_cats = '';
                $post_tagz = '';
                $post_excerpt = '';
                $final_content = '';
                $postID = '';
                $heading_val = '';
                $image_query = '';
                $temp_post = '';
                $cntx = count($amazon_keyword_lines);
                $rss_feeds = array();
                for($ji = 0; $ji < $cntx; $ji++)
                {
                    if (filter_var($amazon_keyword_lines[$ji], FILTER_VALIDATE_URL) !== false && stristr($amazon_keyword_lines[$ji], 'youtu') === false) 
                    {
                        if(aiomatic_endsWith($amazon_keyword_lines[$ji], '.txt'))
                        {
                            $txt_content = aiomatic_get_web_page($amazon_keyword_lines[$ji]);
                            if ($txt_content === FALSE) 
                            {
                                aiomatic_log_to_file('Failed to read text file: ' . $amazon_keyword_lines[$ji]);
                                unset($amazon_keyword_lines[$ji]);
                                if($auto == 1)
                                {
                                    aiomatic_log_to_file($param);
                                }
                                continue;
                            }
                            unset($amazon_keyword_lines[$ji]);
                            $additional_kws = preg_split('/\r\n|\r|\n/', $txt_content);
                        }
                        else
                        {
                            aiomatic_log_to_file('Trying to parse RSS feed items(5): ' . $amazon_keyword_lines[$ji]);
                            try
                            {
                                if(!class_exists('SimplePie_Autoloader', false))
                                {
                                    require_once(dirname(__FILE__) . "/res/simplepie/autoloader.php");
                                }
                            }
                            catch(Exception $e) 
                            {
                                unset($amazon_keyword_lines[$ji]);
                                aiomatic_log_to_file('Exception thrown in SimplePie autoloader: ' . $e->getMessage());
                                if($auto == 1)
                                {
                                    aiomatic_log_to_file($param);
                                }
                                continue;
                            }
                            $feed = new SimplePie();
                            $feed->set_timeout(120);
                            $feed->set_feed_url($amazon_keyword_lines[$ji]);
                            $feed->enable_cache(false);
                            $feed->strip_htmltags(false);
                            $feed->init();
                            $feed->handle_content_type();
                            if ($feed->error()) 
                            {
                                aiomatic_log_to_file('Error in parsing RSS feed: ' . $feed->error() . ' for ' . $amazon_keyword_lines[$ji]);
                                unset($amazon_keyword_lines[$ji]);
                                if($auto == 1)
                                {
                                    aiomatic_clearFromList($param, $type);
                                }
                                continue;
                            }
                            $items = $feed->get_items();
                            $zero = true;
                            foreach($items as $itemx)
                            {
                                if($zero == true)
                                {
                                    $post_link = trim($itemx->get_permalink());
                                    if(isset($rss_items[$post_link]))
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Skipping RSS title because it was already processed before: ' . $itemx->get_title());
                                        }
                                        continue;
                                    }
                                    if ($fauthor = $itemx->get_author()) 
                                    {
                                        $user_name = $fauthor->get_name();
                                    }
                                    else
                                    {
                                        $user_name = '';
                                    }
                                    $feed_cats = array();
                                    $varx = $itemx->get_categories();
                                    if(is_array($varx))
                                    {
                                        foreach ($varx as $xcategory)
                                        {
                                            $feed_cats[] = $xcategory->get_label();
                                        }
                                    }
                                    $post_cats = implode(',', $feed_cats);
                                    $post_excerpt = $itemx->get_description();
                                    $final_content = $itemx->get_content();
                                    $rss_feeds[$itemx->get_title()] = array('url' => $post_link, 'author' => $user_name,  'cats' => $post_cats, 'excerpt' => $post_excerpt, 'content' => $final_content );
                                }
                                else
                                {
                                    $post_link_temp = trim($itemx->get_permalink());
                                    if(isset($rss_items[$post_link_temp]))
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Skipping RSS title because it was already processed before: ' . $itemx->get_title());
                                        }
                                        continue;
                                    }
                                    if ($fauthor = $itemx->get_author()) 
                                    {
                                        $user_name_temp = $fauthor->get_name();
                                    }
                                    else
                                    {
                                        $user_name_temp = '';
                                    }
                                    $feed_cats = array();
                                    $varx = $itemx->get_categories();
                                    if(is_array($varx))
                                    {
                                        foreach ($varx as $xcategory)
                                        {
                                            $feed_cats[] = $xcategory->get_label();
                                        }
                                    }
                                    $post_cats_temp = implode(',', $feed_cats);
                                    $post_excerpt_temp = $itemx->get_description();
                                    $final_content_temp = $itemx->get_content();
                                    $rss_feeds[$itemx->get_title()] = array('url' => $post_link_temp, 'author' => $user_name_temp,  'cats' => $post_cats_temp, 'excerpt' => $post_excerpt_temp, 'content' => $final_content_temp );
                                }
                                $additional_kws[] = $itemx->get_title();
                                $zero = false;
                            }
                            unset($amazon_keyword_lines[$ji]);
                        }
                    }
                }
                if(count($additional_kws) > 0)
                {
                    $amazon_keyword_lines = array_merge($amazon_keyword_lines, $additional_kws);
                }
                $amazon_keyword_lines = array_unique($amazon_keyword_lines);
                if($overwrite_existing == '1')
                {
                    $amazon_keyword_lines_processed = array();
                    foreach($amazon_keyword_lines as $zind => $ptl)
                    {
                        $ptlprocessed = explode('!###!', $ptl);
                        if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                        {
                            $amazon_keyword_lines_processed[$zind] = $ptlprocessed[0];
                        }
                        else
                        {
                            $amazon_keyword_lines_processed[$zind] = $ptl;
                        }
                    }
                    foreach($posted_items as $ptit => $pid)
                    {
                        if (($key = array_search($ptit, $amazon_keyword_lines_processed)) !== false) {
                            $update_post_id = $pid;
                            break;
                        }
                    }
                }
                if($title_once == '1')
                {
                    $skipt = 0;
                    $amazon_keyword_lines_processed = array();
                    foreach($amazon_keyword_lines as $zind => $ptl)
                    {
                        $ptlprocessed = explode('!###!', $ptl);
                        if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                        {
                            $amazon_keyword_lines_processed[$zind] = $ptlprocessed[0];
                        }
                        else
                        {
                            $amazon_keyword_lines_processed[$zind] = $ptl;
                        }
                    }
                    foreach($posted_items as $ptit => $pid)
                    {
                        if (($key = array_search($ptit, $amazon_keyword_lines_processed)) !== false) {
                            aiomatic_log_to_file('Skipping Amazon reviews title, already processed: ' . $ptit);
                            unset($amazon_keyword_lines[$key]);
                            unset($amazon_keyword_lines_processed[$key]);
                            $skipt++;
                        }
                    }
                    if(count($amazon_keyword_lines) == 0 && $skipt > 0)
                    {
                        if (isset($aiomatic_Main_Settings['email_notification']) && $aiomatic_Main_Settings['email_notification'] != '')
                        {
                            if($count === 1)
                            {
                                $email_list = explode(',', $aiomatic_Main_Settings['email_notification']);
                                foreach($email_list as $thisaddr)
                                {
                                    $thisaddr = trim($thisaddr);
                                    try
                                    {
                                        $admin_mail = get_option('admin_email');
                                        $to        = $thisaddr;
                                        $subject   = '[Aimogen] Amazon Reviews Keywords depleted rule ID ' . $param . ' - ' . aiomatic_get_date_now();
                                        $message   = 'Amazon Reviews Rule ID ' . esc_html($param) . ' (' . $rule_description . ') depleted its Amazon keywords list, no new posts publised! Website URL: ' . get_site_url();
                                        $headers[] = 'From: Aimogen Plugin <' . $admin_mail . '>';
                                        $headers[] = 'Reply-To: ' . $admin_mail;
                                        $headers[] = 'X-Mailer: PHP/' . phpversion();
                                        $headers[] = 'Content-Type: text/html';
                                        $headers[] = 'Charset: ' . get_option('blog_charset', 'UTF-8');
                                        wp_mail($to, $subject, $message, $headers);
                                    }
                                    catch (Exception $e) {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Failed to send mail: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                        }
                                    }
                                }
                            }
                        }
                        aiomatic_log_to_file('All Amazon keywords already processed, nothing to do.');
                        if($auto == 1)
                        {
                            aiomatic_clearFromList($param, $type);
                        }
                        return 'nochange';
                    }
                }
                $spintax = new Aiomatic_Spintax();
                $orig_ai_command = $ai_command;
                $orig_ai_command_title = $title_ai_command;
                $orig_ai_command_category = $category_ai_command;
                $orig_ai_command_tag = $tag_ai_command;
                $orig_ai_command_image = $ai_command_image;
                $already_spinned = 0;
                if(isset($aiomatic_Main_Settings['attr_text']) && $aiomatic_Main_Settings['attr_text'] != '')
                {
                    $img_attr = $aiomatic_Main_Settings['attr_text'];
                }
                else
                {
                    $img_attr = '';
                }
                $headings_arr = array();
                if($images_list != '')
                {
                    $images_arr = preg_split('/\r\n|\r|\n/', $images_list);
                    $images_arr = array_map('trim', $images_arr);
                }
                else
                {
                    $images_arr = array();
                }
                require_once(__DIR__ . '/res/amazon-direct.php');
                while(true) 
                {
                    $thread_id = '';
                    $my_title_outro = '';
                    if ($count > intval($max)) {
                        break;
                    }
                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon product review'));
                    $update_post_id  = '';
                    $product_description = '';
                    $current_section = '';
                    $post_sections = '';
                    $post_topic = '';
                    $post_title_keywords = '';
                    $headings_arr_copy = $headings_arr;
                    $added_img_list = array();
                    $raw_img_list = array();
                    $full_result_list = array();
                    $added_images = 0;
                    $heading_results = array();
                    if(count($amazon_keyword_lines) == 0)
                    {
                        break;
                    }
                    if ($count > intval($max)) {
                        break;
                    }
                    if (!isset($aiomatic_Main_Settings['no_random_titles']) || $aiomatic_Main_Settings['no_random_titles'] != 'on')
                    {
                        $current_index = array_rand($amazon_keyword_lines);
                    }
                    else
                    {
                        $current_index = array_key_first($amazon_keyword_lines);
                    }
                    $amazon_kw = trim($amazon_keyword_lines[$current_index]);
                    if($title_once == '1')
                    {
                        unset($amazon_keyword_lines[$current_index]);
                    }

                    $amazon_kw = explode('|', $amazon_kw);
                    $amazon_kw = $amazon_kw[array_rand($amazon_kw)];

                    $ptlprocessed = explode('!###!', $amazon_kw);
                    if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                    {
                        $amazon_kw = $ptlprocessed[0];
                        $post_title_keywords = $ptlprocessed[1];
                    }
                    if(isset($rss_feeds[$amazon_kw]))
                    {
                        $post_link = $rss_feeds[$amazon_kw]['url'];
                        $user_name = $rss_feeds[$amazon_kw]['author'];
                        $post_cats = $rss_feeds[$amazon_kw]['cats'];
                        $post_excerpt = $rss_feeds[$amazon_kw]['excerpt'];
                        $final_content = $rss_feeds[$amazon_kw]['content'];
                    }
                    $tprepp = $spintax->Parse($amazon_kw);
                    if($tprepp != false && $tprepp != '')
                    {
                        $amazon_kw = $tprepp;
                    }
                    $old_title = $amazon_kw;
                    $already_spinned = 0;
                    $allmodels = aiomatic_get_all_models();
                    if($custom_shortcodes != '')
                    {
                        $custom_shortcodes_arr = preg_split('/\r\n|\r|\n/', $custom_shortcodes);
                        foreach($custom_shortcodes_arr as $my_short)
                        {
                            $name_part = explode('=>', $my_short);
                            if(isset($name_part[1]) && !empty(trim($name_part[1])))
                            {
                                $shortname = trim($name_part[0]);
                                if(strstr($amazon_kw, '%%' . $shortname . '%%'))
                                {
                                    $shortval = '';
                                    $name_part[1] = str_replace('%%search_keywords%%', $amazon_kw, $name_part[1]);
                                    $ai_part = explode('@@', $name_part[1]);
                                    if(isset($ai_part[1]) && !empty(trim($ai_part[1])))
                                    {
                                        if(!in_array(trim($ai_part[0]), $allmodels))
                                        {
                                            $aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                        }
                                        else
                                        {
                                            $aimodel = trim($ai_part[0]);
                                        }
                                        $zai_command = trim($ai_part[1]);
                                        $zai_command = aiomatic_replaceSynergyShortcodes($zai_command);
                                        $zai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $zai_command);
                                        foreach($custom_shortcodes_arr as $my_check_short)
                                        {
                                            $check_name_part = explode('=>', $my_check_short);
                                            if(isset($check_name_part[1]) && !empty(trim($check_name_part[1])))
                                            {
                                                $check_shortname = trim($check_name_part[0]);
                                                if($shortname !== $check_shortname && strstr($zai_command, '%%' . $check_shortname . '%%') !== false)
                                                {
                                                    $check_shortval = '';
                                                    $check_ai_part = explode('@@', $check_name_part[1]);
                                                    if(!in_array(trim($check_ai_part[0]), $allmodels))
                                                    {
                                                        $check_aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                                    }
                                                    else
                                                    {
                                                        $check_aimodel = trim($check_ai_part[0]);
                                                    }
                                                    $check_ai_command = trim($check_ai_part[1]);
                                                    $aierror = '';
                                                    $check_ai_command = aiomatic_replaceSynergyShortcodes($check_ai_command);
                                                    $check_ai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $check_ai_command);
                                                    $check_generated_text = aiomatic_generate_custom_shortcode_content($token, $check_aimodel, $check_ai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                                                    if($check_generated_text === false)
                                                    {
                                                        aiomatic_log_to_file('Custom nested shortcode generator error: ' . $aierror);
                                                    }
                                                    else
                                                    {
                                                        $check_shortval = trim(trim($check_generated_text), '.');
                                                    }
                                                    $zai_command = str_replace('%%' . $check_shortname . '%%', $check_shortval, $zai_command);
                                                }
                                            }
                                        }
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating custom shortcodes'));
                                        $aierror = '';
                                        $generated_text = aiomatic_generate_custom_shortcode_content($token, $aimodel, $zai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                                        if($generated_text === false)
                                        {
                                            aiomatic_log_to_file('Custom shortcode generator error: ' . $aierror);
                                        }
                                        else
                                        {
                                            $shortval = trim(trim($generated_text), '.');
                                        }
                                    }
                                    $amazon_kw = str_replace('%%' . $shortname . '%%', $shortval, $amazon_kw);
                                }
                            }
                        } 
                    }
                    $amazon_kw = aiomatic_replaceSynergyShortcodes($amazon_kw);
                    $amazon_kw = apply_filters('aiomatic_replace_aicontent_shortcode', $amazon_kw);
                    if(empty($amazon_kw))
                    {
                        aiomatic_log_to_file('Empty Amazon Keyword Submitted: ' . $amazon_kw);
                        unset($amazon_keyword_lines[$current_index]);
                        continue;
                    }
                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                    {
                        aiomatic_log_to_file('Starting processing Amazon Review keyword: ' . $amazon_kw);
                    }
                    $max_prod = 1;
                    if($product_source == 'clickbank')
                    {
                        $amazresult = aiomatic_clickbank_get_post($cb_affiliate_id, $amazon_kw, $neg_keywords, $item_category, $shipable_only, $pitch_plus, $one_time, $recurring, $affiliate_tools, $spotlight, $mobile_hoplink, $item_language, $activation, $item_gravity, $dollar_sale, $dollar_sale_av, $rebill_total, $per_sale, $per_rebill, $sort_results_cb, $max_prod);
                        if(is_array($amazresult) && isset($amazresult['status']) && $amazresult['status'] == 'nothing')
                        {
                            aiomatic_log_to_file('No results found for ClickBank keyword search: ' . $amazon_kw);
                            unset($amazon_keyword_lines[$current_index]);
                            continue;
                        }
                        if(!is_array($amazresult))
                        {
                            aiomatic_log_to_file('Empty response from ClickBank: ' . $amazon_kw);
                            unset($amazon_keyword_lines[$current_index]);
                            continue;
                        }
                        if(is_array($amazresult) && count($amazresult) == 0)
                        {
                            aiomatic_log_to_file('Empty results found for ClickBank keyword search: ' . $amazon_kw);
                            unset($amazon_keyword_lines[$current_index]);
                            continue;
                        }
                    }
                    else
                    {
                        $amazresult = aiomatic_amazon_get_post($amazon_kw, trim($affiliate_id), $target_country, '', '', '', $max_prod, '1', array());
                        if(is_array($amazresult) && isset($amazresult['status']) && $amazresult['status'] == 'nothing')
                        {
                            aiomatic_log_to_file('No results found for keyword search: ' . $amazon_kw);
                            unset($amazon_keyword_lines[$current_index]);
                            continue;
                        }
                        if(!is_array($amazresult))
                        {
                            aiomatic_log_to_file('Empty rule response from Amazon Reviews: ' . $amazon_kw);
                            unset($amazon_keyword_lines[$current_index]);
                            continue;
                        }
                        if(is_array($amazresult) && count($amazresult) == 0)
                        {
                            aiomatic_log_to_file('Empty results found for keyword search: ' . $amazon_kw);
                            unset($amazon_keyword_lines[$current_index]);
                            continue;
                        }
                    }
                    $product_titles = '';
                    foreach($amazresult as $amr)
                    {
                        $product_titles .= '"' . $amr->offer_title . '",';
                    }
                    shuffle($amazresult);
                    $amazresult = $amazresult[0];
                    $product_titles = rtrim($product_titles, ',');
                    $post_title = '';
                    $amazon_thumb = $amazresult->product_img;
                    $product_title = $amazresult->offer_title;
                    $product_reviews = implode('<br><br>', $amazresult->item_reviews);
                    $product_description = $amazresult->offer_desc;
                    if(trim($affiliate_id) != '')
                    {
                        $aff_url = $amazresult->offer_url;
                    }
                    else
                    {
                        $aff_url = $amazresult->source_link;
                    }
                    $product_author = $amazresult->product_author;
                    $product_brand = $amazresult->product_brand;
                    $product_isbn = $amazresult->product_isbn;
                    $product_upc = $amazresult->product_upc;
                    $offer_price = $amazresult->offer_price;
                    $product_price = $amazresult->product_price;
                    $product_list_price = $amazresult->product_list_price;
                    $price_numeric = $amazresult->price_numeric;
                    $price_currency = $amazresult->price_currency;
                    $product_asin = $amazresult->product_asin;
                    $cart_url = $amazresult->cart_url;
                    $list_price_numeric = $amazresult->list_price_numeric;
                    $product_imgs = $amazresult->product_imgs;
                    
                    //new
                    $item_score = $amazresult->item_score; 
                    $language = $amazresult->language; 
                    $edition = $amazresult->edition; 
                    $pages_count = $amazresult->pages_count; 
                    $publication_date = $amazresult->publication_date; 
                    $contributors = $amazresult->contributors; 
                    $manufacturer = $amazresult->manufacturer; 
                    $binding = $amazresult->binding; 
                    $product_group = $amazresult->product_group; 
                    $rating = $amazresult->rating; 
                    $eans = $amazresult->eans; 
                    $part_no = $amazresult->part_no; 
                    $model = $amazresult->model; 
                    $warranty = $amazresult->warranty; 
                    $color = $amazresult->color; 
                    $is_adult = $amazresult->is_adult; 
                    $dimensions = $amazresult->dimensions; 
                    $date = $amazresult->date; 
                    $size = $amazresult->size; 
                    $unit_count = $amazresult->unit_count;
                    if(!empty($global_prepend))
                    {
                        $global_prepend = aiomatic_replaceSynergyShortcodes($global_prepend);
                        $global_prepend = aiomatic_replaceAIPostShortcodes($global_prepend, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', '');     
                        $global_prepend = aiomatic_replace_review($global_prepend, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                    }
                    if(!empty($global_append))
                    {
                        $global_append = aiomatic_replaceSynergyShortcodes($global_append);
                        $global_append = aiomatic_replace_review($global_append, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                        $global_append = aiomatic_replaceAIPostShortcodes($global_append, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', '');     
                    }
                    if($title_prompt != '')
                    {
                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                        {
                            $title_prompt_arr = preg_split('/\r\n|\r|\n/', $title_prompt);
                            $my_title_prompt = $title_prompt_arr[array_rand($title_prompt_arr)];
                        }
                        else
                        {
                            $my_title_prompt = $title_prompt;
                        }
                        $zatitle_prompt = aiomatic_replace_review($my_title_prompt, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                        if(stristr($run_regex_on, 'title') !== false)
                        {
                            if ($strip_by_regex_prompts !== '')
                            {
                                $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                $xcnt = 0;
                                foreach($xstrip_by_regex as $sbr)
                                {
                                    if(isset($xreplace_regex[$xcnt]))
                                    {
                                        $repreg = $xreplace_regex[$xcnt];
                                    }
                                    else
                                    {
                                        $repreg = '';
                                    }
                                    $xcnt++;
                                    $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $zatitle_prompt);
                                    if($temp_cont !== NULL)
                                    {
                                        $zatitle_prompt = $temp_cont;
                                    }
                                }
                            }
                        }
                        if($zatitle_prompt != '')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon review title'));
                            $written = aiomatic_write_content($zatitle_prompt, $topic_title_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, true, false, 'title', 'user', $assistant_id, $thread_id, $store_data);
                            if($written === false)
                            {
                                aiomatic_log_to_file('Failed to generate title!');
                                if($auto == 1)
                                {
                                    aiomatic_clearFromList($param, $type);
                                }
                                return 'fail';
                            }
                            else
                            {
                                $written = ucfirst(trim(trim($written), '.'));
                                $post_title = $written;
                            }
                        }
                        else
                        {
                            aiomatic_log_to_file('Empty processed title prompt. Nothing to do.');
                            if($auto == 1)
                            {
                                aiomatic_clearFromList($param, $type);
                            }
                            return 'fail';
                        }
                    }
                    if(empty($post_title))
                    {
                        aiomatic_log_to_file('Failed to automatically generate Amazon product roundup title!');
                        if($auto == 1)
                        {
                            aiomatic_clearFromList($param, $type);
                        }
                        return 'fail';
                    }
                    if (strpos($post_title, '%%') === false)
                    {
                        if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                        {
                            $xposts = get_posts(
                                array(
                                    'post_type'              => $post_type,
                                    'title'                  => html_entity_decode($post_title),
                                    'post_status'            => 'any',
                                    'numberposts'            => 1,
                                    'update_post_term_cache' => false,
                                    'update_post_meta_cache' => false,           
                                    'orderby'                => 'post_date ID',
                                    'order'                  => 'ASC',
                                )
                            );
                            if ( ! empty( $xposts ) ) {
                                $zap = $xposts[0];
                            } else {
                                $zap = null;
                            }
                            if($zap !== null)
                            {
                                if($overwrite_existing)
                                {
                                    $update_post_id = $zap->ID;
                                }
                                else
                                {
                                    aiomatic_log_to_file('Post with specified title already existing, skipping it: ' . $post_title);
                                    unset($amazon_keyword_lines[$current_index]);
                                    continue;
                                }
                            }
                        }
                        $new_post_title = $post_title;
                    }
                    else
                    {
                        $new_post_title = $post_title;
                        $new_post_title = aiomatic_replaceContentShortcodes($new_post_title, $img_attr, $ai_command);
                        if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                        {
                            $xposts = get_posts(
                                array(
                                    'post_type'              => $post_type,
                                    'title'                  => html_entity_decode($new_post_title),
                                    'post_status'            => 'any',
                                    'numberposts'            => 1,
                                    'update_post_term_cache' => false,
                                    'update_post_meta_cache' => false,           
                                    'orderby'                => 'post_date ID',
                                    'order'                  => 'ASC',
                                )
                            );
                            if ( ! empty( $xposts ) ) {
                                $zap = $xposts[0];
                            } else {
                                $zap = null;
                            }
                            if($zap !== null)
                            {
                                if($overwrite_existing)
                                {
                                    $update_post_id = $zap->ID;
                                }
                                else
                                {
                                    aiomatic_log_to_file('Post with specified title already published, skipping it: ' . $new_post_title);
                                    unset($amazon_keyword_lines[$current_index]);
                                    continue;
                                }
                            }
                        }
                    }
                    $current_section = '';
                    $headings_arr_copy = $headings_arr;
                    $added_img_list = array();
                    $raw_img_list = array();
                    $full_result_list = array();
                    $added_vid_list = array();
                    $added_images = 0;
                    $added_videos = 0;
                    $heading_results = array();
                    if(empty($post_title))
                    {
                        aiomatic_log_to_file('Empty post title submitted, nothing to do!');
                        continue;
                    }
                    $new_post_content = '';
                    if(stristr($run_regex_on, 'intro') !== false)
                    {
                        if ($strip_by_regex_prompts !== '')
                        {
                            $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                            $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                            $xcnt = 0;
                            foreach($xstrip_by_regex as $sbr)
                            {
                                if(isset($xreplace_regex[$xcnt]))
                                {
                                    $repreg = $xreplace_regex[$xcnt];
                                }
                                else
                                {
                                    $repreg = '';
                                }
                                $xcnt++;
                                $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $intro_prompt);
                                if($temp_cont !== NULL)
                                {
                                    $intro_prompt = $temp_cont;
                                }
                            }
                        }
                    }
                    if($intro_prompt != '')
                    {
                        $my_intro_prompt = $intro_prompt;
                        $my_intro_prompt = aiomatic_replace_review($my_intro_prompt, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                        if($my_intro_prompt != '')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon review intro'));
                            $written = aiomatic_write_content($my_intro_prompt, $topic_intro_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'intro', 'user', $assistant_id, $thread_id, $store_data);
                            if($written === false)
                            {
                                aiomatic_log_to_file('Failed to generate intro for section: ' . $current_section);
                                continue;
                            }
                            else
                            {
                                if($new_post_content != '')
                                {
                                    $new_post_content .= ' ';
                                }
                                $new_post_content .= $written;
                            }
                        }
                        else
                        {
                            aiomatic_log_to_file('Empty processed intro prompt. Nothing to do.');
                        }
                    }
                    
                    if(stristr($run_regex_on, 'sections') !== false)
                    {
                        if ($strip_by_regex_prompts !== '')
                        {
                            $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                            $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                            $xcnt = 0;
                            foreach($xstrip_by_regex as $sbr)
                            {
                                if(isset($xreplace_regex[$xcnt]))
                                {
                                    $repreg = $xreplace_regex[$xcnt];
                                }
                                else
                                {
                                    $repreg = '';
                                }
                                $xcnt++;
                                $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $sections_prompt);
                                if($temp_cont !== NULL)
                                {
                                    $sections_prompt = $temp_cont;
                                }
                            }
                        }
                    }
                    if($sections_prompt != '' && $post_sections_list == '')
                    {
                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                        {
                            $sections_prompt_arr = preg_split('/\r\n|\r|\n/', $sections_prompt);
                            $my_post_section = $sections_prompt_arr[array_rand($sections_prompt_arr)];
                        }
                        else
                        {
                            $my_post_section = $sections_prompt;
                        }
                        $za_post_title = aiomatic_replaceContentShortcodes($post_title, $img_attr, $ai_command);
                        $my_post_section = aiomatic_replace_review($my_post_section, $za_post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                        if($my_post_section != '')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon review section list'));
                            $written = aiomatic_write_content($my_post_section, $topic_sections_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, true, false, 'sections', 'user', $assistant_id, $thread_id, $store_data);
                            if($written === false)
                            {
                                aiomatic_log_to_file('Failed to generate sections!');
                                if($auto == 1)
                                {
                                    aiomatic_clearFromList($param, $type);
                                }
                                return 'fail';
                            }
                            else
                            {
                                $post_sections = $written;
                            }
                        }
                        else
                        {
                            aiomatic_log_to_file('Empty processed sections prompt (2). Nothing to do.');
                            if($auto == 1)
                            {
                                aiomatic_clearFromList($param, $type);
                            }
                            return 'fail';
                        }
                    }
                    else
                    {
                        if($post_sections_list != '')
                        {
                            $post_sections = $spintax->Parse($post_sections_list);
                            $post_sections = str_replace('%%topic%%', $post_topic, $post_sections);
                        }
                    }
                    $post_sections = aiomatic_filter_sections($post_sections);
                    if($post_sections != '')
                    {
                        $post_sections_arr = preg_split('/\r\n|\r|\n/', $post_sections);
                    }
                    else
                    {
                        $post_sections_arr = array();
                    }
                    $product_imgs_arr = explode(',', $product_imgs);
                    if($title_outro != '')
                    {
                        $my_title_outro = $title_outro;
                        $my_title_outro = aiomatic_replace_review($my_title_outro, $za_post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                        $my_title_outro = $spintax->Parse(trim($my_title_outro));
                    }
                    if(!empty($title_toc))
                    {
                        $my_title_toc = $title_toc;
                        $my_title_toc = aiomatic_replace_review($my_title_toc, $za_post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                        $my_title_toc = $spintax->Parse(trim($my_title_toc));
                    }
                    if($title_qa != '')
                    {
                        $my_title_qa = $title_qa;
                        $my_title_qa = aiomatic_replace_review($my_title_qa, $za_post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                        $my_title_qa = $spintax->Parse(trim($my_title_qa));
                    }
                    if($title_reviews != '')
                    {
                        $my_title_reviews = $title_reviews;
                        $my_title_reviews = aiomatic_replace_review($my_title_reviews, $za_post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                        $my_title_reviews = $spintax->Parse(trim($my_title_reviews));
                    }
                    if($title_proscons != '')
                    {
                        $my_title_proscons = $title_proscons;
                        $my_title_proscons = aiomatic_replace_review($my_title_proscons, $za_post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                        $my_title_proscons = $spintax->Parse(trim($my_title_proscons));
                    }
                    if($content_prompt != '')
                    {
                        $toc = '';
                        if($enable_toc == '1')
                        {
                            if(!empty($title_toc))
                            {
                                if($my_title_toc != '')
                                {
                                    $toc .= '<h2>' . $my_title_toc . '</h2>';
                                }
                            }
                            $toc .= '<ul class="toc-class">';
                            foreach($post_sections_arr as $the_current_section)
                            {
                                if(!empty($current_section))
                                {
                                    $toc .= '<li><a href="#' . sanitize_title($the_current_section) . '">' . $the_current_section . '</a></li>';
                                }
                            }
                            if($title_reviews != '')
                            {
                                if($my_title_reviews != '')
                                {
                                    if($reviews_prompt != '' && $enable_reviews == '1')
                                    {
                                        $toc .= '<li><a href="#reviews">' . $my_title_reviews . '</a></li>';
                                    }
                                }
                            }
                            if($title_proscons != '')
                            {
                                if($my_title_proscons != '')
                                {
                                    if($proscons_prompt != '' && $enable_proscons == '1')
                                    {
                                        $toc .= '<li><a href="#proscons">' . $my_title_proscons . '</a></li>';
                                    }
                                }
                            }
                            if($title_qa != '')
                            {
                                if($my_title_qa != '')
                                {
                                    if($qa_prompt != '' && $enable_qa == '1')
                                    {
                                        $toc .= '<li><a href="#qa">' . $my_title_qa . '</a></li>';
                                    }
                                }
                            }
                            if($title_outro != '')
                            {
                                if($my_title_outro != '')
                                {
                                    if($outro_prompt != '')
                                    {
                                        $toc .= '<li><a href="#outro">' . $my_title_outro . '</a></li>';
                                    }
                                }
                            }
                            $toc .= '</ul>';
                            $new_post_content .= '<br/>' . $toc . '<br/>';
                        }
                        $s_id = 1;
                        $last_section_content = '';
                        foreach($post_sections_arr as $the_current_section)
                        {
                            $current_section = trim($the_current_section, '.;');
                            if(empty($current_section))
                            {
                                continue;
                            }
                            $my_post_content = $content_prompt;
                            $my_post_content = aiomatic_replace_review($my_post_content, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                            $my_post_content = str_replace('%%article_so_far%%', $new_post_content, $my_post_content);
                            $my_post_content = str_replace('%%last_section_content%%', $last_section_content, $my_post_content);
                            if(stristr($run_regex_on, 'content') !== false)
                            {
                                if ($strip_by_regex_prompts !== '')
                                {
                                    $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                    $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                    $xcnt = 0;
                                    foreach($xstrip_by_regex as $sbr)
                                    {
                                        if(isset($xreplace_regex[$xcnt]))
                                        {
                                            $repreg = $xreplace_regex[$xcnt];
                                        }
                                        else
                                        {
                                            $repreg = '';
                                        }
                                        $xcnt++;
                                        $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_post_content);
                                        if($temp_cont !== NULL)
                                        {
                                            $my_post_content = $temp_cont;
                                        }
                                    }
                                }
                            }
                            if($my_post_content != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon review section ID #' . $s_id));
                                $s_id++;
                                $written = aiomatic_write_content($my_post_content, $topic_content_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'content', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate content for section: ' . $current_section);
                                    continue;
                                }
                                else
                                {
                                    $written = str_ireplace($current_section, '', $written);
                                    preg_match_all('#\d+\.\s*([\s\S]*)#', $current_section, $mxatches);
                                    if(isset($mxatches[1][0]))
                                    {
                                        $written = str_ireplace(trim($mxatches[1][0]), '', $written);
                                        $written = str_ireplace(str_replace(['"', '\''], '', $mxatches[1][0]), '', $written);
                                    }
                                    $written = str_ireplace('<h2></h2>', '', $written);
                                    $written = str_ireplace('<h3></h3>', '', $written);
                                    $link_to_source = $current_section;
                                    if($no_headlink != '1')
                                    {
                                        $link_to_source = '<a target="_blank" rel="nofollow sponsored noopener" href="' . $aff_url . '">' . $current_section . '</a>';
                                    }
                                    if($sections_role == 'h2')
                                    {
                                        $new_post_content .= '<h2 id="' . sanitize_title($current_section) . '">' . $link_to_source . '</h2>';
                                    }
                                    elseif($sections_role == 'h3')
                                    {
                                        $new_post_content .= '<h3 id="' . sanitize_title($current_section) . '">' . $link_to_source . '</h3>';
                                    }
                                    elseif($sections_role == 'b')
                                    {
                                        $new_post_content .= '<b id="' . sanitize_title($current_section) . '">' . $link_to_source . '</b>';
                                    }
                                    elseif($sections_role == 'i')
                                    {
                                        $new_post_content .= '<i id="' . sanitize_title($current_section) . '">' . $link_to_source . '</i>';
                                    }
                                    elseif($sections_role == 'bi')
                                    {
                                        $new_post_content .= '<b><i id="' . sanitize_title($current_section) . '">' . $link_to_source . '</i></b>';
                                    }
                                    elseif($sections_role == 'p')
                                    {
                                        $new_post_content .= '<p id="' . sanitize_title($current_section) . '">' . $link_to_source . '</p>';
                                    }
                                    elseif($sections_role == 'x')
                                    {
                                        $new_post_content .= '<br/><span id="' . sanitize_title($current_section) . '">' . $link_to_source . '</span><br/>';
                                    }
                                    else
                                    {
                                        $new_post_content .= '<br/>' . $link_to_source . '<br/>';
                                    }
                                    if($topic_images == '1')
                                    {
                                        if(count($product_imgs_arr) > 0)
                                        {
                                            $img_index = array_rand($product_imgs_arr);
                                            $this_img = $product_imgs_arr[$img_index];
                                            unset($product_imgs_arr[$img_index]);
                                            if(isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled')
                                            {
                                                $localpath = aiomatic_copy_image_locally($this_img, $attached_id, '', false, '');
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                                if($localpath !== false)
                                                {
                                                    $this_img = $localpath[0];
                                                }
                                            }
                                            $new_post_content .= '<br/><img class="rimage_class" src="' . $this_img . '" alt="' . esc_attr($post_title) . '"><br/>';
                                            $added_img_list[] = $this_img;
                                            $added_images++;
                                        }
                                    }
                                    $last_section_content = $written;
                                    $new_post_content .= $written;
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed content prompt. Nothing to do.');
                            }
                        }
                    }
                    if($enable_reviews == '1')
                    {
                        if($reviews_prompt != '')
                        {
                            $my_reviews_prompt = $reviews_prompt;
                            $my_reviews_prompt = aiomatic_replace_review($my_reviews_prompt, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                            if(stristr($run_regex_on, 'reviews') !== false)
                            {
                                if ($strip_by_regex_prompts !== '')
                                {
                                    $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                    $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                    $xcnt = 0;
                                    foreach($xstrip_by_regex as $sbr)
                                    {
                                        if(isset($xreplace_regex[$xcnt]))
                                        {
                                            $repreg = $xreplace_regex[$xcnt];
                                        }
                                        else
                                        {
                                            $repreg = '';
                                        }
                                        $xcnt++;
                                        $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_reviews_prompt);
                                        if($temp_cont !== NULL)
                                        {
                                            $my_reviews_prompt = $temp_cont;
                                        }
                                    }
                                }
                            }
                            if($my_reviews_prompt != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon review analysis'));
                                $written = aiomatic_write_content($my_reviews_prompt, $topic_reviews_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'reviews', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate Reviews Analysis for topic: ' . $current_section);
                                    continue;
                                }
                                else
                                {
                                    if($new_post_content != '')
                                    {
                                        $new_post_content .= ' ';
                                    }
                                    if($my_title_reviews !== '')
                                    {
                                        if($sections_role == 'h2')
                                        {
                                            $new_post_content .= '<h2 id="reviews">' . $my_title_reviews . '</h2>';
                                        }
                                        elseif($sections_role == 'h3')
                                        {
                                            $new_post_content .= '<h3 id="reviews">' . $my_title_reviews . '</h3>';
                                        }
                                        elseif($sections_role == 'b')
                                        {
                                            $new_post_content .= '<b id="reviews">' . $my_title_reviews . '</b>';
                                        }
                                        elseif($sections_role == 'i')
                                        {
                                            $new_post_content .= '<i id="reviews">' . $my_title_reviews . '</i>';
                                        }
                                        elseif($sections_role == 'bi')
                                        {
                                            $new_post_content .= '<b><i id="reviews">' . $my_title_reviews . '</i></b>';
                                        }
                                        elseif($sections_role == 'p')
                                        {
                                            $new_post_content .= '<p id="reviews">' . $my_title_reviews . '</p>';
                                        }
                                        elseif($sections_role == 'x')
                                        {
                                            $new_post_content .= '<br/><span id="reviews">' . $my_title_reviews . '</span><br/>';
                                        }
                                        else
                                        {
                                            $new_post_content .= '<br/>' . $my_title_reviews . '<br/>';
                                        }
                                    }
                                    if($topic_images == '1')
                                    {
                                        if(count($product_imgs_arr) > 0)
                                        {
                                            $img_index = array_rand($product_imgs_arr);
                                            $this_img = $product_imgs_arr[$img_index];
                                            unset($product_imgs_arr[$img_index]);
                                            if(isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled')
                                            {
                                                $localpath = aiomatic_copy_image_locally($this_img, $attached_id, '', false, '');
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                                if($localpath !== false)
                                                {
                                                    $this_img = $localpath[0];
                                                }
                                            }
                                            $new_post_content .= '<br/><img class="rimage_class" src="' . $this_img . '" alt="' . esc_attr($post_title) . '"><br/>';
                                            $added_img_list[] = $this_img;
                                            $added_images++;
                                        }
                                    }
                                    $new_post_content .= $written;
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed Q&A prompt. Nothing to do.');
                            }
                        }
                    }
                    if($enable_proscons == '1')
                    {
                        if($proscons_prompt != '')
                        {
                            $my_proscons_prompt = $proscons_prompt;
                            $my_proscons_prompt = aiomatic_replace_review($my_proscons_prompt, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                            if(stristr($run_regex_on, 'proscons') !== false)
                            {
                                if ($strip_by_regex_prompts !== '')
                                {
                                    $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                    $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                    $xcnt = 0;
                                    foreach($xstrip_by_regex as $sbr)
                                    {
                                        if(isset($xreplace_regex[$xcnt]))
                                        {
                                            $repreg = $xreplace_regex[$xcnt];
                                        }
                                        else
                                        {
                                            $repreg = '';
                                        }
                                        $xcnt++;
                                        $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_proscons_prompt);
                                        if($temp_cont !== NULL)
                                        {
                                            $my_proscons_prompt = $temp_cont;
                                        }
                                    }
                                }
                            }
                            if($my_proscons_prompt != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon review pros&cons'));
                                $written = aiomatic_write_content($my_proscons_prompt, $topic_proscons_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'proscons', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate Pros & Cons for topic: ' . $current_section);
                                    continue;
                                }
                                else
                                {
                                    if($new_post_content != '')
                                    {
                                        $new_post_content .= ' ';
                                    }
                                    if($my_title_proscons !== '')
                                    {
                                        if($sections_role == 'h2')
                                        {
                                            $new_post_content .= '<h2 id="proscons">' . $my_title_proscons . '</h2>';
                                        }
                                        elseif($sections_role == 'h3')
                                        {
                                            $new_post_content .= '<h3 id="proscons">' . $my_title_proscons . '</h3>';
                                        }
                                        elseif($sections_role == 'b')
                                        {
                                            $new_post_content .= '<b id="proscons">' . $my_title_proscons . '</b>';
                                        }
                                        elseif($sections_role == 'i')
                                        {
                                            $new_post_content .= '<i id="proscons">' . $my_title_proscons . '</i>';
                                        }
                                        elseif($sections_role == 'bi')
                                        {
                                            $new_post_content .= '<b><i id="proscons">' . $my_title_proscons . '</i></b>';
                                        }
                                        elseif($sections_role == 'p')
                                        {
                                            $new_post_content .= '<p id="proscons">' . $my_title_proscons . '</p>';
                                        }
                                        elseif($sections_role == 'x')
                                        {
                                            $new_post_content .= '<br/><span id="proscons">' . $my_title_proscons . '</span><br/>';
                                        }
                                        else
                                        {
                                            $new_post_content .= '<br/>' . $my_title_proscons . '<br/>';
                                        }
                                    }
                                    if($topic_images == '1')
                                    {
                                        if(count($product_imgs_arr) > 0)
                                        {
                                            $img_index = array_rand($product_imgs_arr);
                                            $this_img = $product_imgs_arr[$img_index];
                                            unset($product_imgs_arr[$img_index]);
                                            if(isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled')
                                            {
                                                $localpath = aiomatic_copy_image_locally($this_img, $attached_id, '', false, '');
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                                if($localpath !== false)
                                                {
                                                    $this_img = $localpath[0];
                                                }
                                            }
                                            $new_post_content .= '<br/><img class="rimage_class" src="' . $this_img . '" alt="' . esc_attr($post_title) . '"><br/>';
                                            $added_img_list[] = $this_img;
                                            $added_images++;
                                        }
                                    }
                                    $new_post_content .= $written;
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed Q&A prompt. Nothing to do.');
                            }
                        }
                    }
                    if($enable_qa == '1')
                    {
                        if($qa_prompt != '')
                        {
                            $my_qa_prompt = $qa_prompt;
                            $my_qa_prompt = aiomatic_replace_review($my_qa_prompt, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                            if(stristr($run_regex_on, 'qa') !== false)
                            {
                                if ($strip_by_regex_prompts !== '')
                                {
                                    $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                    $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                    $xcnt = 0;
                                    foreach($xstrip_by_regex as $sbr)
                                    {
                                        if(isset($xreplace_regex[$xcnt]))
                                        {
                                            $repreg = $xreplace_regex[$xcnt];
                                        }
                                        else
                                        {
                                            $repreg = '';
                                        }
                                        $xcnt++;
                                        $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_qa_prompt);
                                        if($temp_cont !== NULL)
                                        {
                                            $my_qa_prompt = $temp_cont;
                                        }
                                    }
                                }
                            }
                            if($my_qa_prompt != '')
                            {
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon review qa'));
                                $written = aiomatic_write_content($my_qa_prompt, $topic_qa_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, false, false, 'qa', 'user', $assistant_id, $thread_id, $store_data);
                                if($written === false)
                                {
                                    aiomatic_log_to_file('Failed to generate Q&A for topic: ' . $current_section);
                                    continue;
                                }
                                else
                                {
                                    if($new_post_content != '')
                                    {
                                        $new_post_content .= ' ';
                                    }
                                    if($my_title_qa !== '')
                                    {
                                        if($sections_role == 'h2')
                                        {
                                            $new_post_content .= '<h2 id="qa">' . $my_title_qa . '</h2>';
                                        }
                                        elseif($sections_role == 'h3')
                                        {
                                            $new_post_content .= '<h3 id="qa">' . $my_title_qa . '</h3>';
                                        }
                                        elseif($sections_role == 'b')
                                        {
                                            $new_post_content .= '<b id="qa">' . $my_title_qa . '</b>';
                                        }
                                        elseif($sections_role == 'i')
                                        {
                                            $new_post_content .= '<i id="qa">' . $my_title_qa . '</i>';
                                        }
                                        elseif($sections_role == 'bi')
                                        {
                                            $new_post_content .= '<b><i id="qa">' . $my_title_qa . '</i></b>';
                                        }
                                        elseif($sections_role == 'p')
                                        {
                                            $new_post_content .= '<p id="qa">' . $my_title_qa . '</p>';
                                        }
                                        elseif($sections_role == 'x')
                                        {
                                            $new_post_content .= '<br/><span id="qa">' . $my_title_qa . '</span><br/>';
                                        }
                                        else
                                        {
                                            $new_post_content .= '<br/>' . $my_title_qa . '<br/>';
                                        }
                                    }
                                    if($topic_images == '1')
                                    {
                                        if(count($product_imgs_arr) > 0)
                                        {
                                            $img_index = array_rand($product_imgs_arr);
                                            $this_img = $product_imgs_arr[$img_index];
                                            unset($product_imgs_arr[$img_index]);
                                            if(isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled')
                                            {
                                                $localpath = aiomatic_copy_image_locally($this_img, $attached_id, '', false, '');
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                                if($localpath !== false)
                                                {
                                                    $this_img = $localpath[0];
                                                }
                                            }
                                            $new_post_content .= '<br/><img class="rimage_class" src="' . $this_img . '" alt="' . esc_attr($post_title) . '"><br/>';
                                            $added_img_list[] = $this_img;
                                            $added_images++;
                                        }
                                    }
                                    $new_post_content .= $written;
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty processed Q&A prompt. Nothing to do.');
                            }
                        }
                    }
                    if($outro_prompt != '')
                    {
                        $my_outro_prompt = $outro_prompt;
                        $my_outro_prompt = aiomatic_replace_review($my_outro_prompt, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                        if(stristr($run_regex_on, 'outro') !== false)
                        {
                            if ($strip_by_regex_prompts !== '')
                            {
                                $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                $xcnt = 0;
                                foreach($xstrip_by_regex as $sbr)
                                {
                                    if(isset($xreplace_regex[$xcnt]))
                                    {
                                        $repreg = $xreplace_regex[$xcnt];
                                    }
                                    else
                                    {
                                        $repreg = '';
                                    }
                                    $xcnt++;
                                    $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_outro_prompt);
                                    if($temp_cont !== NULL)
                                    {
                                        $my_outro_prompt = $temp_cont;
                                    }
                                }
                            }
                        }
                        if($my_outro_prompt != '')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon review outro'));
                            $written = aiomatic_write_content($my_outro_prompt, $topic_outro_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, true, false, 'outro', 'user', $assistant_id, $thread_id, $store_data);
                            if($written === false)
                            {
                                aiomatic_log_to_file('Failed to generate outro for section: ' . $current_section);
                                continue;
                            }
                            else
                            {
                                if($new_post_content != '')
                                {
                                    $new_post_content .= ' ';
                                }
                                if($title_outro !== '')
                                {
                                    if($my_title_outro != '')
                                    {
                                        if($sections_role == 'h2')
                                        {
                                            $new_post_content .= '<h2 id="outro">' . $my_title_outro . '</h2>';
                                        }
                                        elseif($sections_role == 'h3')
                                        {
                                            $new_post_content .= '<h3 id="outro">' . $my_title_outro . '</h3>';
                                        }
                                        elseif($sections_role == 'b')
                                        {
                                            $new_post_content .= '<b id="outro">' . $my_title_outro . '</b>';
                                        }
                                        elseif($sections_role == 'i')
                                        {
                                            $new_post_content .= '<i id="outro">' . $my_title_outro . '</i>';
                                        }
                                        elseif($sections_role == 'bi')
                                        {
                                            $new_post_content .= '<b><i id="outro">' . $my_title_outro . '</i></b>';
                                        }
                                        elseif($sections_role == 'p')
                                        {
                                            $new_post_content .= '<p id="outro">' . $my_title_outro . '</p>';
                                        }
                                        elseif($sections_role == 'x')
                                        {
                                            $new_post_content .= '<br/><span id="outro">' . $my_title_outro . '</span><br/>';
                                        }
                                        else
                                        {
                                            $new_post_content .= '<br/>' . $my_title_outro . '<br/>';
                                        }
                                    }
                                }
                                else
                                {
                                    $new_post_content .= '<br/><br/>';
                                }
                                if($topic_images == '1')
                                {
                                    if(count($product_imgs_arr) > 0)
                                    {
                                        $img_index = array_rand($product_imgs_arr);
                                        $this_img = $product_imgs_arr[$img_index];
                                        unset($product_imgs_arr[$img_index]);
                                        if(isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled')
                                        {
                                            $localpath = aiomatic_copy_image_locally($this_img, $attached_id, '', false, '');
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                            if($localpath !== false)
                                            {
                                                $this_img = $localpath[0];
                                            }
                                        }
                                        $new_post_content .= '<br/><img class="rimage_class" src="' . $this_img . '" alt="' . esc_attr($post_title) . '"><br/>';
                                        $added_img_list[] = $this_img;
                                        $added_images++;
                                    }
                                }
                                $new_post_content .= $written;
                            }
                        }
                        else
                        {
                            aiomatic_log_to_file('Empty processed outro prompt. Nothing to do.');
                        }
                    }
                    if($new_post_content == '')
                    {
                        aiomatic_log_to_file("Warning, empty post content because of empty content prompt!");
                    }
                    $new_post_excerpt = '';
                    if($excerpt_prompt != '')
                    {
                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                        {
                            $excerpt_prompt_arr = preg_split('/\r\n|\r|\n/', $excerpt_prompt);
                            $my_post_excerpt = $excerpt_prompt_arr[array_rand($excerpt_prompt_arr)];
                        }
                        else
                        {
                            $my_post_excerpt = $excerpt_prompt;
                        }
                        $my_post_excerpt = aiomatic_replace_review($my_post_excerpt, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                        if(stristr($run_regex_on, 'excerpt') !== false)
                        {
                            if ($strip_by_regex_prompts !== '')
                            {
                                $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex_prompts);
                                $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex_prompts);
                                $xcnt = 0;
                                foreach($xstrip_by_regex as $sbr)
                                {
                                    if(isset($xreplace_regex[$xcnt]))
                                    {
                                        $repreg = $xreplace_regex[$xcnt];
                                    }
                                    else
                                    {
                                        $repreg = '';
                                    }
                                    $xcnt++;
                                    $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_post_excerpt);
                                    if($temp_cont !== NULL)
                                    {
                                        $my_post_excerpt = $temp_cont;
                                    }
                                }
                            }
                        }
                        if($my_post_excerpt != '')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Amazon review excerpt'));
                            $written = aiomatic_write_content($my_post_excerpt, $topic_excerpt_model, $temperature, $top_p, $presence_penalty, $frequency_penalty, $max_tokens, $token, $global_prepend, $global_append, true, false, 'excerpt', 'user', $assistant_id, $thread_id, $store_data);
                            if($written === false)
                            {
                                aiomatic_log_to_file('Failed to generate excerpt!');
                            }
                            else
                            {
                                $new_post_excerpt = $written;
                            }
                        }
                        else
                        {
                            aiomatic_log_to_file('Empty processed excerpt prompt. Nothing to do.');
                        }
                    }

                    $get_img = '';
                    if($royalty_free == '1')
                    {
                        if($enable_ai_images == '1')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = aiomatic_get_api_service($token, $image_model);
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    if (isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] == 'on')
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $aierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating AI image'));
                                    $get_img = aiomatic_generate_ai_image($token, 1, $ai_command_image, $image_size, 'featuredImage', $skip_this_copy, 0, $aierror, $image_model, $post_title);
                                    if($get_img !== false)
                                    {
                                        foreach($get_img as $tmpimg)
                                        {
                                            $get_img = $tmpimg;
                                            break;
                                        }
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate AI featured image: ' . $aierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '2')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Stability.AI';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Stable Diffusion AI image'));
                                    $get_img = aiomatic_generate_stability_image($ai_command_image, $height, $width, 'featuredStableImage', 0, false, $ierror, $skip_this_copy, false, '', 0);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img[1]);
                                        }
                                        if(is_array($get_img) && isset($get_img[1]))
                                        {
                                            $get_img = $get_img[1];
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Stability.AI featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '7')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Google';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    if (isset($aiomatic_Main_Settings['google_ai_image_model']) && trim($aiomatic_Main_Settings['google_ai_image_model']) != '') 
                                    {
                                        $model = trim($aiomatic_Main_Settings['google_ai_image_model']);
                                    }
                                    else
                                    {
                                        $model = AIMOGEN_GOOGLE_IMAGE_DEFAULT_MODEL;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Google AI image'));
                                    $get_img = aiomatic_generate_image_google($ai_command_image, $model, 'featuredGoogleImage', false, $ierror, false);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img[1]);
                                        }
                                        if(is_array($get_img) && isset($get_img[1]))
                                        {
                                            $get_img = $get_img[1];
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Stability.AI featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '4')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Midjourney';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1792x1024')
                                    {
                                        $width = '1792';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1024x1792')
                                    {
                                        $width = '1024';
                                        $height = '1792';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Midjourney AI image'));
                                    $get_img = aiomatic_generate_ai_image_midjourney($ai_command_image, $width, $height, 'featuredMidjourneyImage', $skip_this_copy, $ierror);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Midjourney featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '5')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Replicate';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1792x1024')
                                    {
                                        $width = '1792';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1024x1792')
                                    {
                                        $width = '1024';
                                        $height = '1792';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Replicate AI image'));
                                    $get_img = aiomatic_generate_replicate_image($ai_command_image, $width, $height, 'featuredReplicateImage', $skip_this_copy, $ierror);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Replicate featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '9')
                        {
                            $random_image = aiomatic_get_random_media_library_image();

                            if ($random_image !== false)
                            {
                                $get_img = $random_image['url'];

                                if (isset($aiomatic_Main_Settings['enable_detailed_logging']))
                                {
                                    aiomatic_log_to_file(
                                        'Random Media Library featured image selected: ' .
                                        $get_img .
                                        ' (ID: ' . $random_image['id'] . ')'
                                    );
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file(
                                    'Failed to find a random image in Media Library for featured image.'
                                );

                                $get_img = '';
                            }
                        }
                        elseif($enable_ai_images == '6')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Ideogram';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1792x1024')
                                    {
                                        $width = '1792';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1024x1792')
                                    {
                                        $width = '1024';
                                        $height = '1792';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Ideogram AI image'));
                                    $get_img = aiomatic_generate_ideogram_image($ai_command_image, $width, $height, 'featuredIdeogramImage', $skip_this_copy, $ierror);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Ideogram featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '8')
                        {
                            $query_words = $post_title;
                            if($image_query == '')
                            {
                                $image_query = $temp_post;
                            }
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($ai_command_image))
                                {
                                    aiomatic_log_to_file('Empty API featured image seed expression provided!');
                                }
                                else
                                {
                                    
                                    
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = 'Cloudflare';
                                        aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                    }
                                    if($image_size == '256x256')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '512x512')
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    elseif($image_size == '1024x1024')
                                    {
                                        $width = '1024';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1792x1024')
                                    {
                                        $width = '1792';
                                        $height = '1024';
                                    }
                                    elseif($image_size == '1024x1792')
                                    {
                                        $width = '1024';
                                        $height = '1792';
                                    }
                                    else
                                    {
                                        $width = '512';
                                        $height = '512';
                                    }
                                    $skip_this_copy = true;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                    {
                                        $skip_this_copy = false;
                                    }
                                    $ierror = '';
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating Cloudflare AI image'));
                                    $get_img = aiomatic_generate_cloudflare_image($ai_command_image, $width, $height, 'featuredCloudflareImage', $skip_this_copy, $ierror);
                                    if($get_img !== false)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                        }
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate Cloudflare featured image: ' . $ierror);
                                        $get_img = '';
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered.');
                            }
                        }
                        elseif($enable_ai_images == '3')
                        {
                            if ($image_url != '') 
                            {
                                $replacement = str_replace(array('[', ']'), '', $query_words);
                                $image_url_temp = str_replace('%%item_title%%', $replacement, $image_url);
                                $image_url_temp = preg_replace_callback('#%%random_image\[([^\]]*?)\](\[\d+\])?%%#', function ($matches) {
                                    if(isset($matches[2]))
                                    {
                                        $chance = trim($matches[2], '[]');
                                    }
                                    else
                                    {
                                        $chance = '';
                                    }
                                    $arv = array();
                                    $my_img = aiomatic_get_random_image_google($matches[1], 0, 0, $chance, $arv);
                                    return $my_img;
                                }, $image_url_temp);
                                $img_rulx = $spintax->Parse(trim($image_url_temp));
                                $selected_img = aiomatic_select_ai_image($post_title, $img_rulx);
                                if($selected_img === false)
                                {
                                    $img_rulx = explode(',', $img_rulx);
                                    $img_rulx = trim($img_rulx[array_rand($img_rulx)]);
                                    if($img_rulx != '')
                                    {
                                        $get_img = $img_rulx;
                                    }
                                }
                                else
                                {
                                    $get_img = $selected_img;
                                }
                            }
                        }
                        else
                        {
                            $image_query_set = false;
                            $query_words = '';
                            $ai_command_image = '';
                            if($orig_ai_command_image == '')
                            {
                                $orig_ai_command_image = $image_query;
                            }
                            if($orig_ai_command_image != '')
                            {
                                $ai_command_image = $orig_ai_command_image;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $ai_command_image = preg_split('/\r\n|\r|\n/', $ai_command_image);
                                    $ai_command_image = array_filter($ai_command_image);
                                    if(count($ai_command_image) > 0)
                                    {
                                        $ai_command_image = $ai_command_image[array_rand($ai_command_image)];
                                    }
                                    else
                                    {
                                        $ai_command_image = '';
                                    }
                                }
                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                if(!empty($ai_command_image))
                                {
                                    $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $ai_command_image = trim(strip_tags($post_title));
                                }
                                $ai_command_image = trim($ai_command_image);
                                if (filter_var($ai_command_image, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($ai_command_image, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($ai_command_image);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $ai_command_image = $txt_content;
                                                $ai_command_image = aiomatic_replaceSynergyShortcodes($ai_command_image);
                                                $ai_command_image = aiomatic_replaceAIPostShortcodes($ai_command_image, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                            }
                            if($ai_command_image != '')
                            {
                                $query_words = $ai_command_image;
                                $image_query = $ai_command_image;
                                $image_query_set = true;
                            }
                            if(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'textrazor')
                            {
                                if(isset($aiomatic_Main_Settings['textrazor_key']) && trim($aiomatic_Main_Settings['textrazor_key']) != '')
                                {
                                    try
                                    {
                                        if(!class_exists('TextRazor'))
                                        {
                                            require_once(dirname(__FILE__) . "/res/TextRazor.php");
                                        }
                                        TextRazorSettings::setApiKey(trim($aiomatic_Main_Settings['textrazor_key']));
                                        $textrazor = new TextRazor();
                                        $textrazor->addExtractor('entities');
                                        $response = $textrazor->analyze($image_query);
                                        if (isset($response['response']['entities'])) 
                                        {
                                            foreach ($response['response']['entities'] as $entity) 
                                            {
                                                $query_words = '';
                                                if(isset($entity['entityEnglishId']))
                                                {
                                                    $query_words = $entity['entityEnglishId'];
                                                }
                                                else
                                                {
                                                    $query_words = $entity['entityId'];
                                                }
                                                if($query_words != '')
                                                {
                                                    $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                                    if(!empty($attached_id))
                                                    {
                                                        $additional_attachments[] = $attached_id;
                                                    }
                                                    if(!empty($z_img))
                                                    {
                                                        $get_img = $z_img;
                                                        $go_local_image = false;
                                                        if(!function_exists('is_plugin_active'))
                                                        {
                                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                                        }
                                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                                        {
                                                            $go_local_image = true;
                                                        }
                                                        if($go_local_image == true)
                                                        {
                                                            $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, $query_words);
                                                            if(!empty($attached_id))
                                                            {
                                                                $additional_attachments[] = $attached_id;
                                                            }
                                                            if($localpath !== false)
                                                            {
                                                                $get_img = $localpath[0];
                                                            }
                                                        }
                                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                            aiomatic_log_to_file('Royalty Free Image Generated with help of TextRazor (kw: "' . $query_words . '"): ' . $z_img);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch(Exception $e)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Failed to search for keywords using TextRazor (2): ' . $e->getMessage());
                                        }
                                    }
                                }
                            }
                            elseif(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'openai')
                            {
                                if(isset($aiomatic_Main_Settings['keyword_prompts']) && trim($aiomatic_Main_Settings['keyword_prompts']) != '')
                                {
                                    if(isset($aiomatic_Main_Settings['keyword_model']) && $aiomatic_Main_Settings['keyword_model'] != '')
                                    {
                                        $kw_model = $aiomatic_Main_Settings['keyword_model'];
                                    }
                                    else
                                    {
                                        $kw_model = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                    }
                                    if(isset($aiomatic_Main_Settings['keyword_assistant_id']) && $aiomatic_Main_Settings['keyword_assistant_id'] != '')
                                    {
                                        $keyword_assistant_id = $aiomatic_Main_Settings['keyword_assistant_id'];
                                    }
                                    else
                                    {
                                        $keyword_assistant_id = '';
                                    }
                                    $title_ai_command = trim($aiomatic_Main_Settings['keyword_prompts']);
                                    $title_ai_command = str_replace('%%default_post_cats%%', $default_cat_list, $title_ai_command);
                                    $title_ai_command = str_replace('%%original_post_title%%', $post_title, $title_ai_command);
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $title_ai_command = preg_split('/\r\n|\r|\n/', $title_ai_command);
                                        $title_ai_command = array_filter($title_ai_command);
                                        if(count($title_ai_command) > 0)
                                        {
                                            $title_ai_command = $title_ai_command[array_rand($title_ai_command)];
                                        }
                                        else
                                        {
                                            $title_ai_command = '';
                                        }
                                    }
                                    $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                    if(!empty($title_ai_command))
                                    {
                                        $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    $title_ai_command = trim($title_ai_command);
                                    if (filter_var($title_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($title_ai_command, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($title_ai_command);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $title_ai_command = $txt_content;
                                                    $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                                    $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($title_ai_command))
                                    {
                                        aiomatic_log_to_file('Empty API keyword extractor seed expression provided!');
                                        $title_ai_command = 'Type the most relevant keyword, no other text before or after it, for a blog post titled:  ' . trim(strip_tags($post_title));
                                    }
                                    if(aiomatic_strlen($title_ai_command) > $max_seed_tokens * 4)
                                    {
                                        $title_ai_command = aiomatic_substr($title_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                                    }
                                    $title_ai_command = trim($title_ai_command);
                                    if(empty($title_ai_command))
                                    {
                                        aiomatic_log_to_file('Empty API title seed expression provided(3)! ' . print_r($title_ai_command, true));
                                    }
                                    else
                                    {
                                        $query_token_count = count(aiomatic_encode($title_ai_command));
                                        $available_tokens = aiomatic_compute_available_tokens($kw_model, $max_tokens, $title_ai_command, $query_token_count);
                                        if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                        {
                                            $string_len = aiomatic_strlen($title_ai_command);
                                            $string_len = $string_len / 2;
                                            $string_len = intval(0 - $string_len);
                                            $title_ai_command = aiomatic_substr($title_ai_command, 0, $string_len);
                                            $title_ai_command = trim($title_ai_command);
                                            $query_token_count = count(aiomatic_encode($title_ai_command));
                                            $available_tokens = $max_tokens - $query_token_count;
                                        }
                                        $aierror = '';
                                        $finish_reason = '';
                                        if(!empty($global_prepend))
                                        {
                                            $title_ai_command = $global_prepend . ' ' . $title_ai_command;
                                        }
                                        if(!empty($global_append))
                                        {
                                            $title_ai_command = $title_ai_command . ' ' . $global_append;
                                        }
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = aiomatic_get_api_service($token, $kw_model);
                                            aiomatic_log_to_file('Calling ' . $api_service . ' (' . $keyword_assistant_id . '/' . $kw_model . ')(' . $available_tokens . ') for title text: ' . $title_ai_command);
                                        }
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating image search keywords'));
                                        $generated_text = aiomatic_generate_text($token, $kw_model, $title_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'keywordID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $keyword_assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                        if($generated_text === false)
                                        {
                                            aiomatic_log_to_file('Keyword generator error: ' . $aierror);
                                            $ai_title = '';
                                        }
                                        else
                                        {
                                            $ai_title = trim(trim($generated_text), '.');
                                            $ai_titles = explode(',', $ai_title);
                                            foreach($ai_titles as $query_words)
                                            {
                                                $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, trim($query_words), $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                                if(!empty($z_img))
                                                {
                                                    $get_img = $z_img;
                                                    $go_local_image = false;
                                                    if(!function_exists('is_plugin_active'))
                                                    {
                                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                                    }
                                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                                    {
                                                        $go_local_image = true;
                                                    }
                                                    if($go_local_image == true)
                                                    {
                                                        $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, $query_words);
                                                        if(!empty($attached_id))
                                                        {
                                                            $additional_attachments[] = $attached_id;
                                                        }
                                                        if($localpath !== false)
                                                        {
                                                            $get_img = $localpath[0];
                                                        }
                                                    }
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                        aiomatic_log_to_file('Royalty Free Image Generated with help of AI (kw: "' . $query_words . '"): ' . $z_img);
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = aiomatic_get_api_service($token, $kw_model);
                                            aiomatic_log_to_file('Successfully got API keyword result from ' . $api_service . ': ' . $ai_title);
                                        }
                                    }
                                }
                            }
                            if(empty($get_img))
                            {
                                if($image_query_set == true && !empty($image_query))
                                {
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating royalty free image'));
                                    $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $image_query, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                    if(!empty($attached_id))
                                    {
                                        $additional_attachments[] = $attached_id;
                                    }
                                    if($get_img == '' || $get_img === false)
                                    {
                                        if(isset($aiomatic_Main_Settings['bimage']) && $aiomatic_Main_Settings['bimage'] == 'on')
                                        {
                                            $keyword_class = new Aiomatic_keywords();
                                            $image_query = $keyword_class->keywords($image_query, 1);
                                            $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $image_query, $img_attr, $attached_id, 20, true, $raw_img_list, array(), $full_result_list);
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                        }
                                    }
                                }
                                if(empty($get_img))
                                {
                                    $keyword_class = new Aiomatic_keywords();
                                    $query_words = $keyword_class->keywords($post_title, 2);
                                    $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                    if(!empty($attached_id))
                                    {
                                        $additional_attachments[] = $attached_id;
                                    }
                                    if($get_img == '' || $get_img === false)
                                    {
                                        if(isset($aiomatic_Main_Settings['bimage']) && $aiomatic_Main_Settings['bimage'] == 'on')
                                        {
                                            $query_words = $keyword_class->keywords($post_title, 1);
                                            $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 20, true, $raw_img_list, array(), $full_result_list);
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                            if($get_img == '' || $get_img === false)
                                            {
                                                if(isset($aiomatic_Main_Settings['no_royalty_skip']) && $aiomatic_Main_Settings['no_royalty_skip'] == 'on')
                                                {
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                        aiomatic_log_to_file('Skipping importing because no royalty free image found.');
                                                    }
                                                    unset($post_title_lines[$current_index]);
                                                    continue;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if(isset($aiomatic_Main_Settings['no_royalty_skip']) && $aiomatic_Main_Settings['no_royalty_skip'] == 'on')
                                            {
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                    aiomatic_log_to_file('Skipping importing because no royalty free image found.');
                                                }
                                                unset($post_title_lines[$current_index]);
                                                continue;
                                            }
                                        }
                                    }
                                }
                                if(!empty($get_img))
                                {
                                    $go_local_image = false;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                    {
                                        $go_local_image = true;
                                    }
                                    if($go_local_image == true)
                                    {
                                        $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, '');
                                        if(!empty($attached_id))
                                        {
                                            $additional_attachments[] = $attached_id;
                                        }
                                        if($localpath !== false)
                                        {
                                            $get_img = $localpath[0];
                                        }
                                    }
                                }
                            }
                        }
                    }
                    elseif($royalty_free == '2')
                    {
                        $get_img = $amazon_thumb;
                    }
                    if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                    {
                        $already_spinned = '1';
                    }
                    $my_post                              = array();
                    $my_post['aiomatic_post_image']       = $get_img;
                    if($enable_ai_images == '2')
                    {
                        $my_post['aiomatic_local_image']      = '1';
                    }
                    else
                    {
                        $my_post['aiomatic_local_image']      = '0';
                    }
                    $my_post['aiomatic_enable_pingbacks'] = $enable_pingback;
                    $my_post['default_category']          = $default_category;
                    $my_post['post_type']                 = $post_type;
                    $my_post['comment_status']            = $accept_comments;
                    if (isset($aiomatic_Main_Settings['draft_first']) && $aiomatic_Main_Settings['draft_first'] != 'on')
                    {
                        if($post_status == 'publish')
                        {
                            $draft_me = true;
                            $my_post['post_status'] = 'draft';
                        }
                        else
                        {
                            $my_post['post_status']   = $post_status;
                        }
                    }
                    else
                    {
                        $my_post['post_status']               = $post_status;
                    }
                    if($user_name_type == 'rand')
                    {
                        $randid = aiomatic_display_random_user();
                        if($randid === false)
                        {
                            $my_post['post_author']               = aimogen_get_admin_user_id();
                        }
                        else
                        {
                            $my_post['post_author']               = $randid->ID;
                        }
                    }
                    else
                    {
                        $my_post['post_author']               = $post_user_name;
                    }
                    if($strip_title == '1')
                    {
                        $new_post_content = str_replace($post_title, '', $new_post_content);
                        $new_post_content = str_replace('<h2></h2>', '', $new_post_content);
                        $new_post_content = str_replace('<h3></h3>', '', $new_post_content);
                    }
                    if (isset($aiomatic_Main_Settings['swear_filter']) && $aiomatic_Main_Settings['swear_filter'] == 'on') 
                    {
                        require_once(dirname(__FILE__) . "/res/swear.php");
                        $new_post_content = aimogenpro_filterwords($new_post_content);
                    }
                    if(isset($aiomatic_Main_Settings['global_ban_words']) && $aiomatic_Main_Settings['global_ban_words'] != '') {
                        $continue    = false;
                        $aiomatic_Main_Settings['global_ban_words'] = trim(trim(trim($aiomatic_Main_Settings['global_ban_words']), ','));
                        $banned_list = explode(',', $aiomatic_Main_Settings['global_ban_words']);
                        foreach ($banned_list as $banned_word) {
                            if (stripos($new_post_content, trim($banned_word)) !== FALSE) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s content contains global banned word: ' . $banned_word);
                                }
                                $continue = true;
                                break;
                            }
                            if (stripos($post_title, trim($banned_word)) !== FALSE) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s title contains global banned word: ' . $banned_word);
                                }
                                $continue = true;
                                break;
                            }
                        }
                        if ($continue === true) {
                            continue;
                        }
                    }
                    if(isset($aiomatic_Main_Settings['global_req_words']) && $aiomatic_Main_Settings['global_req_words'] != '')
                    {
                        if(isset($aiomatic_Main_Settings['require_only_one']) && $aiomatic_Main_Settings['require_only_one'] == 'on')
                        {
                            $continue      = true;
                            $aiomatic_Main_Settings['global_req_words'] = trim(trim(trim($aiomatic_Main_Settings['global_req_words']), ','));
                            $required_list = explode(',', $aiomatic_Main_Settings['global_req_words']);
                            foreach ($required_list as $required_word) {
                                if (stripos($new_post_content, trim($required_word)) !== FALSE || stripos($post_title, trim($required_word)) !== FALSE) {
                                    $continue = false;
                                    break;
                                }
                            }
                            if ($continue === true) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s content doesn\'t contain global required words.');
                                }
                                continue;
                            }
                        }
                        else
                        {
                            $continue      = false;
                            $aiomatic_Main_Settings['global_req_words'] = trim(trim(trim($aiomatic_Main_Settings['global_req_words']), ','));
                            $required_list = explode(',', $aiomatic_Main_Settings['global_req_words']);
                            foreach ($required_list as $required_word) {
                                if (stripos($new_post_content, trim($required_word)) === FALSE && stripos($post_title, trim($required_word)) === FALSE) {
                                    $continue = true;
                                    break;
                                }
                            }
                            if ($continue === true) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($post_title) . '", because it\'s content doesn\'t contain global required words.');
                                }
                                continue;
                            }
                        }
                    }
                    $new_post_title = $post_title;
                    if (isset($aiomatic_Main_Settings['spin_what']) && $aiomatic_Main_Settings['spin_what'] === 'omni') 
                    {
                        $skip_spin = '1';
                    }
                    $arr = aiomatic_spin_and_translate($new_post_title, $new_post_content, '3', $skip_spin, $skip_translate);
                    if($arr[0] != $new_post_title)
                    {
                        $new_post_title = $arr[0];
                        if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                        {
                            $posts = get_posts(
                                array(
                                    'post_type'              => $post_type,
                                    'title'                  => html_entity_decode($new_post_title),
                                    'post_status'            => 'any',
                                    'numberposts'            => 1,
                                    'update_post_term_cache' => false,
                                    'update_post_meta_cache' => false,           
                                    'orderby'                => 'post_date ID',
                                    'order'                  => 'ASC',
                                )
                            );
                            if ( ! empty( $posts ) ) {
                                $zap = $posts[0];
                            } else {
                                $zap = null;
                            }
                            if($zap !== null)
                            {
                                if($overwrite_existing)
                                {
                                    $update_post_id = $zap->ID;
                                }
                                else
                                {
                                    aiomatic_log_to_file('Post with specified title already existing (after spin/translate), skipping it: ' . $new_post_title);
                                    unset($post_title_lines[$current_index]);
                                    continue;
                                }
                            }
                        }
                    }
                    $new_post_content            = $arr[1];
                    if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                    {
                        $already_spinned = '1';
                    }
                    if ($auto_categories == 'content') {
                        $extra_categories            = aiomatic_extractKeyWords($new_post_content);
                        $extra_categories            = implode(',', $extra_categories);
                    }
                    elseif ($auto_categories == 'title') {
                        $extra_categories            = aiomatic_extractKeyWords($new_post_title);
                        $extra_categories            = implode(',', $extra_categories);
                    }
                    elseif ($auto_categories == 'both') {
                        $extra_categories            = aiomatic_extractKeyWords($new_post_content);
                        $extra_categories            = implode(',', $extra_categories);
                        $extra_categories2            = aiomatic_extractKeyWords($new_post_title);
                        $extra_categories2            = implode(',', $extra_categories2);
                        if($extra_categories2 != '')
                        {
                            $extra_categories .= ',' . $extra_categories2;
                        }
                    }
                    elseif ($auto_categories == 'ai') 
                    {
                        $category_ai_command = $orig_ai_command_category;
                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                        {
                            $category_ai_command = preg_split('/\r\n|\r|\n/', $category_ai_command);
                            $category_ai_command = array_filter($category_ai_command);
                            if(count($category_ai_command) > 0)
                            {
                                $category_ai_command = $category_ai_command[array_rand($category_ai_command)];
                            }
                            else
                            {
                                $category_ai_command = '';
                            }
                        }
                        $category_ai_command = aiomatic_replaceSynergyShortcodes($category_ai_command);
                        if(!empty($category_ai_command))
                        {
                            $category_ai_command = aiomatic_replaceAIPostShortcodes($category_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                            $category_ai_command = aiomatic_replace_review($category_ai_command, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                        }
                        else
                        {
                            $category_ai_command = trim(strip_tags('Write a comma separated list of categories, for the post title: %%post_title%%'));
                        }
                        $category_ai_command = trim($category_ai_command);
                        if (filter_var($category_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($category_ai_command, '.txt'))
                        {
                            $txt_content = aiomatic_get_web_page($category_ai_command);
                            if ($txt_content !== FALSE) 
                            {
                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                $txt_content = array_filter($txt_content);
                                if(count($txt_content) > 0)
                                {
                                    $txt_content = $txt_content[array_rand($txt_content)];
                                    if(trim($txt_content) != '') 
                                    {
                                        $category_ai_command = $txt_content;
                                        $category_ai_command = aiomatic_replaceSynergyShortcodes($category_ai_command);
                                        $category_ai_command = aiomatic_replaceAIPostShortcodes($category_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        $category_ai_command = aiomatic_replace_review($category_ai_command, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                                    }
                                }
                            }
                        }
                        if(empty($category_ai_command))
                        {
                            aiomatic_log_to_file('Empty API post category seed expression provided!');
                        }
                        else
                        {
                            if(aiomatic_strlen($category_ai_command) > $max_seed_tokens * 4)
                            {
                                $category_ai_command = aiomatic_substr($category_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                            }
                            $category_ai_command = trim($category_ai_command);
                            if(empty($category_ai_command))
                            {
                                aiomatic_log_to_file('Empty API category seed expression provided! ' . print_r($category_ai_command, true));
                                break;
                            }
                            $query_token_count = count(aiomatic_encode($category_ai_command));
                            $available_tokens = aiomatic_compute_available_tokens($category_model, $max_tokens, $category_ai_command, $query_token_count);
                            if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                            {
                                $string_len = aiomatic_strlen($category_ai_command);
                                $string_len = $string_len / 2;
                                $string_len = intval(0 - $string_len);
                                $category_ai_command = aiomatic_substr($category_ai_command, 0, $string_len);
                                $category_ai_command = trim($category_ai_command);
                                if(empty($category_ai_command))
                                {
                                    aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($category_ai_command, true));
                                    break;
                                }
                                $query_token_count = count(aiomatic_encode($category_ai_command));
                                $available_tokens = $max_tokens - $query_token_count;
                            }
                            $aierror = '';
                            $finish_reason = '';
                            if(!empty($global_prepend))
                            {
                                $category_ai_command = $global_prepend . ' ' . $category_ai_command;
                            }
                            if(!empty($global_append))
                            {
                                $category_ai_command = $category_ai_command . ' ' . $global_append;
                            }
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $category_model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $category_model . ')(' . $available_tokens . ') for category generator: ' . $category_ai_command);
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating categories'));
                            $generated_text = aiomatic_generate_text($token, $category_model, $category_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'categoryID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', false, $store_data, array(), '', '', '');
                            if($generated_text === false)
                            {
                                aiomatic_log_to_file('Category generator error: ' . $aierror);
                                break;
                            }
                            else
                            {
                                $extra_categories = $generated_text;
                            }
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $category_model);
                                aiomatic_log_to_file('Successfully got API category result from ' . $api_service . ': ' . $generated_text);
                            }
                        }
                    }
                    else
                    {
                        $extra_categories = '';
                    }
                    $my_post['extra_categories'] = $extra_categories;
                    
                    $item_tags                   = aiomatic_extractKeyWords($new_post_content, 3);
                    $item_tags                   = implode(',', $item_tags);
                    $title_tags                   = aiomatic_extractKeyWords($new_post_title, 3);
                    $title_tags                   = implode(',', $title_tags);
                    $item_create_tag_sp = $spintax->Parse($item_create_tag);
                    if ($can_create_tag == 'content') {
                        $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $item_tags;
                        $my_post['extra_tags']       = $item_tags;
                    } else if ($can_create_tag == 'title') {
                        $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $title_tags;
                        $my_post['extra_tags']       = $title_tags;
                    } else if ($can_create_tag == 'both') {
                        $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . ($item_tags != '' ? $item_tags . ',' : '') . $title_tags;
                        $my_post['extra_tags']       = ($item_tags != '' ? $item_tags . ',' : '') . $title_tags;
                    } else if ($can_create_tag == 'ai') {
                        $ai_tags = '';
                        $tag_ai_command = $orig_ai_command_tag;
                        if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                        {
                            $tag_ai_command = preg_split('/\r\n|\r|\n/', $tag_ai_command);
                            $tag_ai_command = array_filter($tag_ai_command);
                            if(count($tag_ai_command) > 0)
                            {
                                $tag_ai_command = $tag_ai_command[array_rand($tag_ai_command)];
                            }
                            else
                            {
                                $tag_ai_command = '';
                            }
                        }
                        $tag_ai_command = aiomatic_replaceSynergyShortcodes($tag_ai_command);
                        if(!empty($tag_ai_command))
                        {
                            $tag_ai_command = aiomatic_replaceAIPostShortcodes($tag_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                            $tag_ai_command = aiomatic_replace_review($tag_ai_command, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                        }
                        else
                        {
                            $tag_ai_command = trim(strip_tags('Write a comma separated list of tags, for the post title: %%post_title%%'));
                        }
                        $tag_ai_command = trim($tag_ai_command);
                        if (filter_var($tag_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($tag_ai_command, '.txt'))
                        {
                            $txt_content = aiomatic_get_web_page($tag_ai_command);
                            if ($txt_content !== FALSE) 
                            {
                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                $txt_content = array_filter($txt_content);
                                if(count($txt_content) > 0)
                                {
                                    $txt_content = $txt_content[array_rand($txt_content)];
                                    if(trim($txt_content) != '') 
                                    {
                                        $tag_ai_command = $txt_content;
                                        $tag_ai_command = aiomatic_replaceSynergyShortcodes($tag_ai_command);
                                        $tag_ai_command = aiomatic_replaceAIPostShortcodes($tag_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                        $tag_ai_command = aiomatic_replace_review($tag_ai_command, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                                    }
                                }
                            }
                        }
                        if(empty($tag_ai_command))
                        {
                            aiomatic_log_to_file('Empty API post tag seed expression provided!');
                        }
                        else
                        {
                            if(aiomatic_strlen($tag_ai_command) > $max_seed_tokens * 4)
                            {
                                $tag_ai_command = aiomatic_substr($tag_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                            }
                            $tag_ai_command = trim($tag_ai_command);
                            if(empty($tag_ai_command))
                            {
                                aiomatic_log_to_file('Empty API tag seed expression provided! ' . print_r($tag_ai_command, true));
                                break;
                            }
                            $query_token_count = count(aiomatic_encode($tag_ai_command));
                            $available_tokens = aiomatic_compute_available_tokens($tag_model, $max_tokens, $tag_ai_command, $query_token_count);
                            if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                            {
                                $string_len = aiomatic_strlen($tag_ai_command);
                                $string_len = $string_len / 2;
                                $string_len = intval(0 - $string_len);
                                $tag_ai_command = aiomatic_substr($tag_ai_command, 0, $string_len);
                                $tag_ai_command = trim($tag_ai_command);
                                if(empty($tag_ai_command))
                                {
                                    aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($tag_ai_command, true));
                                    break;
                                }
                                $query_token_count = count(aiomatic_encode($tag_ai_command));
                                $available_tokens = $max_tokens - $query_token_count;
                            }
                            $aierror = '';
                            $finish_reason = '';
                            if(!empty($global_prepend))
                            {
                                $tag_ai_command = $global_prepend . ' ' . $tag_ai_command;
                            }
                            if(!empty($global_append))
                            {
                                $tag_ai_command = $tag_ai_command . ' ' . $global_append;
                            }
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $tag_model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $tag_model . ')(' . $available_tokens . ') for tag generator: ' . $tag_ai_command);
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating tags'));
                            $generated_text = aiomatic_generate_text($token, $tag_model, $tag_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'tagID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', false, $store_data, array(), '', '', '');
                            if($generated_text === false)
                            {
                                aiomatic_log_to_file('Tag generator error: ' . $aierror);
                                break;
                            }
                            else
                            {
                                $ai_tags = $generated_text;
                            }
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $tag_model);
                                aiomatic_log_to_file('Successfully got API tag result from ' . $api_service . ': ' . $generated_text);
                            }
                        }
                        $post_the_tags = ($item_create_tag_sp != '' ? $item_create_tag_sp . ',' : '') . $ai_tags;
                        $my_post['extra_tags']       = $ai_tags;
                    } else {
                        $post_the_tags = $item_create_tag_sp;
                        $my_post['extra_tags']       = '';
                    }
                    $my_post['tags_input'] = $post_the_tags;
                    $new_post_content = aimogen_bulk_polish_article_content($new_post_content, array('title' => isset($new_post_title) ? $new_post_title : '', 'topic' => isset($post_topic) ? $post_topic : '', 'language' => isset($content_language) ? $content_language : '', 'model' => (isset($topic_content_model) && $topic_content_model !== '') ? $topic_content_model : (isset($model) ? $model : ''), 'token' => isset($token) ? $token : '', 'temperature' => isset($temperature) ? $temperature : '', 'top_p' => isset($top_p) ? $top_p : '', 'presence_penalty' => isset($presence_penalty) ? $presence_penalty : '', 'frequency_penalty' => isset($frequency_penalty) ? $frequency_penalty : '', 'rule_id' => isset($rule_unique_id) ? $rule_unique_id : '', 'global_prepend' => isset($global_prepend) ? $global_prepend : '', 'global_append' => isset($global_append) ? $global_append : '', 'assistant_id' => isset($assistant_id) ? $assistant_id : '', 'thread_id' => isset($thread_id) ? $thread_id : '', 'store_data' => isset($store_data) ? $store_data : 'off'));
                    $new_post_content        = html_entity_decode($new_post_content);
                    $new_post_content = str_replace('</ iframe>', '</iframe>', $new_post_content);
                    if ($strip_by_regex !== '')
                    {
                        $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex);
                        $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex);
                        $xcnt = 0;
                        foreach($xstrip_by_regex as $sbr)
                        {
                            if(isset($xreplace_regex[$xcnt]))
                            {
                                $repreg = $xreplace_regex[$xcnt];
                            }
                            else
                            {
                                $repreg = '';
                            }
                            $xcnt++;
                            $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $new_post_content);
                            if($temp_cont !== NULL)
                            {
                                $new_post_content = $temp_cont;
                            }
                        }
                    }
                    $post_prepender = aiomatic_replaceAIPostShortcodes($post_prepend, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                    $post_prepender = aiomatic_replace_review($post_prepender, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                    $post_appender = aiomatic_replaceAIPostShortcodes($post_append, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                    $post_appender = aiomatic_replace_review($post_appender, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                    $post_appender = aiomatic_replaceSynergyShortcodes($post_appender);
                    $post_prepender = aiomatic_replaceSynergyShortcodes($post_prepender);
                    if($topic_videos == '1' && count($added_vid_list) == 0)
                    {
                        if(isset($aiomatic_Main_Settings['social_list']) && !empty($aiomatic_Main_Settings['social_list']) && is_array($aiomatic_Main_Settings['social_list']))
                        {
                            $social_list = $aiomatic_Main_Settings['social_list'];
                        }
                        else
                        {
                            $social_list = array();
                        }
                        $new_vid = aiomatic_get_video($product_title, '', $social_list);
                        if($new_vid !== false && !in_array($new_vid, $added_vid_list))
                        {
                            $new_post_content .= $new_vid;
                            $added_vid_list[] = $new_vid;
                            $new_vid_arr[] = $new_vid;
                            $added_videos++;
                        }
                    }
                    $zlang = 'en_US';
                    if (isset($aiomatic_Main_Settings['kw_lang']) && !empty($aiomatic_Main_Settings['kw_lang'])) {
                        $zlang = $aiomatic_Main_Settings['kw_lang'];
                    }
                    $rel_search = array('post_title', 'post_content');
                    if (isset($aiomatic_Main_Settings['rel_search']) && is_array($aiomatic_Main_Settings['rel_search'])) {
                        $rel_search = $aiomatic_Main_Settings['rel_search'];
                    }
                    if($max_links !== '' && $inboundlinker !== null && $link_type != 'disabled')
                    {
                        try
                        {
                            $new_post_content = $inboundlinker->add_inbound_links($new_post_content, $max_links, $link_post_types, $zlang, $rel_search, null, $link_type, $link_list, $link_nofollow, '', '', array());
                        }
                        catch(Exception $ex)
                        {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('Failed to add new inbound links to content: ' . $ex->getMessage());
                            }
                        }
                    }
                    if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                    {
                        if($new_post_content === strip_tags($new_post_content)) 
                        {
                            $new_post_content = nl2br($new_post_content);
                        }
                    }
                    if (!isset($aiomatic_Main_Settings['no_undetectibility']) || $aiomatic_Main_Settings['no_undetectibility'] != 'on') 
                    {
                        if (!isset($aiomatic_Main_Settings['no_undetectibility_bulk']) || $aiomatic_Main_Settings['no_undetectibility_bulk'] != 'on') 
                        {
                            if(!isset($xchars))
                            {
                                $xchars = array();
                            }
                            $rand_percentage = wp_rand(10, 20);
                            $new_post_content = aiomatic_make_unique($new_post_content, $xchars, $rand_percentage);
                        }
                    }
                    if($ret_content == 1)
                    {
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                            aiomatic_log_to_file('Returning AI generated content, finished.');
                        }
                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Finished processing'));
                        return array($post_prepender . ' ' . $new_post_content . ' ' . $post_appender, $new_post_title);
                    }
                    $the_final_cont = $post_prepender . ' ' . $new_post_content . ' ' . $post_appender;
                    $trunchi_content = aiomatic_truncate_content($the_final_cont, 16777215);
                    if (isset($aiomatic_Main_Settings['convert_gutenberg']) && trim($aiomatic_Main_Settings['convert_gutenberg']) == 'on')
                    {
                        $my_post['post_content'] = aiomatic_convert_html_to_gutenberg_blocks($trunchi_content);
                    }
                    else
                    {
                        $my_post['post_content'] = $trunchi_content;
                    }
                    if(stristr($my_post['post_content'], '<pre><code>&lt;') !== false)
                    {
                        if (!isset($aiomatic_Main_Settings['pre_code_off']) || trim($aiomatic_Main_Settings['pre_code_off']) != 'on')
                        {
                            $my_post['post_content'] = aiomatic_parse_pre_code_entities($my_post['post_content']);
                        }
                    }
                    $my_post['post_content'] = aimogen_bulk_finalize_prose($my_post['post_content']);
                    $my_post['post_title']           = aiomatic_truncate_title($new_post_title);
                    $my_post['aiomatic_source_title']   = $amazon_kw;
                    $my_post['aiomatic_timestamp']   = aiomatic_get_date_now();
                    $my_post['aiomatic_post_format'] = $post_format;
                    if (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678') 
                    {
                        if(is_array($default_category))
                        {
                            $cextra = '';
                            foreach($default_category as $dc)
                            {
                                $cextra .= ',' . get_cat_name($dc);
                            }
                            $extra_categories_temp = trim( $cextra . ',' . $extra_categories, ',');
                        }
                        else
                        {
                            $extra_categories_temp = trim(get_cat_name($default_category) . ',' .$extra_categories, ',');
                        }
                    }
                    else
                    {
                        $extra_categories_temp = $extra_categories;
                    }
                    $block_arr = array();
                    $custom_arr = array();
                    if($custom_fields != '')
                    {
                        if(stristr($custom_fields, '=>') != false)
                        {
                            $rule_arr = explode(',', trim($custom_fields));
                            foreach($rule_arr as $rule)
                            {
                                $my_args = explode('=>', trim($rule));
                                if(isset($my_args[1]))
                                {
                                    if ( isset( $shortcode_tags['aicontent'] ) ) {
                                        $aicontent_handler = $shortcode_tags['aicontent'];
                                        unset( $shortcode_tags['aicontent'] );
                                    } else {
                                        $aicontent_handler = null;
                                    }
                                    $my_args[1] = do_shortcode($my_args[1]);
                                    $my_args[0] = do_shortcode($my_args[0]);
                                    if ( $aicontent_handler ) {
                                        $shortcode_tags['aicontent'] = $aicontent_handler;
                                    }
                                    $custom_field_content = trim($my_args[1]);
                                    $custom_field_content = aiomatic_replaceAIPostShortcodes($custom_field_content, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    $custom_field_content = aiomatic_replace_review($custom_field_content, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                                    $custom_field_content = aiomatic_replaceSynergyShortcodes($custom_field_content);
                                    $custom_field_content = $spintax->Parse($custom_field_content, $block_arr);
                                    $custom_field_content = aiomatic_replaceContentShortcodes($custom_field_content, $img_attr, $ai_command);
                                    if(stristr($my_args[1], 'serialize_') !== false)
                                    {
                                        $custom_arr[trim($my_args[0])] = array(str_replace('serialize_', '', $custom_field_content));
                                    }
                                    else
                                    {
                                        if(stristr($my_args[0], '[') !== false && stristr($my_args[0], ']') !== false)
                                        {
                                            preg_match_all('#([^\[\]]*?)\[([^\[\]]*?)\]#', $my_args[0], $cfm);
                                            if(isset($cfm[2][0]))
                                            {
                                                if(isset($custom_arr[trim($cfm[1][0])]) && is_array($custom_arr[trim($cfm[1][0])]))
                                                {
                                                    $custom_arr[trim($cfm[1][0])] = array_merge($custom_arr[trim($cfm[1][0])], array(trim($cfm[2][0]) => $custom_field_content));
                                                }
                                                else
                                                {
                                                    $custom_arr[trim($cfm[1][0])] = array(trim($cfm[2][0]) => $custom_field_content);
                                                }
                                            }
                                            else
                                            {
                                                $custom_arr[trim($my_args[0])] = $custom_field_content;
                                            }
                                        }
                                        else
                                        {
                                            $custom_arr[trim($my_args[0])] = $custom_field_content;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $block_arr = array();
                    $custom_arr = array_merge($custom_arr, array('aiomatic_auto_post_spinned' => $already_spinned, 'aiomatic_post_cats' => $extra_categories_temp, 'aiomatic_post_tags' => $post_the_tags));
                    $custom_tax_arr = array();
                    if($custom_tax != '')
                    {
                        if(stristr($custom_tax, '=>') != false)
                        {
                            $rule_arr = explode(';', trim($custom_tax));
                            foreach($rule_arr as $rule)
                            {
                                $my_args = explode('=>', trim($rule));
                                if(isset($my_args[1]))
                                {
                                    $custom_tax_content = trim($my_args[1]);
                                    $custom_tax_content = aiomatic_replaceAIPostShortcodes($custom_tax_content, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    $custom_tax_content = aiomatic_replace_review($custom_tax_content, $post_title, $amazon_kw, $product_title, $product_description, $aff_url, $product_author, $product_brand, $product_isbn, $product_upc, $offer_price, $product_price, $product_list_price, $price_numeric, $price_currency, $product_asin, $cart_url, $list_price_numeric, $product_imgs, $product_titles, $content_language, $writing_style, $writing_tone, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $point_of_view, $product_reviews, $default_cat_list, $item_score, $edition, $language, $pages_count, $publication_date, $contributors, $manufacturer, $binding, $product_group, $rating, $eans, $part_no, $model, $warranty, $color, $is_adult, $dimensions, $date, $size, $unit_count);
                                    $custom_tax_content = aiomatic_replaceSynergyShortcodes($custom_tax_content);
                                    $custom_tax_content = $spintax->Parse($custom_tax_content, $block_arr);
                                    $custom_tax_content = aiomatic_replaceContentShortcodes($custom_tax_content, $img_attr, $ai_command);
                                    if(aiomatic_substr(trim($my_args[0]), 0, 3) === "pa_" && $post_type == 'product' && !empty($custom_tax_content))
                                    {
                                        if(isset($custom_arr['_product_attributes']))
                                        {
                                            $custom_arr['_product_attributes'] = array_merge($custom_arr['_product_attributes'], array(trim($my_args[0]) =>array(
                                                'name' => trim($my_args[0]),
                                                'value' => $custom_tax_content,
                                                'is_visible' => '1',
                                                'is_taxonomy' => '1'
                                            )));
                                        }
                                        else
                                        {
                                            $custom_arr['_product_attributes'] = array(trim($my_args[0]) =>array(
                                                'name' => trim($my_args[0]),
                                                'value' => $custom_tax_content,
                                                'is_visible' => '1',
                                                'is_taxonomy' => '1'
                                            ));
                                        }
                                    }
                                    if(isset($custom_tax_arr[trim($my_args[0])]))
                                    {
                                        $custom_tax_arr[trim($my_args[0])] .= ',' . $custom_tax_content;
                                    }
                                    else
                                    {
                                        $custom_tax_arr[trim($my_args[0])] = $custom_tax_content;
                                    }
                                }
                            }
                        }
                    }
                    if(count($custom_tax_arr) > 0)
                    {
                        $my_post['taxo_input'] = $custom_tax_arr;
                    }
                    if (isset($aiomatic_Main_Settings['external_products']) && $aiomatic_Main_Settings['external_products'] == 'on')
                    {
                        if($post_type == 'product')
                        {
                            $custom_arr['_price'] = $product_price;
                            $custom_arr['_regular_price'] = $product_price;
                            $custom_arr['_product_url'] = $aff_url;
                        }
                    }
                    $my_post['meta_input'] = $custom_arr;
                    if($parent_id != '')
                    {
                        $my_post['post_parent'] = intval($parent_id);
                    }
                    if ($enable_pingback == '1') {
                        $my_post['ping_status'] = 'open';
                    } else {
                        $my_post['ping_status'] = 'closed';
                    }
                    if($min_time != '' && $max_time != '')
                    {
                        $t1 = strtotime($min_time);
                        $t2 = strtotime($max_time);
                        if($t1 != false && $t2 != false)
                        {
                            $int = wp_rand($t1, $t2);
                            $my_post['post_date'] = date('Y-m-d H:i:s', $int);
                        }
                    }
                    elseif($min_time != '')
                    {
                        $t1 = strtotime($min_time);
                        if($t1 != false)
                        {
                            $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                        }
                    }
                    elseif($max_time != '')
                    {
                        $t1 = strtotime($max_time);
                        if($t1 != false)
                        {
                            $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                        }
                    }
                    if($new_post_excerpt != '')
                    {
                        $my_post['post_excerpt']          = $new_post_excerpt;
                    }
                    $count++;
                    if($update_post_id != '')
                    {
                        $my_post['ID'] = $update_post_id;
                    }
                    remove_filter('content_save_pre', 'wp_filter_post_kses');
                    remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                    try
                    {
                        $post_id = wp_insert_post($my_post, true);
                        $my_post['post_content'] = str_replace('\r\n', '', $my_post['post_content']);
                        if (is_wp_error($post_id)) 
                        {
                            aiomatic_log_to_file('Trying publishing again');
                            if (aiomatic_strlen($my_post['post_content']) > 16777215) {
                                $my_post['post_content'] = aiomatic_substr($my_post['post_content'], 0, 16777215);
                            }
                            $my_post['post_content'] = wp_kses_post($my_post['post_content']);
                            $my_post['post_content'] = str_replace('\r\n', '', $my_post['post_content']);
                            $post_id = wp_insert_post($my_post, true);
                        }
                    }
                    catch(Exception $e)
                    {
                        aiomatic_log_to_file('Exception in publishing post (this is coming from another plugin, so we ignore it): ' . $e->getMessage());
                    }
                    add_filter('content_save_pre', 'wp_filter_post_kses');
                    add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                    if (!is_wp_error($post_id)) {
                        if($post_id === 0)
                        {
                            aiomatic_log_to_file('An error occurred while inserting post into wp database! Title:' . $my_post['post_title']);
                            continue;
                        }
                        $words = str_word_count(wp_strip_all_tags($my_post['post_content']));
                        aiomatic_increment_publishing_stats($words);
                        aimogen_bulk_on_post_created($post_id, $my_post['post_title'], isset($new_post_excerpt) ? $new_post_excerpt : '', isset($post_topic) ? $post_topic : (isset($post_title) ? $post_title : ''));
                        aiomatic_set_last_activity(
                            'article',
                            ['post_id' => $post_id]
                        );
                        $posts_inserted++;
                        if($wpml_lang != '' && function_exists('pll_set_post_language'))
                        {
                            pll_set_post_language($post_id, $wpml_lang);
                        }
                        if(!empty($additional_attachments))
                        {
                            foreach($additional_attachments as $add_att)
                            {
                                wp_update_post([
                                    'ID' => $add_att,
                                    'post_parent' => $post_id,
                                ]);
                            }
                        }
                        $default_categories = array();
                        if($remove_default == '1' && ($auto_categories != 'disabled' || (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678')))
                        {
                            $default_categories = wp_get_post_categories($post_id);
                        }
                        if(isset($my_post['taxo_input']))
                        {
                            foreach($my_post['taxo_input'] as $taxn => $taxval)
                            {
                                $taxn = trim($taxn);
                                $taxval = trim($taxval);
                                if(is_taxonomy_hierarchical($taxn))
                                {
                                    $taxval = array_map('trim', explode(',', $taxval));
                                    for($ii = 0; $ii < count($taxval); $ii++)
                                    {
                                        if(!is_numeric($taxval[$ii]))
                                        {
                                            $term_ids = [];
                                            $parent_id = 0;
                                            $hierarchy_parts = array_map('trim', explode('>', $taxval[$ii]));
                                            foreach($hierarchy_parts as $hp)
                                            {
                                                if(!is_numeric($hp))
                                                {
                                                    $xtermid = get_term_by('name', $hp, $taxn);
                                                    if($xtermid !== false)
                                                    {
                                                        $parent_id = $xtermid->term_id;
                                                        if(!is_numeric($taxval[$ii]))
                                                        {
                                                            $taxval[$ii] = intval($xtermid->term_id);
                                                        }
                                                        else
                                                        {
                                                            $taxval[] = intval($xtermid->term_id);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        wp_insert_term( $hp, $taxn, ['parent' => $parent_id]);
                                                        $xtermid = get_term_by('name', $hp, $taxn);
                                                        if($xtermid !== false)
                                                        {
                                                            $parent_id = $xtermid->term_id;
                                                            if($wpml_lang != '' && function_exists('pll_set_term_language'))
                                                            {
                                                                pll_set_term_language($xtermid->term_id, $wpml_lang); 
                                                            }
                                                            elseif($wpml_lang != '' && has_filter('wpml_object_id'))
                                                            {
                                                                $wpml_element_type = apply_filters( 'wpml_element_type', $taxn );
                                                                $pars['element_id'] = $xtermid->term_id;
                                                                $pars['element_type'] = $wpml_element_type;
                                                                $pars['language_code'] = $wpml_lang;
                                                                $pars['trid'] = FALSE;
                                                                $pars['source_language_code'] = NULL;
                                                                do_action('wpml_set_element_language_details', $pars);
                                                            }
                                                            if(!is_numeric($taxval[$ii]))
                                                            {
                                                                $taxval[$ii] = intval($xtermid->term_id);
                                                            }
                                                            else
                                                            {
                                                                $taxval[] = intval($xtermid->term_id);
                                                            }
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    if(!is_numeric($taxval[$ii]))
                                                    {
                                                        $taxval[$ii] = intval($hp);
                                                    }
                                                    else
                                                    {
                                                        $taxval[] = intval($hp);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    wp_set_post_terms($post_id, $taxval, $taxn, true);
                                }
                                else
                                {
                                    $jterms = array_map('trim', explode(',', $taxval));
                                    wp_set_post_terms($post_id, $jterms, $taxn, true);
                                }
                            }
                        }
                        if (isset($aiomatic_Main_Settings['external_products']) && $aiomatic_Main_Settings['external_products'] == 'on')
                        {
                            if($post_type == 'product')
                            {
                                wp_set_post_terms($post_id, 'external', 'product_type', false);
                            }
                        }
                        if (isset($my_post['aiomatic_post_format']) && $my_post['aiomatic_post_format'] != '' && $my_post['aiomatic_post_format'] != 'post-format-standard') {
                            wp_set_post_terms($post_id, $my_post['aiomatic_post_format'], 'post_format', true);
                        }
                        $featured_path = '';
                        $get_img = $my_post['aiomatic_post_image'];
                        if ($get_img != '') {
                            if($my_post['aiomatic_local_image'] == '1')
                            {
                                $local_get_img = $get_img[0];
                                if (!aiomatic_assign_featured_image_path($local_get_img, $post_id)) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('aiomatic_assign_featured_image_path failed for ' . $local_get_img);
                                    }
                                } else {
                                    $featured_path = $get_img[1];
                                }
                            }
                            else
                            {
                                if(is_numeric($get_img))
                                {
                                    $featured_path = aiomatic_assign_featured_image($get_img, $post_id);
                                }
                                else
                                {
                                    if (!aiomatic_generate_featured_image($get_img, $post_id)) {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('aiomatic_generate_featured_image failed for ' . $get_img);
                                        }
                                    } else {
                                        $featured_path = $get_img;
                                    }
                                }
                            }
                        }
                        if($featured_path == '')
                        {
                            if ($image_url != '') {
                                $replacement = str_replace(array('[', ']'), '', $my_post['post_title']);
                                $image_url_temp = str_replace('%%item_title%%', $replacement, $image_url);
                                $image_url_temp = preg_replace_callback('#%%random_image\[([^\]]*?)\](\[\d+\])?%%#', function ($matches) {
                                    if(isset($matches[2]))
                                    {
                                        $chance = trim($matches[2], '[]');
                                    }
                                    else
                                    {
                                        $chance = '';
                                    }
                                    $arv = array();
                                    $my_img = aiomatic_get_random_image_google($matches[1], 0, 0, $chance, $arv);
                                    return $my_img;
                                }, $image_url_temp);
                                $img_rulx = $spintax->Parse(trim($image_url_temp));
                                $selected_img = aiomatic_select_ai_image($my_post['post_title'], $img_rulx);
                                if($selected_img === false)
                                {
                                    $img_rulx = explode(',', $img_rulx);
                                    $img_rulx = trim($img_rulx[array_rand($img_rulx)]);
                                }
                                else
                                {
                                    $img_rulx = $selected_img;
                                }
                                if(is_numeric($img_rulx))
                                {
                                    $featured_path = aiomatic_assign_featured_image($img_rulx, $post_id);
                                }
                                else
                                {
                                    if($img_rulx != '')
                                    {
                                        if (!aiomatic_generate_featured_image($img_rulx, $post_id)) {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                aiomatic_log_to_file('aiomatic_generate_featured_image failed to default value: ' . $img_rulx . '!');
                                            }
                                        } else {
                                            $featured_path = $img_rulx;
                                        }
                                    }
                                }
                            }
                        }
                        if ($auto_categories != 'disabled') {
                            if ($my_post['extra_categories'] != '') {
                                $extra_cats = explode(',', $my_post['extra_categories']);
                                if($post_type == 'product')
                                {
                                    $product_tax = 'product_cat';
                                }
                                else
                                {
                                    $product_tax = 'category';
                                }
                                foreach($extra_cats as $extra_cat)
                                {
                                    $extra_cat = trim($extra_cat);
                                    $extra_cat = strip_tags($extra_cat);
                                    $extra_cat = preg_replace('#^\d+\.\s*#', '', $extra_cat);
                                    if(empty($extra_cat))
                                    {
                                        continue;
                                    }
                                    if ($skip_inexist == '1') 
                                    {
                                        if(!term_exists($extra_cat, $product_tax))
                                        {
                                            continue;
                                        }
                                    }
                                    $termid = aiomatic_create_terms($product_tax, null, trim($extra_cat));
                                    wp_set_post_terms($post_id, $termid, $product_tax, true);
                                    if($wpml_lang != '' && function_exists('pll_set_term_language'))
                                    {
                                        foreach($termid as $tx)
                                        {
                                            pll_set_term_language($tx, $wpml_lang); 
                                        }
                                    }
                                    elseif($wpml_lang != '' && has_filter('wpml_object_id'))
                                    {
                                        $wpml_element_type = apply_filters( 'wpml_element_type', 'product_cat' );
                                        foreach($termid as $tx)
                                        {
                                            $pars['element_id'] = $tx;
                                            $pars['element_type'] = $wpml_element_type;
                                            $pars['language_code'] = $wpml_lang;
                                            $pars['trid'] = FALSE;
                                            $pars['source_language_code'] = NULL;
                                            do_action('wpml_set_element_language_details', $pars);
                                        }
                                    }
                                }
                            }
                        }
                        if (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678') {
                            $cats   = array();
                            if(is_array($default_category))
                            {
                                foreach($default_category as $dc)
                                {
                                    $cats[] = $dc;
                                }
                            }
                            else
                            {
                                $cats[] = $default_category;
                            }
                            global $sitepress;
                            if($wpml_lang != '' && has_filter('wpml_current_language') && $sitepress != null)
                            {
                                $current_language = apply_filters( 'wpml_current_language', NULL );
                                $sitepress->switch_lang($wpml_lang);
                            }
                            $target_cat = 'category';
                            if($post_type == 'product')
                            {
                                $target_cat = 'product_cat';
                            }
                            wp_set_object_terms($post_id, array_map( 'intval', $cats ), $target_cat, true);
                            if($wpml_lang != '' && function_exists('pll_set_term_language'))
                            {
                                foreach($cats as $cc)
                                {
                                    pll_set_term_language($cc, $wpml_lang);
                                }
                            }
                            elseif($wpml_lang != '' && has_filter('wpml_current_language') && $sitepress != null)
                            {
                                $sitepress->switch_lang($current_language);
                            }
                        }
                        if (isset($my_post['tags_input']) && $my_post['tags_input'] != '')
                        {
                            if($post_type == 'product')
                            {
                                wp_set_post_terms($post_id, $my_post['tags_input'], 'product_tag', true);
                            }
                        }
                        $tax_rez = wp_set_object_terms( $post_id, 'aiomatic_' . $type . '_' . $param, 'coderevolution_post_source', true);
                        if (is_wp_error($tax_rez)) {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('wp_set_object_terms failed for: ' . $post_id . '!');
                            }
                        }
                        if($post_type == 'topic' && $parent_id != '')
                        {
                            update_post_meta($post_id, '_bbp_forum_id', $parent_id);
                            update_post_meta($post_id, '_bbp_topic_id', $post_id);
                            update_post_meta($post_id, '_bbp_voice_count', '0');
                            update_post_meta($post_id, '_bbp_reply_count', '0');
                            update_post_meta($post_id, '_bbp_reply_count_hidden', '0');
                            update_post_meta($post_id, '_bbp_last_reply_id', '0');
                            update_post_meta($post_id, '_bbp_last_active_id', $post_id);
                            update_post_meta($post_id, '_bbp_last_active_time', get_post_field( 'post_date', $topic_id, 'db' ));
                            do_action( 'bbp_insert_topic', (int) $post_id, (int) $parent_id );
                        }
                        if($post_type == 'reply' && $parent_id != '')
                        {
                            if(function_exists('bbp_get_topic_forum_id'))
                            {
                                $forum_aidi = bbp_get_topic_forum_id($parent_id);
                                if(empty($forum_aidi))
                                {
                                    $forum_aidi = 0;
                                }
                            }
                            else
                            {
                                $forum_aidi = 0;
                            }
                            do_action( 'bbp_insert_reply', (int) $post_id, (int) $parent_id, (int) $forum_aidi );
                        }
                        if($remove_default == '1' && ($auto_categories != 'disabled' || (isset($default_category) && $default_category !== 'aiomatic_no_category_12345678' && $default_category[0] !== 'aiomatic_no_category_12345678')))
                        {
                            $new_categories = wp_get_post_categories($post_id);
                            $removed_cat = false;
                            if(isset($default_categories) && !($default_categories == $new_categories))
                            {
                                foreach($default_categories as $dc)
                                {
                                    $rem_cat = get_category( $dc );
                                    wp_remove_object_terms( $post_id, $rem_cat->slug, 'category' );
                                    $removed_cat = true;
                                }
                            }
                            if($removed_cat == false)
                            {
                                wp_remove_object_terms( $post_id, 'uncategorized', 'category' );
                            }
                        }
                        aiomatic_addPostMeta($post_id, $my_post, $param, $type, $featured_path, $post_topic, $rule_unique_id, $post_link);
                        if($wpml_lang != '' && (class_exists('SitePress') || function_exists('wpml_object_id')))
                        {
                            $wpml_element_type = apply_filters( 'wpml_element_type', $post_type );
                            $pars['element_id'] = $post_id;
                            $pars['element_type'] = $wpml_element_type;
                            $pars['language_code'] = $wpml_lang;
                            $pars['source_language_code'] = NULL;
                            do_action('wpml_set_element_language_details', $pars);

                            global $wp_filesystem;
                            if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
                                include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() );
                                wp_filesystem($creds);
                            }
                            if($wp_filesystem->exists(WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php'))
                            {
                                include_once( WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php' );
                            }
                            $wpml_lang = trim($wpml_lang);
                            if(function_exists('wpml_update_translatable_content'))
                            {
                                wpml_update_translatable_content('post_' . $post_type, $post_id, $wpml_lang);
                                if($my_post['post_title'] != '')
                                {
                                    global $sitepress;
                                    global $wpdb;
                                    $keyid = md5($my_post['post_title']);
                                    $keyName = $keyid . '_wpml';
                                    $rezxxxa = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}postmeta WHERE `meta_key` = '$keyName' limit 1", ARRAY_A );
                                    if(count($rezxxxa) != 0)
                                    {
                                        $metaRow = $rezxxxa[0];
                                        $metaValue = $metaRow['meta_value'];
                                        $metaParts = explode('_', $metaValue);
                                        $sitepress->set_element_language_details($post_id, 'post_'.$my_post['post_type'] , $metaParts[0], $wpml_lang, $metaParts[1] ); 
                                    }
                                    else
                                    {
                                        $ptrid = $sitepress->get_element_trid($post_id);
                                        update_post_meta($post_id, $keyid.'_wpml', $ptrid.'_'.$wpml_lang );
                                    }
                                }
                                
                            }
                        }
                        if (isset($aiomatic_Main_Settings['draft_first']) && $aiomatic_Main_Settings['draft_first'] == 'on' && $draft_me == true)
                        {
                            aiomatic_change_post_status($post_id, 'publish');
                        }
                    } else {
                        aiomatic_log_to_file('Failed to insert post into wp database(4)! Title:' . $my_post['post_title'] . '! Error: ' . $post_id->get_error_message() . ' Error code: ' . $post_id->get_error_code() . ' Error data: ' . $post_id->get_error_data());
                        continue;
                    }
                }
            }
            elseif($type == '4')
            {
                if($post_title != '')
                {
                    $post_title_lines = preg_split('/\r\n|\r|\n/', $post_title);
                }
                else
                {
                    $post_title_lines = array();
                }
                $raw_img_list = array();
                $full_result_list = array();
                $user_name        = '';
                $featured_image   = '';
                $post_cats = '';
                $post_tagz = '';
                $post_excerpt = '';
                $final_content = '';
                $postID = '';
                $heading_val = '';
                $image_query = '';
                $temp_post = '';
                $cntx = count($post_title_lines);
                shuffle($post_title_lines);
                $rss_feeds = array();
                $csv_data = array();
                $my_csv = '';
                for($ji = 0; $ji < $cntx; $ji++)
                {
                    $txt_content = aiomatic_get_web_page($post_title_lines[$ji]);
                    if ($txt_content === FALSE) 
                    {
                        aiomatic_log_to_file('Failed to read csv file: ' . $post_title_lines[$ji]);
                        if($auto == 1)
                        {
                            aiomatic_log_to_file($param);
                        }
                        continue;
                    }
                    $my_csv = $post_title_lines[$ji];
                    try
                    {
                        if(!class_exists('\ParseCsv\Csv'))
                        {
                            require_once(dirname(__FILE__) . "/res/parsecsv/src/enums/AbstractEnum.php");
                            require_once(dirname(__FILE__) . "/res/parsecsv/src/enums/DatatypeEnum.php");
                            require_once(dirname(__FILE__) . "/res/parsecsv/src/enums/FileProcessingModeEnum.php");
                            require_once(dirname(__FILE__) . "/res/parsecsv/src/enums/SortEnum.php");
                            require_once(dirname(__FILE__) . "/res/parsecsv/src/extensions/DatatypeTrait.php");
                            require_once(dirname(__FILE__) . "/res/parsecsv/src/Csv.php");
                        }
                        $csv = new \ParseCsv\Csv();
                        if($csv_separator == '')
                        {
                            $csv->autoDirectData($txt_content);
                        }
                        else
                        {
                            $csv->delimiter = $csv_separator;
                            $csv->parseData($txt_content);
                        }
                        $csv_data = $csv->data;
                    }
                    catch(Exception $e)
                    {
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                            aiomatic_log_to_file('Failed to load csv file: Exception thrown ' . esc_html($e->getMessage()) . '!');
                        }
                        continue;
                    }
                    break;
                }
                if(!is_array($csv_data) || count($csv_data) == 0)
                {
                    if(is_array($csv_data))
                    {
                        $csv_data = print_r($csv_data, true);
                    }
                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                        aiomatic_log_to_file('Failed to parse csv file data ' . esc_html($csv_data));
                    }
                    return 'fail';
                }
                
                $spintax = new Aiomatic_Spintax();
                $already_spinned = 0;
                if(isset($aiomatic_Main_Settings['attr_text']) && $aiomatic_Main_Settings['attr_text'] != '')
                {
                    $img_attr = $aiomatic_Main_Settings['attr_text'];
                }
                else
                {
                    $img_attr = '';
                }
                if($title_once == '1')
                {
                    $skipt = 0;
                    foreach($csv_data as $indx => $csv)
                    {
                        $csv = array_combine(
                            array_map(function($key){ return trim($key, " \t\n\r\0\x0B\xEF\xBB\xBF"); }, array_keys($csv)), 
                            array_values($csv)
                        );
                        if(!isset($csv['post_title']))
                        {
                            aiomatic_log_to_file('Incorrect CSV file structure, post_title heading not found, please check! ' . print_r($my_csv, true));
                            return 'false';
                        }
                        $csv_original_title = $csv['post_title'];
                        if(array_key_exists($csv_original_title, $posted_items))
                        {
                            aiomatic_log_to_file('Skipping CSV title, already processed: ' . $csv_original_title);
                            unset($csv_data[$indx]);
                            $skipt++;
                        }
                    }
                    if(count($csv_data) == 0 && $skipt > 0)
                    {
                        if (isset($aiomatic_Main_Settings['email_notification']) && $aiomatic_Main_Settings['email_notification'] != '')
                        {
                            if($count === 1)
                            {
                                $email_list = explode(',', $aiomatic_Main_Settings['email_notification']);
                                foreach($email_list as $thisaddr)
                                {
                                    $thisaddr = trim($thisaddr);
                                    try
                                    {
                                        $admin_mail = get_option('admin_email');
                                        $to        = $thisaddr;
                                        $subject   = '[Aimogen] CSV Titles depleted rule ID ' . $param . ' - ' . aiomatic_get_date_now();
                                        $message   = 'CSV Rule ID ' . esc_html($param) . ' (' . $rule_description . ') depleted its titles, no new posts publised! Website URL: ' . get_site_url();
                                        $headers[] = 'From: Aimogen Plugin <' . $admin_mail . '>';
                                        $headers[] = 'Reply-To: ' . $admin_mail;
                                        $headers[] = 'X-Mailer: PHP/' . phpversion();
                                        $headers[] = 'Content-Type: text/html';
                                        $headers[] = 'Charset: ' . get_option('blog_charset', 'UTF-8');
                                        wp_mail($to, $subject, $message, $headers);
                                    }
                                    catch (Exception $e) {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Failed to send mail: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                        }
                                    }
                                }
                            }
                        }
                        aiomatic_log_to_file('All CSV titles already processed, nothing to do.');
                        if($auto == 1)
                        {
                            aiomatic_clearFromList($param, $type);
                        }
                        return 'nochange';
                    }
                }
                if($random_order == '1')
                {
                    shuffle($csv_data);
                }
                $data_id = 1;
                foreach($csv_data as $csv)
                {
                    $csv = array_combine(
                        array_map(function($key){ return trim($key, " \t\n\r\0\x0B\xEF\xBB\xBF"); }, array_keys($csv)), 
                        array_values($csv)
                    );
                    $thread_id = '';
                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing CSV data #' . $data_id));
                    $data_id++;
                    $update_post_id  = '';
                    if ($count > intval($max)) 
                    {
                        break;
                    }
                    if(!isset($csv['post_title']))
                    {
                        aiomatic_log_to_file('Incorrect CSV file structure, post_title heading not found! ' . print_r($my_csv, true));
                        return 'false';
                    }
                    if(!isset($csv['post_content']))
                    {
                        aiomatic_log_to_file('Incorrect CSV file structure, post_content heading not found! ' . print_r($my_csv, true));
                        return 'false';
                    }
                    if(!isset($csv['post_excerpt']))
                    {
                        aiomatic_log_to_file('Incorrect CSV file structure, post_excerpt heading not found! ' . print_r($my_csv, true));
                        return 'false';
                    }
                    if(empty($csv['post_title']) && empty($csv['post_content']) && empty($csv['post_excerpt']))
                    {
                        aiomatic_log_to_file('Blank post title/content/excerpt entered, skipping: ' . print_r($my_csv, true));
                        continue;
                    }
                    if(!isset($csv['post_categories']))
                    {
                        aiomatic_log_to_file('Incorrect CSV file structure, post_categories heading not found! ' . print_r($my_csv, true));
                        return 'false';
                    }
                    if(!isset($csv['post_tags']))
                    {
                        aiomatic_log_to_file('Incorrect CSV file structure, post_tags heading not found! ' . print_r($my_csv, true));
                        return 'false';
                    }
                    if(!isset($csv['featured_image']))
                    {
                        aiomatic_log_to_file('Incorrect CSV file structure, featured_image heading not found! ' . print_r($my_csv, true));
                        return 'false';
                    }
                    if(!isset($csv['featured_image_generator']))
                    {
                        aiomatic_log_to_file('Incorrect CSV file structure, featured_image_generator heading not found! ' . print_r($my_csv, true));
                        return 'false';
                    }
                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                    {
                        aiomatic_log_to_file('Starting processing CSV title: ' . $csv['post_title']);
                    }
                    $csv_original_title = $csv['post_title'];
                    foreach($csv as $ind => $valx)
                    {
                        foreach($csv as $repl_ind => $repl_valx)
                        {
                            if($ind != $repl_ind)
                            {
                                if(strstr($csv[$ind], '%%' . $repl_ind . '%%') !== false)
                                {
                                    if(strstr($repl_valx, '[aicontent') !== false)
                                    {
                                        $repl_valx = apply_filters('aiomatic_replace_aicontent_shortcode', $repl_valx);
                                        $csv[$repl_ind] = $repl_valx;
                                    }
                                    $csv[$ind] = str_replace('%%' . $repl_ind . '%%', $repl_valx, $csv[$ind]);
                                }
                            }
                        }
                        $csv[$ind] = aiomatic_replaceSynergyShortcodes($csv[$ind]);
                    }
                    if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                    {
                        if(!stristr($csv['post_title'], '[aicontent'))
                        {
                            $xposts = get_posts(
                                array(
                                    'post_type'              => $post_type,
                                    'title'                  => html_entity_decode($csv['post_title']),
                                    'post_status'            => 'any',
                                    'numberposts'            => 1,
                                    'update_post_term_cache' => false,
                                    'update_post_meta_cache' => false,           
                                    'orderby'                => 'post_date ID',
                                    'order'                  => 'ASC',
                                )
                            );
                            if ( ! empty( $xposts ) ) {
                                $zap = $xposts[0];
                            } else {
                                $zap = null;
                            }
                            if($zap !== null)
                            {
                                if($overwrite_existing)
                                {
                                    $update_post_id = $zap->ID;
                                }
                                else
                                {
                                    aiomatic_log_to_file('Post with specified title is already existing, we are skipping it: ' . $csv['post_title']);
                                    continue;
                                }
                            }
                        }
                    }
                    foreach($csv as $ind => $initial_value)
                    {
                        $is_ai_content = false;
                        if(strstr($initial_value, '[aicontent') !== false)
                        {
                            $is_ai_content = true;
                        }
                        $csv[$ind] = apply_filters('aiomatic_replace_aicontent_shortcode', $csv[$ind]);
                        if($is_ai_content)
                        {
                            foreach($csv as $ind2 => $initial_value_again)
                            {
                                if($ind2 !== $ind && strstr($initial_value_again, $initial_value) !== false)
                                {
                                    $csv[$ind2] = str_replace($initial_value, $csv[$ind], $csv[$ind2]);
                                }
                            }
                        }
                    }
                    if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                    {
                        $xposts = get_posts(
                            array(
                                'post_type'              => $post_type,
                                'title'                  => html_entity_decode($csv['post_title']),
                                'post_status'            => 'any',
                                'numberposts'            => 1,
                                'update_post_term_cache' => false,
                                'update_post_meta_cache' => false,           
                                'orderby'                => 'post_date ID',
                                'order'                  => 'ASC',
                            )
                        );
                        if ( ! empty( $xposts ) ) {
                            $zap = $xposts[0];
                        } else {
                            $zap = null;
                        }
                        if($zap !== null)
                        {
                            if($overwrite_existing)
                            {
                                $update_post_id = $zap->ID;
                            }
                            else
                            {
                                aiomatic_log_to_file('Post with specified title is already existing, skipping it: ' . $csv['post_title']);
                                continue;
                            }
                        }
                    }
                    if($update_post_id != '')
                    {
                        $csv['ID'] = $update_post_id;
                        $postID = $update_post_id;
                    }
                    $get_img = '';
                    if($csv['featured_image_generator'] !== 'none')
                    {
                        if(stristr($csv['featured_image_generator'], 'manual') !== false || empty($csv['featured_image_generator']))
                        {
                            if(trim($csv['featured_image']) != '')
                            {
                                $get_img = trim($csv['featured_image']);
                            }
                        }
                        elseif(stristr($csv['featured_image_generator'], 'openai') !== false || stristr($csv['featured_image_generator'], 'aiomaticapi') !== false)
                        {
                            $query_words = trim($csv['featured_image']);
                            if($query_words != '')
                            {
                                $image_model = 'gpt-image-2';
                                if(isset($csv['image_model']) && trim($csv['image_model']) !== '')
                                {
                                    $image_model_temp = trim($csv['image_model']);
                                    if(!in_array($image_model_temp, AIMOGEN_DALLE_IMAGE_MODELS))
                                    {
                                        aiomatic_log_to_file('Incorrect Dall-E image model provided ' . $image_model_temp);
                                    }
                                    else
                                    {
                                        $image_model = $image_model_temp;
                                    }
                                }
                                $ai_command_image = $query_words;
                                
                                
                                
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = aiomatic_get_api_service($token, $image_model);
                                    aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                }
                                $skip_this_copy = true;
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                {
                                    $skip_this_copy = false;
                                }
                                if (isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] == 'on')
                                {
                                    $skip_this_copy = false;
                                }
                                $aierror = '';
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing AI image'));
                                $get_img = aiomatic_generate_ai_image($token, 1, $ai_command_image, $image_size, 'featuredImage', $skip_this_copy, 0, $aierror, $image_model, $csv_original_title);
                                if($get_img !== false)
                                {
                                    foreach($get_img as $tmpimg)
                                    {
                                        $get_img = $tmpimg;
                                        break;
                                    }
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to generate AI featured image: ' . $aierror);
                                    $get_img = '';
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI featured image query entered, nothing to do.');
                            }
                        }
                        elseif(stristr($csv['featured_image_generator'], 'stability') !== false)
                        {
                            $query_words = trim($csv['featured_image']);
                            if($query_words != '')
                            {
                                $ai_command_image = $query_words;
                                
                                
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = 'Stability.AI';
                                    aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                }
                                if($image_size == '256x256')
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                elseif($image_size == '512x512')
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                elseif($image_size == '1024x1024')
                                {
                                    $width = '1024';
                                    $height = '1024';
                                }
                                else
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                $skip_this_copy = true;
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                {
                                    $skip_this_copy = false;
                                }
                                $ierror = '';
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing Stable Diffusion AI image'));
                                $get_img = aiomatic_generate_stability_image($ai_command_image, $height, $width, 'featuredStableImage', 0, false, $ierror, $skip_this_copy, false, '', 0);
                                if($get_img !== false)
                                {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        aiomatic_log_to_file('AI generated featured image returned: ' . $get_img[1]);
                                    }
                                    if(is_array($get_img) && isset($get_img[1]))
                                    {
                                        $get_img = $get_img[1];
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to generate Stability.AI featured image: ' . $ierror);
                                    $get_img = '';
                                }
                            }
                        }
                        elseif(stristr($csv['featured_image_generator'], 'midjourney') !== false)
                        {
                            $query_words = trim($csv['featured_image']);
                            if($query_words != '')
                            {
                                $ai_command_image = $query_words;
                                
                                
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = 'Midjourney';
                                    aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                }
                                if($image_size == '256x256')
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                elseif($image_size == '512x512')
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                elseif($image_size == '1024x1024')
                                {
                                    $width = '1024';
                                    $height = '1024';
                                }
                                elseif($image_size == '1792x1024')
                                {
                                    $width = '1792';
                                    $height = '1024';
                                }
                                elseif($image_size == '1024x1792')
                                {
                                    $width = '1024';
                                    $height = '1792';
                                }
                                else
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                $skip_this_copy = true;
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                {
                                    $skip_this_copy = false;
                                }
                                $ierror = '';
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing Midjourney AI image'));
                                $get_img = aiomatic_generate_ai_image_midjourney($ai_command_image, $width, $height, 'featuredMidjourneyImage', $skip_this_copy, $ierror);
                                if($get_img !== false)
                                {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to generate Midjourney featured image: ' . $ierror);
                                    $get_img = '';
                                }
                            }
                        }
                        elseif(stristr($csv['featured_image_generator'], 'google') !== false)
                        {
                            $query_words = trim($csv['featured_image']);
                            if($query_words != '')
                            {
                                $ai_command_image = $query_words;
                                
                                
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = 'Google';
                                    aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                }
                                $skip_this_copy = true;
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                {
                                    $skip_this_copy = false;
                                }
                                $ierror = '';
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing Midjourney AI image'));
                                $get_img = aiomatic_generate_image_google($input_tai_command_imageext, $model, 'featuredGoogleImage', false, $ierror, $skip_this_copy);
                                if($get_img !== false)
                                {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        aiomatic_log_to_file('AI generated featured image returned: ' . $get_img[1]);
                                    }
                                    if(is_array($get_img) && isset($get_img[1]))
                                    {
                                        $get_img = $get_img[1];
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to generate Midjourney featured image: ' . $ierror);
                                    $get_img = '';
                                }
                            }
                        }
                        elseif(stristr($csv['featured_image_generator'], 'replicate') !== false)
                        {
                            $query_words = trim($csv['featured_image']);
                            if($query_words != '')
                            {
                                $ai_command_image = $query_words;
                                
                                
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = 'Replicate';
                                    aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                }
                                if($image_size == '256x256')
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                elseif($image_size == '512x512')
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                elseif($image_size == '1024x1024')
                                {
                                    $width = '1024';
                                    $height = '1024';
                                }
                                elseif($image_size == '1792x1024')
                                {
                                    $width = '1792';
                                    $height = '1024';
                                }
                                elseif($image_size == '1024x1792')
                                {
                                    $width = '1024';
                                    $height = '1792';
                                }
                                else
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                $skip_this_copy = true;
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                {
                                    $skip_this_copy = false;
                                }
                                $ierror = '';
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing Replicate AI image'));
                                $get_img = aiomatic_generate_replicate_image($ai_command_image, $width, $height, 'featuredReplicateImage', $skip_this_copy, $ierror);
                                if($get_img !== false)
                                {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to generate Replicate featured image: ' . $ierror);
                                    $get_img = '';
                                }
                            }
                        }
                        elseif(stristr($csv['featured_image_generator'], 'ideogram') !== false)
                        {
                            $query_words = trim($csv['featured_image']);
                            if($query_words != '')
                            {
                                $ai_command_image = $query_words;
                                
                                
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = 'Ideogram';
                                    aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                }
                                if($image_size == '256x256')
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                elseif($image_size == '512x512')
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                elseif($image_size == '1024x1024')
                                {
                                    $width = '1024';
                                    $height = '1024';
                                }
                                elseif($image_size == '1792x1024')
                                {
                                    $width = '1792';
                                    $height = '1024';
                                }
                                elseif($image_size == '1024x1792')
                                {
                                    $width = '1024';
                                    $height = '1792';
                                }
                                else
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                $skip_this_copy = true;
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                {
                                    $skip_this_copy = false;
                                }
                                $ierror = '';
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing Ideogram AI image'));
                                $get_img = aiomatic_generate_ideogram_image($ai_command_image, $width, $height, 'featuredIdeogramImage', $skip_this_copy, $ierror);
                                if($get_img !== false)
                                {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to generate Ideogram featured image: ' . $ierror);
                                    $get_img = '';
                                }
                            }
                        }
                        elseif(stristr($csv['featured_image_generator'], 'cloudflare') !== false)
                        {
                            $query_words = trim($csv['featured_image']);
                            if($query_words != '')
                            {
                                $ai_command_image = $query_words;
                                
                                
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = 'Cloudflare';
                                    aiomatic_log_to_file('Calling ' . $api_service . ' for featured image: ' . $ai_command_image);
                                }
                                if($image_size == '256x256')
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                elseif($image_size == '512x512')
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                elseif($image_size == '1024x1024')
                                {
                                    $width = '1024';
                                    $height = '1024';
                                }
                                elseif($image_size == '1792x1024')
                                {
                                    $width = '1792';
                                    $height = '1024';
                                }
                                elseif($image_size == '1024x1792')
                                {
                                    $width = '1024';
                                    $height = '1792';
                                }
                                else
                                {
                                    $width = '512';
                                    $height = '512';
                                }
                                $skip_this_copy = true;
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on') 
                                {
                                    $skip_this_copy = false;
                                }
                                $ierror = '';
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing Cloudflare AI image'));
                                $get_img = aiomatic_generate_cloudflare_image($ai_command_image, $width, $height, 'featuredCloudflareImage', $skip_this_copy, $ierror);
                                if($get_img !== false)
                                {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        aiomatic_log_to_file('AI generated featured image returned: ' . $get_img);
                                    }
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to generate Cloudflare featured image: ' . $ierror);
                                    $get_img = '';
                                }
                            }
                        }
                        else
                        {
                            $image_query = trim($csv['featured_image']);
                            if(empty($image_query))
                            {
                                $image_query = trim($csv['post_title']);
                            }
                            if(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'textrazor')
                            {
                                if(isset($aiomatic_Main_Settings['textrazor_key']) && trim($aiomatic_Main_Settings['textrazor_key']) != '')
                                {
                                    try
                                    {
                                        if(!class_exists('TextRazor'))
                                        {
                                            require_once(dirname(__FILE__) . "/res/TextRazor.php");
                                        }
                                        TextRazorSettings::setApiKey(trim($aiomatic_Main_Settings['textrazor_key']));
                                        $textrazor = new TextRazor();
                                        $textrazor->addExtractor('entities');
                                        $response = $textrazor->analyze($image_query);
                                        if (isset($response['response']['entities'])) 
                                        {
                                            foreach ($response['response']['entities'] as $entity) 
                                            {
                                                $query_words = '';
                                                if(isset($entity['entityEnglishId']))
                                                {
                                                    $query_words = $entity['entityEnglishId'];
                                                }
                                                else
                                                {
                                                    $query_words = $entity['entityId'];
                                                }
                                                if($query_words != '')
                                                {
                                                    $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                                    if(!empty($attached_id))
                                                    {
                                                        $additional_attachments[] = $attached_id;
                                                    }
                                                    if(!empty($z_img))
                                                    {
                                                        $get_img = $z_img;
                                                        $go_local_image = false;
                                                        if(!function_exists('is_plugin_active'))
                                                        {
                                                            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                                        }
                                                        if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                                        {
                                                            $go_local_image = true;
                                                        }
                                                        if($go_local_image == true)
                                                        {
                                                            $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, $query_words);
                                                            if(!empty($attached_id))
                                                            {
                                                                $additional_attachments[] = $attached_id;
                                                            }
                                                            if($localpath !== false)
                                                            {
                                                                $get_img = $localpath[0];
                                                            }
                                                        }
                                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                            aiomatic_log_to_file('Royalty Free Image Generated with help of TextRazor (kw: "' . $query_words . '"): ' . $z_img);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch(Exception $e)
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Failed to search for keywords using TextRazor (2): ' . $e->getMessage());
                                        }
                                    }
                                }
                            }
                            elseif(isset($aiomatic_Main_Settings['improve_keywords']) && trim($aiomatic_Main_Settings['improve_keywords']) == 'openai')
                            {
                                if(isset($aiomatic_Main_Settings['keyword_prompts']) && trim($aiomatic_Main_Settings['keyword_prompts']) != '')
                                {
                                    if(isset($aiomatic_Main_Settings['keyword_model']) && $aiomatic_Main_Settings['keyword_model'] != '')
                                    {
                                        $kw_model = $aiomatic_Main_Settings['keyword_model'];
                                    }
                                    else
                                    {
                                        $kw_model = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                    }
                                    if(isset($aiomatic_Main_Settings['keyword_assistant_id']) && $aiomatic_Main_Settings['keyword_assistant_id'] != '')
                                    {
                                        $keyword_assistant_id = $aiomatic_Main_Settings['keyword_assistant_id'];
                                    }
                                    else
                                    {
                                        $keyword_assistant_id = '';
                                    }
                                    $title_ai_command = trim($aiomatic_Main_Settings['keyword_prompts']);
                                    $title_ai_command = str_replace('%%default_post_cats%%', $default_cat_list, $title_ai_command);
                                    $title_ai_command = str_replace('%%original_post_title%%', $csv['post_title'], $title_ai_command);
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $title_ai_command = preg_split('/\r\n|\r|\n/', $title_ai_command);
                                        $title_ai_command = array_filter($title_ai_command);
                                        if(count($title_ai_command) > 0)
                                        {
                                            $title_ai_command = $title_ai_command[array_rand($title_ai_command)];
                                        }
                                        else
                                        {
                                            $title_ai_command = '';
                                        }
                                    }
                                    $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                    if(!empty($title_ai_command))
                                    {
                                        $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $csv['post_title'], $blog_title, $csv['post_excerpt'], $csv['post_content'], $user_name, '', $csv['post_categories'], $csv['post_tags'], $postID, $img_attr, '', '', '', '', '');
                                    }
                                    $title_ai_command = trim($title_ai_command);
                                    if (filter_var($title_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($title_ai_command, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($title_ai_command);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $title_ai_command = $txt_content;
                                                    $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                                    $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $csv['post_title'], $blog_title, $csv['post_excerpt'], $csv['post_content'], $user_name, '', $csv['post_categories'], $csv['post_tags'], $postID, $img_attr, '', '', '', '', '');
                                                }
                                            }
                                        }
                                    }
                                    if(empty($title_ai_command))
                                    {
                                        aiomatic_log_to_file('Empty API keyword extractor seed expression provided!');
                                        $title_ai_command = 'Type the most relevant keyword, no other text before or after it, for a blog post titled:  ' . trim(strip_tags($post_title));
                                    } 
                                    if(aiomatic_strlen($title_ai_command) > $max_seed_tokens * 4)
                                    {
                                        $title_ai_command = aiomatic_substr($title_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                                    }
                                    $title_ai_command = trim($title_ai_command);
                                    if(empty($title_ai_command))
                                    {
                                        aiomatic_log_to_file('Empty API title seed expression provided(3)! ' . print_r($title_ai_command, true));
                                    }
                                    else
                                    {
                                        $query_token_count = count(aiomatic_encode($title_ai_command));
                                        $available_tokens = aiomatic_compute_available_tokens($kw_model, $max_tokens, $title_ai_command, $query_token_count);
                                        if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                        {
                                            $string_len = aiomatic_strlen($title_ai_command);
                                            $string_len = $string_len / 2;
                                            $string_len = intval(0 - $string_len);
                                            $title_ai_command = aiomatic_substr($title_ai_command, 0, $string_len);
                                            $title_ai_command = trim($title_ai_command);
                                            $query_token_count = count(aiomatic_encode($title_ai_command));
                                            $available_tokens = $max_tokens - $query_token_count;
                                        }
                                        $aierror = '';
                                        $finish_reason = '';
                                        if(!empty($global_prepend))
                                        {
                                            $title_ai_command = $global_prepend . ' ' . $title_ai_command;
                                        }
                                        if(!empty($global_append))
                                        {
                                            $title_ai_command = $title_ai_command . ' ' . $global_append;
                                        }
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = aiomatic_get_api_service($token, $kw_model);
                                            aiomatic_log_to_file('Calling ' . $api_service . ' (' . $keyword_assistant_id . '/' . $kw_model . ')(' . $available_tokens . ') for title text: ' . $title_ai_command);
                                        }
                                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating image search keywords'));
                                        $generated_text = aiomatic_generate_text($token, $kw_model, $title_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'keywordID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $keyword_assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                        if($generated_text === false)
                                        {
                                            aiomatic_log_to_file('Keyword generator error: ' . $aierror);
                                            $ai_title = '';
                                        }
                                        else
                                        {
                                            $ai_title = trim(trim($generated_text), '.');
                                            $ai_titles = explode(',', $ai_title);
                                            foreach($ai_titles as $query_words)
                                            {
                                                $z_img = aiomatic_get_free_image($aiomatic_Main_Settings, trim($query_words), $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                                if(!empty($z_img))
                                                {
                                                    $get_img = $z_img;
                                                    $go_local_image = false;
                                                    if(!function_exists('is_plugin_active'))
                                                    {
                                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                                    }
                                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                                    {
                                                        $go_local_image = true;
                                                    }
                                                    if($go_local_image == true)
                                                    {
                                                        $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, $query_words);
                                                        if(!empty($attached_id))
                                                        {
                                                            $additional_attachments[] = $attached_id;
                                                        }
                                                        if($localpath !== false)
                                                        {
                                                            $get_img = $localpath[0];
                                                        }
                                                    }
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                        aiomatic_log_to_file('Royalty Free Image Generated with help of AI (kw: "' . $query_words . '"): ' . $z_img);
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                        {
                                            $api_service = aiomatic_get_api_service($token, $kw_model);
                                            aiomatic_log_to_file('Successfully got API keyword result from ' . $api_service . ': ' . $ai_title);
                                        }
                                    }
                                }
                            }
                            if(empty($get_img))
                            {
                                if($image_query_set == true && !empty($image_query))
                                {
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing royalty free image'));
                                    $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $image_query, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                    if(!empty($attached_id))
                                    {
                                        $additional_attachments[] = $attached_id;
                                    }
                                    if($get_img == '' || $get_img === false)
                                    {
                                        if(isset($aiomatic_Main_Settings['bimage']) && $aiomatic_Main_Settings['bimage'] == 'on')
                                        {
                                            $keyword_class = new Aiomatic_keywords();
                                            $image_query = $keyword_class->keywords($image_query, 1);
                                            $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $image_query, $img_attr, $attached_id, 20, true, $raw_img_list, array(), $full_result_list);
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                        }
                                    }
                                }
                                if(empty($get_img))
                                {
                                    $keyword_class = new Aiomatic_keywords();
                                    $query_words = $keyword_class->keywords($post_title, 2);
                                    $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, true, $raw_img_list, array(), $full_result_list);
                                    if(!empty($attached_id))
                                    {
                                        $additional_attachments[] = $attached_id;
                                    }
                                    if($get_img == '' || $get_img === false)
                                    {
                                        if(isset($aiomatic_Main_Settings['bimage']) && $aiomatic_Main_Settings['bimage'] == 'on')
                                        {
                                            $query_words = $keyword_class->keywords($post_title, 1);
                                            $get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 20, true, $raw_img_list, array(), $full_result_list);
                                            if(!empty($attached_id))
                                            {
                                                $additional_attachments[] = $attached_id;
                                            }
                                            if($get_img == '' || $get_img === false)
                                            {
                                                if(isset($aiomatic_Main_Settings['no_royalty_skip']) && $aiomatic_Main_Settings['no_royalty_skip'] == 'on')
                                                {
                                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                        aiomatic_log_to_file('Skipping importing because no royalty free image found.');
                                                    }
                                                    unset($post_title_lines[$current_index]);
                                                    continue;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if(isset($aiomatic_Main_Settings['no_royalty_skip']) && $aiomatic_Main_Settings['no_royalty_skip'] == 'on')
                                            {
                                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                    aiomatic_log_to_file('Skipping importing because no royalty free image found.');
                                                }
                                                unset($post_title_lines[$current_index]);
                                                continue;
                                            }
                                        }
                                    }
                                }
                                if(!empty($get_img))
                                {
                                    $go_local_image = false;
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                    {
                                        $go_local_image = true;
                                    }
                                    if($go_local_image == true)
                                    {
                                        $localpath = aiomatic_copy_image_locally($get_img, $attached_id, '', false, '');
                                        if(!empty($attached_id))
                                        {
                                            $additional_attachments[] = $attached_id;
                                        }
                                        if($localpath !== false)
                                        {
                                            $get_img = $localpath[0];
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                    {
                        $already_spinned = '1';
                    }
                    $my_post                              = $csv;
                    if(isset($my_post['post_content']) && stristr($my_post['post_content'], '<pre><code>&lt;') !== false)
                    {
                        if (!isset($aiomatic_Main_Settings['pre_code_off']) || trim($aiomatic_Main_Settings['pre_code_off']) != 'on')
                        {
                            $my_post['post_content'] = aiomatic_parse_pre_code_entities($my_post['post_content']);
                        }
                    }
                    $my_post['post_content'] = aimogen_bulk_finalize_prose($my_post['post_content']);
                    $my_post['aiomatic_post_image']       = $get_img;
                    if(stristr($csv['featured_image_generator'], 'stability') !== false)
                    {
                        $my_post['aiomatic_local_image']      = '1';
                    }
                    else
                    {
                        $my_post['aiomatic_local_image']      = '0';
                    }
                    $my_post['aiomatic_enable_pingbacks'] = $enable_pingback;
                    $my_post['post_type']                 = $post_type;
                    $my_post['comment_status']            = $accept_comments;
                    if (isset($aiomatic_Main_Settings['draft_first']) && $aiomatic_Main_Settings['draft_first'] != 'on')
                    {
                        if($post_status == 'publish')
                        {
                            $draft_me = true;
                            $my_post['post_status'] = 'draft';
                        }
                        else
                        {
                            $my_post['post_status']   = $post_status;
                        }
                    }
                    else
                    {
                        $my_post['post_status']               = $post_status;
                    }
                    if($user_name_type == 'rand')
                    {
                        $randid = aiomatic_display_random_user();
                        if($randid === false)
                        {
                            $my_post['post_author']               = aimogen_get_admin_user_id();
                        }
                        else
                        {
                            $my_post['post_author']               = $randid->ID;
                        }
                    }
                    else
                    {
                        if(isset($csv['post_author']) && $csv['post_author'] != '')
                        {
                            $post_user_name = $csv['post_author'];
                        }
                        else
                        {
                            $post_user_name = $user_name_type;
                        }
                        $my_post['post_author']               = $post_user_name;
                    }
                    if($strip_title == '1')
                    {
                        $my_post['post_content'] = str_replace($my_post['post_title'], '', $my_post['post_content']);
                        $my_post['post_content'] = str_replace('<h2></h2>', '', $my_post['post_content']);
                        $my_post['post_content'] = str_replace('<h3></h3>', '', $my_post['post_content']);
                    }
                    if (isset($aiomatic_Main_Settings['swear_filter']) && $aiomatic_Main_Settings['swear_filter'] == 'on') 
                    {
                        require_once(dirname(__FILE__) . "/res/swear.php");
                        $my_post['post_content'] = aimogenpro_filterwords($my_post['post_content']);
                    }
                    if(isset($aiomatic_Main_Settings['global_ban_words']) && $aiomatic_Main_Settings['global_ban_words'] != '') {
                        $continue    = false;
                        $aiomatic_Main_Settings['global_ban_words'] = trim(trim(trim($aiomatic_Main_Settings['global_ban_words']), ','));
                        $banned_list = explode(',', $aiomatic_Main_Settings['global_ban_words']);
                        foreach ($banned_list as $banned_word) {
                            if (stripos($my_post['post_content'], trim($banned_word)) !== FALSE) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($my_post['post_title']) . '", because it\'s content contains global banned word: ' . $banned_word);
                                }
                                $continue = true;
                                break;
                            }
                            if (stripos($my_post['post_title'], trim($banned_word)) !== FALSE) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($my_post['post_title']) . '", because it\'s title contains global banned word: ' . $banned_word);
                                }
                                $continue = true;
                                break;
                            }
                        }
                        if ($continue === true) {
                            continue;
                        }
                    }
                    if(isset($aiomatic_Main_Settings['global_req_words']) && $aiomatic_Main_Settings['global_req_words'] != '')
                    {
                        if(isset($aiomatic_Main_Settings['require_only_one']) && $aiomatic_Main_Settings['require_only_one'] == 'on')
                        {
                            $continue      = true;
                            $aiomatic_Main_Settings['global_req_words'] = trim(trim(trim($aiomatic_Main_Settings['global_req_words']), ','));
                            $required_list = explode(',', $aiomatic_Main_Settings['global_req_words']);
                            foreach ($required_list as $required_word) {
                                if (stripos($my_post['post_content'], trim($required_word)) !== FALSE || stripos($my_post['post_title'], trim($required_word)) !== FALSE) {
                                    $continue = false;
                                    break;
                                }
                            }
                            if ($continue === true) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($my_post['post_title']) . '", because it\'s content doesn\'t contain global required words.');
                                }
                                continue;
                            }
                        }
                        else
                        {
                            $continue      = false;
                            $aiomatic_Main_Settings['global_req_words'] = trim(trim(trim($aiomatic_Main_Settings['global_req_words']), ','));
                            $required_list = explode(',', $aiomatic_Main_Settings['global_req_words']);
                            foreach ($required_list as $required_word) {
                                if (stripos($my_post['post_content'], trim($required_word)) === FALSE && stripos($my_post['post_title'], trim($required_word)) === FALSE) {
                                    $continue = true;
                                    break;
                                }
                            }
                            if ($continue === true) {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Skipping post "' . esc_html($my_post['post_title']) . '", because it\'s content doesn\'t contain global required words.');
                                }
                                continue;
                            }
                        }
                    }
                    if (isset($aiomatic_Main_Settings['spin_what']) && $aiomatic_Main_Settings['spin_what'] === 'omni') 
                    {
                        $skip_spin = '1';
                    }
                    $arr = aiomatic_spin_and_translate($my_post['post_title'], $my_post['post_content'], '3', $skip_spin, $skip_translate);
                    if($arr[0] != $my_post['post_title'])
                    {
                        $my_post['post_title'] = aiomatic_truncate_title($arr[0]);
                        if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                        {
                            $posts = get_posts(
                                array(
                                    'post_type'              => $post_type,
                                    'title'                  => html_entity_decode($my_post['post_title']),
                                    'post_status'            => 'any',
                                    'numberposts'            => 1,
                                    'update_post_term_cache' => false,
                                    'update_post_meta_cache' => false,           
                                    'orderby'                => 'post_date ID',
                                    'order'                  => 'ASC',
                                )
                            );
                            if ( ! empty( $posts ) ) {
                                $zap = $posts[0];
                            } else {
                                $zap = null;
                            }
                            if($zap !== null)
                            {
                                if($overwrite_existing)
                                {
                                    $update_post_id = $zap->ID;
                                }
                                else
                                {
                                    aiomatic_log_to_file('Post with specified title already existing (after spin/translate), skipping it: ' . $my_post['post_title']);
                                    unset($post_title_lines[$current_index]);
                                    continue;
                                }
                            }
                        }
                    }
                    $my_post['post_content'] = $arr[1];
                    if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                    {
                        $already_spinned = '1';
                    }
                    $my_post['tags_input'] = $my_post['post_tags'];
                    if ($strip_by_regex !== '')
                    {
                        $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex);
                        $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex);
                        $xcnt = 0;
                        foreach($xstrip_by_regex as $sbr)
                        {
                            if(isset($xreplace_regex[$xcnt]))
                            {
                                $repreg = $xreplace_regex[$xcnt];
                            }
                            else
                            {
                                $repreg = '';
                            }
                            $xcnt++;
                            $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $my_post['post_content']);
                            if($temp_cont !== NULL)
                            {
                                $my_post['post_content'] = $temp_cont;
                            }
                        }
                    }
                    $zlang = 'en_US';
                    if (isset($aiomatic_Main_Settings['kw_lang']) && !empty($aiomatic_Main_Settings['kw_lang'])) {
                        $zlang = $aiomatic_Main_Settings['kw_lang'];
                    }
                    $rel_search = array('post_title', 'post_content');
                    if (isset($aiomatic_Main_Settings['rel_search']) && is_array($aiomatic_Main_Settings['rel_search'])) {
                        $rel_search = $aiomatic_Main_Settings['rel_search'];
                    }
                    if($max_links !== '' && $inboundlinker !== null && $link_type != 'disabled')
                    {
                        try
                        {
                            $my_post['post_content'] = $inboundlinker->add_inbound_links($my_post['post_content'], $max_links, $link_post_types, $zlang, $rel_search, null, $link_type, $link_list, $link_nofollow, '', '', array());
                        }
                        catch(Exception $ex)
                        {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('Failed to add inbound links to content: ' . $ex->getMessage());
                            }
                        }
                    }
                    if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                    {
                        if($my_post['post_content'] === strip_tags($my_post['post_content'])) 
                        {
                            $my_post['post_content'] = nl2br($my_post['post_content']);
                        }
                    }
                    if (!isset($aiomatic_Main_Settings['no_undetectibility']) || $aiomatic_Main_Settings['no_undetectibility'] != 'on') 
                    {
                        if (!isset($aiomatic_Main_Settings['no_undetectibility_bulk']) || $aiomatic_Main_Settings['no_undetectibility_bulk'] != 'on') 
                        {
                            if(!isset($xchars))
                            {
                                $xchars = array();
                            }
                            $rand_percentage = wp_rand(10, 20);
                            $my_post['post_content'] = aiomatic_make_unique($my_post['post_content'], $xchars, $rand_percentage);
                        }
                    }
                    if (isset($aiomatic_Main_Settings['convert_gutenberg']) && trim($aiomatic_Main_Settings['convert_gutenberg']) == 'on')
                    {
                        $my_post['post_content'] = aiomatic_convert_html_to_gutenberg_blocks($my_post['post_content']);
                    }
                    if($ret_content == 1)
                    {
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                            aiomatic_log_to_file('Returning AI generated content, finished.');
                        }
                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Finished processing'));
                        return array($my_post['post_content'], $my_post['post_title']);
                    }
                    $my_post['aiomatic_source_title']   = $csv_original_title;
                    $my_post['aiomatic_timestamp']   = aiomatic_get_date_now();
                    $my_post['aiomatic_post_format'] = $post_format;
                    $block_arr = array();
                    $custom_arr = array();
                    if($custom_fields != '')
                    {
                        if(stristr($custom_fields, '=>') != false)
                        {
                            foreach($csv as $ind => $valx)
                            {
                                foreach($csv as $repl_ind => $repl_valx)
                                {
                                    $custom_fields = str_replace('%%' . $repl_ind . '%%', $repl_valx, $custom_fields);
                                }
                                $custom_fields = aiomatic_replaceSynergyShortcodes($custom_fields);
                            }
                            foreach($csv as $ind => $valx)
                            {
                                $custom_fields = apply_filters('aiomatic_replace_aicontent_shortcode', $custom_fields);
                            }
                            $rule_arr = explode(',', trim($custom_fields));
                            foreach($rule_arr as $rule)
                            {
                                $my_args = explode('=>', trim($rule));
                                if(isset($my_args[1]))
                                {
                                    $my_args[1] = do_shortcode($my_args[1]);
                                    $my_args[0] = do_shortcode($my_args[0]);
                                    $custom_field_content = trim($my_args[1]);
                                    $custom_field_content = $spintax->Parse($custom_field_content, $block_arr);
                                    $custom_field_content = aiomatic_replaceContentShortcodes($custom_field_content, $img_attr, $ai_command);
                                    if(stristr($my_args[1], 'serialize_') !== false)
                                    {
                                        $custom_arr[trim($my_args[0])] = array(str_replace('serialize_', '', $custom_field_content));
                                    }
                                    else
                                    {
                                        if(stristr($my_args[0], '[') !== false && stristr($my_args[0], ']') !== false)
                                        {
                                            preg_match_all('#([^\[\]]*?)\[([^\[\]]*?)\]#', $my_args[0], $cfm);
                                            if(isset($cfm[2][0]))
                                            {
                                                if(isset($custom_arr[trim($cfm[1][0])]) && is_array($custom_arr[trim($cfm[1][0])]))
                                                {
                                                    $custom_arr[trim($cfm[1][0])] = array_merge($custom_arr[trim($cfm[1][0])], array(trim($cfm[2][0]) => $custom_field_content));
                                                }
                                                else
                                                {
                                                    $custom_arr[trim($cfm[1][0])] = array(trim($cfm[2][0]) => $custom_field_content);
                                                }
                                            }
                                            else
                                            {
                                                $custom_arr[trim($my_args[0])] = $custom_field_content;
                                            }
                                        }
                                        else
                                        {
                                            $custom_arr[trim($my_args[0])] = $custom_field_content;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $block_arr = array();
                    $custom_arr = array_merge($custom_arr, array('aiomatic_auto_post_spinned' => $already_spinned, 'aiomatic_post_cats' => $csv['post_categories'], 'aiomatic_post_tags' => $csv['post_tags']));
                    $custom_tax_arr = array();
                    if($custom_tax != '')
                    {
                        if(stristr($custom_tax, '=>') != false)
                        {
                            foreach($csv as $ind => $valx)
                            {
                                foreach($csv as $repl_ind => $repl_valx)
                                {
                                    $custom_tax = str_replace('%%' . $repl_ind . '%%', $repl_valx, $custom_tax);
                                }
                                $custom_tax = aiomatic_replaceSynergyShortcodes($custom_tax);
                            }
                            foreach($csv as $ind => $valx)
                            {
                                $custom_tax = apply_filters('aiomatic_replace_aicontent_shortcode', $custom_tax);
                            }
                            $rule_arr = explode(';', trim($custom_tax));
                            foreach($rule_arr as $rule)
                            {
                                $my_args = explode('=>', trim($rule));
                                if(isset($my_args[1]))
                                {
                                    $custom_tax_content = trim($my_args[1]);
                                    $custom_tax_content = $spintax->Parse($custom_tax_content, $block_arr);
                                    $custom_tax_content = aiomatic_replaceContentShortcodes($custom_tax_content, $img_attr, $ai_command);
                                    if(aiomatic_substr(trim($my_args[0]), 0, 3) === "pa_" && $post_type == 'product' && !empty($custom_tax_content))
                                    {
                                        if(isset($custom_arr['_product_attributes']))
                                        {
                                            $custom_arr['_product_attributes'] = array_merge($custom_arr['_product_attributes'], array(trim($my_args[0]) =>array(
                                                'name' => trim($my_args[0]),
                                                'value' => $custom_tax_content,
                                                'is_visible' => '1',
                                                'is_taxonomy' => '1'
                                            )));
                                        }
                                        else
                                        {
                                            $custom_arr['_product_attributes'] = array(trim($my_args[0]) =>array(
                                                'name' => trim($my_args[0]),
                                                'value' => $custom_tax_content,
                                                'is_visible' => '1',
                                                'is_taxonomy' => '1'
                                            ));
                                        }
                                    }
                                    if(isset($custom_tax_arr[trim($my_args[0])]))
                                    {
                                        $custom_tax_arr[trim($my_args[0])] .= ',' . $custom_tax_content;
                                    }
                                    else
                                    {
                                        $custom_tax_arr[trim($my_args[0])] = $custom_tax_content;
                                    }
                                }
                            }
                        }
                    }
                    if(count($custom_tax_arr) > 0)
                    {
                        $my_post['taxo_input'] = $custom_tax_arr;
                    }
                    $my_post['meta_input'] = $custom_arr;
                    if($parent_id != '')
                    {
                        $my_post['post_parent'] = intval($parent_id);
                    }
                    if ($enable_pingback == '1') {
                        $my_post['ping_status'] = 'open';
                    } else {
                        $my_post['ping_status'] = 'closed';
                    }
                    if($min_time != '' && $max_time != '')
                    {
                        $t1 = strtotime($min_time);
                        $t2 = strtotime($max_time);
                        if($t1 != false && $t2 != false)
                        {
                            $int = wp_rand($t1, $t2);
                            $my_post['post_date'] = date('Y-m-d H:i:s', $int);
                        }
                    }
                    elseif($min_time != '')
                    {
                        $t1 = strtotime($min_time);
                        if($t1 != false)
                        {
                            $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                        }
                    }
                    elseif($max_time != '')
                    {
                        $t1 = strtotime($max_time);
                        if($t1 != false)
                        {
                            $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                        }
                    }
                    $count++;
                    if($update_post_id != '')
                    {
                        $my_post['ID'] = $update_post_id;
                    }
                    remove_filter('content_save_pre', 'wp_filter_post_kses');
                    remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                    try
                    {
                        $post_id = wp_insert_post($my_post, true);
                        $my_post['post_content'] = str_replace('\r\n', '', $my_post['post_content']);
                        if (is_wp_error($post_id)) 
                        {
                            aiomatic_log_to_file('Trying publishing again');
                            if (aiomatic_strlen($my_post['post_content']) > 16777215) {
                                $my_post['post_content'] = aiomatic_substr($my_post['post_content'], 0, 16777215);
                            }
                            $my_post['post_content'] = wp_kses_post($my_post['post_content']);
                            $my_post['post_content'] = str_replace('\r\n', '', $my_post['post_content']);
                            $post_id = wp_insert_post($my_post, true);
                        }
                    }
                    catch(Exception $e)
                    {
                        aiomatic_log_to_file('Exception in publishing post (this is coming from another plugin, so we ignore it): ' . $e->getMessage());
                    }
                    add_filter('content_save_pre', 'wp_filter_post_kses');
                    add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                    if (!is_wp_error($post_id)) {
                        if($post_id === 0)
                        {
                            aiomatic_log_to_file('An error occurred while inserting post into wp database! Title:' . $my_post['post_title']);
                            continue;
                        }
                        $words = str_word_count(wp_strip_all_tags($my_post['post_content']));
                        aiomatic_increment_publishing_stats($words);
                        aimogen_bulk_on_post_created($post_id, $my_post['post_title'], isset($new_post_excerpt) ? $new_post_excerpt : '', isset($post_topic) ? $post_topic : (isset($post_title) ? $post_title : ''));
                        aiomatic_set_last_activity(
                            'article',
                            ['post_id' => $post_id]
                        );
                        $posts_inserted++;
                        if($wpml_lang != '' && function_exists('pll_set_post_language'))
                        {
                            pll_set_post_language($post_id, $wpml_lang);
                        }
                        if(!empty($additional_attachments))
                        {
                            foreach($additional_attachments as $add_att)
                            {
                                wp_update_post([
                                    'ID' => $add_att,
                                    'post_parent' => $post_id,
                                ]);
                            }
                        }
                        $default_categories = array();
                        if($remove_default == '1' && $my_post['post_categories'] != '')
                        {
                            $default_categories = wp_get_post_categories($post_id);
                        }
                        if(isset($my_post['taxo_input']))
                        {
                            foreach($my_post['taxo_input'] as $taxn => $taxval)
                            {
                                $taxn = trim($taxn);
                                $taxval = trim($taxval);
                                if(is_taxonomy_hierarchical($taxn))
                                {
                                    $taxval = array_map('trim', explode(',', $taxval));
                                    for($ii = 0; $ii < count($taxval); $ii++)
                                    {
                                        if(!is_numeric($taxval[$ii]))
                                        {
                                            $term_ids = [];
                                            $parent_id = 0;
                                            $hierarchy_parts = array_map('trim', explode('>', $taxval[$ii]));
                                            foreach($hierarchy_parts as $hp)
                                            {
                                                if(!is_numeric($hp))
                                                {
                                                    $xtermid = get_term_by('name', $hp, $taxn);
                                                    if($xtermid !== false)
                                                    {
                                                        $parent_id = $xtermid->term_id;
                                                        if(!is_numeric($taxval[$ii]))
                                                        {
                                                            $taxval[$ii] = intval($xtermid->term_id);
                                                        }
                                                        else
                                                        {
                                                            $taxval[] = intval($xtermid->term_id);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        wp_insert_term( $hp, $taxn, ['parent' => $parent_id]);
                                                        $xtermid = get_term_by('name', $hp, $taxn);
                                                        if($xtermid !== false)
                                                        {
                                                            $parent_id = $xtermid->term_id;
                                                            if($wpml_lang != '' && function_exists('pll_set_term_language'))
                                                            {
                                                                pll_set_term_language($xtermid->term_id, $wpml_lang); 
                                                            }
                                                            elseif($wpml_lang != '' && has_filter('wpml_object_id'))
                                                            {
                                                                $wpml_element_type = apply_filters( 'wpml_element_type', $taxn );
                                                                $pars['element_id'] = $xtermid->term_id;
                                                                $pars['element_type'] = $wpml_element_type;
                                                                $pars['language_code'] = $wpml_lang;
                                                                $pars['trid'] = FALSE;
                                                                $pars['source_language_code'] = NULL;
                                                                do_action('wpml_set_element_language_details', $pars);
                                                            }
                                                            if(!is_numeric($taxval[$ii]))
                                                            {
                                                                $taxval[$ii] = intval($xtermid->term_id);
                                                            }
                                                            else
                                                            {
                                                                $taxval[] = intval($xtermid->term_id);
                                                            }
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    if(!is_numeric($taxval[$ii]))
                                                    {
                                                        $taxval[$ii] = intval($hp);
                                                    }
                                                    else
                                                    {
                                                        $taxval[] = intval($hp);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    wp_set_post_terms($post_id, $taxval, $taxn, true);
                                }
                                else
                                {
                                    $jterms = array_map('trim', explode(',', $taxval));
                                    wp_set_post_terms($post_id, $jterms, $taxn, true);
                                }
                            }
                        }
                        if (isset($my_post['aiomatic_post_format']) && $my_post['aiomatic_post_format'] != '' && $my_post['aiomatic_post_format'] != 'post-format-standard') {
                            wp_set_post_terms($post_id, $my_post['aiomatic_post_format'], 'post_format', true);
                        }
                        $featured_path = '';
                        $get_img = $my_post['aiomatic_post_image'];
                        if ($get_img != '') {
                            if($my_post['aiomatic_local_image'] == '1')
                            {
                                $local_get_img = $get_img[0];
                                if (!aiomatic_assign_featured_image_path($local_get_img, $post_id)) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('aiomatic_assign_featured_image_path failed for ' . $local_get_img);
                                    }
                                } else {
                                    $featured_path = $get_img[1];
                                }
                            }
                            else
                            {
                                if(is_numeric($get_img))
                                {
                                    $featured_path = aiomatic_assign_featured_image($get_img, $post_id);
                                }
                                else
                                {
                                    if (!aiomatic_generate_featured_image($get_img, $post_id)) {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('aiomatic_generate_featured_image failed for ' . $get_img);
                                        }
                                    } else {
                                        $featured_path = $get_img;
                                    }
                                }
                            }
                        }
                        if ($my_post['post_categories'] != '') {
                            $extra_cats = explode(',', $my_post['post_categories']);
                            foreach($extra_cats as $extra_cat)
                            {
                                $extra_cat = trim($extra_cat);
                                $extra_cat = strip_tags($extra_cat);
                                $extra_cat = preg_replace('#^\d+\.\s*#', '', $extra_cat);
                                if($post_type == 'product')
                                {
                                    $product_tax = 'product_cat';
                                }
                                else
                                {
                                    $product_tax = 'category';
                                }
                                if(empty($extra_cat))
                                {
                                    continue;
                                }
                                if ($skip_inexist == '1') 
                                {
                                    if(!term_exists($extra_cat, $product_tax))
                                    {
                                        continue;
                                    }
                                }
                                $termid = aiomatic_create_terms($product_tax, null, trim($extra_cat));
                                wp_set_post_terms($post_id, $termid, $product_tax, true);
                                if($wpml_lang != '' && function_exists('pll_set_term_language'))
                                {
                                    foreach($termid as $tx)
                                    {
                                        pll_set_term_language($tx, $wpml_lang); 
                                    }
                                }
                                elseif($wpml_lang != '' && has_filter('wpml_object_id'))
                                {
                                    $wpml_element_type = apply_filters( 'wpml_element_type', 'product_cat' );
                                    foreach($termid as $tx)
                                    {
                                        $pars['element_id'] = $tx;
                                        $pars['element_type'] = $wpml_element_type;
                                        $pars['language_code'] = $wpml_lang;
                                        $pars['trid'] = FALSE;
                                        $pars['source_language_code'] = NULL;
                                        do_action('wpml_set_element_language_details', $pars);
                                    }
                                }
                            }
                        }
                        if (isset($my_post['tags_input']) && $my_post['tags_input'] != '')
                        {
                            if($post_type == 'product')
                            {
                                wp_set_post_terms($post_id, $my_post['tags_input'], 'product_tag', true);
                            }
                        }
                        $tax_rez = wp_set_object_terms( $post_id, 'aiomatic_' . $type . '_' . $param, 'coderevolution_post_source', true);
                        if (is_wp_error($tax_rez)) {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('wp_set_object_terms failed for: ' . $post_id . '!');
                            }
                        }
                        if($post_type == 'topic' && $parent_id != '')
                        {
                            update_post_meta($post_id, '_bbp_forum_id', $parent_id);
                            update_post_meta($post_id, '_bbp_topic_id', $post_id);
                            update_post_meta($post_id, '_bbp_voice_count', '0');
                            update_post_meta($post_id, '_bbp_reply_count', '0');
                            update_post_meta($post_id, '_bbp_reply_count_hidden', '0');
                            update_post_meta($post_id, '_bbp_last_reply_id', '0');
                            update_post_meta($post_id, '_bbp_last_active_id', $post_id);
                            update_post_meta($post_id, '_bbp_last_active_time', get_post_field( 'post_date', $topic_id, 'db' ));
                            do_action( 'bbp_insert_topic', (int) $post_id, (int) $parent_id );
                        }
                        if($post_type == 'reply' && $parent_id != '')
                        {
                            if(function_exists('bbp_get_topic_forum_id'))
                            {
                                $forum_aidi = bbp_get_topic_forum_id($parent_id);
                                if(empty($forum_aidi))
                                {
                                    $forum_aidi = 0;
                                }
                            }
                            else
                            {
                                $forum_aidi = 0;
                            }
                            do_action( 'bbp_insert_reply', (int) $post_id, (int) $parent_id, (int) $forum_aidi );
                        }
                        if($remove_default == '1' && $my_post['post_categories'] != '')
                        {
                            $new_categories = wp_get_post_categories($post_id);
                            if(isset($default_categories) && !($default_categories == $new_categories))
                            {
                                foreach($default_categories as $dc)
                                {
                                    $rem_cat = get_category( $dc );
                                    wp_remove_object_terms( $post_id, $rem_cat->slug, 'category' );
                                }
                            }
                        }
                        $my_post['extra_tags'] = '';
                        $my_post['extra_categories'] = '';
                        aiomatic_addPostMeta($post_id, $my_post, $param, $type, $get_img, '', $rule_unique_id, $post_link);
                        if($wpml_lang != '' && (class_exists('SitePress') || function_exists('wpml_object_id')))
                        {
                            $wpml_element_type = apply_filters( 'wpml_element_type', $post_type );
                            $pars['element_id'] = $post_id;
                            $pars['element_type'] = $wpml_element_type;
                            $pars['language_code'] = $wpml_lang;
                            $pars['source_language_code'] = NULL;
                            do_action('wpml_set_element_language_details', $pars);

                            global $wp_filesystem;
                            if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
                                include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() );
                                wp_filesystem($creds);
                            }
                            if($wp_filesystem->exists(WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php'))
                            {
                                include_once( WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php' );
                            }
                            $wpml_lang = trim($wpml_lang);
                            if(function_exists('wpml_update_translatable_content'))
                            {
                                wpml_update_translatable_content('post_' . $post_type, $post_id, $wpml_lang);
                                if($my_post['post_title'] != '')
                                {
                                    global $sitepress;
                                    global $wpdb;
                                    $keyid = md5($my_post['post_title']);
                                    $keyName = $keyid . '_wpml';
                                    $rezxxxa = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}postmeta WHERE `meta_key` = '$keyName' limit 1", ARRAY_A );
                                    if(count($rezxxxa) != 0)
                                    {
                                        $metaRow = $rezxxxa[0];
                                        $metaValue = $metaRow['meta_value'];
                                        $metaParts = explode('_', $metaValue);
                                        $sitepress->set_element_language_details($post_id, 'post_'.$my_post['post_type'] , $metaParts[0], $wpml_lang, $metaParts[1] ); 
                                    }
                                    else
                                    {
                                        $ptrid = $sitepress->get_element_trid($post_id);
                                        update_post_meta($post_id, $keyid.'_wpml', $ptrid.'_'.$wpml_lang );
                                    }
                                }
                                
                            }
                        }
                        if (isset($aiomatic_Main_Settings['draft_first']) && $aiomatic_Main_Settings['draft_first'] == 'on' && $draft_me == true)
                        {
                            aiomatic_change_post_status($post_id, 'publish');
                        }
                    } else {
                        aiomatic_log_to_file('Failed to insert post into wp database(5)! Title:' . $my_post['post_title'] . '! Error: ' . $post_id->get_error_message() . ' Error code: ' . $post_id->get_error_code() . ' Error data: ' . $post_id->get_error_data());
                        continue;
                    }
                }
            }
            elseif($type == '5')
            {
                $count = 1;
                $keyword_arr = preg_split('/\r\n|\r|\n/', trim($main_keywords));
                $keyword_arr = array_unique($keyword_arr);
                $skipt = 0;
                $kiwis = array();
                $more_kws_arr = preg_split('/\r\n|\r|\n/', trim($more_keywords));
                foreach($more_kws_arr as $this_kw)
                {
                    if(strstr($this_kw, '=>') !== false)
                    {
                        $expl_kw = explode('=>', $this_kw);
                        if(isset($expl_kw[1]))
                        {
                            $kiwis[trim($expl_kw[0])] = trim($expl_kw[1]);
                        }
                    }
                }
                $block_data = json_decode($sortable_cards, true);
                if($block_data === null)
                {
                    aiomatic_log_to_file('Error in parsing OmniBlock data: ' . $sortable_cards);
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
                if(empty($block_data))
                {
                    aiomatic_log_to_file('No Block data added: ' . $sortable_cards);
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
                require_once(__DIR__ . '/res/amazon-direct.php');
                require_once(__DIR__ . '/aiomatic-automation.php');
                $default_block_types = aiomatic_omniblocks_default_block_types(); 
                $omni_cache = array();
                while(!empty($keyword_arr)) 
                {
                    if ($count > intval($max)) {
                        break;
                    }
                    $block_results = array();
                    $thread_id = '';
                    if (!isset($aiomatic_Main_Settings['no_random_titles']) || $aiomatic_Main_Settings['no_random_titles'] != 'on')
                    {
                        $rand_ind = array_rand($keyword_arr);
                    }
                    else
                    {
                        $rand_ind = array_key_first($keyword_arr);
                    }
                    $current_keyword = $keyword_arr[$rand_ind];
                    if($title_once == '1')
                    {
                        do
                        {
                            $args = array(
                                'post_type'      => 'any', 
                                'posts_per_page' => 1,  
                                'post_status'    => 'any', 
                                'title'          => $current_keyword 
                            );
                            $query = new WP_Query($args);
                            if ($query->have_posts()) 
                            {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    aiomatic_log_to_file('A post with the same title as the OmniBlock keyword already processed, skipping it: ' . $current_keyword);
                                }
                                unset($keyword_arr[$rand_ind]);
                                if(!empty($keyword_arr))
                                {
                                    if (!isset($aiomatic_Main_Settings['no_random_titles']) || $aiomatic_Main_Settings['no_random_titles'] != 'on')
                                    {
                                        $rand_ind = array_rand($keyword_arr);
                                    }
                                    else
                                    {
                                        $rand_ind = array_key_first($keyword_arr);
                                    }
                                    $current_keyword = $keyword_arr[$rand_ind];
                                }
                            } 
                        }
                        while($query->have_posts() && !empty($keyword_arr));
                        
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                        {
                            $addmx = 'no';
                            if(aiomatic_is_keyword_processed($current_keyword))
                            {
                                $addmx = 'yes';
                            }
                            aiomatic_log_to_file('Checking if keyword is processed: "' . $current_keyword . '" - result: ' . $addmx);
                        }
                        while (aiomatic_is_keyword_processed($current_keyword) && !empty($keyword_arr)) 
                        {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                aiomatic_log_to_file('OmniBlock keyword already processed, skipping it: ' . $current_keyword);
                            }
                            unset($keyword_arr[$rand_ind]);
                            if(!empty($keyword_arr))
                            {
                                if (!isset($aiomatic_Main_Settings['no_random_titles']) || $aiomatic_Main_Settings['no_random_titles'] != 'on')
                                {
                                    $rand_ind = array_rand($keyword_arr);
                                }
                                else
                                {
                                    $rand_ind = array_key_first($keyword_arr);
                                }
                                $current_keyword = $keyword_arr[$rand_ind];
                            }
                        }
                        if(empty($stop_omnmiblock_id) && empty($keyword_arr))
                        {
                            aiomatic_log_to_file('All keywords already processed, nothing to do');
                            if($auto == 1)
                            {
                                aiomatic_clearFromList($param, $type);
                            }
                            return 'nochange';
                        }
                        if(!empty($keyword_arr))
                        {
                            unset($keyword_arr[$rand_ind]);
                        }
                    }
                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                    {
                        aiomatic_log_to_file('Starting OmniBlock processing for keyword: ' . $current_keyword);
                    }
                    $index = 0;
                    while ($index < count($block_data)) 
                    {
                        $current_block = $block_data[$index];
                        $index++;
                        $card_type_found = array();
                        $block_id = $current_block['identifier'];
                        $critical = '0';
                        $disabled = '0';
                        if(isset($current_block['parameters']['critical']))
                        {
                            $critical = $current_block['parameters']['critical'];
                        }
                        if(isset($current_block['parameters']['disabled']))
                        {
                            $disabled = $current_block['parameters']['disabled'];
                        }
                        if((empty($stop_omnmiblock_id) || $stop_omnmiblock_id != $block_id) && $disabled == '1')
                        {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('Skipping OmniBlock ID because it is disabled: ' . esc_html($block_id));
                            }
                            $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
                            continue;
                        }
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                            aiomatic_log_to_file('Running OmniBlock type: ' . $current_block['type'] . ' - ID: ' . esc_html($block_id));
                        }
                        foreach($default_block_types as $def_card)
                        {
                            if($current_block['type'] == $def_card['id'])
                            {
                                $card_type_found = $def_card;
                                break;
                            }
                        }
                        if(empty($card_type_found))
                        {
                            if($critical == '1')
                            {
                                aiomatic_log_to_file('Halting execution (inexistent card type), as critical block failed (ID ' . esc_html($block_id) . ')');
                                return 'fail';
                            }
                            else
                            {
                                aiomatic_log_to_file('Block type not found in blocks array: ' . print_r($current_block, true));
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array('');
                                }
                                $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
                                continue;
                            }
                        }
                        if(isset($card_type_found['required_plugin']) && !empty($card_type_found['required_plugin']))
                        {
                            $need_continue = false;
                            foreach($card_type_found['required_plugin'] as $pslug => $pname)
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                if (!is_plugin_active($pslug)) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (inexistent plugin extension), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need enable the "' . $pname[0] . '" (' . $pslug . ') plugin for this OmniBlock type to work: ' . $pname[1]);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
                                        $need_continue = true;
                                        break;
                                    }
                                }
                            }
                            if($need_continue == true)
                            {
                                continue;
                            }
                        }
                        if($current_block['type'] == 'ai_text')
                        {
                            if (isset($aiomatic_Main_Settings['omni_fpenalty']) && trim($aiomatic_Main_Settings['omni_fpenalty']) != '')
                            {
                                $frequency_penalty = floatval($aiomatic_Main_Settings['omni_fpenalty']);
                            } 
                            else 
                            {
                                $frequency_penalty = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_ppenalty']) && trim($aiomatic_Main_Settings['omni_ppenalty']) != '')
                            {
                                $presence_penalty = floatval($aiomatic_Main_Settings['omni_ppenalty']);
                            } 
                            else 
                            {
                                $presence_penalty = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_top_p']) && trim($aiomatic_Main_Settings['omni_top_p']) != '')
                            {
                                $max_p = floatval($aiomatic_Main_Settings['omni_top_p']);
                            } 
                            else 
                            {
                                $max_p = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_temperature']) && trim($aiomatic_Main_Settings['omni_temperature']) != '')
                            {
                                $temperature = floatval($aiomatic_Main_Settings['omni_temperature']);
                            } 
                            else 
                            {
                                $temperature = '';
                            }
                            $prompt = $current_block['parameters']['prompt'];
                            $prompt = aiomatic_replace_omniblocks_data($prompt, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($prompt)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty text prompt entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty text prompt entered, block ID: ' . $block_id);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $model = $current_block['parameters']['model'];
                            $assistant_id = $current_block['parameters']['assistant_id'];
                            $max_tokens = aimogenpro_get_max_tokens($model);
                            $query_token_count = count(aiomatic_encode($prompt));
                            $available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $prompt, $query_token_count);
                            if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                            {
                                $string_len = aiomatic_strlen($prompt);
                                $string_len = $string_len / 2;
                                $string_len = intval(0 - $string_len);
                                $prompt = aiomatic_substr($prompt, 0, $string_len);
                                $prompt = trim($prompt);
                                $query_token_count = count(aiomatic_encode($prompt));
                                $available_tokens = $max_tokens - $query_token_count;
                            }
                            $aierror = '';
                            $finish_reason = '';
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for OmniBlock text ID: ' . $block_id);
                                aiomatic_log_to_file('AI Prompt is: ' . $prompt);
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock AI content'));
                            $generated_text = aiomatic_generate_text($token, $model, $prompt, $available_tokens, $temperature, $max_p, $presence_penalty, $frequency_penalty, false, 'omniBlocksWriter', 0, $finish_reason, $aierror, false, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                            
                            if($generated_text === false)
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (failed to generate AI content), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to generate non-critical OmniBlock content using AI writer (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                            else
                            {
                                if(empty($generated_text))
                                {
                                    aiomatic_log_to_file('Empty content generated using AI OmniBlock writer (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                                else
                                {
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array($generated_text);
                                    }
                                    $block_results[$block_id] = array($current_block['type'], $generated_text);
                                }
                            }
                        }
                        elseif($current_block['type'] == 'ai_vision')
                        {
                            if (isset($aiomatic_Main_Settings['omni_fpenalty']) && trim($aiomatic_Main_Settings['omni_fpenalty']) != '')
                            {
                                $frequency_penalty = floatval($aiomatic_Main_Settings['omni_fpenalty']);
                            } 
                            else 
                            {
                                $frequency_penalty = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_ppenalty']) && trim($aiomatic_Main_Settings['omni_ppenalty']) != '')
                            {
                                $presence_penalty = floatval($aiomatic_Main_Settings['omni_ppenalty']);
                            } 
                            else 
                            {
                                $presence_penalty = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_top_p']) && trim($aiomatic_Main_Settings['omni_top_p']) != '')
                            {
                                $max_p = floatval($aiomatic_Main_Settings['omni_top_p']);
                            } 
                            else 
                            {
                                $max_p = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_temperature']) && trim($aiomatic_Main_Settings['omni_temperature']) != '')
                            {
                                $temperature = floatval($aiomatic_Main_Settings['omni_temperature']);
                            } 
                            else 
                            {
                                $temperature = '';
                            }
                            $image_url = $current_block['parameters']['image_url'];
                            $image_url = aiomatic_replace_omniblocks_data($image_url, $current_keyword, $kiwis, $block_results, $load_variables);
                            $prompt = $current_block['parameters']['prompt'];
                            $prompt = aiomatic_replace_omniblocks_data($prompt, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($prompt)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty text prompt entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    if(empty($image_url))
                                    {
                                        aiomatic_log_to_file('Empty text prompt entered, block ID: ' . $block_id);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                        continue;
                                    }
                                    else
                                    {
                                        $prompt = 'Analyze this image in detail';
                                    }
                                }
                            }
                            $model = $current_block['parameters']['model'];
                            $assistant_id = $current_block['parameters']['assistant_id'];
                            $max_tokens = aimogenpro_get_max_tokens($model);
                            $query_token_count = count(aiomatic_encode($prompt));
                            $available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $prompt, $query_token_count);
                            if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                            {
                                $string_len = aiomatic_strlen($prompt);
                                $string_len = $string_len / 2;
                                $string_len = intval(0 - $string_len);
                                $prompt = aiomatic_substr($prompt, 0, $string_len);
                                $prompt = trim($prompt);
                                $query_token_count = count(aiomatic_encode($prompt));
                                $available_tokens = $max_tokens - $query_token_count;
                            }
                            $aierror = '';
                            $finish_reason = '';
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for OmniBlock text ID: ' . $block_id);
                                aiomatic_log_to_file('AI Prompt is: ' . $prompt);
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock AI content'));
                            $generated_text = aiomatic_generate_text($token, $model, $prompt, $available_tokens, $temperature, $max_p, $presence_penalty, $frequency_penalty, false, 'omniBlocksWriter', 0, $finish_reason, $aierror, false, false, false, $image_url, '', 'user', $assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                            
                            if($generated_text === false)
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (failed to generate AI vision content), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to generate non-critical OmniBlock vision content using AI writer (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                            else
                            {
                                if(empty($generated_text))
                                {
                                    aiomatic_log_to_file('Empty vision content generated using AI OmniBlock writer (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                                else
                                {
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array($generated_text);
                                    }
                                    $block_results[$block_id] = array($current_block['type'], $generated_text);
                                }
                            }
                        }
                        elseif($current_block['type'] == 'ai_text_foreach')
                        {
                            $final_text = '';
                            if (isset($aiomatic_Main_Settings['omni_fpenalty']) && trim($aiomatic_Main_Settings['omni_fpenalty']) != '')
                            {
                                $frequency_penalty = floatval($aiomatic_Main_Settings['omni_fpenalty']);
                            } 
                            else 
                            {
                                $frequency_penalty = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_ppenalty']) && trim($aiomatic_Main_Settings['omni_ppenalty']) != '')
                            {
                                $presence_penalty = floatval($aiomatic_Main_Settings['omni_ppenalty']);
                            } 
                            else 
                            {
                                $presence_penalty = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_top_p']) && trim($aiomatic_Main_Settings['omni_top_p']) != '')
                            {
                                $max_p = floatval($aiomatic_Main_Settings['omni_top_p']);
                            } 
                            else 
                            {
                                $max_p = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_temperature']) && trim($aiomatic_Main_Settings['omni_temperature']) != '')
                            {
                                $temperature = floatval($aiomatic_Main_Settings['omni_temperature']);
                            } 
                            else 
                            {
                                $temperature = '';
                            }
                            $multiline_input = $current_block['parameters']['multiline_input'];
                            $multiline_input = aiomatic_replace_omniblocks_data($multiline_input, $current_keyword, $kiwis, $block_results, $load_variables);
                            $prepend = $current_block['parameters']['prepend'];
                            $prepend = aiomatic_replace_omniblocks_data($prepend, $current_keyword, $kiwis, $block_results, $load_variables);
                            $append = $current_block['parameters']['append'];
                            $append = aiomatic_replace_omniblocks_data($append, $current_keyword, $kiwis, $block_results, $load_variables);
                            $max_runs = $current_block['parameters']['max_runs'];
                            if (empty($multiline_input)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty text multiline_input entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty text multiline_input entered, block ID: ' . $block_id);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $prompt = $current_block['parameters']['prompt'];
                            if (empty($prompt)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty text prompt entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty text prompt entered, block ID: ' . $block_id);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $multiline_input_arr = preg_split('/\r\n|\r|\n/', trim($multiline_input));
                            $current_line_counter = 1;
                            foreach($multiline_input_arr as $curr_line)
                            {
                                if(!empty($max_runs) && is_numeric($max_runs))
                                {
                                    if(intval($max_runs) < $current_line_counter)
                                    {
                                        break;
                                    }
                                }
                                $prompt_now = $prompt;
                                $prompt_now = aiomatic_replace_omniblocks_data($prompt_now, $current_keyword, $kiwis, $block_results, $load_variables);
                                $prompt_now = str_replace('%%current_input_line%%', $curr_line, $prompt_now);
                                $prompt_now = str_replace('%%current_input_line_counter%%', $current_line_counter, $prompt_now);
                                $prompt_now = str_replace('%%all_input_lines%%', $multiline_input, $prompt_now);
                                $current_line_counter++;
                                if (empty($prompt_now)) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (empty text prompt_now entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Empty text prompt_now entered, block ID: ' . $block_id);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                        continue;
                                    }
                                }
                                $model = $current_block['parameters']['model'];
                                $assistant_id = $current_block['parameters']['assistant_id'];
                                $max_tokens = aimogenpro_get_max_tokens($model);

                                $query_token_count = count(aiomatic_encode($prompt_now));
                                $available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $prompt_now, $query_token_count);
                                if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                {
                                    $string_len = aiomatic_strlen($prompt_now);
                                    $string_len = $string_len / 2;
                                    $string_len = intval(0 - $string_len);
                                    $prompt_now = aiomatic_substr($prompt_now, 0, $string_len);
                                    $prompt_now = trim($prompt_now);
                                    $query_token_count = count(aiomatic_encode($prompt_now));
                                    $available_tokens = $max_tokens - $query_token_count;
                                }
                                $aierror = '';
                                $finish_reason = '';
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $api_service = aiomatic_get_api_service($token, $model);
                                    aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for OmniBlock text ID: ' . $block_id);
                                    aiomatic_log_to_file('Current AI Prompt is: ' . $prompt_now);
                                }
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock AI content'));
                                $generated_text = aiomatic_generate_text($token, $model, $prompt_now, $available_tokens, $temperature, $max_p, $presence_penalty, $frequency_penalty, false, 'omniBlocksWriter', 0, $finish_reason, $aierror, false, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', false, $store_data, array(), '', '', '');
                                if($generated_text === false)
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (AI content failed), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to generate non-critical OmniBlock content using AI writer (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                    }
                                }
                                else
                                {
                                    if(empty($generated_text))
                                    {
                                        aiomatic_log_to_file('Empty content generated using AI OmniBlock writer (ID ' . esc_html($block_id) . '): ' . $model);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                    }
                                    else
                                    {
                                        $final_text .= ' ' . $prepend . $generated_text . $append;
                                    }
                                }
                            }
                            if(empty($final_text))
                            {
                                aiomatic_log_to_file('Empty content generated using AI OmniBlock multiline writer (ID ' . esc_html($block_id) . '): ' . $model);
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array('');
                                }
                                $block_results[$block_id] = array($current_block['type'], '');
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($final_text);
                                }
                                $block_results[$block_id] = array($current_block['type'], $final_text);
                            }
                        }
                        elseif($current_block['type'] == 'text_translate')
                        {
                            $translation = false;
                            $pre_tags_matches = array();
                            $pre_tags_matches_s = array();
                            $conseqMatchs = array();
                            $final_content = $current_block['parameters']['input_text'];
                            $final_content = aiomatic_replace_omniblocks_data($final_content, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($final_content)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty text input entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty text input entered, block ID: ' . $block_id);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $translate = $current_block['parameters']['translate'];
                            if (empty($translate) || $translate == 'disabled') 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (translation disabled), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Translation disabled for block: ' . $block_id);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $translate_source = $current_block['parameters']['translate_source'];
                            $second_translate = $current_block['parameters']['second_translate'];
                            if(!empty($translate_source) && $translate_source != 'disabled')
                            {
                                $tr = $translate_source;
                            }
                            else
                            {
                                $tr = 'auto';
                            }
                            $htmlfounds = array();
                            $final_content = aiomatic_replaceExcludes($final_content, $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs);
                            $translation = aiomatic_translate('test', $final_content, $tr, $translate);
                            if (is_array($translation) && isset($translation[1]))
                            {
                                $translation[1] = preg_replace('#(?<=[\*(])\s+(?=[\*)])#', '', $translation[1]);
                                $translation[1] = preg_replace('#([^(*\s]\s)\*+\)#', '$1', $translation[1]);
                                $translation[1] = preg_replace('#\(\*+([\s][^)*\s])#', '$1', $translation[1]);
                                if(isset($second_translate) && $second_translate != 'disabled')
                                {
                                    $translation = aiomatic_translate('test', $translation[1], $translate, $second_translate);
                                    if (is_array($translation) && isset($translation[1]))
                                    {
                                        $translation[1] = aiomatic_restoreExcludes($translation[1], $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs);
                                    }
                                    else
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (second translation failed), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to translate text the second time, from ' . $translate . ' to ' . $second_translate . ' in OmniBlock ID: ' . $block_id);
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type'], '');
                                            continue;
                                        }
                                    }
                                }
                                else
                                {
                                    $translation[1] = aiomatic_restoreExcludes($translation[1], $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs);
                                }
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (translation failed), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to translate text, from ' . $tr . ' to ' . $translate . ' in OmniBlock ID: ' . $block_id);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            if ($translation !== FALSE) {
                                if (is_array($translation) && isset($translation[0]) && isset($translation[1])) 
                                {
                                    $final_content = $translation[1];
                                    $final_content = str_replace('</ iframe>', '</iframe>', $final_content);
                                    if(stristr($final_content, '<head>') !== false)
                                    {
                                        $d = new DOMDocument;
                                        $mock = new DOMDocument;
                                        $internalErrors = libxml_use_internal_errors(true);
                                        $d->loadHTML('<?xml encoding="utf-8" ?>' . $final_content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
                                        libxml_use_internal_errors($internalErrors);
                                        $body = $d->getElementsByTagName('body')->item(0);
                                        foreach ($body->childNodes as $child)
                                        {
                                            $mock->appendChild($mock->importNode($child, true));
                                        }
                                        $new_post_content_temp = $mock->saveHTML();
                                        if($new_post_content_temp !== '' && $new_post_content_temp !== false)
                                        {
                                            $new_post_content_temp = str_replace('<?xml encoding="utf-8" ?>', '', $new_post_content_temp);
                                            $final_content = preg_replace("/_addload\(function\(\){([^<]*)/i", "", $new_post_content_temp); 
                                        }
                                    }
                                    $final_content = htmlspecialchars_decode($final_content);
                                    $final_content = str_replace('</ ', '</', $final_content);
                                    $final_content = str_replace(' />', '/>', $final_content);
                                    $final_content = str_replace('< br/>', '<br/>', $final_content);
                                    $final_content = str_replace('< / ', '</', $final_content);
                                    $final_content = str_replace(' / >', '/>', $final_content);
                                    $final_content = preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $final_content);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array($final_content);
                                    }
                                    $block_results[$block_id] = array($current_block['type'], $final_content);
                                } 
                                else 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (translation failed, malformed data), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to translate text, malformed data, from ' . $tr . ' to ' . $translate . ' in OmniBlock ID: ' . $block_id);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                        continue;
                                    }
                                }
                            } 
                            else 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (translation returned false), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to translate text, from ' . $tr . ' to ' . $translate . ', translation returned false in OmniBlock ID: ' . $block_id);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                        }
                        elseif($current_block['type'] == 'text_spinner')
                        {
                            if (isset($aiomatic_Main_Settings['spin_what']) && $aiomatic_Main_Settings['spin_what'] === 'bulk') 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (spinning disabled for omniblocks), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Spinning disabled for OmniBlocks, from plugin\'s \'Settings\' menu -> \'Bulk Posts\' tab -> \'Enable Spinner For\' settings field, in OmniBlock ID: ' . $block_id);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $translation = false;
                            $pre_tags_matches = array();
                            $pre_tags_matches_s = array();
                            $conseqMatchs = array();
                            $final_content = $current_block['parameters']['input_text'];
                            $final_content = aiomatic_replace_omniblocks_data($final_content, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($final_content)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty text input entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty text input entered, block ID: ' . $block_id);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                            {
                                $htmlfounds = array();
                                $final_content = aiomatic_replaceExcludes($final_content, $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs);
                                if ($aiomatic_Main_Settings['spin_text'] == 'builtin') {
                                    $translation = aiomatic_builtin_spin_text('test', $final_content);
                                } elseif ($aiomatic_Main_Settings['spin_text'] == 'wikisynonyms') {
                                    $translation = aiomatic_spin_text('test', $final_content, false);
                                } elseif ($aiomatic_Main_Settings['spin_text'] == 'freethesaurus') {
                                    $translation = aiomatic_spin_text('test', $final_content, true);
                                } elseif ($aiomatic_Main_Settings['spin_text'] == 'best') {
                                    $translation = aiomatic_best_spin_text('test', $final_content);
                                } elseif ($aiomatic_Main_Settings['spin_text'] == 'wordai') {
                                    $translation = aiomatic_wordai_spin_text('test', $final_content);
                                } elseif ($aiomatic_Main_Settings['spin_text'] == 'spinrewriter') {
                                    $translation = aiomatic_spinrewriter_spin_text('test', $final_content);
                                } elseif ($aiomatic_Main_Settings['spin_text'] == 'spinnerchief') {
                                    $translation = aiomatic_spinnerchief_spin_text('test', $final_content);
                                } elseif ($aiomatic_Main_Settings['spin_text'] == 'chimprewriter') {
                                    $translation = aiomatic_chimprewriter_spin_text('test', $final_content);
                                } elseif ($aiomatic_Main_Settings['spin_text'] == 'contentprofessor') {
                                    $translation = aiomatic_contentprofessor_spin_text('test', $final_content);
                                }
                                if ($translation !== FALSE) 
                                {
                                    if (is_array($translation) && isset($translation[0]) && isset($translation[1])) {
                                        if (!isset($aiomatic_Main_Settings['no_title']) || $aiomatic_Main_Settings['no_title'] != 'on') {
                                            $final_content = $translation[1];
                                        }
                                        $final_content = aiomatic_fix_spinned_content($final_content, $aiomatic_Main_Settings['spin_text']);
                                        $final_content = aiomatic_restoreExcludes($final_content, $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array($final_content);
                                        }
                                        $block_results[$block_id] = array($current_block['type'], $final_content);
                                    } 
                                    else 
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (spinning failed, malformed data), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Text Spinning failed - malformed data, block ID: ' . $block_id);
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type'], '');
                                            continue;
                                        }
                                    }
                                } 
                                else 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (spinning failed, returned false), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Text Spinning failed - returned false, block ID: ' . $block_id);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                        continue;
                                    }
                                }
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (spinning disabled in settings), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Spinning disabled from \'Settings\' menu of the plugin, skipping, block ID: ' . $block_id);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                        }
                        elseif($current_block['type'] == 'plain_text')
                        {
                            $final_content = $current_block['parameters']['input_text'];
                            $final_content = aiomatic_replace_omniblocks_data($final_content, $current_keyword, $kiwis, $block_results, $load_variables);
                            $final_content = do_shortcode($final_content);
                            $block_arr = array();
                            $spintax = new Aiomatic_Spintax();
                            $final_content = $spintax->Parse($final_content, $block_arr);
                            if (empty($final_content)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty text input entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty text input entered, block ID: ' . $block_id);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                            {
                                return array($final_content);
                            }
                            $block_results[$block_id] = array($current_block['type'], $final_content);
                        }
                        elseif ($current_block['type'] == 'diy')
                        {
                            $final_content = $current_block['parameters']['input_text'];
                            $final_content = aiomatic_replace_omniblocks_data($final_content, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (!has_filter("aimogen_diy_omniblock_{$block_id}")) 
                            {
                                if (!has_filter("aiomatic_diy_omniblock_{$block_id}")) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (filter not defined: "aimogen_diy_omniblock_' . $block_id . '"), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Filter not defined: "aimogen_diy_omniblock_' . $block_id . '" for block ID: ' . $block_id);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                        continue;
                                    }
                                }
                                $final_content = apply_filters("aiomatic_diy_omniblock_{$block_id}", $final_content, [
                                    'current_keyword' => $current_keyword,
                                    'more_keywords'   => $kiwis,
                                    'block_results'   => $block_results,
                                ]);
                                if (empty($final_content)) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (empty text input entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Empty text input entered, block ID: ' . $block_id);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                        continue;
                                    }
                                }
                                if (!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id) 
                                {
                                    return array($final_content);
                                }
                                $block_results[$block_id] = array($current_block['type'], $final_content);
                            }
                            $final_content = apply_filters("aimogen_diy_omniblock_{$block_id}", $final_content, [
                                'current_keyword' => $current_keyword,
                                'more_keywords'   => $kiwis,
                                'block_results'   => $block_results,
                            ]);
                            if (empty($final_content)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty text input entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty text input entered, block ID: ' . $block_id);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            if (!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id) 
                            {
                                return array($final_content);
                            }
                            $block_results[$block_id] = array($current_block['type'], $final_content);
                        }
                        elseif($current_block['type'] == 'embeddings')
                        {
                            $input_text = $current_block['parameters']['input_text'];
                            $embeddings_namespace = $current_block['parameters']['embeddings_namespace'];
                            $input_text = aiomatic_replace_omniblocks_data($input_text, $current_keyword, $kiwis, $block_results, $load_variables);
                            $embeddings_namespace = aiomatic_replace_omniblocks_data($embeddings_namespace, $current_keyword, $kiwis, $block_results, $load_variables);
                            $embed_rez = aiomatic_embeddings_result($input_text, $token, $embeddings_namespace);
                            if($embed_rez['status'] == 'error')
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (embeddings result failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Embeddings result failed, block ID: ' . $block_id . ' embeddings data: ' . print_r($embed_rez, true));
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($embed_rez['data']);
                                }
                                $block_results[$block_id] = array($current_block['type'], $embed_rez['data']);
                            }
                        }
                        elseif($current_block['type'] == 'internet_access')
                        {
                            $input_text = $current_block['parameters']['input_text'];
                            $input_text = aiomatic_replace_omniblocks_data($input_text, $current_keyword, $kiwis, $block_results, $load_variables);
                            $locale = '';
                            if (isset($aiomatic_Main_Settings['internet_gl']) && $aiomatic_Main_Settings['internet_gl'] != '')
                            {
                                $locale = $aiomatic_Main_Settings['internet_gl'];
                            }
                            $internet_rez = aiomatic_internet_result($input_text, false, $locale);
                            shuffle($internet_rez);
                            if (isset($aiomatic_Main_Settings['results_num']) && trim($aiomatic_Main_Settings['results_num']) != '')
                            {
                                $results = intval(trim($aiomatic_Main_Settings['results_num']));
                            }
                            else
                            {
                                $results = 3;
                            }
                            $gotcnt = 0;
                            $internet_results = '';
                            $internet_results_parts = [];
                            foreach($internet_rez as $emb)
                            {
                                if($gotcnt >= $results)
                                {
                                    break;
                                }
                                if (isset($aiomatic_Main_Settings['internet_single_template']) && trim($aiomatic_Main_Settings['internet_single_template']) != '')
                                {
                                    $internet_single_template = $aiomatic_Main_Settings['internet_single_template'];
                                }
                                else
                                {
                                    $internet_single_template = '[%%result_counter%%]: %%result_title%% %%result_snippet%% ' . PHP_EOL . 'URL: %%result_link%%';
                                }
                                $internet_single_template = str_replace('%%result_counter%%', $gotcnt + 1, $internet_single_template);
                                $internet_single_template = str_replace('%%result_title%%', $emb['title'], $internet_single_template);
                                $internet_single_template = str_replace('%%result_snippet%%', $emb['snippet'], $internet_single_template);
                                $internet_single_template = str_replace('%%result_link%%', $emb['link'], $internet_single_template);
                                $internet_results_parts[] = $internet_single_template;
                                $gotcnt++;
                            }
                            $internet_results = implode(PHP_EOL, $internet_results_parts);
                            if(empty($internet_results))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (internet search result no data returned), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Internet search result failed, block ID: ' . $block_id . ', no data returned');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                            {
                                return array($internet_results);
                            }
                            $block_results[$block_id] = array($current_block['type'], $internet_results);
                        }
                        elseif($current_block['type'] == 'load_file')
                        {
                            $input_text = $current_block['parameters']['input_text'];
                            global $wp_filesystem;
                            if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
                                include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() );
                                wp_filesystem($creds);
                            }
                            if($input_text == 'random')
                            {
                                $omni_files = get_posts([
                                    'post_type' => 'aiomatic_omni_file',
                                    'post_status' => 'publish',
                                    'numberposts' => -1
                                ]);
                                if(empty($omni_files))
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (no OmniBlock Files found), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('No OmniBlock Files found, block ID: ' . $block_id);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                        continue;
                                    }
                                }
                                else
                                {
                                    $this_post = $omni_files[array_rand($omni_files)];
                                }
                            }
                            elseif($input_text == 'latest')
                            {
                                $paged = 1; 
                                $posts_per_page = 100; 
                                $omni_files = array(); 
                                do {
                                    $args = array(
                                        'post_type'      => 'aiomatic_omni_file',
                                        'post_status'    => 'publish',    
                                        'posts_per_page' => $posts_per_page,   
                                        'paged'          => $paged,          
                                        'orderby'        => 'date',       
                                        'order'          => 'DESC',      
                                    );

                                    $query = new WP_Query($args);

                                    if ($query->have_posts()) {
                                        $omni_files = array_merge($omni_files, $query->posts); 
                                    }

                                    $paged++;
                                    wp_reset_postdata(); 
                                } while ($query->have_posts());
                                if(empty($omni_files))
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (no OmniBlock Files found), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('No OmniBlock Files found, block ID: ' . $block_id);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                        continue;
                                    }
                                }
                                else
                                {
                                    $this_post = reset($omni_files);
                                }
                            }
                            else
                            {
                                $this_post = get_post($input_text);
                            }
                            if($this_post === null)
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (file result failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('File result failed, block ID: ' . $block_id . ' file ID: ' . print_r($input_text, true));
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            else
                            {
                                $post_urlx = $this_post->post_content;
                                if(aiomatic_endsWith($post_urlx, '.xlsx'))
                                {
                                    $items = aiomatic_extract_remote_xlsx($post_urlx, '1');
                                    if($items === false)
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (Failed to parse xlsx), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to parse xlsx, block ID: ' . $block_id . ' file URL: ' . print_r($post_urlx, true));
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type'], '');
                                            continue;
                                        }
                                    }
                                    if (count($items) == 0) 
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (Empty xlsx file), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Empty xlsx file, block ID: ' . $block_id . ' file URL: ' . print_r($post_urlx, true));
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type'], '');
                                            continue;
                                        }
                                    }
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array($items);
                                    }
                                    $block_results[$block_id] = array($current_block['type'], $items);
                                }
                                elseif(aiomatic_endsWith($post_urlx, '.pdf'))
                                {
                                    if(!function_exists('is_plugin_active'))
                                    {
                                        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                    }
                                    if (!is_plugin_active('aiomatic-extension-pdf-files/aiomatic-extension-pdf-files.php')) 
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (PDF Parser Extension plugin is not active, please activate it to use this functionality), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Aimogen Extension - PDF File Storage And Parsing plugin is not active, please activate it to use this functionality');
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type'], '');
                                            continue;
                                        }
                                    }
                                    $htmlc = aiomatic_extension_pdfext_getRemoteFile($post_urlx);
                                    if($htmlc === false)
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (Failed to download pdf file), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to download file: ' . $post_urlx);
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type'], '');
                                            continue;
                                        }
                                    }
                                    $file_data = '';
                                    $pdf =  new PdfToText();
                                    $pdf->LoadFromString($htmlc);
                                    $page_range = '';
                                    if($page_range == '')
                                    {
                                        $file_data = $pdf->Text;
                                    }
                                    else
                                    {
                                        $page_range = array_map('trim', aiomatic_extension_pdfext_extract_range($page_range));
                                        foreach( $pdf->Pages as $page_number => $page_contents)
                                        {
                                            if(count($page_range) == 0)
                                            {
                                                break;
                                            }
                                            if(in_array($page_number, $page_range))
                                            {
                                                $page_range = array_diff($page_range, array($page_number));
                                                $file_data .= $page_contents;
                                            }
                                        }
                                    }
                                    if($file_data === false || empty(trim($file_data)))
                                    {
                                        $pparser = new \Smalot\PdfParser\Parser();
                                        $document = $pparser->parseContent($htmlc);
                                        if($page_range == '')
                                        {
                                            $file_data  = $document->getText();
                                        }
                                        else
                                        {
                                            $page_range = array_map('trim', aiomatic_extension_pdfext_extract_range($page_range));
                                            $nr = 1;
                                            $pages  = $document->getPages();
                                            foreach ($pages as $page) {
                                                if(count($page_range) == 0)
                                                {
                                                    break;
                                                }
                                                if(in_array($nr, $page_range))
                                                {
                                                    $page_range = array_diff($page_range, array($nr));
                                                    $file_data .= $page->getText();
                                                }
                                                $nr++;
                                            }
                                            $pages = count($pages);
                                        }
                                    }
                                    $file_data = nl2br($file_data);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array($file_data);
                                    }
                                    $block_results[$block_id] = array($current_block['type'], $file_data);
                                }
                                else
                                {
                                    $file_data = aiomatic_get_web_page($post_urlx);
                                    if($file_data === false)
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (file content opening failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to open file content, block ID: ' . $block_id . ' file URL: ' . print_r($post_urlx, true));
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type'], '');
                                            continue;
                                        }
                                    }
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array($file_data);
                                    }
                                    $block_results[$block_id] = array($current_block['type'], $file_data);
                                }
                            }
                        }
                        elseif($current_block['type'] == 'dalle_ai_image')
                        {
                            $prompt = $current_block['parameters']['prompt'];
                            $prompt = aiomatic_replace_omniblocks_data($prompt, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($prompt)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty image prompt entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty image prompt entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $model = $current_block['parameters']['model'];
                            $image_size = $current_block['parameters']['image_size'];
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock Dall-E images'));
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for OmniBlock Dall-E image');
                            }
                            $aierror = '';
                            $response_text = aiomatic_generate_ai_image($token, 1, $prompt, $image_size, 'omniBlocksWriterDalleImage', false, 0, $aierror, $model, $prompt);
                            if($response_text !== false && is_array($response_text))
                            {
                                foreach($response_text as $tmpimg)
                                {
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array($tmpimg);
                                    }
                                    $block_results[$block_id] = array($current_block['type'], $tmpimg);
                                    break;
                                }
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Dall-E error), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Error occurred in Dall-E image generator (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                        }
                        elseif($current_block['type'] == 'stable_ai_image')
                        {
                            $prompt = $current_block['parameters']['prompt'];
                            $prompt = aiomatic_replace_omniblocks_data($prompt, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($prompt)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty image prompt entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty image prompt entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $model = $current_block['parameters']['model'];
                            $image_size = $current_block['parameters']['image_size'];
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock Stable images'));
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for OmniBlock Stable image');
                            }
                            $aierror = '';
                            $response_text = aiomatic_generate_stability_image($prompt, $height, $width, 'omniBlocksWriterStableImage', 0, false, $aierror, false, $model, '', 0);
                            if($response_text !== false && isset($response_text[1]))
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($response_text[1]);
                                }
                                $block_results[$block_id] = array($current_block['type'], $response_text[1]);
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Stable Diffusion error), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Error occurred in Stable Diffusion image generator (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                        }
                        elseif($current_block['type'] == 'google_ai_image')
                        {
                            $prompt = $current_block['parameters']['prompt'];
                            $prompt = aiomatic_replace_omniblocks_data($prompt, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($prompt)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty image prompt entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty image prompt entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $model = $current_block['parameters']['model'];
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock Google images'));
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ') for OmniBlock Google image');
                            }
                            $aierror = '';
                            $response_text = aiomatic_generate_image_google($prompt, $model, 'omniBlocksWriterGoogleImage', false, $ierror, false);
                            if($response_text !== false && isset($response_text[1]))
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($response_text[1]);
                                }
                                $block_results[$block_id] = array($current_block['type'], $response_text[1]);
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Stable Diffusion error), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Error occurred in Stable Diffusion image generator (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                        }
                        elseif($current_block['type'] == 'midjourney_ai_image')
                        {
                            $prompt = $current_block['parameters']['prompt'];
                            $prompt = aiomatic_replace_omniblocks_data($prompt, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($prompt)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty image prompt entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty image prompt entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $image_size = $current_block['parameters']['image_size'];
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            elseif($image_size == '1024x1792')
                            {
                                $width = '1024';
                                $height = '1792';
                            }
                            elseif($image_size == '1792x1024')
                            {
                                $width = '1792';
                                $height = '1024';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock Midjourney images'));
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for OmniBlock Midjourney image');
                            }
                            $aierror = '';
                            $response_text = aiomatic_generate_ai_image_midjourney($prompt, $width, $height, 'omniBlocksWriterMidjourneyImage', false, $aierror);
                            if($response_text !== false)
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($response_text);
                                }
                                $block_results[$block_id] = array($current_block['type'], $response_text);
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Midjourney error), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Error occurred in Midjourney image generator (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                        }
                        elseif($current_block['type'] == 'replicate_ai_image')
                        {
                            $prompt = $current_block['parameters']['prompt'];
                            $prompt = aiomatic_replace_omniblocks_data($prompt, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($prompt)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty image prompt entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty image prompt entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $image_size = $current_block['parameters']['image_size'];
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            elseif($image_size == '1024x1792')
                            {
                                $width = '1024';
                                $height = '1792';
                            }
                            elseif($image_size == '1792x1024')
                            {
                                $width = '1792';
                                $height = '1024';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock Replicate images'));
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for OmniBlock Replicate image');
                            }
                            $aierror = '';
                            $response_text = aiomatic_generate_replicate_image($prompt, $width, $height, 'omniBlocksWriterReplicateImage', false, $aierror);
                            if($response_text !== false)
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($response_text);
                                }
                                $block_results[$block_id] = array($current_block['type'], $response_text);
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Replicate error), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Error occurred in Replicate image generator (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                        }
                        elseif($current_block['type'] == 'ideogram_ai_image')
                        {
                            $prompt = $current_block['parameters']['prompt'];
                            $prompt = aiomatic_replace_omniblocks_data($prompt, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($prompt)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty image prompt entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty image prompt entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $image_size = $current_block['parameters']['image_size'];
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            elseif($image_size == '1024x1792')
                            {
                                $width = '1024';
                                $height = '1792';
                            }
                            elseif($image_size == '1792x1024')
                            {
                                $width = '1792';
                                $height = '1024';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock Ideogram images'));
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for OmniBlock Ideogram image');
                            }
                            $aierror = '';
                            $response_text = aiomatic_generate_ideogram_image($prompt, $width, $height, 'omniBlocksWriterIdeogramImage', false, $aierror);
                            if($response_text !== false)
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($response_text);
                                }
                                $block_results[$block_id] = array($current_block['type'], $response_text);
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Ideogram error), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Error occurred in Ideogram image generator (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                        }
                        elseif($current_block['type'] == 'cloudflare_ai_image')
                        {
                            $prompt = $current_block['parameters']['prompt'];
                            $prompt = aiomatic_replace_omniblocks_data($prompt, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($prompt)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty image prompt entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty image prompt entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $image_size = $current_block['parameters']['image_size'];
                            if($image_size == '512x512')
                            {
                                $width = '512';
                                $height = '512';
                            }
                            elseif($image_size == '1024x1024')
                            {
                                $width = '1024';
                                $height = '1024';
                            }
                            elseif($image_size == '1024x1792')
                            {
                                $width = '1024';
                                $height = '1792';
                            }
                            elseif($image_size == '1792x1024')
                            {
                                $width = '1792';
                                $height = '1024';
                            }
                            else
                            {
                                $width = '512';
                                $height = '512';
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock Cloudflare images'));
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for OmniBlock Cloudflare image');
                            }
                            $aierror = '';
                            $response_text = aiomatic_generate_cloudflare_image($prompt, $width, $height, 'omniBlocksWriterCloudflareImage', false, $aierror);
                            if($response_text !== false)
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($response_text);
                                }
                                $block_results[$block_id] = array($current_block['type'], $response_text);
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Cloudflare error), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Error occurred in Cloudflare image generator (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                        }
                        elseif($current_block['type'] == 'stable_ai_video')
                        {
                            $image_url = $current_block['parameters']['image_url'];
                            $image_url = aiomatic_replace_omniblocks_data($image_url, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($image_url)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty video image_url entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty video image_url entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $image_size = $current_block['parameters']['image_size'];
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock Stable video'));
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' for OmniBlock Stable video');
                            }
                            $aierror = '';
                            $response_text = aiomatic_generate_stability_video($image_url, $image_size, 'omniBlocksWriterStableVideo', 0, false, $aierror, false);
                            if($response_text !== false && isset($response_text[1]))
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($response_text[1]);
                                }
                                $block_results[$block_id] = array($current_block['type'], $response_text[1]);
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Stable Diffusion video error), as critical block failed (ID ' . esc_html($block_id) . '): error: ' . $aierror);
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Error occurred in Stable Diffusion video generator (ID ' . esc_html($block_id) . '): error: ' . $aierror);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                        }
                        elseif($current_block['type'] == 'nlp_entities')
                        {
                            $input_text = $current_block['parameters']['input_text'];
                            $input_text = aiomatic_replace_omniblocks_data($input_text, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($input_text)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty input_text entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty input_text entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '');
                                    continue;
                                }
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock NLP Entities With TextRazor'));
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                aiomatic_log_to_file('Getting TextRazor NLP entities for keyword: ' . $input_text);
                            }
                            if(isset($aiomatic_Main_Settings['textrazor_key']) && trim($aiomatic_Main_Settings['textrazor_key']) != '')
                            {
                                try
                                {
                                    if(!class_exists('TextRazor'))
                                    {
                                        require_once(dirname(__FILE__) . "/res/TextRazor.php");
                                    }
                                    TextRazorSettings::setApiKey(trim($aiomatic_Main_Settings['textrazor_key']));
                                    $textrazor = new TextRazor();
                                    $textrazor->addExtractor('entities');
                                    $zresponse = $textrazor->analyze($input_text);
                                    if (isset($zresponse['response']['entities'])) 
                                    {
                                        $query_words_tr = array();
                                        $entity_details = array();
                                        foreach ($zresponse['response']['entities'] as $entity) 
                                        {
                                            if(isset($entity['entityEnglishId']))
                                            {
                                                $query_words_tr[] = $entity['entityEnglishId'];
                                            }
                                            else
                                            {
                                                $query_words_tr[] = $entity['entityId'];
                                            }
                                            if(isset($entity['id']))
                                            {
                                                unset($entity['id']);
                                            }
                                            if(isset($entity['matchingTokens']))
                                            {
                                                unset($entity['matchingTokens']);
                                            }
                                            if(isset($entity['freebaseTypes']))
                                            {
                                                unset($entity['freebaseTypes']);
                                            }
                                            if(isset($entity['confidenceScore']))
                                            {
                                                unset($entity['confidenceScore']);
                                            }
                                            if(isset($entity['matchedText']))
                                            {
                                                unset($entity['matchedText']);
                                            }
                                            if(isset($entity['freebaseId']))
                                            {
                                                unset($entity['freebaseId']);
                                            }
                                            if(isset($entity['relevanceScore']))
                                            {
                                                unset($entity['relevanceScore']);
                                            }
                                            if(isset($entity['startingPos']))
                                            {
                                                unset($entity['startingPos']);
                                            }
                                            if(isset($entity['endingPos']))
                                            {
                                                unset($entity['endingPos']);
                                            }
                                            if(isset($entity['wikidataId']))
                                            {
                                                unset($entity['wikidataId']);
                                            }
                                            $entity_details[] = $entity;
                                        }
                                        if(count($query_words_tr) > 0)
                                        {
                                            $wr = implode(',', $query_words_tr);
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array($wr, json_encode($entity_details));
                                            }
                                            $block_results[$block_id] = array($current_block['type'], $wr, json_encode($entity_details));
                                        }
                                        else
                                        {
                                            if($critical == '1')
                                            {
                                                aiomatic_log_to_file('Halting execution (TextRazor no empty found), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                return 'fail';
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Empty results found for TextRazor search: ' . print_r($zresponse, true));
                                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                {
                                                    return array('', '');
                                                }
                                                $block_results[$block_id] = array($current_block['type'], '', '');
                                                continue;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (TextRazor no results found), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('No results found for TextRazor search: ' . print_r($zresponse, true));
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('', '');
                                            }
                                            $block_results[$block_id] = array($current_block['type'], '', '');
                                            continue;
                                        }
                                    }
                                }
                                catch(Exception $e)
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (TextRazor exception(2)), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to search for keywords using TextRazor (2): ' . $e->getMessage());
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('', '');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '', '');
                                        continue;
                                    }
                                }
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (TextRazor API key not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('TextRazor API key not added in plugin settings!');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '');
                                    continue;
                                }
                            }
                        }
                        elseif($current_block['type'] == 'nlp_entities_neuron')
                        {
                            $input_text = $current_block['parameters']['input_text'];
                            $input_text = aiomatic_replace_omniblocks_data($input_text, $current_keyword, $kiwis, $block_results, $load_variables);
                            $engine = $current_block['parameters']['engine'];
                            $language = $current_block['parameters']['language'];
                            if (empty($input_text)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty input_text entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty input_text entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '', '', '', '', '', '', '', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '');
                                    continue;
                                }
                            }
                            if (empty($engine)) 
                            {
                                $engine = 'google.com';
                            }
                            if (empty($language)) 
                            {
                                $language = 'English';
                            }

                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock NLP Entities With NeuronWriter'));
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                aiomatic_log_to_file('Getting NeuronWriter NLP entities for keyword: ' . $input_text);
                            }
                            if(isset($aiomatic_Main_Settings['neuron_key']) && trim($aiomatic_Main_Settings['neuron_key']) != '')
                            {
                                if(isset($aiomatic_Main_Settings['neuron_project']) && trim($aiomatic_Main_Settings['neuron_project']) != '')
                                {
                                    try
                                    {
                                        if(!class_exists('NeuronWriterAPI'))
                                        {
                                            require_once (dirname(__FILE__) . "/res/NeuronWriter.php");
                                        }
                                        $appk = trim($aiomatic_Main_Settings['neuron_key']);
                                        $projid = trim($aiomatic_Main_Settings['neuron_project']);
                                        $neuronAPI = new NeuronWriterAPI($appk);
                                        $response = $neuronAPI->createNewQuery($projid, $input_text, $engine, $language);
                                        $rp = json_decode($response);
                                        if(!isset($rp->query))
                                        {
                                            if($critical == '1')
                                            {
                                                aiomatic_log_to_file('Halting execution (Failed to create new query in NeuronWriter), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                return 'fail';
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to create new query in NeuronWriter: ' . print_r($response, true));
                                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                {
                                                    return array('', '', '', '', '', '', '', '', '');
                                                }
                                                $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '');
                                                continue;
                                            }
                                        }
                                        else
                                        {
                                            $queryId = $rp->query;
                                            $timeout_max = 300;
                                            $current_time = 0;
                                            $qs = false;
                                            while($current_time <= $timeout_max && $qs === false)
                                            {
                                                $qs = $neuronAPI->getQueryStatus($queryId);
                                                if($qs === false)
                                                {
                                                    sleep(3);
                                                }
                                                $current_time += 3;
                                            }
                                            if($current_time > $timeout_max && $qs === false)
                                            {
                                                if($critical == '1')
                                                {
                                                    aiomatic_log_to_file('Halting execution (NeuronWriter timeout), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                    return 'fail';
                                                }
                                                else
                                                {
                                                    aiomatic_log_to_file('NeuronWriter timeout!');
                                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                    {
                                                        return array('', '', '', '', '', '', '', '', '');
                                                    }
                                                    $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '');
                                                    continue;
                                                }
                                            }
                                            elseif($qs === false)
                                            {
                                                if($critical == '1')
                                                {
                                                    aiomatic_log_to_file('Halting execution (NeuronWriter critical failure), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                    return 'fail';
                                                }
                                                else
                                                {
                                                    aiomatic_log_to_file('NeuronWriter critical failure');
                                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                    {
                                                        return array('', '', '', '', '', '', '', '', '');
                                                    }
                                                    $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '');
                                                    continue;
                                                }
                                            }
                                            else
                                            {
                                                if(!isset($qs['terms_txt']['title']))
                                                {
                                                    if($critical == '1')
                                                    {
                                                        aiomatic_log_to_file('Halting execution (NeuronWriter failed to interpret results), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                        return 'fail';
                                                    }
                                                    else
                                                    {
                                                        aiomatic_log_to_file('NeuronWriter failed to interpret results: ' . print_r($qs, true));
                                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                        {
                                                            return array('', '', '', '', '', '', '', '', '');
                                                        }
                                                        $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '');
                                                        continue;
                                                    }
                                                }
                                                else
                                                {
                                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                    {
                                                        return array($qs['terms_txt']['title'], $qs['terms_txt']['desc_title'], $qs['terms_txt']['h1'], $qs['terms_txt']['h2'], $qs['terms_txt']['content_basic'], $qs['terms_txt']['content_basic_w_ranges'], $qs['terms_txt']['content_extended'], $qs['terms_txt']['content_extended_w_ranges'], $qs['terms_txt']['entities']);
                                                    }
                                                    $block_results[$block_id] = array($current_block['type'], $qs['terms_txt']['title'], $qs['terms_txt']['desc_title'], $qs['terms_txt']['h1'], $qs['terms_txt']['h2'], $qs['terms_txt']['content_basic'], $qs['terms_txt']['content_basic_w_ranges'], $qs['terms_txt']['content_extended'], $qs['terms_txt']['content_extended_w_ranges'], $qs['terms_txt']['entities']);
                                                }
                                            }
                                        }
                                    }
                                    catch(Exception $e)
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (NeuronWriter exception(2)), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to search for keywords using NeuronWriter (2): ' . $e->getMessage());
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('', '', '', '', '', '', '', '', '');
                                            }
                                            $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '');
                                            continue;
                                        }
                                    }
                                }
                                else
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (NeuronWriter Project ID not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('NeuronWriter Project ID not added in plugin settings!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('', '', '', '', '', '', '', '', '');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '');
                                        continue;
                                    }
                                }
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (NeuronWriter API key not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('NeuronWriter API key not added in plugin settings!');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '', '', '', '', '', '', '', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '');
                                    continue;
                                }
                            }
                        }
                        elseif($current_block['type'] == 'tts_openai')
                        {
                            $input_text = $current_block['parameters']['input_text'];
                            $input_text = aiomatic_replace_omniblocks_data($input_text, $current_keyword, $kiwis, $block_results, $load_variables);
                            $open_model_id = $current_block['parameters']['model'];
                            $open_voice = $current_block['parameters']['voice'];
                            $open_format = $current_block['parameters']['output'];
                            $stability = $current_block['parameters']['stability'];
                            if(empty($input_text))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty input_text), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty input_text provided in TTS OpenAI (ID ' . esc_html($block_id) . ')');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                            else
                            {
                                $result = aiomatic_openai_voice_stream($token, $open_model_id, $open_voice, $open_format, $stability, $input_text);
                                if(is_array($result))
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (OpenAI TTS error), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('OpenAI TTS Failed (ID ' . esc_html($block_id) . '): ' . print_r($result, true));
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                    }
                                }
                                else
                                {
                                    $filename = uniqid() . '.' . $open_format;
                                    $local_arr = aiomatic_copy_file_locally($result, $filename, '', false);
                                    if(isset($local_arr[0]))
                                    {
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array($local_arr[0]);
                                        }
                                        $block_results[$block_id] = array($current_block['type'], $local_arr[0]);
                                    }
                                    else
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (OpenAI TTS failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('OpenAI TTS Error (ID ' . esc_html($block_id) . '): ' . print_r($local_arr, true));
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type'], '');
                                        }
                                    }
                                }
                            }
                        }
                        elseif($current_block['type'] == 'stt_openai')
                        {
                            $audio_url = $current_block['parameters']['audio_url'];
                            $audio_url = aiomatic_replace_omniblocks_data($audio_url, $current_keyword, $kiwis, $block_results, $load_variables);
                            $prompt = $current_block['parameters']['prompt'];
                            $prompt = aiomatic_replace_omniblocks_data($prompt, $current_keyword, $kiwis, $block_results, $load_variables);
                            $purpose = $current_block['parameters']['purpose'];
                            $model = $current_block['parameters']['model'];
                            $language = $current_block['parameters']['language'];
                            $temperature = $current_block['parameters']['temperature'];
                            if(empty($audio_url))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty audio_url), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty audio_url provided in STT OpenAI (ID ' . esc_html($block_id) . ')');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                            else
                            {
                                $result = aiomatic_generate_audio_convertion($prompt, $audio_url, $purpose, $model, $temperature, $language);
                                if(!is_array($result) || !isset($result['status']) || $result['status'] != 'success' || !isset($result['data']))
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (OpenAI STT error), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('OpenAI STT Failed (ID ' . esc_html($block_id) . '): ' . print_r($result, true));
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                    }
                                }
                                else
                                {
                                    $result = $result['data'];
                                    if(!empty($result))
                                    {
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array($result);
                                        }
                                        $block_results[$block_id] = array($current_block['type'], $result);
                                    }
                                    else
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (OpenAI STT failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('OpenAI STT Error (ID ' . esc_html($block_id) . '): ' . print_r($local_arr, true));
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type'], '');
                                        }
                                    }
                                }
                            }
                        }
                        elseif($current_block['type'] == 'webhook_fire')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Getting OmniBlock Webhook Data'));
                            if(empty($omniWebhookID) || $omniWebhookID != $block_id)
                            {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    aiomatic_log_to_file('Getting OmniBlock Webhook Data (this request was not called from a webhook, this OmniBlock will always return an empty string)');
                                }
                                $block_results[$block_id] = array($current_block['type'], array());
                            }
                            else
                            {
                                $api_key = trim($current_block['parameters']['api_key']);
                                if (!empty($api_key)) 
                                {
                                    if(!isset($_REQUEST['apikey']))
                                    {
                                        aiomatic_log_to_file('Halting execution (OmniBLock Webhook API key not provided in request) (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    if($_REQUEST['apikey'] != $api_key)
                                    {
                                        aiomatic_log_to_file('Halting execution (OmniBLock Webhook invalid API key provided in request) (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                }
                                if (isset($_GET['apikey'])) {
                                    unset($_GET['apikey']);
                                }
                                if (isset($_POST['apikey'])) {
                                    unset($_POST['apikey']);
                                }
                                if (isset($_REQUEST['apikey'])) {
                                    unset($_REQUEST['apikey']);
                                }
                                if (isset($_GET['omniblockid'])) {
                                    unset($_GET['omniblockid']);
                                }
                                if (isset($_POST['omniblockid'])) {
                                    unset($_POST['omniblockid']);
                                }
                                if (isset($_REQUEST['omniblockid'])) {
                                    unset($_REQUEST['omniblockid']);
                                }
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    aiomatic_log_to_file('Getting OmniBlock Webhook Data (from inside a successful OmniBlock Webhook request)');
                                }
                                if (isset($_REQUEST['input'])) 
                                {
                                    $block_results[$block_id] = array($current_block['type'], $_REQUEST['input']);
                                }
                                else
                                {
                                    $block_results[$block_id] = array($current_block['type'], $_REQUEST);
                                }
                            }
                        }
                        elseif($current_block['type'] == 'ai_forms_omniblock')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Getting OmniBlock AI Forms Data'));
                            if(empty($omniWebhookID) || $omniWebhookID != $block_id)
                            {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    aiomatic_log_to_file('This request was not called from an AI Form, this OmniBlock will always return an empty string');
                                }
                                $block_results[$block_id] = array($current_block['type'], array());
                            }
                            else
                            {
                                $api_key = trim($current_block['parameters']['api_key']);
                                if (!empty($api_key)) 
                                {
                                    if(!isset($_REQUEST['apikey']))
                                    {
                                        aiomatic_log_to_file('Halting execution (OmniBLock AI Forms API key not provided in request) (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    if($_REQUEST['apikey'] != $api_key)
                                    {
                                        aiomatic_log_to_file('Halting execution (OmniBLock AI Forms invalid API key provided in request) (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                }
                                if (isset($_GET['apikey'])) {
                                    unset($_GET['apikey']);
                                }
                                if (isset($_POST['apikey'])) {
                                    unset($_POST['apikey']);
                                }
                                if (isset($_REQUEST['apikey'])) {
                                    unset($_REQUEST['apikey']);
                                }
                                if (isset($_GET['omniblockid'])) {
                                    unset($_GET['omniblockid']);
                                }
                                if (isset($_POST['omniblockid'])) {
                                    unset($_POST['omniblockid']);
                                }
                                if (isset($_REQUEST['omniblockid'])) {
                                    unset($_REQUEST['omniblockid']);
                                }
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    aiomatic_log_to_file('Getting OmniBlock AI Forms Data (from inside a successful OmniBlock AI Forms request)');
                                }
                                if (isset($_REQUEST['input'])) 
                                {
                                    $block_results[$block_id] = array($current_block['type'], $_REQUEST['input']);
                                }
                                else
                                {
                                    $block_results[$block_id] = array($current_block['type'], $_REQUEST);
                                }
                            }
                        }
                        elseif($current_block['type'] == 'ai_chatbot_omniblock')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Getting OmniBlock AI Chatbot Data'));
                            if(empty($omniWebhookID) || $omniWebhookID != $block_id)
                            {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    aiomatic_log_to_file('This request was not called from an AI Chatbot, this OmniBlock will always return an empty string');
                                }
                                $block_results[$block_id] = array($current_block['type'], array());
                            }
                            else
                            {
                                if (isset($_GET['omniblockid'])) {
                                    unset($_GET['omniblockid']);
                                }
                                if (isset($_POST['omniblockid'])) {
                                    unset($_POST['omniblockid']);
                                }
                                if (isset($_REQUEST['omniblockid'])) {
                                    unset($_REQUEST['omniblockid']);
                                }
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    aiomatic_log_to_file('Getting OmniBlock AI Chatbot Data (from inside a successful OmniBlock AI Chatbot request)');
                                }
                                if (isset($_REQUEST['input'])) 
                                {
                                    $block_results[$block_id] = array($current_block['type'], $_REQUEST['input']);
                                }
                                else
                                {
                                    $block_results[$block_id] = array($current_block['type'], $_REQUEST);
                                }
                            }
                        }
                        elseif($current_block['type'] == 'wp_event_trigger')
                        {
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'OmniBlock WordPress Event Trigger'));
                            if(empty($omniWebhookID) || $omniWebhookID != $block_id)
                            {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    aiomatic_log_to_file('OmniBlock WordPress Event Trigger (this request was not called from a WordPress Event, this OmniBlock will always return an empty string)');
                                }
                                $block_results[$block_id] = array($current_block['type'], array());
                            }
                            else
                            {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    aiomatic_log_to_file('OmniBlock WordPress Event Trigger (running from inside a valid WordPress event context)');
                                }
                                $event_params = array_values($event_context ?? []);
                                $prepared_data = [];

                                for ($i = 0; $i < 10; $i++) {
                                    $key = 'event_param' . ($i + 1) . '_';
                                    $value = $event_params[$i] ?? '';
                                    if (!is_scalar($value)) {
                                        $value = json_encode($value);
                                    }
                                    $prepared_data[$key] = $value;
                                }

                                $block_results[$block_id] = array($current_block['type'], $prepared_data);
                            }
                        }
                        elseif($current_block['type'] == 'crawl_sites')
                        {
                            $url = $current_block['parameters']['url'];
                            $url = aiomatic_replace_omniblocks_data($url, $current_keyword, $kiwis, $block_results, $load_variables);
                            $url = preg_split('/\r\n|\r|\n/', trim($url));
                            $url = array_filter($url);
                            $max_chars = $current_block['parameters']['max_chars'];
                            if(empty($url))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty scraper url), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('No URLs found in scraper input (ID ' . esc_html($block_id) . ')');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                            else
                            {
                                $url = stripslashes($url[array_rand($url)]);
                                $scrape_method = $current_block['parameters']['scrape_method'];
                                $scrape_selector = $current_block['parameters']['scrape_selector'];
                                $scrape_string = $current_block['parameters']['scrape_string'];
                                $strip_tags = $current_block['parameters']['strip_tags'];
                                aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock website scraping results'));
                                $scraped_data = '';
                                if (isset($aiomatic_Main_Settings['omni_caching']) && trim($aiomatic_Main_Settings['omni_caching']) == 'on')
                                {
                                    if(isset($omni_cache['scrape' . $url . $scrape_method . $scrape_selector . $scrape_string]))
                                    {
                                        $scraped_data = $omni_cache['scrape' . $url . $scrape_method . $scrape_selector . $scrape_string];
                                    }
                                }
                                if(empty($scraped_data))
                                {
                                    $scraped_data = aiomatic_scrape_page($url, $scrape_method, $scrape_selector, $scrape_string);
                                }
                                if($scraped_data === false)
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (scraping error), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to scrape URL (ID ' . esc_html($block_id) . ')');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                    }
                                }
                                else
                                {
                                    if (isset($aiomatic_Main_Settings['omni_caching']) && trim($aiomatic_Main_Settings['omni_caching']) == 'on')
                                    {
                                        if(!isset($omni_cache['scrape' . $url . $scrape_method . $scrape_selector . $scrape_string]))
                                        {
                                            $omni_cache['scrape' . $url . $scrape_method . $scrape_selector . $scrape_string] = $scraped_data;
                                        }
                                    }
                                    if($strip_tags == '1')
                                    {
                                        $scraped_data = wp_strip_all_tags($scraped_data);
                                    }
                                    else
                                    {
                                        $scraped_data = aiomatic_fix_relative_links($scraped_data, $url);
                                    }
                                    if(!empty($max_chars) && is_numeric($max_chars))
                                    {
                                        $scraped_data = (aiomatic_strlen($scraped_data) > intval($max_chars)) ? aiomatic_substr($scraped_data, 0, intval($max_chars)) : $scraped_data;
                                    }
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array($scraped_data, aiomatic_removeDuplicateNewLines(wp_strip_all_tags($scraped_data)));
                                    }
                                    $block_results[$block_id] = array($current_block['type'], $scraped_data);
                                }
                            }
                        }
                        elseif($current_block['type'] == 'crawl_rss')
                        {
                            $final_res = '';
                            if (isset($aiomatic_Main_Settings['omni_fpenalty']) && trim($aiomatic_Main_Settings['omni_fpenalty']) != '')
                            {
                                $frequency_penalty = floatval($aiomatic_Main_Settings['omni_fpenalty']);
                            } 
                            else 
                            {
                                $frequency_penalty = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_ppenalty']) && trim($aiomatic_Main_Settings['omni_ppenalty']) != '')
                            {
                                $presence_penalty = floatval($aiomatic_Main_Settings['omni_ppenalty']);
                            } 
                            else 
                            {
                                $presence_penalty = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_top_p']) && trim($aiomatic_Main_Settings['omni_top_p']) != '')
                            {
                                $max_p = floatval($aiomatic_Main_Settings['omni_top_p']);
                            } 
                            else 
                            {
                                $max_p = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_temperature']) && trim($aiomatic_Main_Settings['omni_temperature']) != '')
                            {
                                $temperature = floatval($aiomatic_Main_Settings['omni_temperature']);
                            } 
                            else 
                            {
                                $temperature = '';
                            }
                            $rss_feeds = array();
                            $url = $current_block['parameters']['url'];
                            $url = aiomatic_replace_omniblocks_data($url, $current_keyword, $kiwis, $block_results, $load_variables);
                            $scrape = $current_block['parameters']['scrape'];
                            $scrape_method = $current_block['parameters']['scrape_method'];
                            $max_chars = $current_block['parameters']['max_chars'];
                            $prompt = $current_block['parameters']['prompt'];
                            $prompt = aiomatic_replace_omniblocks_data($prompt, $current_keyword, $kiwis, $block_results, $load_variables);
                            $model = $current_block['parameters']['model'];
                            $assistant_id = $current_block['parameters']['assistant_id'];
                            if (empty($url)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty RSS URL entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty RSS feed URL entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $template = $current_block['parameters']['template'];
                            $template = aiomatic_replace_omniblocks_data($template, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($template)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty RSS template entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty RSS feed template entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $max_items = $current_block['parameters']['max_items'];
                            if(!empty($max_items))
                            {
                                $max_items = intval($max_items);
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock RSS feed scraping results'));
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('Trying to parse RSS feed items: ' . $url);
                            }
                            try
                            {
                                if(!class_exists('SimplePie_Autoloader', false))
                                {
                                    require_once(dirname(__FILE__) . "/res/simplepie/autoloader.php");
                                }
                            }
                            catch(Exception $e) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (failed to load RSS parser), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to load RSS parser (ID ' . esc_html($block_id) . ')');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $items = false;
                            if (isset($aiomatic_Main_Settings['omni_caching']) && trim($aiomatic_Main_Settings['omni_caching']) == 'on')
                            {
                                if(isset($omni_cache['rss' . $url]))
                                {
                                    $items = $omni_cache['rss' . $url];
                                }
                            }
                            if(empty($items))
                            {
                                $feed = new SimplePie();
                                $feed->set_timeout(120);
                                $feed->set_feed_url($url);
                                $feed->enable_cache(false);
                                $feed->strip_htmltags(false);
                                $feed->init();
                                $feed->handle_content_type();
                                if ($feed->error()) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (error in parsing RSS feed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Error in parsing RSS feed: ' . $feed->error() . ' for ' . $url);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                        continue;
                                    }
                                }
                                $items = $feed->get_items();
                                if (isset($aiomatic_Main_Settings['omni_caching']) && trim($aiomatic_Main_Settings['omni_caching']) == 'on')
                                {
                                    if(!isset($omni_cache['rss' . $url]))
                                    {
                                        $omni_cache['rss' . $url] = $items;
                                    }
                                }
                            }
                            if(!empty($items))
                            {
                                foreach($items as $itemx)
                                {
                                    $post_link = trim($itemx->get_permalink());
                                    if ($fauthor = $itemx->get_author()) 
                                    {
                                        $user_name = $fauthor->get_name();
                                    }
                                    else
                                    {
                                        $user_name = '';
                                    }
                                    $feed_cats = array();
                                    $varx = $itemx->get_categories();
                                    if(is_array($varx))
                                    {
                                        foreach ($varx as $xcategory)
                                        {
                                            $feed_cats[] = $xcategory->get_label();
                                        }
                                    }
                                    $post_cats = implode(',', $feed_cats);
                                    $post_excerpt = $itemx->get_description();
                                    $final_content = $itemx->get_content();
                                    $rss_feeds[$itemx->get_title()] = array('url' => $post_link, 'author' => $user_name,  'cats' => $post_cats, 'excerpt' => $post_excerpt, 'content' => $final_content );
                                }
                            }
                            $template_copy = '';
                            $processed = 0;
                            foreach($rss_feeds as $rtitle => $this_rss)
                            {
                                if(!empty($max_items) && $processed >= $max_items)
                                {
                                    break;
                                }
                                $scraped_data = '';
                                if($scrape == '1' && strstr($template, '%%item_scraped_data%%') !== false)
                                {
                                    $scraped_data = aiomatic_scrape_page($this_rss['url'], $scrape_method, 'auto', '');
                                    if($scraped_data === false)
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (RSS scraping error), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to scrape URL ' . $this_rss['url'] . ' (ID ' . esc_html($block_id) . ')');
                                        }
                                        $scraped_data = '';
                                    }
                                    else
                                    {
                                        if(!empty($max_chars) && is_numeric($max_chars))
                                        {
                                            $scraped_data = (aiomatic_strlen($scraped_data) > intval($max_chars)) ? aiomatic_substr($scraped_data, 0, intval($max_chars)) : $scraped_data;
                                        }
                                    }
                                }
                                $template_copy = $template;
                                $template_copy = str_replace('%%item_counter%%', $processed + 1, $template_copy);
                                $template_copy = str_replace('%%item_title%%', $rtitle, $template_copy);
                                $template_copy = str_replace('%%item_content%%', $this_rss['content'], $template_copy);
                                $template_copy = str_replace('%%item_description%%', $this_rss['excerpt'], $template_copy);
                                $template_copy = str_replace('%%item_url%%', $this_rss['url'], $template_copy);
                                $template_copy = str_replace('%%item_author%%', $this_rss['author'], $template_copy);
                                $template_copy = str_replace('%%item_categories%%', $this_rss['cats'], $template_copy);
                                $template_copy = str_replace('%%item_scraped_data%%', $scraped_data, $template_copy);
                                if(!empty($prompt) && !empty($template_copy))
                                {
                                    $prompt_copy = $prompt;
                                    if(!strstr($prompt_copy, '%%current_item%%'))
                                    {
                                        $prompt_copy .= '\n' . $template_copy;
                                    }
                                    else
                                    {
                                        $prompt_copy = str_replace('%%current_item%%', $template_copy, $prompt_copy);
                                    }
                                    $max_tokens = aimogenpro_get_max_tokens($model);
                                    $query_token_count = count(aiomatic_encode($prompt_copy));
                                    $available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $prompt_copy, $query_token_count);
                                    if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                    {
                                        $string_len = aiomatic_strlen($prompt_copy);
                                        $string_len = $string_len / 2;
                                        $string_len = intval(0 - $string_len);
                                        $prompt_copy = aiomatic_substr($prompt_copy, 0, $string_len);
                                        $prompt_copy = trim($prompt_copy);
                                        $query_token_count = count(aiomatic_encode($prompt_copy));
                                        $available_tokens = $max_tokens - $query_token_count;
                                    }
                                    $aierror = '';
                                    $finish_reason = '';
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = aiomatic_get_api_service($token, $model);
                                        aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for OmniBlock RSS item processing ID: ' . $block_id);
                                        aiomatic_log_to_file('AI Prompt is: ' . $prompt_copy);
                                    }
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock AI RSS item content'));
                                    $generated_text = aiomatic_generate_text($token, $model, $prompt_copy, $available_tokens, $temperature, $max_p, $presence_penalty, $frequency_penalty, false, 'omniBlocksWriter', 0, $finish_reason, $aierror, false, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                    if($generated_text === false || empty($generated_text))
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (AI generated RSS text failed), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate non-critical OmniBlock content using AI writer (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type'], '');
                                        }
                                    }
                                    else
                                    {
                                        if(!empty($generated_text))
                                        {
                                            $template_copy = $generated_text;
                                        }
                                    }
                                }
                                if(!empty($template_copy))
                                {
                                    $final_res .= $template_copy . PHP_EOL;
                                }
                                $processed++;
                            }
                            if($final_res == '')
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (no rss data returned), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('No data returned after parsing RSS feed: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($final_res);
                                }
                                $block_results[$block_id] = array($current_block['type'], $final_res);
                            }
                        }
                        elseif($current_block['type'] == 'google_search')
                        {
                            if (isset($aiomatic_Main_Settings['omni_fpenalty']) && trim($aiomatic_Main_Settings['omni_fpenalty']) != '')
                            {
                                $frequency_penalty = floatval($aiomatic_Main_Settings['omni_fpenalty']);
                            } 
                            else 
                            {
                                $frequency_penalty = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_ppenalty']) && trim($aiomatic_Main_Settings['omni_ppenalty']) != '')
                            {
                                $presence_penalty = floatval($aiomatic_Main_Settings['omni_ppenalty']);
                            } 
                            else 
                            {
                                $presence_penalty = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_top_p']) && trim($aiomatic_Main_Settings['omni_top_p']) != '')
                            {
                                $max_p = floatval($aiomatic_Main_Settings['omni_top_p']);
                            } 
                            else 
                            {
                                $max_p = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_temperature']) && trim($aiomatic_Main_Settings['omni_temperature']) != '')
                            {
                                $temperature = floatval($aiomatic_Main_Settings['omni_temperature']);
                            } 
                            else 
                            {
                                $temperature = '';
                            }
                            $keyword = $current_block['parameters']['keyword'];
                            $keyword = aiomatic_replace_omniblocks_data($keyword, $current_keyword, $kiwis, $block_results, $load_variables);
                            $locale = $current_block['parameters']['locale'];
                            $locale = aiomatic_replace_omniblocks_data($locale, $current_keyword, $kiwis, $block_results, $load_variables);
                            $template = $current_block['parameters']['template'];
                            $template = aiomatic_replace_omniblocks_data($template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $scrape = $current_block['parameters']['scrape'];
                            $scrape_method = $current_block['parameters']['scrape_method'];
                            $max_chars = $current_block['parameters']['max_chars'];
                            $prompt = '';
                            if(isset($current_block['parameters']['prompt']))
                            {
                                $prompt = $current_block['parameters']['prompt'];
                            }
                            $prompt = aiomatic_replace_omniblocks_data($prompt, $current_keyword, $kiwis, $block_results, $load_variables);
                            $model = AIMOGEN_DEFAULT_MODEL;
                            if(isset($current_block['parameters']['model']))
                            {
                                $model = $current_block['parameters']['model'];
                            }
                            $assistant_id = '';
                            if(isset($current_block['parameters']['assistant_id']))
                            {
                                $assistant_id = $current_block['parameters']['assistant_id'];
                            }
                            if(empty($locale))
                            {
                                if (isset($aiomatic_Main_Settings['internet_gl']) && $aiomatic_Main_Settings['internet_gl'] != '')
                                {
                                    $locale = $aiomatic_Main_Settings['internet_gl'];
                                }
                            }
                            $final_res = '';
                            if (empty($template)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty search results template entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty search results template entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $max_items = $current_block['parameters']['max_items'];
                            if(!empty($max_items))
                            {
                                $max_items = intval($max_items);
                            }
                            if (empty($keyword)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty Google search keyword entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty Google search keyword entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock Google Search results'));
                            $internet_rez = aiomatic_internet_result($keyword, true, $locale);
                            $processed = 0;
                            foreach($internet_rez as $emb)
                            {
                                if(!empty($max_items) && $processed >= $max_items)
                                {
                                    break;
                                }
                                $scraped_data = '';
                                if($scrape == '1' && strstr($template, '%%item_scraped_data%%') !== false)
                                {
                                    $scraped_data = aiomatic_scrape_page($emb['link'], $scrape_method, 'auto', '');
                                    if($scraped_data === false)
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (SERP scraping error), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to scrape URL ' . $emb['link'] . ' (ID ' . esc_html($block_id) . ')');
                                        }
                                        $scraped_data = '';
                                    }
                                    else
                                    {
                                        if(!empty($max_chars) && is_numeric($max_chars))
                                        {
                                            $scraped_data = (aiomatic_strlen($scraped_data) > intval($max_chars)) ? aiomatic_substr($scraped_data, 0, intval($max_chars)) : $scraped_data;
                                        }
                                    }
                                }
                                $template_copy = $template;
                                $template_copy = str_replace('%%item_counter%%', $processed + 1, $template_copy);
                                $template_copy = str_replace('%%item_title%%', $emb['title'], $template_copy);
                                $template_copy = str_replace('%%item_snippet%%', $emb['snippet'], $template_copy);
                                $template_copy = str_replace('%%item_url%%', $emb['link'], $template_copy);
                                $template_copy = str_replace('%%item_scraped_data%%', $scraped_data, $template_copy);
                                if(!empty($prompt) && !empty($template_copy))
                                {
                                    $prompt_copy = $prompt;
                                    if(!strstr($prompt_copy, '%%current_item%%'))
                                    {
                                        $prompt_copy .= '\n' . $template_copy;
                                    }
                                    else
                                    {
                                        $prompt_copy = str_replace('%%current_item%%', $template_copy, $prompt_copy);
                                    }
                                    $max_tokens = aimogenpro_get_max_tokens($model);
                                    $query_token_count = count(aiomatic_encode($prompt_copy));
                                    $available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $prompt_copy, $query_token_count);
                                    if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                    {
                                        $string_len = aiomatic_strlen($prompt_copy);
                                        $string_len = $string_len / 2;
                                        $string_len = intval(0 - $string_len);
                                        $prompt_copy = aiomatic_substr($prompt_copy, 0, $string_len);
                                        $prompt_copy = trim($prompt_copy);
                                        $query_token_count = count(aiomatic_encode($prompt_copy));
                                        $available_tokens = $max_tokens - $query_token_count;
                                    }
                                    $aierror = '';
                                    $finish_reason = '';
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = aiomatic_get_api_service($token, $model);
                                        aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for OmniBlock SERP item processing ID: ' . $block_id);
                                        aiomatic_log_to_file('AI Prompt is: ' . $prompt_copy);
                                    }
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock AI SERP item content'));
                                    $generated_text = aiomatic_generate_text($token, $model, $prompt_copy, $available_tokens, $temperature, $max_p, $presence_penalty, $frequency_penalty, false, 'omniBlocksWriter', 0, $finish_reason, $aierror, false, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                    if($generated_text === false || empty($generated_text))
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (AI generated SERP text failed), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to generate non-critical OmniBlock content using AI writer (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type'], '');
                                        }
                                    }
                                    else
                                    {
                                        if(!empty($generated_text))
                                        {
                                            $template_copy = $generated_text;
                                        }
                                    }
                                }
                                $final_res .= $template_copy . PHP_EOL;
                                $processed++;
                            }
                            if($final_res == '')
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (no search results data found), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('No data returned after parsing search results: ' . $keyword);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($final_res);
                                }
                                $block_results[$block_id] = array($current_block['type'], $final_res);
                            }
                        }
                        elseif($current_block['type'] == 'amazon_product')
                        {
                            $asin = $current_block['parameters']['asin'];
                            $asin = aiomatic_replace_omniblocks_data($asin, $current_keyword, $kiwis, $block_results, $load_variables);
                            $aff_id = $current_block['parameters']['aff_id'];
                            $aff_id = aiomatic_replace_omniblocks_data($aff_id, $current_keyword, $kiwis, $block_results, $load_variables);
                            $target_country = $current_block['parameters']['target_country'];
                            $target_country = aiomatic_replace_omniblocks_data($target_country, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($asin)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty search results asin entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty search results asin entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
                                    continue;
                                }
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock Amazon product details'));
                            
                            $max_prod = 1;
                            $amazresult = aiomatic_amazon_get_post($asin, trim($aff_id), $target_country, '', '', '', $max_prod, '1', array());
                            if(is_array($amazresult) && isset($amazresult['status']) && $amazresult['status'] == 'nothing')
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (No results found for keyword search), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('No results found for keyword search: ' . $asin);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
                                    continue;
                                }
                            }
                            if(!is_array($amazresult))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Empty response from Amazon), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty response from Amazon Reviews: ' . $asin);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
                                    continue;
                                }
                            }
                            if(is_array($amazresult) && count($amazresult) == 0)
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Empty results found for keyword search), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty results found for keyword search: ' . $asin);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
                                    continue;
                                }
                            }
                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                            {
                                return array($amazresult[0]->offer_title, $amazresult[0]->offer_desc, $amazresult[0]->offer_url, $amazresult[0]->offer_price, $amazresult[0]->product_list_price, $amazresult[0]->offer_img, $amazresult[0]->cart_url, $amazresult[0]->product_imgs, $amazresult[0]->product_imgs_html, implode(PHP_EOL, $amazresult[0]->item_reviews), $amazresult[0]->item_score, $amazresult[0]->language, $amazresult[0]->edition, $amazresult[0]->pages_count, $amazresult[0]->publication_date, $amazresult[0]->contributors, $amazresult[0]->manufacturer, $amazresult[0]->binding, $amazresult[0]->product_group, $amazresult[0]->rating, $amazresult[0]->eans, $amazresult[0]->part_no, $amazresult[0]->model, $amazresult[0]->warranty, $amazresult[0]->color, $amazresult[0]->is_adult, $amazresult[0]->dimensions, $amazresult[0]->date, $amazresult[0]->size, $amazresult[0]->unit_count);
                            }
                            $block_results[$block_id] = array($current_block['type'], $amazresult[0]->offer_title, $amazresult[0]->offer_desc, $amazresult[0]->offer_url, $amazresult[0]->offer_price, $amazresult[0]->product_list_price, $amazresult[0]->offer_img, $amazresult[0]->cart_url, $amazresult[0]->product_imgs, $amazresult[0]->product_imgs_html, implode(PHP_EOL, $amazresult[0]->item_reviews), $amazresult[0]->item_score, $amazresult[0]->language, $amazresult[0]->edition, $amazresult[0]->pages_count, $amazresult[0]->publication_date, $amazresult[0]->contributors, $amazresult[0]->manufacturer, $amazresult[0]->binding, $amazresult[0]->product_group, $amazresult[0]->rating, $amazresult[0]->eans, $amazresult[0]->part_no, $amazresult[0]->model, $amazresult[0]->warranty, $amazresult[0]->color, $amazresult[0]->is_adult, $amazresult[0]->dimensions, $amazresult[0]->date, $amazresult[0]->size, $amazresult[0]->unit_count);
                        }
                        elseif($current_block['type'] == 'amazon_listing')
                        {
                            $asin = $current_block['parameters']['asin'];
                            $asin = aiomatic_replace_omniblocks_data($asin, $current_keyword, $kiwis, $block_results, $load_variables);
                            $aff_id = $current_block['parameters']['aff_id'];
                            $aff_id = aiomatic_replace_omniblocks_data($aff_id, $current_keyword, $kiwis, $block_results, $load_variables);
                            $target_country = $current_block['parameters']['target_country'];
                            $target_country = aiomatic_replace_omniblocks_data($target_country, $current_keyword, $kiwis, $block_results, $load_variables);
                            $max_product_count = $current_block['parameters']['max_product_count'];
                            $max_product_count = aiomatic_replace_omniblocks_data($max_product_count, $current_keyword, $kiwis, $block_results, $load_variables);
                            if(isset($current_block['parameters']['sort_results']))
                            {
                                $amaz_sort_results = $current_block['parameters']['sort_results'];
                            }
                            else
                            {
                                $amaz_sort_results = '';
                            }
                            if(strstr($max_product_count, '-') !== false)
                            {
                                $pr_arr = explode('-', $max_product_count);
                                $minx = trim($pr_arr[0]);
                                $maxx = trim($pr_arr[1]);
                                if(is_numeric($minx) && is_numeric($maxx))
                                {
                                    $max_product_count = wp_rand(intval($minx), intval($maxx));
                                }
                                else
                                {
                                    if(is_numeric($minx))
                                    {
                                        $max_product_count = intval($minx);
                                    }
                                    elseif(is_numeric($maxx))
                                    {
                                        $max_product_count = intval($maxx);
                                    }
                                    else
                                    {
                                        $max_product_count = 100;
                                    }
                                }
                            }
                            $listing_template = $current_block['parameters']['listing_template'];
                            $listing_template = aiomatic_replace_omniblocks_data($listing_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($asin)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty search results asin entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty search results asin entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            if (empty($listing_template)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty search listing_template entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty search listing_template entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock Amazon product listings'));
                            if(!empty($max_product_count) && is_numeric($max_product_count))
                            {
                                $max_prod = intval($max_product_count);
                            }
                            else
                            {
                                $max_prod = 100;
                            }
                            $amazresult = aiomatic_amazon_get_post($asin, trim($aff_id), $target_country, '', '', $amaz_sort_results, $max_prod, '1', array());
                            if(is_array($amazresult) && isset($amazresult['status']) && $amazresult['status'] == 'nothing')
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (No results found for keyword search), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('No results found for keyword search: ' . $asin);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            if(!is_array($amazresult))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Empty response from Amazon), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty response from Amazon Listing: ' . $asin);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            if(is_array($amazresult) && count($amazresult) == 0)
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Empty results found for keyword search), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty results found for keyword search: ' . $asin);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $final_result = '';
                            $counter = 1;
                            foreach($amazresult as $myprod)
                            {
                                $copy_template = $listing_template;
                                $copy_template = str_replace('%%product_counter%%', $counter, $copy_template);
                                $copy_template = str_replace('%%product_title%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_title)), $copy_template);
                                $copy_template = str_replace('%%product_description%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_desc)), $copy_template);
                                $copy_template = str_replace('%%product_url%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_url)), $copy_template);
                                $copy_template = str_replace('%%product_price%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_price)), $copy_template);
                                $copy_template = str_replace('%%product_list_price%%', trim(preg_replace('/\s+/', ' ', $myprod->product_list_price)), $copy_template);
                                $copy_template = str_replace('%%product_image%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_img)), $copy_template);
                                $copy_template = str_replace('%%product_cart_url%%', trim(preg_replace('/\s+/', ' ', $myprod->cart_url)), $copy_template);
                                $copy_template = str_replace('%%product_images_urls%%', trim(preg_replace('/\s+/', ' ', $myprod->product_imgs)), $copy_template);
                                $copy_template = str_replace('%%product_images%%', trim(preg_replace('/\s+/', ' ', $myprod->product_imgs_html)), $copy_template);
                                $copy_template = str_replace('%%product_reviews%%', trim(preg_replace('/\s+/', ' ', implode(PHP_EOL, $myprod->item_reviews))), $copy_template);
                                //new
                                $copy_template = str_replace('%%product_score%%', $myprod->item_score, $copy_template);
                                $copy_template = str_replace('%%product_edition%%', $myprod->edition, $copy_template);
                                $copy_template = str_replace('%%product_language%%', $myprod->language, $copy_template);
                                $copy_template = str_replace('%%product_pages_count%%', $myprod->pages_count, $copy_template);
                                $copy_template = str_replace('%%product_publication_date%%', $myprod->publication_date, $copy_template);
                                $copy_template = str_replace('%%product_contributors%%', $myprod->contributors, $copy_template);
                                $copy_template = str_replace('%%product_manufacturer%%', $myprod->manufacturer, $copy_template);
                                $copy_template = str_replace('%%product_binding%%', $myprod->binding, $copy_template);
                                $copy_template = str_replace('%%product_product_group%%', $myprod->product_group, $copy_template);
                                $copy_template = str_replace('%%product_rating%%', $myprod->rating, $copy_template);
                                $copy_template = str_replace('%%product_ean%%', $myprod->eans, $copy_template);
                                $copy_template = str_replace('%%product_part_no%%', $myprod->part_no, $copy_template);
                                $copy_template = str_replace('%%product_model%%', $myprod->model, $copy_template);
                                $copy_template = str_replace('%%product_warranty%%', $myprod->warranty, $copy_template);
                                $copy_template = str_replace('%%product_color%%', $myprod->color, $copy_template);
                                $copy_template = str_replace('%%product_is_adult%%', $myprod->is_adult, $copy_template);
                                $copy_template = str_replace('%%product_dimensions%%', $myprod->dimensions, $copy_template);
                                $copy_template = str_replace('%%product_date%%', $myprod->date, $copy_template);
                                $copy_template = str_replace('%%product_size%%', $myprod->size, $copy_template);
                                $copy_template = str_replace('%%product_unit_count%%', $myprod->unit_count, $copy_template);
                                $counter++;
                                $final_result .= $copy_template . '\r\n'; 
                            }
                            $final_result = trim($final_result);
                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                            {
                                return array($final_result);
                            }
                            $block_results[$block_id] = array($current_block['type'], $final_result);
                        }
                        elseif($current_block['type'] == 'clickbank_listing')
                        {
                            $asin = $current_block['parameters']['asin'];
                            $asin = aiomatic_replace_omniblocks_data($asin, $current_keyword, $kiwis, $block_results, $load_variables);
                            $aff_id = $current_block['parameters']['aff_id'];
                            $aff_id = aiomatic_replace_omniblocks_data($aff_id, $current_keyword, $kiwis, $block_results, $load_variables);
                            $neg_keywords = $current_block['parameters']['neg_keywords'];
                            $neg_keywords = aiomatic_replace_omniblocks_data($neg_keywords, $current_keyword, $kiwis, $block_results, $load_variables);
                            $dollar_sale = $current_block['parameters']['dollar_sale'];
                            $dollar_sale = aiomatic_replace_omniblocks_data($dollar_sale, $current_keyword, $kiwis, $block_results, $load_variables);
                            $dollar_sale_av = $current_block['parameters']['dollar_sale_av'];
                            $dollar_sale_av = aiomatic_replace_omniblocks_data($dollar_sale_av, $current_keyword, $kiwis, $block_results, $load_variables);
                            $activation = $current_block['parameters']['activation'];
                            $activation = aiomatic_replace_omniblocks_data($activation, $current_keyword, $kiwis, $block_results, $load_variables);
                            $listing_template = $current_block['parameters']['listing_template'];
                            $listing_template = aiomatic_replace_omniblocks_data($listing_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $max_product_count = $current_block['parameters']['max_product_count'];
                            $max_product_count = aiomatic_replace_omniblocks_data($max_product_count, $current_keyword, $kiwis, $block_results, $load_variables);
                            if(strstr($max_product_count, '-') !== false)
                            {
                                $pr_arr = explode('-', $max_product_count);
                                $minx = trim($pr_arr[0]);
                                $maxx = trim($pr_arr[1]);
                                if(is_numeric($minx) && is_numeric($maxx))
                                {
                                    $max_product_count = wp_rand(intval($minx), intval($maxx));
                                }
                                else
                                {
                                    if(is_numeric($minx))
                                    {
                                        $max_product_count = intval($minx);
                                    }
                                    elseif(is_numeric($maxx))
                                    {
                                        $max_product_count = intval($maxx);
                                    }
                                    else
                                    {
                                        $max_product_count = 100;
                                    }
                                }
                            }
                            if (empty($asin)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty search results asin entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty search results asin entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            if (empty($listing_template)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty search listing_template entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty search listing_template entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock ClickBank product listings'));
                            if(!empty($max_product_count) && is_numeric($max_product_count))
                            {
                                $max_prod = intval($max_product_count);
                            }
                            else
                            {
                                $max_prod = 20;
                            }
                            $item_category = 'All';
                            $shipable_only = '';
                            $pitch_plus = '';
                            $one_time = '';
                            $recurring = '';
                            $affiliate_tools = '';
                            $spotlight = '';
                            $mobile_hoplink = '';
                            $item_language = '';
                            $item_gravity = '';
                            $rebill_total = '';
                            $per_sale = '';
                            $per_rebill = '';
                            $sort_results_cb = '';
                            $amazresult = aiomatic_clickbank_get_post($aff_id, $asin, $neg_keywords, $item_category, $shipable_only, $pitch_plus, $one_time, $recurring, $affiliate_tools, $spotlight, $mobile_hoplink, $item_language, $activation, $item_gravity, $dollar_sale, $dollar_sale_av, $rebill_total, $per_sale, $per_rebill, $sort_results_cb, $max_prod);
                            if(is_array($amazresult) && isset($amazresult['status']) && $amazresult['status'] == 'nothing')
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (No results found for keyword search), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('No results found for keyword search: ' . $asin);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            if(!is_array($amazresult))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Empty response from ClickBank), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty response from ClickBank Listing: ' . $asin);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            if(is_array($amazresult) && count($amazresult) == 0)
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Empty results found for keyword search), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty results found for keyword search: ' . $asin);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $final_result = '';
                            $counter = 1;
                            foreach($amazresult as $myprod)
                            {
                                $copy_template = $listing_template;
                                $copy_template = str_replace('%%product_counter%%', $counter, $copy_template);
                                $copy_template = str_replace('%%product_title%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_title)), $copy_template);
                                $copy_template = str_replace('%%product_description%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_desc)), $copy_template);
                                $copy_template = str_replace('%%product_url%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_url)), $copy_template);
                                $copy_template = str_replace('%%product_price%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_price)), $copy_template);
                                $copy_template = str_replace('%%product_list_price%%', trim(preg_replace('/\s+/', ' ', $myprod->product_list_price)), $copy_template);
                                $copy_template = str_replace('%%product_image%%', trim(preg_replace('/\s+/', ' ', $myprod->offer_img)), $copy_template);
                                $copy_template = str_replace('%%product_cart_url%%', trim(preg_replace('/\s+/', ' ', $myprod->cart_url)), $copy_template);
                                $copy_template = str_replace('%%product_images_urls%%', trim(preg_replace('/\s+/', ' ', $myprod->product_imgs)), $copy_template);
                                $copy_template = str_replace('%%product_images%%', trim(preg_replace('/\s+/', ' ', $myprod->product_imgs_html)), $copy_template);
                                $copy_template = str_replace('%%product_reviews%%', trim(preg_replace('/\s+/', ' ', implode(PHP_EOL, $myprod->item_reviews))), $copy_template);
                                //new
                                $copy_template = str_replace('%%product_score%%', $myprod->item_score, $copy_template);
                                $copy_template = str_replace('%%product_edition%%', $myprod->edition, $copy_template);
                                $copy_template = str_replace('%%product_language%%', $myprod->language, $copy_template);
                                $copy_template = str_replace('%%product_pages_count%%', $myprod->pages_count, $copy_template);
                                $copy_template = str_replace('%%product_publication_date%%', $myprod->publication_date, $copy_template);
                                $copy_template = str_replace('%%product_contributors%%', $myprod->contributors, $copy_template);
                                $copy_template = str_replace('%%product_manufacturer%%', $myprod->manufacturer, $copy_template);
                                $copy_template = str_replace('%%product_binding%%', $myprod->binding, $copy_template);
                                $copy_template = str_replace('%%product_product_group%%', $myprod->product_group, $copy_template);
                                $copy_template = str_replace('%%product_rating%%', $myprod->rating, $copy_template);
                                $copy_template = str_replace('%%product_ean%%', $myprod->eans, $copy_template);
                                $copy_template = str_replace('%%product_part_no%%', $myprod->part_no, $copy_template);
                                $copy_template = str_replace('%%product_model%%', $myprod->model, $copy_template);
                                $copy_template = str_replace('%%product_warranty%%', $myprod->warranty, $copy_template);
                                $copy_template = str_replace('%%product_color%%', $myprod->color, $copy_template);
                                $copy_template = str_replace('%%product_is_adult%%', $myprod->is_adult, $copy_template);
                                $copy_template = str_replace('%%product_dimensions%%', $myprod->dimensions, $copy_template);
                                $copy_template = str_replace('%%product_date%%', $myprod->date, $copy_template);
                                $copy_template = str_replace('%%product_size%%', $myprod->size, $copy_template);
                                $copy_template = str_replace('%%product_unit_count%%', $myprod->unit_count, $copy_template);
                                $counter++;
                                $final_result .= $copy_template . '\r\n'; 
                            }
                            $final_result = trim($final_result);
                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                            {
                                return array($final_result);
                            }
                            $block_results[$block_id] = array($current_block['type'], $final_result);
                        }
                        elseif($current_block['type'] == 'post_import')
                        {
                            $input_array = array();
                            $input_text = $current_block['parameters']['input_text'];
                            $input_text = aiomatic_replace_omniblocks_data($input_text, $current_keyword, $kiwis, $block_results, $load_variables);
                            $input_text = trim($input_text);
                            if (empty($input_text)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty post ID entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty post ID entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '', '', '', '', '', '', '', '', '', '', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '', '', '', '');
                                    continue;
                                }
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock post importing search results'));
                            if(!is_numeric($input_text))
                            {
                                if(strstr($input_text, '=') === false)
                                {
                                    $input_text = 's=' . $input_text;
                                }
                                if(aiomatic_substr($input_text, 0, 1) !== "&")
                                {
                                    $input_text = '&' . $input_text;
                                }
                                parse_str($input_text, $input_array);
                                if(isset($input_array['unique_tag']) && !empty($input_array['unique_tag']))
                                {
                                    $input_array['meta_key'] = 'aiomatic_unique_tag';
                                    $input_array['meta_value'] = $input_array['unique_tag'];
                                    $input_array['meta_compare'] = 'NOT EXISTS';
                                }
                                $the_query = new WP_Query($input_array);

                                if ($the_query->have_posts()) {
                                    $the_query->the_post();
                                    $input_text = get_the_ID();
                                    wp_reset_postdata();
                                } 
                                else 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (post search query not found), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Post search query not found: ' . trim($input_text));
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('', '', '', '', '', '', '', '', '', '', '', '');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '', '', '', '');
                                        continue;
                                    }
                                }
                            }
                            $returned_post = get_post(trim($input_text));
                            if($returned_post === null)
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (post ID not found), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Post ID not found: ' . trim($input_text));
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '', '', '', '', '', '', '', '', '', '', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '', '', '', '', '', '', '', '', '', '', '');
                                    continue;
                                }
                            }
                            $cats = array();
                            $categories = get_the_category($returned_post->ID);
                            foreach($categories as $thiscat)
                            {
                                $cats[] = $thiscat->slug;
                            }
                            $cats = implode(',', $cats);
                            $tags = array();
                            $categories = get_the_tags($returned_post->ID);
                            if(!is_wp_error($categories) && $categories !== false)
                            {
                                foreach($categories as $thiscat)
                                {
                                    $tags[] = $thiscat->slug;
                                }
                            }
                            $tags = implode(',', $tags);
                            $the_img = get_the_post_thumbnail_url($returned_post->ID);
                            if($the_img === false)
                            {
                                $the_img = '';
                            }
                            if(isset($input_array['unique_tag']) && !empty($input_array['unique_tag']))
                            {
                                update_post_meta($returned_post->ID, 'aiomatic_unique_tag', $input_array['unique_tag']);
                            }
                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                            {
                                return array($returned_post->ID, get_post_permalink($returned_post->ID), $returned_post->post_title, $returned_post->post_content, $returned_post->post_excerpt, $cats, $tags, $returned_post->post_author, $returned_post->post_date, $returned_post->post_status, $returned_post->post_type, $the_img);
                            }
                            $block_results[$block_id] = array($current_block['type'], $returned_post->ID, get_post_permalink($returned_post->ID), $returned_post->post_title, $returned_post->post_content, $returned_post->post_excerpt, $cats, $tags, $returned_post->post_author, $returned_post->post_date, $returned_post->post_status, $returned_post->post_type, $the_img);
                        }
                        elseif($current_block['type'] == 'random_line')
                        {
                            $input_array = array();
                            $input_text = $current_block['parameters']['input_text'];
                            $input_text = aiomatic_replace_omniblocks_data($input_text, $current_keyword, $kiwis, $block_results, $load_variables);
                            $input_text = trim($input_text);
                            if (empty($input_text)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty input provided), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty input entered for random line OmniBlock');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock random line'));
                            $input_text_arr = preg_split('/\r\n|\r|\n/', $input_text);
                            $random_line = $input_text_arr[array_rand($input_text_arr)];
                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                            {
                                return array($random_line);
                            }
                            $block_results[$block_id] = array($current_block['type'], $random_line);
                        }
                        elseif($current_block['type'] == 'royalty_image')
                        {
                            $raw_img_list = array();
                            $full_result_list = array();
                            $query_words = $current_block['parameters']['input_text'];
                            $query_words = aiomatic_replace_omniblocks_data($query_words, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($query_words)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty keyword entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty royalty free keyword entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            if(isset($aiomatic_Main_Settings['attr_text']) && $aiomatic_Main_Settings['attr_text'] != '')
                            {
                                $img_attr = $aiomatic_Main_Settings['attr_text'];
                            }
                            else
                            {
                                $img_attr = '';
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock royalty free image results'));
                            $temp_get_img = aiomatic_get_free_image($aiomatic_Main_Settings, $query_words, $img_attr, $attached_id, 10, false, $raw_img_list, array(), $full_result_list);
                            if(!empty($attached_id))
                            {
                                $additional_attachments[] = $attached_id;
                            }
                            if($temp_get_img == '' || $temp_get_img === false)
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (failed to find royalty free image), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to find royalty free image for: ' . $query_words);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($temp_get_img);
                                }
                                $block_results[$block_id] = array($current_block['type'], $temp_get_img);
                            }
                        }
                        elseif($current_block['type'] == 'youtube_video')
                        {
                            $query_words = $current_block['parameters']['input_text'];
                            $query_words = aiomatic_replace_omniblocks_data($query_words, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($query_words)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty video keyword entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty YouTube video keyword entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '');
                                    continue;
                                }
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock YouTube video results'));
                            $new_vid = aiomatic_get_video($query_words, '', array());
                            if($new_vid !== false)
                            {
                                if (isset($aiomatic_Main_Settings['player_width']) && $aiomatic_Main_Settings['player_width'] !== '') {
                                    $vwidth = esc_attr($aiomatic_Main_Settings['player_width']);
                                }
                                else
                                {
                                    $vwidth = 580;
                                }
                                if (isset($aiomatic_Main_Settings['player_height']) && $aiomatic_Main_Settings['player_height'] !== '') {
                                    $vheight = esc_attr($aiomatic_Main_Settings['player_height']);
                                }
                                else
                                {
                                    $vheight = 380;
                                }
                                $vid_id = '';
                                preg_match_all('#"https:\/\/www\.youtube\.com\/embed\/([^"]*?)"#i', $new_vid, $zmatches);
                                if(isset($zmatches[1][0]))
                                {
                                    $vid_id = 'https://www.youtube.com/watch?v=' . $zmatches[1][0];
                                }
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($vid_id, $new_vid);
                                }
                                $block_results[$block_id] = array($current_block['type'], $vid_id, $new_vid);
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (failed to find YouTube video), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to find YouTube video for: ' . $query_words);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '');
                                    continue;
                                }
                            }
                        }
                        elseif($current_block['type'] == 'youtube_caption')
                        {
                            $url = $current_block['parameters']['url'];
                            $url = aiomatic_replace_omniblocks_data($url, $current_keyword, $kiwis, $block_results, $load_variables);
                            $url = aiomatic_extractYouTubeVideoId($url);
                            if (empty($url)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty YouTube URL entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty YouTube video URL entered: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '', '', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '', '', '');
                                    continue;
                                }
                            }
                            $max_caption = $current_block['parameters']['max_caption'];
                            if(!empty($max_caption))
                            {
                                $max_caption = intval($max_caption);
                            }
                            $default_lang = array();
                            $returned_caption = '';
                            $vid_title = '';
                            $vid_desc = '';
                            $youtube_thumb = '';
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating OmniBlock YouTube caption results'));
                            $za_video_page = '';
                            $ch  = curl_init();
                            if ($ch !== FALSE) 
                            {
                                if (isset($aiomatic_Main_Settings['proxy_url']) && $aiomatic_Main_Settings['proxy_url'] != '' && $aiomatic_Main_Settings['proxy_url'] != 'disable' && $aiomatic_Main_Settings['proxy_url'] != 'disabled') {
                                    $prx = explode(',', $aiomatic_Main_Settings['proxy_url']);
                                    $randomness = array_rand($prx);
                                    curl_setopt( $ch, CURLOPT_PROXY, trim($prx[$randomness]));
                                    if (isset($aiomatic_Main_Settings['proxy_auth']) && $aiomatic_Main_Settings['proxy_auth'] != '') 
                                    {
                                        $prx_auth = explode(',', $aiomatic_Main_Settings['proxy_auth']);
                                        if(isset($prx_auth[$randomness]) && trim($prx_auth[$randomness]) != '')
                                        {
                                            curl_setopt( $ch, CURLOPT_PROXYUSERPWD, trim($prx_auth[$randomness]));
                                        }
                                    }
                                }
                                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                                if (isset($aiomatic_Main_Settings['max_timeout']) && $aiomatic_Main_Settings['max_timeout'] != '')
                                {
                                    $ztime = intval($aiomatic_Main_Settings['max_timeout']);
                                }
                                else
                                {
                                    $ztime = 300;
                                }
                                if (isset($aiomatic_Main_Settings['youtube_cookies']) && $aiomatic_Main_Settings['youtube_cookies'] != '')
                                {
                                    curl_setopt($ch, CURLOPT_COOKIE, $aiomatic_Main_Settings['youtube_cookies']);
                                }
                                curl_setopt($ch, CURLOPT_TIMEOUT, $ztime);
                                curl_setopt($ch, CURLOPT_HTTPGET, 1);
                                curl_setopt($ch, CURLOPT_REFERER, get_site_url());
                                curl_setopt($ch, CURLOPT_URL, $url);
                                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                                $za_video_page = curl_exec($ch);
                                if($za_video_page === false)
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (failed to download video URL), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to download video URL: ' . $url);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('', '', '', '');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '', '', '', '');
                                        continue;
                                    }
                                }
                                curl_close($ch);
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (failed to init curl), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to init curl in YouTube caption importing: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '', '', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '', '', '');
                                    continue;
                                }
                            }
                            if($za_video_page !== false)
                            {
                                preg_match_all('#<meta name="title" content="([^"]*?)">#i', $za_video_page, $zmatches);
                                if(isset($zmatches[1][0]))
                                {
                                    $vid_title = $zmatches[1][0];
                                }
                                else
                                {
                                    preg_match_all('#<title>([^"]*?) - YouTube<\/title>#i', $za_video_page, $zmatches);
                                    if(isset($zmatches[1][0]))
                                    {
                                        $vid_title = $zmatches[1][0];
                                    }
                                    else
                                    {
                                        preg_match_all('#<meta property="og:title" content="([^"]*?)">#i', $za_video_page, $zmatches);
                                        if(isset($zmatches[1][0]))
                                        {
                                            $vid_title = $zmatches[1][0];
                                        }
                                        else
                                        {
                                            preg_match_all('#<meta property="twitter:title" content="([^"]*?)">#i', $za_video_page, $zmatches);
                                            if(isset($zmatches[1][0]))
                                            {
                                                $vid_title = $zmatches[1][0];
                                            }
                                            else
                                            {
                                                preg_match_all('#<meta itemprop="name" content="([^"]*?)">#i', $za_video_page, $zmatches);
                                                if(isset($zmatches[1][0]))
                                                {
                                                    $vid_title = $zmatches[1][0];
                                                }
                                            }
                                        }
                                    }
                                }
                                preg_match_all('#"description":{"simpleText":"([^"]*?)"#i', $za_video_page, $zmatches);
                                if(isset($zmatches[1][0]))
                                {
                                    $vid_desc = $zmatches[1][0];
                                }
                                else
                                {
                                    preg_match_all('#"attributedDescription":{"content":"([^"]*?)"#i', $za_video_page, $zmatches);
                                    if(isset($zmatches[1][0]))
                                    {
                                        $vid_desc = $zmatches[1][0];
                                    }
                                    else
                                    {
                                        preg_match_all('#"attributedDescriptionBodyText":{"content":"([^"]*?)"#i', $za_video_page, $zmatches);
                                        if(isset($zmatches[1][0]))
                                        {
                                            $vid_desc = $zmatches[1][0];
                                        }
                                        else
                                        {
                                            preg_match_all('#"shortDescription":"([^"]*?)"#i', $za_video_page, $zmatches);
                                            if(isset($zmatches[1][0]))
                                            {
                                                $vid_desc = $zmatches[1][0];
                                            }
                                        }
                                    }
                                }
                                $video_id = '';
                                preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user|shorts)\/))([^\?&\"'>]+)/", $video_url, $amatches);
                                if(isset($amatches[1]))
                                {
                                    $video_id = $amatches[1];
                                }
                                $caprez = false;
                                if(!empty($video_id))
                                {
                                    try
                                    {
                                        $caprez = aiomatic_get_video_transcript($video_id);
                                    }
                                    catch(Exception $e)
                                    {
                                        try 
                                        {
                                            $caprez = aiomatic_get_video_transcript_2($video_id);
                                        } 
                                        catch (Exception $e) 
                                        {
                                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                                aiomatic_log_to_file('Failed to get transcript for video ID ' . $video_id . ': ' . $e->getMessage());
                                            }
                                        }
                                    }
                                }
                                if(is_array($caprez) && isset($caprez['text']))
                                {
                                    $returned_caption = $caprez['text'];
                                }
                            }
                            if(empty($returned_caption))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Failed to find subtitles for video URL), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to find subtitles for video URL: ' . $url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '', '', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '', '', '');
                                    continue;
                                }
                            }
                            preg_match_all('#<link rel="image_src" href="([^"]*?)">#i', $za_video_page, $zmatches);
                            if(isset($zmatches[1][0]))
                            {
                                $youtube_thumb = $zmatches[1][0];
                            }
                            else
                            {
                                preg_match_all('#<meta property="og:image" content="([^"]*?)">#i', $za_video_page, $zmatches);
                                if(isset($zmatches[1][0]))
                                {
                                    $youtube_thumb = $zmatches[1][0];
                                }
                                else
                                {
                                    preg_match_all('#<meta name="twitter:image" content="([^"]*?)">#i', $za_video_page, $zmatches);
                                    if(isset($zmatches[1][0]))
                                    {
                                        $youtube_thumb = $zmatches[1][0];
                                    }
                                    else
                                    {
                                        preg_match_all('#<link itemprop="thumbnailUrl" href="([^"]*?)">#i', $za_video_page, $zmatches);
                                        if(isset($zmatches[1][0]))
                                        {
                                            $youtube_thumb = $zmatches[1][0];
                                        }
                                    }
                                }
                            }
                            if(!empty($max_caption) && aiomatic_strlen($returned_caption) > $max_caption)
                            {
                                $returned_caption = aiomatic_substr($returned_caption, 0, $max_caption);
                            }
                            if(!empty($max_caption) && aiomatic_strlen($vid_desc) > $max_caption)
                            {
                                $vid_desc = aiomatic_substr($vid_desc, 0, $max_caption);
                            }
                            if($returned_caption == '')
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (no YouTube caption data found), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('No YouTube caption results returned: ' . $keyword);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '', '', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '', '', '');
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($returned_caption, $vid_title, $vid_desc, $youtube_thumb);
                                }
                                $block_results[$block_id] = array($current_block['type'], $returned_caption, $vid_title, $vid_desc, $youtube_thumb);
                            }
                        }
                        elseif($current_block['type'] == 'send_email')
                        {
                            $my_post = array();
                            $email_title = $current_block['parameters']['email_title'];
                            $email_title = aiomatic_replace_omniblocks_data($email_title, $current_keyword, $kiwis, $block_results, $load_variables);
                            $email_content = $current_block['parameters']['email_content'];
                            $email_content = aiomatic_replace_omniblocks_data($email_content, $current_keyword, $kiwis, $block_results, $load_variables);
                            $email_recipient = $current_block['parameters']['email_recipient'];
                            $email_recipient = aiomatic_replace_omniblocks_data($email_recipient, $current_keyword, $kiwis, $block_results, $load_variables);
                            if ((empty($email_title) && empty($email_content)) || empty($email_recipient)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty email data entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty email data entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            try 
                            {
                                $admin_mail = get_option('admin_email');
                                $to        = $email_recipient;
                                $subject   = $email_title;
                                $message   = $email_content;
                                $headers[] = 'From: Aimogen Plugin <' . $admin_mail . '>';
                                $headers[] = 'Reply-To: ' . $admin_mail;
                                $headers[] = 'X-Mailer: PHP/' . phpversion();
                                $headers[] = 'Content-Type: text/html';
                                $headers[] = 'Charset: ' . get_option('blog_charset', 'UTF-8');
                                $sent = wp_mail($to, $subject, $message, $headers);
                                if($sent === false)
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (failed to send email), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to send email to: ' . $to);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                else
                                {
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('ok');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    $posts_inserted++;
                                }
                            }
                            catch (Exception $e) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (send mail exception), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to send mail: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                        }
                        elseif($current_block['type'] == 'send_twitter')
                        {
                            $post_template = $current_block['parameters']['post_template'];
                            $post_template = aiomatic_replace_omniblocks_data($post_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $featured_image = $current_block['parameters']['featured_image'];
                            $featured_image = aiomatic_replace_omniblocks_data($featured_image, $current_keyword, $kiwis, $block_results, $load_variables);
                            if ((empty($post_template) && empty($featured_image))) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty X (Twitter) post data entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty X (Twitter) post data entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $return_me = aiomatic_post_to_twitter($card_type_found, $post_template, $featured_image);
                            if(isset($return_me['error']))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (X (Twitter) social posting failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('X (Twitter) social posting failed: ' . $return_me['error']);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            elseif(empty($return_me))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (X (Twitter) social posting failed to be parsed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to parse social posting results to X (Twitter)');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array('ok');
                                }
                                $block_results[$block_id] = array($current_block['type']);
                                $posts_inserted++;
                            }
                        }
                        elseif($current_block['type'] == 'send_threads')
                        {
                            $post_template = $current_block['parameters']['post_template'];
                            $post_template = aiomatic_replace_omniblocks_data($post_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $featured_image = $current_block['parameters']['featured_image'];
                            $featured_image = aiomatic_replace_omniblocks_data($featured_image, $current_keyword, $kiwis, $block_results, $load_variables);
                            if ((empty($post_template) && empty($featured_image))) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty Threads post data entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty Threads post data entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $return_me = aiomatic_post_to_threads($card_type_found, $post_template, $featured_image);
                            if(isset($return_me['error']))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Threads social posting failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Threads social posting failed: ' . $return_me['error']);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            elseif(empty($return_me))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Threads social posting failed to be parsed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to parse social posting results to Threads');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array('ok');
                                }
                                $block_results[$block_id] = array($current_block['type']);
                                $posts_inserted++;
                            }
                        }
                        elseif($current_block['type'] == 'send_gmb')
                        {
                            $post_template = $current_block['parameters']['post_template'];
                            $post_template = aiomatic_replace_omniblocks_data($post_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $featured_image = $current_block['parameters']['featured_image'];
                            $featured_image = aiomatic_replace_omniblocks_data($featured_image, $current_keyword, $kiwis, $block_results, $load_variables);
                            $page_to_post = $current_block['parameters']['page_to_post'];
                            if ((empty($post_template) && empty($featured_image))) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty Google My Business post data entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty Google My Business post data entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $return_me = aiomatic_post_to_gmb($card_type_found, $post_template, $featured_image, $page_to_post);
                            if(isset($return_me['error']))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Google My Business social posting failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Google My Business social posting failed: ' . $return_me['error']);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            elseif(empty($return_me))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Google My Business social posting failed to be parsed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to parse social posting results to Google My Business');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array('ok');
                                }
                                $block_results[$block_id] = array($current_block['type']);
                                $posts_inserted++;
                            }
                        }
                        elseif($current_block['type'] == 'send_community_youtube')
                        {
                            $post_template = $current_block['parameters']['post_template'];
                            $post_template = aiomatic_replace_omniblocks_data($post_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $featured_image = $current_block['parameters']['featured_image'];
                            $featured_image = aiomatic_replace_omniblocks_data($featured_image, $current_keyword, $kiwis, $block_results, $load_variables);
                            $send_type = $current_block['parameters']['send_type'];
                            if(empty($send_type))
                            {
                                $send_type = 'text';
                            }
                            if ((empty($post_template) && empty($featured_image))) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty YouTube Community post data entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty YouTube Community post data entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            if($featured_image != '')
                            {
                                $media = array($featured_image);
                            }
                            else
                            {
                                $media = array();
                            }
                            $return_me = aiomatic_post_to_youtube_community($card_type_found, $post_template, $send_type, $media);
                            if(isset($return_me['error']))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution YouTube Community social posting failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('YouTube Community social posting failed: ' . $return_me['error']);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            elseif(empty($return_me))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (YouTube Community social posting failed to be parsed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to parse social posting results to YouTube Community');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array('ok');
                                }
                                $block_results[$block_id] = array($current_block['type']);
                                $posts_inserted++;
                            }
                        }
                        elseif($current_block['type'] == 'send_reddit')
                        {
                            $title_template = $current_block['parameters']['title_template'];
                            $title_template = aiomatic_replace_omniblocks_data($title_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $post_template = $current_block['parameters']['post_template'];
                            $post_template = aiomatic_replace_omniblocks_data($post_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $subreddit_to_post = $current_block['parameters']['subreddit_to_post'];
                            $subreddit_to_post = aiomatic_replace_omniblocks_data($subreddit_to_post, $current_keyword, $kiwis, $block_results, $load_variables);
                            $send_type = $current_block['parameters']['send_type'];
                            if(empty($send_type))
                            {
                                $send_type = 'self';
                            }
                            if ((empty($post_template) && empty($title_template))) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty Reddit post data entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty Reddit post data entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $return_me = aiomatic_post_to_reddit($card_type_found, $title_template, $post_template, $send_type, $subreddit_to_post);
                            if(isset($return_me['error']))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution Reddit social posting failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Reddit social posting failed: ' . $return_me['error']);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            elseif(empty($return_me))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (Reddit social posting failed to be parsed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to parse social posting results to Reddit');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array('ok');
                                }
                                $block_results[$block_id] = array($current_block['type']);
                                $posts_inserted++;
                            }
                        }
                        elseif($current_block['type'] == 'god_mode')
                        { 
                            if (isset($aiomatic_Main_Settings['omni_fpenalty']) && trim($aiomatic_Main_Settings['omni_fpenalty']) != '')
                            {
                                $frequency_penalty = floatval($aiomatic_Main_Settings['omni_fpenalty']);
                            } 
                            else 
                            {
                                $frequency_penalty = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_ppenalty']) && trim($aiomatic_Main_Settings['omni_ppenalty']) != '')
                            {
                                $presence_penalty = floatval($aiomatic_Main_Settings['omni_ppenalty']);
                            } 
                            else 
                            {
                                $presence_penalty = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_top_p']) && trim($aiomatic_Main_Settings['omni_top_p']) != '')
                            {
                                $max_p = floatval($aiomatic_Main_Settings['omni_top_p']);
                            } 
                            else 
                            {
                                $max_p = '';
                            }
                            if (isset($aiomatic_Main_Settings['omni_temperature']) && trim($aiomatic_Main_Settings['omni_temperature']) != '')
                            {
                                $temperature = floatval($aiomatic_Main_Settings['omni_temperature']);
                            } 
                            else 
                            {
                                $temperature = '';
                            }
                            $prompt = $current_block['parameters']['prompt'];
                            $prompt = aiomatic_replace_omniblocks_data($prompt, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($prompt)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty text prompt entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty text prompt entered, block ID: ' . $block_id);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                    continue;
                                }
                            }
                            $model = $current_block['parameters']['model'];
                            $assistant_id = $current_block['parameters']['assistant_id'];
                            $max_tokens = aimogenpro_get_max_tokens($model);
                            $query_token_count = count(aiomatic_encode($prompt));
                            $available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $prompt, $query_token_count);
                            if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                            {
                                $string_len = aiomatic_strlen($prompt);
                                $string_len = $string_len / 2;
                                $string_len = intval(0 - $string_len);
                                $prompt = aiomatic_substr($prompt, 0, $string_len);
                                $prompt = trim($prompt);
                                $query_token_count = count(aiomatic_encode($prompt));
                                $available_tokens = $max_tokens - $query_token_count;
                            }
                            $aierror = '';
                            $finish_reason = '';
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                            {
                                $api_service = aiomatic_get_api_service($token, $model);
                                aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for God Mode OmniBlock text ID: ' . $block_id);
                                aiomatic_log_to_file('AI Prompt is: ' . $prompt);
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Calling OmniBlock AI God Mode'));
                            require_once (dirname(__FILE__) . "/aiomatic-god-mode-omniblock.php");
                            require_once (dirname(__FILE__) . "/aiomatic-god-mode-parser.php");
                            $generated_text = aiomatic_run_functions($token, $model, $prompt, $available_tokens, $temperature, $max_p, $presence_penalty, $frequency_penalty, true, 'omniBlocksWriter', 0, $finish_reason, $aierror, false, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', false);
                            remove_filter('aiomatic_ai_functions', 'aiomatic_add_god_mode_omniblock', 999);
                            if($generated_text === false)
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (failed to generate AI content), as critical block failed (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to generate non-critical OmniBlock content using AI writer (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                            }
                            else
                            {
                                if(empty($generated_text))
                                {
                                    aiomatic_log_to_file('Empty content generated using AI OmniBlock writer (ID ' . esc_html($block_id) . '): ' . $model . ' - error: ' . $aierror);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '');
                                }
                                else
                                {
                                    if(is_string($generated_text))
                                    {
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array($generated_text);
                                        }
                                        $block_results[$block_id] = array($current_block['type'], $generated_text);
                                    }
                                    else
                                    {
                                        $return_me = '';
                                        if(isset($generated_text->tool_calls))
                                        {
                                            foreach($generated_text->tool_calls as $tcx)
                                            {
                                                $return_me .= 'Executed: ' . $tcx->function->name . '(' . $tcx->function->arguments->parameter_array . ')' . PHP_EOL;
                                            }
                                        }
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array($return_me);
                                        }
                                        $block_results[$block_id] = array($current_block['type'], $return_me);
                                    }
                                }
                            }
                        }
                        elseif($current_block['type'] == 'send_webhook')
                        {
                            $webhook_url = $current_block['parameters']['webhook_url'];
                            $webhook_method = $current_block['parameters']['webhook_method'];
                            $content_type = $current_block['parameters']['content_type'];
                            $post_template = $current_block['parameters']['post_template'];
                            $headers_template = $current_block['parameters']['headers_template'];
                            $headers_template = aiomatic_replace_omniblocks_data($headers_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            if ((empty($webhook_url))) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty webhook_url entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty webhook_url entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            $urlParsed = wp_parse_url( $webhook_url, PHP_URL_HOST );
                            if ( filter_var( $webhook_url, FILTER_VALIDATE_URL ) === FALSE || empty( $urlParsed ) )
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (invalid webhook_url entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Invalid webhook_url entered ' . $webhook_url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            else if ( $content_type === 'JSON' && empty( json_decode( $post_template, TRUE ) ) )
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (The JSON data must be valid), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('The JSON data must be valid ' . $webhook_url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            $headers = [];
                            if(!empty($headers_template))
                            {
                                $headers_template_arr = preg_split('/\r\n|\r|\n/', trim($headers_template));
                                foreach($headers_template_arr as $arr_fr)
                                {
                                    if(!empty(trim($arr_fr)) && strstr($arr_fr, '=>'))
                                    {
                                        $small_arr = explode('=>', $arr_fr);
                                        $headers[] = trim($small_arr[0]) . ':' . trim($small_arr[1]);
                                    }
                                }
                            }
                            $content_params = [];
                            if(!empty($post_template))
                            {
                                $post_template_arr = preg_split('/\r\n|\r|\n/', trim($post_template));
                                foreach($post_template_arr as $arr_fr)
                                {
                                    if(!empty(trim($arr_fr)) && strstr($arr_fr, '=>'))
                                    {
                                        $small_arr = explode('=>', $arr_fr);
                                        $small_arr[0] = aiomatic_replace_omniblocks_data($small_arr[0], $current_keyword, $kiwis, $block_results, $load_variables);
                                        $small_arr[1] = aiomatic_replace_omniblocks_data($small_arr[1], $current_keyword, $kiwis, $block_results, $load_variables);
                                        $content_params[trim($small_arr[0])] = trim($small_arr[1]);
                                    }
                                }
                            }
                            $post_template = aiomatic_replace_omniblocks_data($post_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $ch = curl_init();
                            if ($ch === false) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (failed to init curl), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to init curl in webhook execution');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            if (isset($aiomatic_Main_Settings['proxy_url']) && $aiomatic_Main_Settings['proxy_url'] != '' && $aiomatic_Main_Settings['proxy_url'] != 'disable' && $aiomatic_Main_Settings['proxy_url'] != 'disabled') {
                                $prx = explode(',', $aiomatic_Main_Settings['proxy_url']);
                                $randomness = array_rand($prx);
                                curl_setopt( $ch, CURLOPT_PROXY, trim($prx[$randomness]));
                                if (isset($aiomatic_Main_Settings['proxy_auth']) && $aiomatic_Main_Settings['proxy_auth'] != '') 
                                {
                                    $prx_auth = explode(',', $aiomatic_Main_Settings['proxy_auth']);
                                    if(isset($prx_auth[$randomness]) && trim($prx_auth[$randomness]) != '')
                                    {
                                        curl_setopt( $ch, CURLOPT_PROXYUSERPWD, trim($prx_auth[$randomness]));
                                    }
                                }
                            }
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                            if ($webhook_method === 'POST' || $webhook_method === 'PUT' || $webhook_method === 'DELETE') 
                            {
                                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $webhook_method);
                                if (!empty($content_params) && $content_type === 'form') {
                                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($content_params));
                                } elseif (!empty($post_template) && $content_type === 'JSON') {
                                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_template));
                                    $headers[] = 'Content-Type: application/json';
                                    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                                }
                            }
                            else
                            {
                                $query_string = http_build_query($content_params);
                                $webhook_url = $webhook_url . (strpos($webhook_url, '?') === false ? '?' : '&') . $query_string;
                            }
                            curl_setopt($ch, CURLOPT_URL, $webhook_url);

                            $response = curl_exec($ch);
                            if($response === false)
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (failed to send webhook request), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to send webhook request to ' . $webhook_url);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            $err = curl_error($ch);
                            $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                            curl_close($ch);
                            if ($err) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (webhook request error), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Webhook request error to URL ' . $webhook_url . ' - error: ' . $err);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }

                            if ($statusCode >= 200 && $statusCode <= 299) 
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array('ok');
                                }
                                $block_results[$block_id] = array($current_block['type']);
                                $posts_inserted++;
                            } 
                            else 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (webhook unexpected return code), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Webhook unexpected return code to URL ' . $webhook_url . ' - return code: ' . $statusCode);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                        }
                        elseif($current_block['type'] == 'send_linkedin')
                        {
                            $post_template = $current_block['parameters']['post_template'];
                            $post_template = aiomatic_replace_omniblocks_data($post_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $featured_image = $current_block['parameters']['featured_image'];
                            $featured_image = aiomatic_replace_omniblocks_data($featured_image, $current_keyword, $kiwis, $block_results, $load_variables);
                            $post_title = $current_block['parameters']['post_title'];
                            $post_title = aiomatic_replace_omniblocks_data($post_title, $current_keyword, $kiwis, $block_results, $load_variables);
                            $post_link = $current_block['parameters']['post_link'];
                            $post_link = aiomatic_replace_omniblocks_data($post_link, $current_keyword, $kiwis, $block_results, $load_variables);
                            $post_description = $current_block['parameters']['post_description'];
                            $post_description = aiomatic_replace_omniblocks_data($post_description, $current_keyword, $kiwis, $block_results, $load_variables);
                            $attach_lnk = $current_block['parameters']['attach_lnk'];
                            $selected_pages = $current_block['parameters']['page_to_post'];
                            if ((empty($post_template) && empty($featured_image))) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty LinkedIn post data entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty LinkedIn post data entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            if (empty($selected_pages))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty LinkedIn selected_pages entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty LinkedIn selected_pages entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            
                            $return_me = aiomatic_post_to_linkedin($card_type_found, $post_template, $featured_image, $post_title, $post_link, $post_description, $attach_lnk, $selected_pages);
                            if(isset($return_me['error']))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (LinkedIn social posting failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('LinkedIn social posting failed: ' . $return_me['error']);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            elseif(empty($return_me))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (LinkedIn social posting failed to be parsed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to parse social posting results to LinkedIn');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array('ok');
                                }
                                $block_results[$block_id] = array($current_block['type']);
                                $posts_inserted++;
                            }
                        }
                        elseif($current_block['type'] == 'save_file')
                        {
                            $post_template = $current_block['parameters']['post_template'];
                            $post_template = aiomatic_replace_omniblocks_data($post_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $send_type = $current_block['parameters']['send_type'];
                            $file_type = $current_block['parameters']['file_type'];
                            if(empty($file_type))
                            {
                                $file_type = 'txt';
                            }
                            $file_name = "file_" . $param . "_" . date("Y-m-d_H-i-s") . "_" . uniqid() . '.' . $file_type;
                            if ((empty($post_template) && empty($send_type))) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty local file data entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty local file data entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            if($file_type == 'pdf')
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                if (!is_plugin_active('aiomatic-extension-pdf-files/aiomatic-extension-pdf-files.php')) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (PDF Parser Extension plugin is not active, please activate it to use this functionality), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Aimogen Extension - PDF File Storage And Parsing plugin is not active, please activate it to use this functionality');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                        continue;
                                    }
                                }
                                $html2pdf = new \Spipu\Html2Pdf\Html2Pdf();
                                $html2pdf->writeHTML($post_template);
                                $pdf_str = $html2pdf->output('doc.pdf', 'S');
                                if($pdf_str === false)
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (pdf file saving failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to save pdf document to file');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                        continue;
                                    }
                                }
                                else
                                {
                                    $post_template = $pdf_str;
                                }
                            }
                            if($file_type == 'doc')
                            {
                                require_once(dirname(__FILE__) . "/res/html_to_doc/ExportToWord.inc.php");
                                $doc_str = ExportToWord::htmlToDoc($post_template, '');
                                if($doc_str === false)
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (doc file saving failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to save doc document to file');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '');
                                        continue;
                                    }
                                }
                                else
                                {
                                    $post_template = $doc_str;
                                }
                            }
                            $filesize = aiomatic_strlen($post_template);
                            if($send_type == 'local')
                            {
                                global $wp_filesystem;
                                if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
                                    include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() );
                                    wp_filesystem($creds);
                                }
                                $upload_dir = wp_upload_dir();
                                $aiomatic_directory = $upload_dir['basedir'] . '/aiomatic/';
                                $aiomatic_url = $upload_dir['baseurl'] . '/aiomatic/';
                                wp_mkdir_p($aiomatic_directory);
                                $new_pdf = $aiomatic_directory . $file_name;
                                $new_url = $aiomatic_url . $file_name;
                                $ret = $wp_filesystem->put_contents($new_pdf, $post_template);
                                if ($ret === FALSE) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (failed to upload file), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to upload file: ' . $file_name . ' to ' . $new_pdf);
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                else
                                {
                                    $forms_data = array(
                                        'post_type' => 'aiomatic_omni_file',
                                        'post_title' => $file_name,
                                        'post_content' => $new_url,
                                        'post_status' => 'publish'
                                    );
                                    remove_filter('content_save_pre', 'wp_filter_post_kses');
                                    remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                                    $forms_id = wp_insert_post($forms_data);
                                    add_filter('content_save_pre', 'wp_filter_post_kses');
                                    add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                                    if(is_wp_error($forms_id))
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (failed to insert file data), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to insert file data: ' . $forms_id->get_error_message());
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type']);
                                            continue;
                                        }
                                    }
                                    elseif($forms_id === 0)
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (failed to insert file to db), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file('Failed to insert file to db');
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type']);
                                            continue;
                                        }
                                    }
                                    else 
                                    {
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('ok');
                                        }
                                        $cat_arr = array($send_type);
                                        wp_set_object_terms($forms_id, $cat_arr, 'ai_file_type');
                                        $new_pdf = str_replace('\\', '/', $new_pdf);
                                        update_post_meta($forms_id, 'local_id', $new_pdf);
                                        $block_results[$block_id] = array($current_block['type']);
                                        $posts_inserted++;
                                    }
                                }      
                            }
                            elseif($send_type == 'amazon')
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                if (!is_plugin_active('aiomatic-extension-amazon-s3-images/aiomatic-extension-amazon-s3-images.php')) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 extension not loaded), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need enable the "Aimogen Extension: Amazon S3 Storage" plugin for this feature to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['bucket_name']) || trim($aiomatic_Main_Settings['bucket_name']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 bucket_name not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Amazon S3 bucket_name for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['s3_user']) || trim($aiomatic_Main_Settings['s3_user']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 s3_user not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Amazon S3 s3_user for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['s3_pass']) || trim($aiomatic_Main_Settings['s3_pass']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 s3_pass not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Amazon S3 s3_pass for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['bucket_region']) || trim($aiomatic_Main_Settings['bucket_region']) == '')
                                {
                                    $aiomatic_Main_Settings['bucket_region'] = 'eu-central-1';
                                }
                                try
                                {
                                    $credentials = array('key' => trim($aiomatic_Main_Settings['s3_user']), 'secret' => trim($aiomatic_Main_Settings['s3_pass']));
                                    $s3 = new S3Client([
                                        'version' => 'latest',
                                        'region'  => trim($aiomatic_Main_Settings['bucket_region']),
                                        'credentials' => $credentials
                                    ]);
                                }
                                catch(Exception $e)
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 init failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to initialize Amazon S3 API: ' . $e->getMessage());
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (trim($aiomatic_Main_Settings['drive_directory']) != '') {
                                    $s3_remote_path = trim(trim($aiomatic_Main_Settings['drive_directory']), '/');
                                    $s3_remote_path = trailingslashit($s3_remote_path);
                                }
                                else
                                {
                                    $s3_remote_path = '';
                                }
                                try 
                                {
                                    $obj_arr = [
                                        'Bucket' => trim($aiomatic_Main_Settings['bucket_name']),
                                        'Key'    => $s3_remote_path . $file_name,
                                        'Body'   => $post_template,
                                        'Content-Length' => $filesize,
                                        'ContentLength' => $filesize
                                    ];
                                    $obj_arr['ACL'] = 'public-read';
                                    $awsret = $s3->putObject($obj_arr);
                                    if(isset($awsret['ObjectURL']))
                                    {
                                        $forms_data = array(
                                            'post_type' => 'aiomatic_omni_file',
                                            'post_title' => $file_name,
                                            'post_content' => $awsret['ObjectURL'],
                                            'post_status' => 'publish'
                                        );
                                        remove_filter('content_save_pre', 'wp_filter_post_kses');
                                        remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                                        $forms_id = wp_insert_post($forms_data);
                                        add_filter('content_save_pre', 'wp_filter_post_kses');
                                        add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                                        if(is_wp_error($forms_id))
                                        {
                                            if($critical == '1')
                                            {
                                                aiomatic_log_to_file('Halting execution (failed to insert file data), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                return 'fail';
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to insert file data: ' . $forms_id->get_error_message());
                                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                {
                                                    return array('');
                                                }
                                                $block_results[$block_id] = array($current_block['type']);
                                                continue;
                                            }
                                        }
                                        elseif($forms_id === 0)
                                        {
                                            if($critical == '1')
                                            {
                                                aiomatic_log_to_file('Halting execution (failed to insert file to db), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                return 'fail';
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to insert file to db');
                                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                {
                                                    return array('');
                                                }
                                                $block_results[$block_id] = array($current_block['type']);
                                                continue;
                                            }
                                        }
                                        else 
                                        {
                                            $cat_arr = array($send_type);
                                            wp_set_object_terms($forms_id, $cat_arr, 'ai_file_type');
                                            $uri = $awsret['ObjectURL'];
                                            $urlComponents = wp_parse_url($uri);
                                            $key = ltrim($urlComponents['path'], '/');
                                            update_post_meta($forms_id, 'local_id', $key);
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('ok');
                                            }
                                            $block_results[$block_id] = array($current_block['type']);
                                            $posts_inserted++;
                                        }   
                                    }
                                    else
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (Amazon S3 error response decoding), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file("Failed to decode Amazon S3 API response: " . print_r($awsret, true));
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type']);
                                            continue;
                                        }
                                    }
                                } 
                                catch (Exception $e) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 error uploading file), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file("There was an error uploading the file " . $image_url . " to Amazon S3: " . $e->getMessage());
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                } 
                            }
                            elseif($send_type == 'wasabi')
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                if (!is_plugin_active('aiomatic-extension-amazon-s3-images/aiomatic-extension-amazon-s3-images.php')) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 extension not loaded), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need enable the "Aimogen Extension: Amazon S3 Storage" plugin for this feature to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['wasabi_bucket']) || trim($aiomatic_Main_Settings['wasabi_bucket']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 wasabi_bucket not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Amazon S3 wasabi_bucket for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['wasabi_region']) || trim($aiomatic_Main_Settings['wasabi_region']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 wasabi_region not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Amazon S3 wasabi_region for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['wasabi_user']) || trim($aiomatic_Main_Settings['wasabi_user']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 wasabi_user not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Amazon S3 wasabi_user for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['wasabi_pass']) || trim($aiomatic_Main_Settings['wasabi_pass']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 wasabi_pass not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Amazon S3 wasabi_pass for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['bucket_region']) || trim($aiomatic_Main_Settings['bucket_region']) == '')
                                {
                                    $aiomatic_Main_Settings['bucket_region'] = 'eu-central-1';
                                }
                                try
                                {
                                    $credentials = array('key' => trim($aiomatic_Main_Settings['wasabi_user']), 'secret' => trim($aiomatic_Main_Settings['wasabi_pass']));
                                    $s3 = new S3Client([
                                        'endpoint' => "https://" . trim($aiomatic_Main_Settings['wasabi_bucket']) . ".s3." . trim($aiomatic_Main_Settings['wasabi_region']) . ".wasabisys.com/",
                                        'bucket_endpoint' => true,
                                        'version' => 'latest',
                                        'region'  => trim($aiomatic_Main_Settings['wasabi_region']),
                                        'credentials' => $credentials
                                    ]);
                                }
                                catch(Exception $e)
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 init failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to initialize Amazon S3 API: ' . $e->getMessage());
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (trim($aiomatic_Main_Settings['wasabi_directory']) != '') {
                                    $s3_remote_path = trim(trim($aiomatic_Main_Settings['wasabi_directory']), '/');
                                    $s3_remote_path = trailingslashit($s3_remote_path);
                                }
                                else
                                {
                                    $s3_remote_path = '';
                                }
                                try 
                                {
                                    $obj_arr = [
                                        'Bucket' => trim($aiomatic_Main_Settings['wasabi_bucket']),
                                        'Key'    => $s3_remote_path . $file_name,
                                        'Body'   => $post_template,
                                        'Content-Length' => $filesize,
                                        'ContentLength' => $filesize
                                    ];
                                    $obj_arr['ACL'] = 'public-read';
                                    $awsret = $s3->putObject($obj_arr);
                                    if(isset($awsret['ObjectURL']))
                                    {
                                        $forms_data = array(
                                            'post_type' => 'aiomatic_omni_file',
                                            'post_title' => $file_name,
                                            'post_content' => $awsret['ObjectURL'],
                                            'post_status' => 'publish'
                                        );
                                        remove_filter('content_save_pre', 'wp_filter_post_kses');
                                        remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                                        $forms_id = wp_insert_post($forms_data);
                                        add_filter('content_save_pre', 'wp_filter_post_kses');
                                        add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                                        if(is_wp_error($forms_id))
                                        {
                                            if($critical == '1')
                                            {
                                                aiomatic_log_to_file('Halting execution (failed to insert file data), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                return 'fail';
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to insert file data: ' . $forms_id->get_error_message());
                                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                {
                                                    return array('');
                                                }
                                                $block_results[$block_id] = array($current_block['type']);
                                                continue;
                                            }
                                        }
                                        elseif($forms_id === 0)
                                        {
                                            if($critical == '1')
                                            {
                                                aiomatic_log_to_file('Halting execution (failed to insert file to db), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                return 'fail';
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to insert file to db');
                                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                {
                                                    return array('');
                                                }
                                                $block_results[$block_id] = array($current_block['type']);
                                                continue;
                                            }
                                        }
                                        else 
                                        {
                                            $cat_arr = array($send_type);
                                            wp_set_object_terms($forms_id, $cat_arr, 'ai_file_type');
                                            $uri = $awsret['ObjectURL'];
                                            $urlComponents = wp_parse_url($uri);
                                            $key = ltrim($urlComponents['path'], '/');
                                            update_post_meta($forms_id, 'local_id', $key);
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('ok');
                                            }
                                            $block_results[$block_id] = array($current_block['type']);
                                            $posts_inserted++;
                                        }   
                                    }
                                    else
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (Amazon S3 error response decoding), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file("Failed to decode Amazon S3 API response: " . print_r($awsret, true));
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type']);
                                            continue;
                                        }
                                    }
                                } 
                                catch (Exception $e) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 error uploading file), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file("There was an error uploading the file " . $image_url . " to Amazon S3: " . $e->getMessage());
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                } 
                            }
                            elseif($send_type == 'generics3')
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                if (!is_plugin_active('aiomatic-extension-amazon-s3-images/aiomatic-extension-amazon-s3-images.php')) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 extension not loaded), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need enable the "Aimogen Extension: Amazon S3 Storage" plugin for this feature to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['generic_bucket']) || trim($aiomatic_Main_Settings['generic_bucket']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Generic Amazon S3 bucket not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Generic Amazon S3 bucket for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['generic_url']) || trim($aiomatic_Main_Settings['generic_url']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Generic Amazon S3 URL not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Generic Amazon S3 URL for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['generic_region']) || trim($aiomatic_Main_Settings['generic_region']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Generic Amazon S3 region not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Generic Amazon S3 region for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['generic_user']) || trim($aiomatic_Main_Settings['generic_user']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Generic Amazon S3 user not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Generic Amazon S3 user for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['generic_pass']) || trim($aiomatic_Main_Settings['generic_pass']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Generic Amazon S3 password not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Generic Amazon S3 password for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['bucket_region']) || trim($aiomatic_Main_Settings['bucket_region']) == '')
                                {
                                    $aiomatic_Main_Settings['bucket_region'] = 'eu-central-1';
                                }
                                try
                                {
                                    $credentials = array('key' => trim($aiomatic_Main_Settings['generic_user']), 'secret' => trim($aiomatic_Main_Settings['generic_pass']));
                                    $s3 = new S3Client([
                                        'endpoint' => trim($aiomatic_Main_Settings['generic_url']),
                                        'bucket_endpoint' => true,
                                        'version' => 'latest',
                                        'region'  => trim($aiomatic_Main_Settings['generic_region']),
                                        'credentials' => $credentials
                                    ]);
                                }
                                catch(Exception $e)
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 init failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to initialize Amazon S3 API: ' . $e->getMessage());
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (trim($aiomatic_Main_Settings['generic_directory']) != '') {
                                    $s3_remote_path = trim(trim($aiomatic_Main_Settings['generic_directory']), '/');
                                    $s3_remote_path = trailingslashit($s3_remote_path);
                                }
                                else
                                {
                                    $s3_remote_path = '';
                                }
                                try 
                                {
                                    $obj_arr = [
                                        'Bucket' => trim($aiomatic_Main_Settings['generic_bucket']),
                                        'Key'    => $s3_remote_path . $file_name,
                                        'Body'   => $post_template,
                                        'Content-Length' => $filesize,
                                        'ContentLength' => $filesize
                                    ];
                                    $obj_arr['ACL'] = 'public-read';
                                    $awsret = $s3->putObject($obj_arr);
                                    if(isset($awsret['ObjectURL']))
                                    {
                                        $forms_data = array(
                                            'post_type' => 'aiomatic_omni_file',
                                            'post_title' => $file_name,
                                            'post_content' => $awsret['ObjectURL'],
                                            'post_status' => 'publish'
                                        );
                                        remove_filter('content_save_pre', 'wp_filter_post_kses');
                                        remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                                        $forms_id = wp_insert_post($forms_data);
                                        add_filter('content_save_pre', 'wp_filter_post_kses');
                                        add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                                        if(is_wp_error($forms_id))
                                        {
                                            if($critical == '1')
                                            {
                                                aiomatic_log_to_file('Halting execution (failed to insert file data), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                return 'fail';
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to insert file data: ' . $forms_id->get_error_message());
                                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                {
                                                    return array('');
                                                }
                                                $block_results[$block_id] = array($current_block['type']);
                                                continue;
                                            }
                                        }
                                        elseif($forms_id === 0)
                                        {
                                            if($critical == '1')
                                            {
                                                aiomatic_log_to_file('Halting execution (failed to insert file to db), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                return 'fail';
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to insert file to db');
                                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                {
                                                    return array('');
                                                }
                                                $block_results[$block_id] = array($current_block['type']);
                                                continue;
                                            }
                                        }
                                        else 
                                        {
                                            $cat_arr = array($send_type);
                                            wp_set_object_terms($forms_id, $cat_arr, 'ai_file_type');
                                            $uri = $awsret['ObjectURL'];
                                            $urlComponents = wp_parse_url($uri);
                                            $key = ltrim($urlComponents['path'], '/');
                                            update_post_meta($forms_id, 'local_id', $key);
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('ok');
                                            }
                                            $block_results[$block_id] = array($current_block['type']);
                                            $posts_inserted++;
                                        }   
                                    }
                                    else
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (Amazon S3 error response decoding), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file("Failed to decode Amazon S3 API response: " . print_r($awsret, true));
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type']);
                                            continue;
                                        }
                                    }
                                } 
                                catch (Exception $e) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 error uploading file), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file("There was an error uploading the file " . $image_url . " to Amazon S3: " . $e->getMessage());
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                } 
                            }
                            elseif($send_type == 'cloudflare')
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                if (!is_plugin_active('aiomatic-extension-amazon-s3-images/aiomatic-extension-amazon-s3-images.php')) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 extension not loaded), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need enable the "Aimogen Extension: Amazon S3 Storage" plugin for this feature to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['cloud_bucket']) || trim($aiomatic_Main_Settings['cloud_bucket']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 cloud_bucket not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Amazon S3 cloud_bucket for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['cloud_account']) || trim($aiomatic_Main_Settings['cloud_account']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 cloud_account not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Amazon S3 cloud_account for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['cloud_user']) || trim($aiomatic_Main_Settings['cloud_user']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 cloud_user not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Amazon S3 cloud_user for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['cloud_pass']) || trim($aiomatic_Main_Settings['cloud_pass']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 cloud_pass not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Amazon S3 cloud_pass for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                try
                                {
                                    $credentials = array('key' => trim($aiomatic_Main_Settings['cloud_user']), 'secret' => trim($aiomatic_Main_Settings['cloud_pass']));
                                    $s3 = new S3Client([
                                        'endpoint' => "https://" . trim($aiomatic_Main_Settings['cloud_account']) . ".r2.cloudflarestorage.com",
                                        'bucket_endpoint' => true,
                                        'version' => 'latest',
                                        'region' => 'us-east-1',
                                        'credentials' => $credentials
                                    ]);
                                }
                                catch(Exception $e)
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 init failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to initialize Amazon S3 API: ' . $e->getMessage());
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (trim($aiomatic_Main_Settings['cloud_directory']) != '') {
                                    $s3_remote_path = trim(trim($aiomatic_Main_Settings['cloud_directory']), '/');
                                    $s3_remote_path = trailingslashit($s3_remote_path);
                                }
                                else
                                {
                                    $s3_remote_path = '';
                                }
                                try 
                                {
                                    $obj_arr = [
                                        'Bucket' => trim($aiomatic_Main_Settings['cloud_bucket']),
                                        'Key'    => $s3_remote_path . $file_name,
                                        'Body'   => $post_template,
                                        'Content-Length' => $filesize,
                                        'ContentLength' => $filesize
                                    ];
                                    $obj_arr['ACL'] = 'public-read';
                                    $awsret = $s3->putObject($obj_arr);
                                    if(isset($awsret['ObjectURL']))
                                    {
                                        if (isset($aiomatic_Main_Settings['cloud_public']) && trim($aiomatic_Main_Settings['cloud_public']) != '')
                                        {
                                            $awsret['ObjectURL'] = preg_replace(
                                                '/https:\/\/[^\/]+\.r2\.cloudflarestorage\.com/',
                                                esc_url(trim($aiomatic_Main_Settings['cloud_public'])),
                                                $awsret['ObjectURL'],
                                                1
                                            );
                                        }
                                        $forms_data = array(
                                            'post_type' => 'aiomatic_omni_file',
                                            'post_title' => $file_name,
                                            'post_content' => $awsret['ObjectURL'],
                                            'post_status' => 'publish'
                                        );
                                        remove_filter('content_save_pre', 'wp_filter_post_kses');
                                        remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                                        $forms_id = wp_insert_post($forms_data);
                                        add_filter('content_save_pre', 'wp_filter_post_kses');
                                        add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                                        if(is_wp_error($forms_id))
                                        {
                                            if($critical == '1')
                                            {
                                                aiomatic_log_to_file('Halting execution (failed to insert file data), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                return 'fail';
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to insert file data: ' . $forms_id->get_error_message());
                                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                {
                                                    return array('');
                                                }
                                                $block_results[$block_id] = array($current_block['type']);
                                                continue;
                                            }
                                        }
                                        elseif($forms_id === 0)
                                        {
                                            if($critical == '1')
                                            {
                                                aiomatic_log_to_file('Halting execution (failed to insert file to db), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                return 'fail';
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to insert file to db');
                                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                {
                                                    return array('');
                                                }
                                                $block_results[$block_id] = array($current_block['type']);
                                                continue;
                                            }
                                        }
                                        else 
                                        {
                                            $cat_arr = array($send_type);
                                            wp_set_object_terms($forms_id, $cat_arr, 'ai_file_type');
                                            $uri = $awsret['ObjectURL'];
                                            $urlComponents = wp_parse_url($uri);
                                            $key = ltrim($urlComponents['path'], '/');
                                            update_post_meta($forms_id, 'local_id', $key);
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('ok');
                                            }
                                            $block_results[$block_id] = array($current_block['type']);
                                            $posts_inserted++;
                                        }   
                                    }
                                    else
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (Amazon S3 error response decoding), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file("Failed to decode Amazon S3 API response: " . print_r($awsret, true));
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type']);
                                            continue;
                                        }
                                    }
                                } 
                                catch (Exception $e) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 error uploading file), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file("There was an error uploading the file " . $image_url . " to Amazon S3: " . $e->getMessage());
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                } 
                            }
                            elseif($send_type == 'digital')
                            {
                                if(!function_exists('is_plugin_active'))
                                {
                                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                }
                                if (!is_plugin_active('aiomatic-extension-amazon-s3-images/aiomatic-extension-amazon-s3-images.php')) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 extension not loaded), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need enable the "Aimogen Extension: Amazon S3 Storage" plugin for this feature to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['digital_endpoint']) || trim($aiomatic_Main_Settings['digital_endpoint']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 digital_endpoint not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Amazon S3 digital_endpoint for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['digital_user']) || trim($aiomatic_Main_Settings['digital_user']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 cloud_user not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Amazon S3 cloud_user for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (!isset($aiomatic_Main_Settings['digital_pass']) || trim($aiomatic_Main_Settings['digital_pass']) == '')
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 digital_pass not added), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('You need to enter a Amazon S3 digital_pass for this to work!');
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                $bucket_name = '';
                                preg_match_all('#https:\/\/([^.]*?)\.(?:[^.]*?)\.digitaloceanspaces\.com#i', trim($aiomatic_Main_Settings['digital_endpoint']), $zmatches);
                                if(isset($zmatches[1][0]))
                                {
                                    $bucket_name = $zmatches[1][0];
                                }
                                else
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (failed to parse Digital Ocean endpoint), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to parse Digital Ocean Spaces URL: ' . trim($aiomatic_Main_Settings['digital_endpoint']));
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                $endpoint_plain_url = preg_replace('#https?:\/\/([^.]*?\.)([^.]*?)\.digitaloceanspaces\.com#i', 'https://$2.digitaloceanspaces.com', trim($aiomatic_Main_Settings['digital_endpoint']));
                                try
                                {
                                    $credentials = array('key' => trim($aiomatic_Main_Settings['digital_user']), 'secret' => trim($aiomatic_Main_Settings['digital_pass']));
                                    $s3 = new S3Client([
                                        'version' => 'latest',
                                        'region'  => 'us-east-1',
                                        'endpoint' => $endpoint_plain_url,
                                        'use_path_style_endpoint' => false,
                                        'credentials' => $credentials
                                    ]);
                                }
                                catch(Exception $e)
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 init failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Failed to initialize Amazon S3 API: ' . $e->getMessage());
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                }
                                if (trim($aiomatic_Main_Settings['digital_directory']) != '') {
                                    $s3_remote_path = trim(trim($aiomatic_Main_Settings['digital_directory']), '/');
                                    $s3_remote_path = trailingslashit($s3_remote_path);
                                }
                                else
                                {
                                    $s3_remote_path = '';
                                }
                                try 
                                {
                                    $obj_arr = [
                                        'Bucket' => trim($bucket_name),
                                        'Key'    => $s3_remote_path . $file_name,
                                        'Body'   => $post_template,
                                        'Content-Length' => $filesize,
                                        'ContentLength' => $filesize
                                    ];
                                    $obj_arr['ACL'] = 'public-read';
                                    $awsret = $s3->putObject($obj_arr);
                                    if(isset($awsret['ObjectURL']))
                                    {
                                        $forms_data = array(
                                            'post_type' => 'aiomatic_omni_file',
                                            'post_title' => $file_name,
                                            'post_content' => $awsret['ObjectURL'],
                                            'post_status' => 'publish'
                                        );
                                        remove_filter('content_save_pre', 'wp_filter_post_kses');
                                        remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                                        $forms_id = wp_insert_post($forms_data);
                                        add_filter('content_save_pre', 'wp_filter_post_kses');
                                        add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                                        if(is_wp_error($forms_id))
                                        {
                                            if($critical == '1')
                                            {
                                                aiomatic_log_to_file('Halting execution (failed to insert file data), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                return 'fail';
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to insert file data: ' . $forms_id->get_error_message());
                                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                {
                                                    return array('');
                                                }
                                                $block_results[$block_id] = array($current_block['type']);
                                                continue;
                                            }
                                        }
                                        elseif($forms_id === 0)
                                        {
                                            if($critical == '1')
                                            {
                                                aiomatic_log_to_file('Halting execution (failed to insert file to db), as critical block failed (ID ' . esc_html($block_id) . ')');
                                                return 'fail';
                                            }
                                            else
                                            {
                                                aiomatic_log_to_file('Failed to insert file to db');
                                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                {
                                                    return array('');
                                                }
                                                $block_results[$block_id] = array($current_block['type']);
                                                continue;
                                            }
                                        }
                                        else 
                                        {
                                            $cat_arr = array($send_type);
                                            wp_set_object_terms($forms_id, $cat_arr, 'ai_file_type');
                                            $uri = $awsret['ObjectURL'];
                                            $urlComponents = wp_parse_url($uri);
                                            $key = ltrim($urlComponents['path'], '/');
                                            update_post_meta($forms_id, 'local_id', $key);
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('ok');
                                            }
                                            $block_results[$block_id] = array($current_block['type']);
                                            $posts_inserted++;
                                        }   
                                    }
                                    else
                                    {
                                        if($critical == '1')
                                        {
                                            aiomatic_log_to_file('Halting execution (Amazon S3 error response decoding), as critical block failed (ID ' . esc_html($block_id) . ')');
                                            return 'fail';
                                        }
                                        else
                                        {
                                            aiomatic_log_to_file("Failed to decode Amazon S3 API response: " . print_r($awsret, true));
                                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                            {
                                                return array('');
                                            }
                                            $block_results[$block_id] = array($current_block['type']);
                                            continue;
                                        }
                                    }
                                } 
                                catch (Exception $e) 
                                {
                                    if($critical == '1')
                                    {
                                        aiomatic_log_to_file('Halting execution (Amazon S3 error uploading file), as critical block failed (ID ' . esc_html($block_id) . ')');
                                        return 'fail';
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file("There was an error uploading the file " . $image_url . " to Amazon S3: " . $e->getMessage());
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('');
                                        }
                                        $block_results[$block_id] = array($current_block['type']);
                                        continue;
                                    }
                                } 
                            }
                            else
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (unknown file location sent), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Unknown file location sent: ' . $send_type);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                        }
                        elseif($current_block['type'] == 'send_facebook')
                        {
                            $post_template = $current_block['parameters']['post_template'];
                            $post_template = aiomatic_replace_omniblocks_data($post_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $post_link = $current_block['parameters']['post_link'];
                            $post_link = aiomatic_replace_omniblocks_data($post_link, $current_keyword, $kiwis, $block_results, $load_variables);
                            $page_to_post = $current_block['parameters']['page_to_post'];
                            if ((empty($post_template) && empty($post_link))) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty Facebook post data entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty Facebook post data entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            if (empty($page_to_post))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty Facebook page_to_post entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty Facebook page_to_post entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $return_me = aiomatic_post_to_facebook($card_type_found, $post_template, $post_link, $page_to_post);
                            if(isset($return_me['error']))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (social posting failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Social posting failed: ' . $return_me['error']);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            elseif(empty($return_me))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (social posting failed to be parsed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to parse social posting results');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array('ok');
                                }
                                $block_results[$block_id] = array($current_block['type']);
                                $posts_inserted++;
                            }
                        }
                        elseif($current_block['type'] == 'send_image_facebook')
                        {
                            $post_template = $current_block['parameters']['post_template'];
                            $post_template = aiomatic_replace_omniblocks_data($post_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $image_link = $current_block['parameters']['image_link'];
                            $image_link = aiomatic_replace_omniblocks_data($image_link, $current_keyword, $kiwis, $block_results, $load_variables);
                            $page_to_post = $current_block['parameters']['page_to_post'];
                            if (empty($image_link))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty Facebook image_link entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty Facebook image_link entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            if (empty($page_to_post))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty Facebook page_to_post entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty Facebook page_to_post entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $return_me = aiomatic_post_image_to_facebook($card_type_found, $post_template, $image_link, $page_to_post);
                            if(isset($return_me['error']))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (social posting failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Social posting failed: ' . $return_me['error']);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            elseif(empty($return_me))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (social posting failed to be parsed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to parse social posting results');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array('ok');
                                }
                                $block_results[$block_id] = array($current_block['type']);
                                $posts_inserted++;
                            }
                        }
                        elseif($current_block['type'] == 'send_image_instagram')
                        {
                            $post_template = $current_block['parameters']['post_template'];
                            $post_template = aiomatic_replace_omniblocks_data($post_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $image_link = $current_block['parameters']['image_link'];
                            $image_link = aiomatic_replace_omniblocks_data($image_link, $current_keyword, $kiwis, $block_results, $load_variables);
                            if (empty($image_link))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty Instagram image_link entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty Instagram image_link entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $return_me = aiomatic_post_image_to_instagram($card_type_found, $post_template, $image_link);
                            if(isset($return_me['error']))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (social posting failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Social posting failed: ' . $return_me['error']);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            elseif(empty($return_me))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (social posting failed to be parsed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to parse social posting results');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array('ok');
                                }
                                $block_results[$block_id] = array($current_block['type']);
                                $posts_inserted++;
                            }
                        }
                        elseif($current_block['type'] == 'send_image_pinterest')
                        {
                            $post_template = $current_block['parameters']['post_template'];
                            $post_template = aiomatic_replace_omniblocks_data($post_template, $current_keyword, $kiwis, $block_results, $load_variables);
                            $post_title = $current_block['parameters']['post_title'];
                            $post_title = aiomatic_replace_omniblocks_data($post_title, $current_keyword, $kiwis, $block_results, $load_variables);
                            $pin_me = $current_block['parameters']['pin_me'];
                            $pin_me = aiomatic_replace_omniblocks_data($pin_me, $current_keyword, $kiwis, $block_results, $load_variables);
                            $image_link = $current_block['parameters']['image_link'];
                            $image_link = aiomatic_replace_omniblocks_data($image_link, $current_keyword, $kiwis, $block_results, $load_variables);
                            $page_to_post = $current_block['parameters']['page_to_post'];
                            if (empty($image_link))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty Pinterest image_link entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty Pinterest image_link entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            if (empty($page_to_post))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty Pinterest page_to_post entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty Pinterest page_to_post entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            require_once(dirname(__FILE__) . "/aiomatic-socials.php");
                            $return_me = aiomatic_post_image_to_pinterest($card_type_found, $post_template, $post_title, $pin_me, $image_link, $page_to_post);
                            if(isset($return_me['error']))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (social posting failed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Social posting failed: ' . $return_me['error']);
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            elseif(empty($return_me))
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (social posting failed to be parsed), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Failed to parse social posting results');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array('ok');
                                }
                                $block_results[$block_id] = array($current_block['type']);
                                $posts_inserted++;
                            }
                        }
                        elseif($current_block['type'] == 'save_post')
                        {
                            $my_post = array();
                            $post_title = aiomatic_truncate_title($current_block['parameters']['post_title']);
                            $post_title = aiomatic_replace_omniblocks_data($post_title, $current_keyword, $kiwis, $block_results, $load_variables);
                            $post_content = $current_block['parameters']['post_content'];
                            $post_content = aiomatic_replace_omniblocks_data($post_content, $current_keyword, $kiwis, $block_results, $load_variables);
                            $post_excerpt = $current_block['parameters']['post_excerpt'];
                            $post_excerpt = aiomatic_replace_omniblocks_data($post_excerpt, $current_keyword, $kiwis, $block_results, $load_variables);
                            if(isset($current_block['parameters']['post_slug']))
                            {
                                $post_slug = $current_block['parameters']['post_slug'];
                                $post_slug = aiomatic_replace_omniblocks_data($post_slug, $current_keyword, $kiwis, $block_results, $load_variables);
                            }
                            else
                            {
                                $post_slug = '';
                            }
                            $strip_by_regex = $current_block['parameters']['content_regex'];
                            $strip_by_regex = aiomatic_replace_omniblocks_data($strip_by_regex, $current_keyword, $kiwis, $block_results, $load_variables);
                            $replace_regex = $current_block['parameters']['replace_regex'];
                            $replace_regex = aiomatic_replace_omniblocks_data($replace_regex, $current_keyword, $kiwis, $block_results, $load_variables);
                            if ($strip_by_regex !== '')
                            {
                                $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex);
                                $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex);
                                $xcnt = 0;
                                foreach($xstrip_by_regex as $sbr)
                                {
                                    if(isset($xreplace_regex[$xcnt]))
                                    {
                                        $repreg = $xreplace_regex[$xcnt];
                                    }
                                    else
                                    {
                                        $repreg = '';
                                    }
                                    $xcnt++;
                                    $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $post_content);
                                    if($temp_cont !== NULL)
                                    {
                                        $post_content = $temp_cont;
                                    }
                                }
                            }

                            if (empty($post_title) && empty($post_content) && empty($post_excerpt)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty post title and content entered), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty post title and content entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '');
                                    continue;
                                }
                            }
                            if(!empty($post_title))
                            {
                                $my_post['post_title'] = aiomatic_truncate_title($post_title);
                            }
                            if(isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled')
                            {
                                preg_match_all('#<img[^>]*?src="([^"]*?)"[^>]*?>#', $post_content, $cfm);
                                if(isset($cfm[1][0]))
                                {
                                    foreach($cfm[1] as $timg)
                                    {
                                        $show_url = '';
                                        $localpath = aiomatic_copy_image_locally($timg, $attached_id, '', false, '');
                                        if(!empty($attached_id))
                                        {
                                            $additional_attachments[] = $attached_id;
                                        }
                                        if($localpath !== false)
                                        {
                                            $show_url = $localpath[0];
                                        }
                                        if(!empty($show_url))
                                        {
                                            $post_content = str_replace($timg, $show_url, $post_content);
                                        }
                                    }
                                }
                            }
                            if(!empty($post_content))
                            {
                                $my_post['post_content'] = aiomatic_truncate_content($post_content, 16777215);
                                if(stristr($my_post['post_content'], '<pre><code>&lt;') !== false)
                                {
                                    if (!isset($aiomatic_Main_Settings['pre_code_off']) || trim($aiomatic_Main_Settings['pre_code_off']) != 'on')
                                    {
                                        $my_post['post_content'] = aiomatic_parse_pre_code_entities($my_post['post_content']);
                                    }
                                }
                                $my_post['post_content'] = str_replace('’', '\'', $my_post['post_content']);
                                $my_post['post_content'] = str_replace('—', '-', $my_post['post_content']);
                                $my_post['post_content'] = str_replace('genuinely ', '', $my_post['post_content']);
                                $my_post['post_content'] = str_replace(', and', 'and', $my_post['post_content']);
                                $my_post['post_content'] = str_replace(', or', 'or', $my_post['post_content']);
                            }
                            if(!empty($post_excerpt))
                            {
                                $my_post['post_excerpt'] = $post_excerpt;
                            }
                            if(!empty($post_slug))
                            {
                                $my_post['post_name'] = sanitize_title($post_slug);
                            }
                            if (!empty($post_content) && isset($aiomatic_Main_Settings['swear_filter']) && $aiomatic_Main_Settings['swear_filter'] == 'on') 
                            {
                                require_once(dirname(__FILE__) . "/res/swear.php");
                                $my_post['post_content'] = aimogenpro_filterwords($my_post['post_content']);
                            }
                            if (!isset($aiomatic_Main_Settings['no_undetectibility']) || $aiomatic_Main_Settings['no_undetectibility'] != 'on') 
                            {
                                if (!isset($aiomatic_Main_Settings['no_undetectibility_omni']) || $aiomatic_Main_Settings['no_undetectibility_omni'] != 'on') 
                                {
                                    if(!isset($xchars))
                                    {
                                        $xchars = array();
                                    }
                                    $rand_percentage = wp_rand(10, 20);
                                    $my_post['post_content'] = aiomatic_make_unique($my_post['post_content'], $xchars, $rand_percentage);
                                }
                            }
                            if (isset($aiomatic_Main_Settings['convert_gutenberg']) && trim($aiomatic_Main_Settings['convert_gutenberg']) == 'on')
                            {
                                $my_post['post_content'] = aiomatic_convert_html_to_gutenberg_blocks($my_post['post_content']);
                            }
                            $featured_image = $current_block['parameters']['featured_image'];
                            $featured_image = aiomatic_replace_omniblocks_data($featured_image, $current_keyword, $kiwis, $block_results, $load_variables);
                            $post_user_name = $current_block['parameters']['post_author'];
                            $post_user_name = aiomatic_replace_omniblocks_data($post_user_name, $current_keyword, $kiwis, $block_results, $load_variables);
                            if($post_user_name == '%%random_user%%')
                            {
                                $randid = aiomatic_display_random_user();
                                if($randid === false)
                                {
                                    $my_post['post_author']               = aimogen_get_admin_user_id();
                                }
                                else
                                {
                                    $my_post['post_author']               = $randid->ID;
                                }
                            }
                            else
                            {
                                $userid = get_user_by('login', $post_user_name);
                                if($userid !== false)
                                {
                                    $my_post['post_author'] = $userid->ID;
                                }
                                else
                                {
                                    $my_post['post_author'] = $post_user_name;
                                }
                            }
                            $post_status = $current_block['parameters']['post_status'];
                            $post_status = trim($post_status);
                            if(!empty($post_status))
                            {
                                $my_post['post_status'] = $post_status;
                                if (isset($aiomatic_Main_Settings['draft_first']) && $aiomatic_Main_Settings['draft_first'] != 'on')
                                {
                                    if($post_status == 'publish')
                                    {
                                        $draft_me = true;
                                        $my_post['post_status'] = 'draft';
                                    }
                                }
                            }
                            $post_type = $current_block['parameters']['post_type'];
                            $post_type = trim($post_type);
                            if(!empty($post_type))
                            {
                                $my_post['post_type'] = $post_type;
                            }
                            $post_format = $current_block['parameters']['post_format'];
                            $post_format = trim($post_format);
                            $post_parent = $current_block['parameters']['post_parent'];
                            $post_parent = trim($post_parent);
                            if(!empty($post_parent))
                            {
                                $my_post['post_parent'] = intval($post_parent);
                            }
                            $post_comments = $current_block['parameters']['post_comments'];
                            $post_comments = trim($post_comments);
                            if(!empty($post_comments))
                            {
                                if($post_comments == '1')
                                {
                                    $my_post['comment_status'] = 'open';
                                }
                                else
                                {
                                    $my_post['comment_status'] = 'closed';
                                }
                            }
                            $post_pingbacks = $current_block['parameters']['post_pingbacks'];
                            $post_pingbacks = trim($post_pingbacks);
                            if(!empty($post_pingbacks))
                            {
                                if($post_pingbacks == '1')
                                {
                                    $my_post['ping_status'] = 'open';
                                }
                                else
                                {
                                    $my_post['ping_status'] = 'closed';
                                }
                            }
                            $post_date = $current_block['parameters']['post_date'];
                            $post_date = aiomatic_replace_omniblocks_data($post_date, $current_keyword, $kiwis, $block_results, $load_variables);
                            if(strstr($post_date, '~') !== false)
                            {
                                $post_date = explode('~', $post_date);
                                $min_time = trim($post_date[0]);
                                $max_time = trim($post_date[1]);
                                if($min_time != '' && $max_time != '')
                                {
                                    $t1 = strtotime($min_time);
                                    $t2 = strtotime($max_time);
                                    if($t1 != false && $t2 != false)
                                    {
                                        $int = wp_rand($t1, $t2);
                                        $my_post['post_date'] = date('Y-m-d H:i:s', $int);
                                    }
                                }
                            }
                            else
                            {
                                $t1 = strtotime($post_date);
                                if($t1 != false)
                                {
                                    $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                                }
                            }
                            $wpml_lang = $current_block['parameters']['post_lang'];
                            $wpml_lang = aiomatic_replace_omniblocks_data($wpml_lang, $current_keyword, $kiwis, $block_results, $load_variables);
                            $overwrite_existing = $current_block['parameters']['overwrite_existing'];
                            $overwrite_existing = trim($overwrite_existing);
                            if($overwrite_existing == '1')
                            {
                                $posts = get_posts(
                                    array(
                                        'post_type'              => $post_type,
                                        'title'                  => html_entity_decode($post_title),
                                        'post_status'            => 'any',
                                        'numberposts'            => 1,
                                        'update_post_term_cache' => false,
                                        'update_post_meta_cache' => false,           
                                        'orderby'                => 'post_date ID',
                                        'order'                  => 'ASC',
                                    )
                                );
                                if ( ! empty( $posts ) ) {
                                    $zap = $posts[0];
                                } else {
                                    $zap = null;
                                }
                                if($zap !== null)
                                {
                                    $my_post['ID'] = $zap->ID;
                                }
                            }
                            elseif($overwrite_existing == '2')
                            {
                                $posts = get_posts(
                                    array(
                                        'post_type'              => $post_type,
                                        'title'                  => html_entity_decode($post_title),
                                        'post_status'            => 'any',
                                        'numberposts'            => 1,
                                        'update_post_term_cache' => false,
                                        'update_post_meta_cache' => false,           
                                        'orderby'                => 'post_date ID',
                                        'order'                  => 'ASC',
                                    )
                                );
                                if ( ! empty( $posts ) ) {
                                    aiomatic_log_to_file('Post with same title already published, skipping OmniBlock publishing: ' . esc_html($post_title));
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('0', 'skipped');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '0', 'skipped');
                                    continue;
                                }
                            }
                            $custom_fields = $current_block['parameters']['post_custom_fields'];
                            $block_arr = array();
                            $custom_arr = array();
                            if($custom_fields != '')
                            {
                                if(stristr($custom_fields, '=>') != false)
                                {
                                    $rule_arr = explode(',', trim($custom_fields));
                                    foreach($rule_arr as $rule)
                                    {
                                        $my_args = explode('=>', trim($rule));
                                        if(isset($my_args[1]))
                                        {
                                            $my_args[1] = do_shortcode($my_args[1]);
                                            $my_args[0] = do_shortcode($my_args[0]);
                                            $my_args[0] = aiomatic_replace_omniblocks_data($my_args[0], $current_keyword, $kiwis, $block_results, $load_variables);
                                            $custom_field_content = trim($my_args[1]);
                                            $custom_field_content = aiomatic_replace_omniblocks_data($custom_field_content, $current_keyword, $kiwis, $block_results, $load_variables);
                                            if(stristr($my_args[1], 'serialize_') !== false)
                                            {
                                                $custom_arr[trim($my_args[0])] = array(str_replace('serialize_', '', $custom_field_content));
                                            }
                                            else
                                            {
                                                if(stristr($my_args[0], '[') !== false && stristr($my_args[0], ']') !== false)
                                                {
                                                    preg_match_all('#([^\[\]]*?)\[([^\[\]]*?)\]#', $my_args[0], $cfm);
                                                    if(isset($cfm[2][0]))
                                                    {
                                                        if(isset($custom_arr[trim($cfm[1][0])]) && is_array($custom_arr[trim($cfm[1][0])]))
                                                        {
                                                            $custom_arr[trim($cfm[1][0])] = array_merge($custom_arr[trim($cfm[1][0])], array(trim($cfm[2][0]) => $custom_field_content));
                                                        }
                                                        else
                                                        {
                                                            $custom_arr[trim($cfm[1][0])] = array(trim($cfm[2][0]) => $custom_field_content);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        $custom_arr[trim($my_args[0])] = $custom_field_content;
                                                    }
                                                }
                                                else
                                                {
                                                    $custom_arr[trim($my_args[0])] = $custom_field_content;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if(!empty($custom_arr))
                            {
                                $my_post['meta_input'] = $custom_arr;
                            }
                            $post_categories = $current_block['parameters']['post_categories'];
                            $post_categories = aiomatic_replace_omniblocks_data($post_categories, $current_keyword, $kiwis, $block_results, $load_variables);
                            $post_tags = $current_block['parameters']['post_tags'];
                            $post_tags = aiomatic_replace_omniblocks_data($post_tags, $current_keyword, $kiwis, $block_results, $load_variables);
                            if(!empty($post_tags))
                            {
                                $my_post['tags_input'] = $post_tags;
                            }
                            $post_custom_taxonomies = $current_block['parameters']['post_custom_taxonomies'];
                            $custom_tax_arr = array();
                            if($post_custom_taxonomies != '')
                            {
                                if(stristr($post_custom_taxonomies, '=>') != false)
                                {
                                    $rule_arr = explode(';', trim($post_custom_taxonomies));
                                    foreach($rule_arr as $rule)
                                    {
                                        $my_args = explode('=>', trim($rule));
                                        if(isset($my_args[1]))
                                        {
                                            $custom_tax_content = trim($my_args[1]);
                                            $custom_tax_content = aiomatic_replace_omniblocks_data($custom_tax_content, $current_keyword, $kiwis, $block_results, $load_variables);
                                            $my_args[0] = aiomatic_replace_omniblocks_data($my_args[0], $current_keyword, $kiwis, $block_results, $load_variables);
                                            $spintax = new Aiomatic_Spintax();
                                            $custom_tax_content = $spintax->Parse($custom_tax_content, $block_arr);
                                            if(isset($custom_tax_arr[trim($my_args[0])]))
                                            {
                                                $custom_tax_arr[trim($my_args[0])] .= ',' . $custom_tax_content;
                                            }
                                            else
                                            {
                                                $custom_tax_arr[trim($my_args[0])] = $custom_tax_content;
                                            }
                                        }
                                    }
                                }
                            }
                            if(count($custom_tax_arr) > 0)
                            {
                                $my_post['taxo_input'] = $custom_tax_arr;
                            }
                            if(isset($current_block['parameters']['post_id']))
                            {
                                $uppost_id = $current_block['parameters']['post_id'];
                                $uppost_id = aiomatic_replace_omniblocks_data($uppost_id, $current_keyword, $kiwis, $block_results, $load_variables);
                            }
                            else
                            {
                                $uppost_id = '';
                            }
                            if(!empty($uppost_id))
                            {
                                $my_post['ID'] = $uppost_id;
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Saving OmniBlock Post'));
                            
                            remove_filter('content_save_pre', 'wp_filter_post_kses');
                            remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                            try
                            {
                                if(!empty($uppost_id))
                                {
                                    $post_id = wp_update_post($my_post, true);
                                }
                                else
                                {
                                    $my_post['post_content'] = str_replace('\r\n', '', $my_post['post_content']);
                                    $post_id = wp_insert_post($my_post, true);
                                    if (is_wp_error($post_id)) 
                                    {
                                        aiomatic_log_to_file('Trying publishing again');
                                        if (aiomatic_strlen($my_post['post_content']) > 16777215) {
                                            $my_post['post_content'] = aiomatic_substr($my_post['post_content'], 0, 16777215);
                                        }
                                        $my_post['post_content'] = wp_kses_post($my_post['post_content']);
                                        $my_post['post_content'] = str_replace('\r\n', '', $my_post['post_content']);
                                        $post_id = wp_insert_post($my_post, true);
                                    }
                                }
                            }
                            catch(Exception $e)
                            {
                                aiomatic_log_to_file('Exception in publishing post (this is coming from another plugin, so we ignore it): ' . $e->getMessage());
                            }
                            add_filter('content_save_pre', 'wp_filter_post_kses');
                            add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                            if (!is_wp_error($post_id)) 
                            {
                                if($post_id === 0)
                                {
                                    aiomatic_log_to_file('An error occurred while inserting post into wp database! Title:' . $my_post['post_title']);
                                    if($critical == '1')
                                    {
                                        return 'fail';
                                    }
                                    else
                                    {
                                        if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                        {
                                            return array('', '');
                                        }
                                        $block_results[$block_id] = array($current_block['type'], '', '');
                                        continue;
                                    }
                                }
                                else
                                {
                                    $words = str_word_count(wp_strip_all_tags($my_post['post_content']));
                                    aiomatic_increment_publishing_stats($words);
                                aimogen_bulk_on_post_created($post_id, $my_post['post_title'], isset($new_post_excerpt) ? $new_post_excerpt : '', isset($post_topic) ? $post_topic : (isset($post_title) ? $post_title : ''));
                                    aiomatic_set_last_activity(
                                        'article',
                                        ['post_id' => $post_id]
                                    );
                                    $posts_inserted++;
                                    if(!isset($my_post['taxo_input']))
                                    {
                                        $my_post['taxo_input'] = array();
                                    }
                                    if(!empty($featured_image))
                                    {
                                        if(is_numeric($featured_image))
                                        {
                                            $featured_path = aiomatic_assign_featured_image($featured_image, $post_id);
                                        }
                                        else
                                        {
                                            $go_local_image = false;
                                            if(!function_exists('is_plugin_active'))
                                            {
                                                include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                                            }
                                            if ((is_plugin_active('featured-image-from-url/featured-image-from-url.php') || is_plugin_active('fifu-premium/fifu-premium.php')) && isset($aiomatic_Main_Settings['url_image']) && trim($aiomatic_Main_Settings['url_image']) == 'on' && isset($aiomatic_Main_Settings['copy_locally']) && $aiomatic_Main_Settings['copy_locally'] != 'disabled' && $aiomatic_Main_Settings['copy_locally'] != 'on') 
                                            {
                                                $go_local_image = true;
                                            }
                                            if($go_local_image == true)
                                            {
                                                $localpath = aiomatic_copy_image_locally($featured_image, $attached_id, '', false, '');
                                                if(!empty($attached_id))
                                                {
                                                    $additional_attachments[] = $attached_id;
                                                }
                                                if($localpath !== false)
                                                {
                                                    $featured_image = $localpath[0];
                                                }
                                            }
                                            if (!aiomatic_generate_featured_image($featured_image, $post_id)) {
                                                aiomatic_log_to_file('Failed to generate featured image for post ID: ' . $post_id . ' - image URL: ' . $featured_image);
                                                if($critical == '1')
                                                {
                                                    return 'fail';
                                                }
                                                else
                                                {
                                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                                    {
                                                        return array('', '');
                                                    }
                                                    $block_results[$block_id] = array($current_block['type'], '', '');
                                                    continue;
                                                }
                                            }
                                        }
                                    }
                                    $cat_str = http_build_query($my_post['taxo_input'], '', ',');
                                    $wp_default_category = get_option('default_category');
                                    $def_cat_name = get_cat_name($wp_default_category);
                                    $default_categories = array();
                                    $extra_cats = explode(',', $post_categories);
                                    if(($post_categories != '' && !in_array($def_cat_name, $extra_cats)) || (isset($my_post['taxo_input']) && stristr($cat_str, 'category') !== false && strstr($cat_str, $def_cat_name) === false && !in_array($def_cat_name, $extra_cats)))
                                    {
                                        $default_categories = wp_get_post_categories($post_id);
                                    }
                                    if(isset($my_post['taxo_input']))
                                    {
                                        foreach($my_post['taxo_input'] as $taxn => $taxval)
                                        {
                                            $taxn = trim($taxn);
                                            $taxval = trim($taxval);
                                            if(is_taxonomy_hierarchical($taxn))
                                            {
                                                $taxval = array_map('trim', explode(',', $taxval));
                                                for($ii = 0; $ii < count($taxval); $ii++)
                                                {
                                                    if(!is_numeric($taxval[$ii]))
                                                    {
                                                        $term_ids = [];
                                                        $parent_id = 0;
                                                        $hierarchy_parts = array_map('trim', explode('>', $taxval[$ii]));
                                                        foreach($hierarchy_parts as $hp)
                                                        {
                                                            if(!is_numeric($hp))
                                                            {
                                                                $xtermid = get_term_by('name', $hp, $taxn);
                                                                if($xtermid !== false)
                                                                {
                                                                    $parent_id = $xtermid->term_id;
                                                                    if(!is_numeric($taxval[$ii]))
                                                                    {
                                                                        $taxval[$ii] = intval($xtermid->term_id);
                                                                    }
                                                                    else
                                                                    {
                                                                        $taxval[] = intval($xtermid->term_id);
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    wp_insert_term( $hp, $taxn, ['parent' => $parent_id]);
                                                                    $xtermid = get_term_by('name', $hp, $taxn);
                                                                    if($xtermid !== false)
                                                                    {
                                                                        $parent_id = $xtermid->term_id;
                                                                        if($wpml_lang != '' && function_exists('pll_set_term_language'))
                                                                        {
                                                                            pll_set_term_language($xtermid->term_id, $wpml_lang); 
                                                                        }
                                                                        elseif($wpml_lang != '' && has_filter('wpml_object_id'))
                                                                        {
                                                                            $wpml_element_type = apply_filters( 'wpml_element_type', $taxn );
                                                                            $pars['element_id'] = $xtermid->term_id;
                                                                            $pars['element_type'] = $wpml_element_type;
                                                                            $pars['language_code'] = $wpml_lang;
                                                                            $pars['trid'] = FALSE;
                                                                            $pars['source_language_code'] = NULL;
                                                                            do_action('wpml_set_element_language_details', $pars);
                                                                        }
                                                                        if(!is_numeric($taxval[$ii]))
                                                                        {
                                                                            $taxval[$ii] = intval($xtermid->term_id);
                                                                        }
                                                                        else
                                                                        {
                                                                            $taxval[] = intval($xtermid->term_id);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                if(!is_numeric($taxval[$ii]))
                                                                {
                                                                    $taxval[$ii] = intval($hp);
                                                                }
                                                                else
                                                                {
                                                                    $taxval[] = intval($hp);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                wp_set_post_terms($post_id, $taxval, $taxn, true);
                                            }
                                            else
                                            {
                                                $jterms = array_map('trim', explode(',', $taxval));
                                                wp_set_post_terms($post_id, $jterms, $taxn, true);
                                            }
                                        }
                                    }
                                    if(!empty($post_format) && $post_format != 'post-format-standard')
                                    {
                                        wp_set_post_terms($post_id, $post_format, 'post_format', true);
                                    }
                                    if($wpml_lang != '' && function_exists('pll_set_post_language'))
                                    {
                                        pll_set_post_language($post_id, $wpml_lang);
                                    }
                                    if(!empty($additional_attachments))
                                    {
                                        foreach($additional_attachments as $add_att)
                                        {
                                            wp_update_post([
                                                'ID' => $add_att,
                                                'post_parent' => $post_id,
                                            ]);
                                        }
                                    }
                                    if($wpml_lang != '' && (class_exists('SitePress') || function_exists('wpml_object_id')))
                                    {
                                        $wpml_element_type = apply_filters( 'wpml_element_type', $post_type );
                                        $pars['element_id'] = $post_id;
                                        $pars['element_type'] = $wpml_element_type;
                                        $pars['language_code'] = $wpml_lang;
                                        $pars['source_language_code'] = NULL;
                                        do_action('wpml_set_element_language_details', $pars);

                                        global $wp_filesystem;
                                        if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
                                            include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() );
                                            wp_filesystem($creds);
                                        }
                                        if($wp_filesystem->exists(WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php'))
                                        {
                                            include_once( WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php' );
                                        }
                                        if(function_exists('wpml_update_translatable_content'))
                                        {
                                            wpml_update_translatable_content('post_' . $post_type, $post_id, $wpml_lang);
                                            if($my_post['post_title'] != '')
                                            {
                                                global $sitepress;
                                                global $wpdb;
                                                $keyid = md5($my_post['post_title']);
                                                $keyName = $keyid . '_wpml';
                                                $rezxxxa = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}postmeta WHERE `meta_key` = '$keyName' limit 1", ARRAY_A );
                                                if(count($rezxxxa) != 0)
                                                {
                                                    $metaRow = $rezxxxa[0];
                                                    $metaValue = $metaRow['meta_value'];
                                                    $metaParts = explode('_', $metaValue);
                                                    $sitepress->set_element_language_details($post_id, 'post_'.$my_post['post_type'] , $metaParts[0], $wpml_lang, $metaParts[1] ); 
                                                }
                                                else
                                                {
                                                    $ptrid = $sitepress->get_element_trid($post_id);
                                                    update_post_meta($post_id, $keyid.'_wpml', $ptrid.'_'.$wpml_lang );
                                                }
                                            }
                                            
                                        }
                                    }
                                    if(!empty($post_custom_taxonomies))
                                    {
                                        $custom_tax_arr = array();
                                        if(stristr($post_custom_taxonomies, '=>') != false)
                                        {
                                            $rule_arr = explode(';', trim($post_custom_taxonomies));
                                            foreach($rule_arr as $rule)
                                            {
                                                $my_args = explode('=>', trim($rule));
                                                if(isset($my_args[1]))
                                                {
                                                    $custom_tax_content = trim($my_args[1]);
                                                    $custom_tax_content = aiomatic_replace_omniblocks_data($custom_tax_content, $current_keyword, $kiwis, $block_results, $load_variables);
                                                    if(aiomatic_substr(trim($my_args[0]), 0, 3) === "pa_" && $post_type == 'product' && !empty($custom_tax_content))
                                                    {
                                                        if(isset($custom_arr['_product_attributes']))
                                                        {
                                                            $custom_arr['_product_attributes'] = array_merge($custom_arr['_product_attributes'], array(trim($my_args[0]) =>array(
                                                                'name' => trim($my_args[0]),
                                                                'value' => $custom_tax_content,
                                                                'is_visible' => '1',
                                                                'is_taxonomy' => '1'
                                                            )));
                                                        }
                                                        else
                                                        {
                                                            $custom_arr['_product_attributes'] = array(trim($my_args[0]) =>array(
                                                                'name' => trim($my_args[0]),
                                                                'value' => $custom_tax_content,
                                                                'is_visible' => '1',
                                                                'is_taxonomy' => '1'
                                                            ));
                                                        }
                                                    }
                                                    if(isset($custom_tax_arr[trim($my_args[0])]))
                                                    {
                                                        $custom_tax_arr[trim($my_args[0])] .= ',' . $custom_tax_content;
                                                    }
                                                    else
                                                    {
                                                        $custom_tax_arr[trim($my_args[0])] = $custom_tax_content;
                                                    }
                                                }
                                            }
                                        }
                                        foreach($custom_tax_arr as $taxn => $taxval)
                                        {
                                            $taxn = trim($taxn);
                                            $taxval = trim($taxval);
                                            if(is_taxonomy_hierarchical($taxn))
                                            {
                                                $taxval = array_map('trim', explode(',', $taxval));
                                                for($ii = 0; $ii < count($taxval); $ii++)
                                                {
                                                    if(!is_numeric($taxval[$ii]))
                                                    {
                                                        $term_ids = [];
                                                        $parent_id = 0;
                                                        $hierarchy_parts = array_map('trim', explode('>', $taxval[$ii]));
                                                        foreach($hierarchy_parts as $hp)
                                                        {
                                                            if(!is_numeric($hp))
                                                            {
                                                                $xtermid = get_term_by('name', $hp, $taxn);
                                                                if($xtermid !== false)
                                                                {
                                                                    $parent_id = $xtermid->term_id;
                                                                    if(!is_numeric($taxval[$ii]))
                                                                    {
                                                                        $taxval[$ii] = intval($xtermid->term_id);
                                                                    }
                                                                    else
                                                                    {
                                                                        $taxval[] = intval($xtermid->term_id);
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    wp_insert_term( $hp, $taxn, ['parent' => $parent_id]);
                                                                    $xtermid = get_term_by('name', $hp, $taxn);
                                                                    if($xtermid !== false)
                                                                    {
                                                                        $parent_id = $xtermid->term_id;
                                                                        if($wpml_lang != '' && function_exists('pll_set_term_language'))
                                                                        {
                                                                            pll_set_term_language($xtermid->term_id, $wpml_lang); 
                                                                        }
                                                                        elseif($wpml_lang != '' && has_filter('wpml_object_id'))
                                                                        {
                                                                            $wpml_element_type = apply_filters( 'wpml_element_type', $taxn );
                                                                            $pars['element_id'] = $xtermid->term_id;
                                                                            $pars['element_type'] = $wpml_element_type;
                                                                            $pars['language_code'] = $wpml_lang;
                                                                            $pars['trid'] = FALSE;
                                                                            $pars['source_language_code'] = NULL;
                                                                            do_action('wpml_set_element_language_details', $pars);
                                                                        }
                                                                        if(!is_numeric($taxval[$ii]))
                                                                        {
                                                                            $taxval[$ii] = intval($xtermid->term_id);
                                                                        }
                                                                        else
                                                                        {
                                                                            $taxval[] = intval($xtermid->term_id);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                if(!is_numeric($taxval[$ii]))
                                                                {
                                                                    $taxval[$ii] = intval($hp);
                                                                }
                                                                else
                                                                {
                                                                    $taxval[] = intval($hp);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                wp_set_post_terms($post_id, $taxval, $taxn, true);
                                            }
                                            else
                                            {
                                                $jterms = array_map('trim', explode(',', $taxval));
                                                wp_set_post_terms($post_id, $jterms, $taxn, true);
                                            }
                                        }
                                    }
                                    if ($post_categories != '') 
                                    {
                                        if($post_type == 'product')
                                        {
                                            $product_tax = 'product_cat';
                                        }
                                        else
                                        {
                                            $product_tax = 'category';
                                        }
                                        foreach($extra_cats as $extra_cat)
                                        {
                                            $extra_cat = trim($extra_cat);
                                            $extra_cat = strip_tags($extra_cat);
                                            $extra_cat = preg_replace('#^\d+\.\s*#', '', $extra_cat);
                                            if(empty($extra_cat))
                                            {
                                                continue;
                                            }
                                            if ($skip_inexist == '1') 
                                            {
                                                if(!term_exists($extra_cat, $product_tax))
                                                {
                                                    continue;
                                                }
                                            }
                                            $termid = aiomatic_create_terms($product_tax, null, trim($extra_cat));
                                            wp_set_post_terms($post_id, $termid, $product_tax, true);
                                            if($wpml_lang != '' && function_exists('pll_set_term_language'))
                                            {
                                                foreach($termid as $tx)
                                                {
                                                    pll_set_term_language($tx, $wpml_lang); 
                                                }
                                            }
                                            elseif($wpml_lang != '' && has_filter('wpml_object_id'))
                                            {
                                                $wpml_element_type = apply_filters( 'wpml_element_type', 'product_cat' );
                                                foreach($termid as $tx)
                                                {
                                                    $pars['element_id'] = $tx;
                                                    $pars['element_type'] = $wpml_element_type;
                                                    $pars['language_code'] = $wpml_lang;
                                                    $pars['trid'] = FALSE;
                                                    $pars['source_language_code'] = NULL;
                                                    do_action('wpml_set_element_language_details', $pars);
                                                }
                                            }
                                        }
                                    }
                                    if (isset($my_post['tags_input']) && $my_post['tags_input'] != '')
                                    {
                                        if($post_type == 'product')
                                        {
                                            wp_set_post_terms($post_id, $my_post['tags_input'], 'product_tag', true);
                                        }
                                    }
                                    $tax_rez = wp_set_object_terms( $post_id, 'aiomatic_' . $type . '_' . $param, 'coderevolution_post_source', true);
                                    if (is_wp_error($tax_rez)) {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('wp_set_object_terms failed for: ' . $post_id . '!');
                                        }
                                    }
                                    if($post_type == 'topic' && $parent_id != '')
                                    {
                                        update_post_meta($post_id, '_bbp_forum_id', $parent_id);
                                        update_post_meta($post_id, '_bbp_topic_id', $post_id);
                                        update_post_meta($post_id, '_bbp_voice_count', '0');
                                        update_post_meta($post_id, '_bbp_reply_count', '0');
                                        update_post_meta($post_id, '_bbp_reply_count_hidden', '0');
                                        update_post_meta($post_id, '_bbp_last_reply_id', '0');
                                        update_post_meta($post_id, '_bbp_last_active_id', $post_id);
                                        update_post_meta($post_id, '_bbp_last_active_time', get_post_field( 'post_date', $topic_id, 'db' ));
                                        do_action( 'bbp_insert_topic', (int) $post_id, (int) $parent_id );
                                    }
                                    if($post_type == 'reply' && $parent_id != '')
                                    {
                                        if(function_exists('bbp_get_topic_forum_id'))
                                        {
                                            $forum_aidi = bbp_get_topic_forum_id($parent_id);
                                            if(empty($forum_aidi))
                                            {
                                                $forum_aidi = 0;
                                            }
                                        }
                                        else
                                        {
                                            $forum_aidi = 0;
                                        }
                                        do_action( 'bbp_insert_reply', (int) $post_id, (int) $parent_id, (int) $forum_aidi );
                                    }
                                    if(($post_categories != '' && !in_array($def_cat_name, $extra_cats)) || (isset($my_post['taxo_input']) && stristr($cat_str, 'category') !== false && strstr($cat_str, $def_cat_name) === false && !in_array($def_cat_name, $extra_cats)))
                                    {
                                        $new_categories = wp_get_post_categories($post_id);
                                        if(isset($default_categories) && !($default_categories == $new_categories))
                                        {
                                            foreach($default_categories as $dc)
                                            {
                                                $rem_cat = get_category( $dc );
                                                wp_remove_object_terms( $post_id, $rem_cat->slug, 'category' );
                                            }
                                        }
                                    }
                                    aiomatic_addPostMeta_special($post_id, $param, $type, $current_keyword, $rule_unique_id);
                                    if (isset($aiomatic_Main_Settings['draft_first']) && $aiomatic_Main_Settings['draft_first'] == 'on' && $draft_me == true)
                                    {
                                        aiomatic_change_post_status($post_id, 'publish');
                                    }
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array($post_id, get_permalink($post_id));
                                    }
                                    $block_results[$block_id] = array($current_block['type'], $post_id, get_permalink($post_id));
                                }
                            }
                            else 
                            {
                                aiomatic_log_to_file('Failed to insert post into wp database(6)! Title:' . $my_post['post_title'] . '! Error: ' . $post_id->get_error_message() . ' Error code: ' . $post_id->get_error_code() . ' Error data: ' . $post_id->get_error_data());
                                if($critical == '1')
                                {
                                    return 'fail';
                                }
                                else
                                {
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '');
                                    continue;
                                }
                            }
                        }
                        elseif($current_block['type'] == 'save_product')
                        {
                            $post_title = aiomatic_replace_omniblocks_data($current_block['parameters']['post_title'], $current_keyword, $kiwis, $block_results, $load_variables);
                            $post_content = aiomatic_replace_omniblocks_data($current_block['parameters']['post_content'], $current_keyword, $kiwis, $block_results, $load_variables);
                            $post_excerpt = aiomatic_replace_omniblocks_data($current_block['parameters']['post_excerpt'], $current_keyword, $kiwis, $block_results, $load_variables);
                            
                            if (empty($post_title)) {
                                aiomatic_log_to_file('Product title is empty, skipping.');
                                continue;
                            }

                            $my_post = array(
                                'post_title'   => aiomatic_truncate_title($post_title),
                                'post_content' => $post_content,
                                'post_excerpt' => $post_excerpt,
                                'post_status'  => aiomatic_replace_omniblocks_data($current_block['parameters']['post_status'], $current_keyword, $kiwis, $block_results, $load_variables),
                                'post_type'    => 'product',
                            );
                            $post_user_name = $current_block['parameters']['post_author'];
                            $post_user_name = aiomatic_replace_omniblocks_data($post_user_name, $current_keyword, $kiwis, $block_results, $load_variables);
                            if($post_user_name == '%%random_user%%')
                            {
                                $randid = aiomatic_display_random_user();
                                if($randid === false)
                                {
                                    $my_post['post_author']               = aimogen_get_admin_user_id();
                                }
                                else
                                {
                                    $my_post['post_author']               = $randid->ID;
                                }
                            }
                            else
                            {
                                $userid = get_user_by('login', $post_user_name);
                                if($userid !== false)
                                {
                                    $my_post['post_author'] = $userid->ID;
                                }
                                else
                                {
                                    $my_post['post_author'] = $post_user_name;
                                }
                            }
                            $post_date = $current_block['parameters']['post_date'];
                            $post_date = aiomatic_replace_omniblocks_data($post_date, $current_keyword, $kiwis, $block_results, $load_variables);
                            if(strstr($post_date, '~') !== false)
                            {
                                $post_date = explode('~', $post_date);
                                $min_time = trim($post_date[0]);
                                $max_time = trim($post_date[1]);
                                if($min_time != '' && $max_time != '')
                                {
                                    $t1 = strtotime($min_time);
                                    $t2 = strtotime($max_time);
                                    if($t1 != false && $t2 != false)
                                    {
                                        $int = wp_rand($t1, $t2);
                                        $my_post['post_date'] = date('Y-m-d H:i:s', $int);
                                    }
                                }
                            }
                            else
                            {
                                $t1 = strtotime($post_date);
                                if($t1 != false)
                                {
                                    $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                                }
                            }
                            if(isset($current_block['parameters']['post_slug']))
                            {
                                $post_slug = $current_block['parameters']['post_slug'];
                                $post_slug = aiomatic_replace_omniblocks_data($post_slug, $current_keyword, $kiwis, $block_results, $load_variables);
                            }
                            else
                            {
                                $post_slug = '';
                            }
                            if(!empty($post_slug))
                            {
                                $my_post['post_name'] = sanitize_title($post_slug);
                            }
                            $overwrite = aiomatic_replace_omniblocks_data($current_block['parameters']['overwrite_existing'], $current_keyword, $kiwis, $block_results, $load_variables);
                            $existing_id = aiomatic_replace_omniblocks_data($current_block['parameters']['post_id'], $current_keyword, $kiwis, $block_results, $load_variables);
                            
                            if (!empty($existing_id)) {
                                $my_post['ID'] = $existing_id;
                            } elseif ($overwrite == '1') {
                                $existing_post = aiomatic_get_page_by_title($post_title, OBJECT, 'product');
                                if ($existing_post) {
                                    $my_post['ID'] = $existing_post->ID;
                                }
                            }

                            $product_id = wp_insert_post($my_post);

                            if (!is_wp_error($product_id) && $product_id > 0) {
                                
                                if ( !class_exists( 'WooCommerce' ) ) 
                                {
                                    aiomatic_log_to_file('WooCommerce is not active, cannot create product!');
                                    continue;
                                }
                                $words = str_word_count(wp_strip_all_tags($my_post['post_content']));
                                aiomatic_increment_publishing_stats($words);
                                aimogen_bulk_on_post_created($post_id, $my_post['post_title'], isset($new_post_excerpt) ? $new_post_excerpt : '', isset($post_topic) ? $post_topic : (isset($post_title) ? $post_title : ''));
                                aiomatic_set_last_activity(
                                    'article',
                                    ['post_id' => $product_id]
                                );
                                $product = wc_get_product($product_id);
                                
                                $type = aiomatic_replace_omniblocks_data($current_block['parameters']['product_type'], $current_keyword, $kiwis, $block_results, $load_variables); 
                                if ($type == 'external') {
                                    $product = new WC_Product_External($product_id);
                                    
                                    $ext_url = aiomatic_replace_omniblocks_data($current_block['parameters']['external_url'], $current_keyword, $kiwis, $block_results, $load_variables);
                                    if (!empty($ext_url)) $product->set_product_url($ext_url);

                                    $btn_text = aiomatic_replace_omniblocks_data($current_block['parameters']['button_text'], $current_keyword, $kiwis, $block_results, $load_variables);
                                    if (!empty($btn_text)) $product->set_button_text($btn_text);
                                }
                                $reg_price = aiomatic_replace_omniblocks_data($current_block['parameters']['regular_price'], $current_keyword, $kiwis, $block_results, $load_variables);
                                if ($reg_price !== '') $product->set_regular_price($reg_price);

                                $sale_price = aiomatic_replace_omniblocks_data($current_block['parameters']['sale_price'], $current_keyword, $kiwis, $block_results, $load_variables);
                                if ($sale_price !== '') $product->set_sale_price($sale_price);

                                $sku = aiomatic_replace_omniblocks_data($current_block['parameters']['sku'], $current_keyword, $kiwis, $block_results, $load_variables);
                                if (!empty($sku)) $product->set_sku($sku);

                                if (isset($current_block['parameters']['manage_stock'])) {
                                    $manage_stock = (aiomatic_replace_omniblocks_data($current_block['parameters']['manage_stock'], $current_keyword, $kiwis, $block_results, $load_variables) == '1');
                                    $product->set_manage_stock($manage_stock);
                                    
                                    if ($manage_stock && isset($current_block['parameters']['stock_quantity'])) {
                                        $product->set_stock_quantity(aiomatic_replace_omniblocks_data($current_block['parameters']['stock_quantity'], $current_keyword, $kiwis, $block_results, $load_variables));
                                    }
                                }
                                if (!empty($current_block['parameters']['weight'])) $product->set_weight(aiomatic_replace_omniblocks_data($current_block['parameters']['weight'], $current_keyword, $kiwis, $block_results, $load_variables));
                                if (!empty($current_block['parameters']['length'])) $product->set_length(aiomatic_replace_omniblocks_data($current_block['parameters']['length'], $current_keyword, $kiwis, $block_results, $load_variables));
                                if (!empty($current_block['parameters']['width']))  $product->set_width(aiomatic_replace_omniblocks_data($current_block['parameters']['width'], $current_keyword, $kiwis, $block_results, $load_variables));
                                if (!empty($current_block['parameters']['height'])) $product->set_height(aiomatic_replace_omniblocks_data($current_block['parameters']['height'], $current_keyword, $kiwis, $block_results, $load_variables));

                                $purchase_note = aiomatic_replace_omniblocks_data($current_block['parameters']['purchase_note'], $current_keyword, $kiwis, $block_results, $load_variables);
                                if (!empty($purchase_note)) $product->set_purchase_note($purchase_note);

                                if (!empty($current_block['parameters']['upsell_ids'])) {
                                    $upsells = explode(',', aiomatic_replace_omniblocks_data($current_block['parameters']['upsell_ids'], $current_keyword, $kiwis, $block_results, $load_variables));
                                    $product->set_upsell_ids(array_filter(array_map('intval', $upsells)));
                                }
                                $product->save();

                                $cats = aiomatic_replace_omniblocks_data($current_block['parameters']['post_categories'], $current_keyword, $kiwis, $block_results, $load_variables);
                                if (!empty($cats)) {
                                    wp_set_object_terms($product_id, explode(',', $cats), 'product_cat');
                                }

                                $tags = aiomatic_replace_omniblocks_data($current_block['parameters']['post_tags'], $current_keyword, $kiwis, $block_results, $load_variables);
                                if (!empty($tags)) {
                                    wp_set_object_terms($product_id, explode(',', $tags), 'product_tag');
                                }

                                $feat_img = aiomatic_replace_omniblocks_data($current_block['parameters']['featured_image'], $current_keyword, $kiwis, $block_results, $load_variables);
                                if (!empty($feat_img)) {
                                    $attachment_id = is_numeric($feat_img) ? $feat_img : aiomatic_copy_image_locally($feat_img, $product_id);
                                    set_post_thumbnail($product_id, $attachment_id);
                                }

                                $gallery = aiomatic_replace_omniblocks_data($current_block['parameters']['gallery_images'], $current_keyword, $kiwis, $block_results, $load_variables);
                                if (!empty($gallery)) {
                                    $gallery_ids = array();
                                    foreach (explode(',', $gallery) as $g_url) {
                                        $g_url = trim($g_url);
                                        $gallery_ids[] = is_numeric($g_url) ? $g_url : aiomatic_copy_image_locally($g_url, $product_id);
                                    }
                                    $product->set_gallery_image_ids($gallery_ids);
                                    $product->save();
                                }
                                aiomatic_addPostMeta_special($product_id, $param, $type, $current_keyword, $rule_unique_id);
                                if (isset($aiomatic_Main_Settings['draft_first']) && $aiomatic_Main_Settings['draft_first'] == 'on' && $draft_me == true)
                                {
                                    aiomatic_change_post_status($product_id, 'publish');
                                }
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array($product_id, get_permalink($product_id));
                                }
                                $block_results[$block_id] = array($current_block['type'], $product_id, get_permalink($product_id));
                            }
                            else 
                            {
                                aiomatic_log_to_file('Failed to insert product into wp database! Title:' . $my_post['post_title'] . '! Error: ' . $product_id->get_error_message() . ' Error code: ' . $product_id->get_error_code() . ' Error data: ' . $product_id->get_error_data());
                                if($critical == '1')
                                {
                                    return 'fail';
                                }
                                else
                                {
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('', '');
                                    }
                                    $block_results[$block_id] = array($current_block['type'], '', '');
                                    continue;
                                }
                            }
                        }
                        elseif($current_block['type'] == 'if_block')
                        {
                            $condition = $current_block['parameters']['condition'];
                            $condition = aiomatic_replace_omniblocks_data($condition, $current_keyword, $kiwis, $block_results, $load_variables);
                            $evaluation_method = $current_block['parameters']['evaluation_method'];
                            $expected_value = $current_block['parameters']['expected_value'];
                            $expected_value = aiomatic_replace_omniblocks_data($expected_value, $current_keyword, $kiwis, $block_results, $load_variables);
                            $true_blocks = $current_block['parameters']['true_blocks'];
                            $true_blocks = aiomatic_replace_omniblocks_data($true_blocks, $current_keyword, $kiwis, $block_results, $load_variables);
                            $true_blocks = explode(',', $true_blocks);
                            $true_blocks = array_map('trim', $true_blocks);
                            $true_blocks = array_filter($true_blocks);
                            $false_blocks = $current_block['parameters']['false_blocks'];
                            $false_blocks = aiomatic_replace_omniblocks_data($false_blocks, $current_keyword, $kiwis, $block_results, $load_variables);
                            $false_blocks = explode(',', $false_blocks);
                            $false_blocks = array_map('trim', $false_blocks);
                            $false_blocks = array_filter($false_blocks);
                            if (empty($evaluation_method)) 
                            {
                                if($critical == '1')
                                {
                                    aiomatic_log_to_file('Halting execution (empty evaluation_method), as critical block failed (ID ' . esc_html($block_id) . ')');
                                    return 'fail';
                                }
                                else
                                {
                                    aiomatic_log_to_file('Empty evaluation_method entered');
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            $new_blocks = [];
                            $condition_met = 'not_run';
                            if($evaluation_method == 'equals')
                            {
                                if($condition == $expected_value)
                                {
                                    $condition_met = true;
                                }
                                else
                                {
                                    $condition_met = false;
                                }
                            }
                            elseif($evaluation_method == 'not_equals')
                            {
                                if($condition != $expected_value)
                                {
                                    $condition_met = true;
                                }
                                else
                                {
                                    $condition_met = false;
                                }
                            }
                            elseif($evaluation_method == 'contains')
                            {
                                if(strstr($condition, $expected_value) !== false)
                                {
                                    $condition_met = true;
                                }
                                else
                                {
                                    $condition_met = false;
                                }
                            }
                            elseif($evaluation_method == 'not_contains')
                            {
                                if(strstr($condition, $expected_value) === false)
                                {
                                    $condition_met = true;
                                }
                                else
                                {
                                    $condition_met = false;
                                }
                            }
                            elseif($evaluation_method == 'greater_than')
                            {
                                if(floatval($conditio) > floatval($expected_value))
                                {
                                    $condition_met = true;
                                }
                                else
                                {
                                    $condition_met = false;
                                }
                            }
                            elseif($evaluation_method == 'starts_with')
                            {
                                if(aiomatic_starts_with($conditio, $expected_value) === true)
                                {
                                    $condition_met = true;
                                }
                                else
                                {
                                    $condition_met = false;
                                }
                            }
                            elseif($evaluation_method == 'not_starts_with')
                            {
                                if(aiomatic_starts_with($conditio, $expected_value) === false)
                                {
                                    $condition_met = true;
                                }
                                else
                                {
                                    $condition_met = false;
                                }
                            }
                            elseif($evaluation_method == 'ends_with')
                            {
                                if(aiomatic_ends_with($conditio, $expected_value) === true)
                                {
                                    $condition_met = true;
                                }
                                else
                                {
                                    $condition_met = false;
                                }
                            }
                            elseif($evaluation_method == 'not_ends_with')
                            {
                                if(aiomatic_ends_with($conditio, $expected_value) === false)
                                {
                                    $condition_met = true;
                                }
                                else
                                {
                                    $condition_met = false;
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Unknown expected_value parameter sent: ' . $evaluation_method);
                            }
                            if($condition_met === true)
                            {
                                if(!empty($true_blocks))
                                {
                                    foreach($true_blocks as $my_block)
                                    {
                                        if($my_block == $block_id)
                                        {
                                            aiomatic_log_to_file('You cannot execute the same IF OmniBlock in a loop: ' . $block_id);
                                            continue;
                                        }
                                        $bl_found = false;
                                        foreach($block_data as $swindex => $sw_current_block)
                                        {
                                            if($my_block == $sw_current_block['identifier'])
                                            {
                                                $sw_current_block['parameters']['disabled'] = 0;
                                                $new_blocks[] = $sw_current_block;
                                                $bl_found = true;
                                            }
                                        }
                                        if($bl_found === false)
                                        {
                                            aiomatic_log_to_file('Failed to find True condition block ID: ' . $my_block);
                                        }
                                    }
                                }
                            }
                            elseif($condition_met === false)
                            {
                                if(!empty($false_blocks))
                                {
                                    foreach($false_blocks as $my_block)
                                    {
                                        if($my_block == $block_id)
                                        {
                                            aiomatic_log_to_file('You cannot execute the same IF OmniBlock in a loop: ' . $block_id);
                                            continue;
                                        }
                                        $bl_found = false;
                                        foreach($block_data as $swindex => $sw_current_block)
                                        {
                                            if($my_block == $sw_current_block['identifier'])
                                            {
                                                $sw_current_block['parameters']['disabled'] = 0;
                                                $new_blocks[] = $sw_current_block;
                                                $bl_found = true;
                                            }
                                        }
                                        if($bl_found === false)
                                        {
                                            aiomatic_log_to_file('Failed to find False condition block ID: ' . $my_block);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Error in processing IF block, condition state is unknown: ' . $condition_met);
                                if($critical == '1')
                                {
                                    return 'fail';
                                }
                                else
                                {
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            if(!empty($new_blocks))
                            {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                {
                                    $blids = [];
                                    foreach($new_blocks as $nb)
                                    {
                                        $blids[] = $nb['identifier'];
                                    }
                                    aiomatic_log_to_file('Adding new OmniBlock IDs to the queue: ' . implode(',', $blids));
                                }
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    $stop_omnmiblock_id = array_values(array_slice($new_blocks, -1))[0];
                                }
                                array_splice($block_data, $index, 0, $new_blocks);
                                $block_results[$block_id] = array($current_block['type']);
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    return array('ok');
                                }
                                $block_results[$block_id] = array($current_block['type']);
                            }
                        }
                        elseif($current_block['type'] == 'jump_block')
                        {
                            $jumpto = $current_block['parameters']['jumpto'];
                            $jumpto = aiomatic_replace_omniblocks_data($jumpto, $current_keyword, $kiwis, $block_results, $load_variables);
                            $jumpto = explode(',', $jumpto);
                            $jumpto = trim($jumpto[array_rand($jumpto)]);
                            if(empty($jumpto))
                            {
                                aiomatic_log_to_file('Error in processing JUMP block, empty jump block ID provided');
                                if($critical == '1')
                                {
                                    return 'fail';
                                }
                                else
                                {
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            $jumpfound = false;
                            for($searchindex = 0; $searchindex < count($block_data); $searchindex++)
                            {
                                if($block_data[$searchindex]['identifier'] == trim($jumpto))
                                {
                                    $index = $searchindex;
                                    $jumpfound = true;
                                    break;
                                }
                            }
                            if($jumpfound == false)
                            {
                                aiomatic_log_to_file('Error in processing JUMP block, jump block ID not found: ' . $jumpto);
                                if($critical == '1')
                                {
                                    return 'fail';
                                }
                                else
                                {
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            else
                            {
                                if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                {
                                    $stop_omnmiblock_id = $block_data[$index]['identifier'];
                                }
                                $block_results[$block_id] = array($current_block['type']);
                            }
                        }
                        elseif($current_block['type'] == 'wait_block')
                        {
                            $wait = $current_block['parameters']['wait'];
                            $wait = aiomatic_replace_omniblocks_data($wait, $current_keyword, $kiwis, $block_results, $load_variables);
                            $wait = explode(',', $wait);
                            $wait = trim($wait[array_rand($wait)]);
                            if(empty($wait))
                            {
                                aiomatic_log_to_file('Error in processing WAIT block, empty wait time provided');
                                if($critical == '1')
                                {
                                    return 'fail';
                                }
                                else
                                {
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            try 
                            {
                                $microseconds = aiomatic_parseTime($wait);
                                usleep((int)$microseconds);
                            } 
                            catch (Exception $e) 
                            {
                                aiomatic_log_to_file('Error in processing SLEEP block: ' . $e->getMessage());
                                if($critical == '1')
                                {
                                    return 'fail';
                                }
                                else
                                {
                                    if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                                    {
                                        return array('');
                                    }
                                    $block_results[$block_id] = array($current_block['type']);
                                    continue;
                                }
                            }
                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                            {
                                $stop_omnmiblock_id = $block_data[$index]['identifier'];
                            }
                            $block_results[$block_id] = array($current_block['type']);
                        }
                        elseif($current_block['type'] == 'exit_block')
                        {
                            aiomatic_log_to_file('Exit OmniBlock encountered, stopping execution and exiting OmniBlock queue: ' . $current_block['type']);
                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                            {
                                return array('');
                            }
                            break;
                        }
                        else
                        {
                            aiomatic_log_to_file('Unknown OmniBlock type found: ' . $current_block['type']);
                            if(!empty($stop_omnmiblock_id) && $stop_omnmiblock_id == $block_id)
                            {
                                return array('');
                            }
                        }
                    }
                    if($title_once == '1')
                    {
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                            aiomatic_log_to_file('Remembering processed keyword: ' . $current_keyword);
                        }
                        aiomatic_add_processed_keyword($current_keyword);
                    }
                    $count++;
                }
                
                if(count($keyword_arr) == 0 && $skipt > 0)
                {
                    if (isset($aiomatic_Main_Settings['email_notification']) && $aiomatic_Main_Settings['email_notification'] != '')
                    {
                        if($count === 1)
                        {
                            $email_list = explode(',', $aiomatic_Main_Settings['email_notification']);
                            foreach($email_list as $thisaddr)
                            {
                                $thisaddr = trim($thisaddr);
                                try
                                {
                                    $admin_mail = get_option('admin_email');
                                    $to        = $thisaddr;
                                    $subject   = '[Aimogen] OmniBlocks Keywords depleted rule ID ' . $param . ' - ' . aiomatic_get_date_now();
                                    $message   = 'OmniBlocks Rule ID ' . esc_html($param) . ' (' . $rule_description . ') depleted its keywords list, no new posts publised! Website URL: ' . get_site_url();
                                    $headers[] = 'From: Aimogen Plugin <' . $admin_mail . '>';
                                    $headers[] = 'Reply-To: ' . $admin_mail;
                                    $headers[] = 'X-Mailer: PHP/' . phpversion();
                                    $headers[] = 'Content-Type: text/html';
                                    $headers[] = 'Charset: ' . get_option('blog_charset', 'UTF-8');
                                    wp_mail($to, $subject, $message, $headers);
                                }
                                catch (Exception $e) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('Failed to send mail: Exception thrown ' . esc_html($e->getMessage()) . '!');
                                    }
                                }
                            }
                        }
                    }
                    aiomatic_log_to_file('All OmniBlocks keywords already processed, nothing to do.');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'nochange';
                }
            }
            elseif($type == 7)
            {
                if(!function_exists('is_plugin_active'))
                {
                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                }
                if (!is_plugin_active('aiomatic-extension-wpforo/aiomatic-extension-wpforo.php')) 
                {
                    aiomatic_log_to_file('This feature requires the Aimogen Extension for AI Forum Creation plugin to be installed and activated!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
                if (!is_plugin_active('wpforo/wpforo.php')) 
                {
                    aiomatic_log_to_file('This feature requires the wpForo plugin to be installed and activated!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
                if($post_title != '')
                {
                    $post_title_lines = preg_split('/\r\n|\r|\n/', $post_title);
                }
                else
                {
                    $post_title_lines = array();
                }
                $additional_kws = array();
                $user_name        = '';
                $featured_image   = '';
                $post_cats = '';
                $post_tagz = '';
                $post_excerpt = '';
                $final_content = '';
                $postID = '';
                $heading_val = '';
                $image_query = '';
                $temp_post = '';
                $cntx = count($post_title_lines);
                $rss_feeds = array();
                for($ji = 0; $ji < $cntx; $ji++)
                {
                    if (filter_var($post_title_lines[$ji], FILTER_VALIDATE_URL) !== false) 
                    {
                        if(aiomatic_endsWith($post_title_lines[$ji], '.txt'))
                        {
                            
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing txt file'));
                            $txt_content = aiomatic_get_web_page($post_title_lines[$ji]);
                            if ($txt_content === FALSE) 
                            {
                                aiomatic_log_to_file('Failed to read text file: ' . $post_title_lines[$ji]);
                                unset($post_title_lines[$ji]);
                                if($auto == 1)
                                {
                                    aiomatic_log_to_file($param);
                                }
                                continue;
                            }
                            unset($post_title_lines[$ji]);
                            $additional_kws = preg_split('/\r\n|\r|\n/', $txt_content);
                        }
                        else
                        {
                            aiomatic_log_to_file('Trying to parse RSS feed items(1x): ' . $post_title_lines[$ji]);
                            try
                            {
                                if(!class_exists('SimplePie_Autoloader', false))
                                {
                                    require_once(dirname(__FILE__) . "/res/simplepie/autoloader.php");
                                }
                            }
                            catch(Exception $e) 
                            {
                                unset($post_title_lines[$ji]);
                                aiomatic_log_to_file('Exception thrown in SimplePie autoloader: ' . $e->getMessage());
                                if($auto == 1)
                                {
                                    aiomatic_log_to_file($param);
                                }
                                continue;
                            }
                            
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Processing RSS feed'));
                            $feed = new SimplePie();
                            $feed->set_timeout(120);
                            $feed->set_feed_url($post_title_lines[$ji]);
                            $feed->enable_cache(false);
                            $feed->strip_htmltags(false);
                            $feed->init();
                            $feed->handle_content_type();
                            if ($feed->error()) 
                            {
                                aiomatic_log_to_file('Error in parsing RSS feed: ' . $feed->error() . ' for ' . $post_title_lines[$ji]);
                                unset($post_title_lines[$ji]);
                                if($auto == 1)
                                {
                                    aiomatic_clearFromList($param, $type);
                                }
                                continue;
                            }
                            $items = $feed->get_items();
                            $zero = true;
                            foreach($items as $itemx)
                            {
                                if($zero == true)
                                {
                                    $post_link = trim($itemx->get_permalink());
                                    if(isset($rss_items[$post_link]))
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Skipping RSS title because it was already processed before: ' . $itemx->get_title());
                                        }
                                        continue;
                                    }
                                    if ($fauthor = $itemx->get_author()) 
                                    {
                                        $user_name = $fauthor->get_name();
                                    }
                                    else
                                    {
                                        $user_name = '';
                                    }
                                    $feed_cats = array();
                                    $varx = $itemx->get_categories();
                                    if(is_array($varx))
                                    {
                                        foreach ($varx as $xcategory)
                                        {
                                            $feed_cats[] = $xcategory->get_label();
                                        }
                                    }
                                    $post_cats = implode(',', $feed_cats);
                                    $post_excerpt = $itemx->get_description();
                                    $final_content = $itemx->get_content();
                                    $rss_feeds[$itemx->get_title()] = array('url' => $post_link, 'author' => $user_name,  'cats' => $post_cats, 'excerpt' => $post_excerpt, 'content' => $final_content );
                                }
                                else
                                {
                                    $post_link_temp = trim($itemx->get_permalink());
                                    if(isset($rss_items[$post_link_temp]))
                                    {
                                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                            aiomatic_log_to_file('Skipping RSS title because it was already processed before: ' . $itemx->get_title());
                                        }
                                        continue;
                                    }
                                    if ($fauthor = $itemx->get_author()) 
                                    {
                                        $user_name_temp = $fauthor->get_name();
                                    }
                                    else
                                    {
                                        $user_name_temp = '';
                                    }
                                    $feed_cats = array();
                                    $varx = $itemx->get_categories();
                                    if(is_array($varx))
                                    {
                                        foreach ($varx as $xcategory)
                                        {
                                            $feed_cats[] = $xcategory->get_label();
                                        }
                                    }
                                    $post_cats_temp = implode(',', $feed_cats);
                                    $post_excerpt_temp = $itemx->get_description();
                                    $final_content_temp = $itemx->get_content();
                                    $rss_feeds[$itemx->get_title()] = array('url' => $post_link_temp, 'author' => $user_name_temp,  'cats' => $post_cats_temp, 'excerpt' => $post_excerpt_temp, 'content' => $final_content_temp );
                                }
                                $additional_kws[] = $itemx->get_title();
                                $zero = false;
                            }
                            unset($post_title_lines[$ji]);
                        }
                    }
                }
                if(count($additional_kws) > 0)
                {
                    $post_title_lines = array_merge($post_title_lines, $additional_kws);
                }
                $post_title_lines = array_unique($post_title_lines);
                $spintax = new Aiomatic_Spintax();
                $orig_ai_command = $ai_command;
                $orig_ai_command_title = $title_ai_command;
                $orig_ai_command_image = $ai_command_image;
                $already_spinned = 0;
                if(isset($aiomatic_Main_Settings['attr_text']) && $aiomatic_Main_Settings['attr_text'] != '')
                {
                    $img_attr = $aiomatic_Main_Settings['attr_text'];
                }
                else
                {
                    $img_attr = '';
                }
                $headings_arr = array();
                $images_arr = array();
                $no_init_topics = false;
                while(true) 
                {
                    $thread_id = '';
                    $post_link = '';
                    $user_name = '';
                    $post_cats = '';
                    $post_excerpt = '';
                    $final_content = '';
                    $update_post_id = '';
                    $featured_image = '';
                    $post_tagz = '';
                    $postID = '';
                    $old_title = '';
                    if ($count > intval($max)) {
                        break;
                    }
                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Starting processing topic ID #' . $count));
                    $current_section = '';
                    $post_sections = '';
                    $post_topic = '';
                    $post_title_keywords = '';
                    $posting_mode = 'title';
                    if($posting_mode == 'title')
                    {
                        $headings_arr_copy = $headings_arr;
                        $added_img_list = array();
                        $raw_img_list = array();
                        $full_result_list = array();
                        $added_images = 0;
                        $heading_results = array();
                        if(count($post_title_lines) == 0)
                        {
                            break;
                        }
                        if ($count > intval($max)) {
                            break;
                        }
                        if (!isset($aiomatic_Main_Settings['no_random_titles']) || $aiomatic_Main_Settings['no_random_titles'] != 'on')
                        {
                            $current_index = array_rand($post_title_lines);
                        }
                        else
                        {
                            $current_index = array_key_first($post_title_lines);
                        }
                        $post_title = trim($post_title_lines[$current_index]);
                        $ptlprocessed = explode('!###!', $post_title);
                        if(isset($ptlprocessed[1]) && !empty($ptlprocessed[1]) && !empty($ptlprocessed[0]))
                        {
                            $post_title = $ptlprocessed[0];
                            $post_title_keywords = $ptlprocessed[1];
                        }
                        if(isset($rss_feeds[$post_title]))
                        {
                            $post_link = $rss_feeds[$post_title]['url'];
                            $user_name = $rss_feeds[$post_title]['author'];
                            $post_cats = $rss_feeds[$post_title]['cats'];
                            $post_excerpt = $rss_feeds[$post_title]['excerpt'];
                            $final_content = $rss_feeds[$post_title]['content'];
                        }
                        $tprepp = $spintax->Parse($post_title);
                        if($tprepp != false && $tprepp != '')
                        {
                            $post_title = $tprepp;
                        }
                        if($title_once == '1' && aiomatic_check_processed_keyword($post_title))
                        {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('Skipping already processed topic title: ' . $post_title);
                            }
                            unset($post_title_lines[$current_index]);
                            continue;
                        }
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                        {
                            aiomatic_log_to_file('Starting processing post title: ' . $post_title);
                        }
                        $old_title = $post_title;
                        $already_spinned = 0;
                        if (filter_var($post_title, FILTER_VALIDATE_URL) === false && stristr($post_title, '%%ai_generated_title%%') === false)
                        {
                            unset($post_title_lines[$current_index]);
                        }
                        $allmodels = aiomatic_get_all_models();
                        if(!empty($global_prepend))
                        {
                            $global_prepend = aiomatic_replaceSynergyShortcodes($global_prepend);
                            $global_prepend = aiomatic_replaceAIPostShortcodes($global_prepend, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', '');     
                        }
                        if(!empty($global_append))
                        {
                            $global_append = aiomatic_replaceSynergyShortcodes($global_append);
                            $global_append = aiomatic_replaceAIPostShortcodes($global_append, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', '');     
                        }
                        if($custom_shortcodes != '')
                        {
                            $custom_shortcodes_arr = preg_split('/\r\n|\r|\n/', $custom_shortcodes);
                            foreach($custom_shortcodes_arr as $my_short)
                            {
                                $name_part = explode('=>', $my_short);
                                if(isset($name_part[1]) && !empty(trim($name_part[1])))
                                {
                                    $shortname = trim($name_part[0]);
                                    if(strstr($post_title, '%%' . $shortname . '%%'))
                                    {
                                        $shortval = '';
                                        $name_part[1] = str_replace('%%post_title%%', $post_title, $name_part[1]);
                                        $ai_part = explode('@@', $name_part[1]);
                                        if(isset($ai_part[1]) && !empty(trim($ai_part[1])))
                                        {
                                            if(!in_array(trim($ai_part[0]), $allmodels))
                                            {
                                                $aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                            }
                                            else
                                            {
                                                $aimodel = trim($ai_part[0]);
                                            }
                                            $zai_command = trim($ai_part[1]);
                                            $zai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $zai_command);
                                            $zai_command = aiomatic_replaceSynergyShortcodes($zai_command);
                                            $zai_command = aiomatic_replaceAIPostShortcodes($zai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', ''); 
                                            $zai_command = str_replace('%%topic_user_name%%', $post_user_name, $zai_command);
                                            $zai_command = str_replace('%%language%%', $content_language, $zai_command);
                                            $zai_command = str_replace('%%writing_style%%', $writing_style, $zai_command);
                                            $zai_command = str_replace('%%writing_tone%%', $writing_tone, $zai_command);
                                            foreach($custom_shortcodes_arr as $my_check_short)
                                            {
                                                $check_name_part = explode('=>', $my_check_short);
                                                if(isset($check_name_part[1]) && !empty(trim($check_name_part[1])))
                                                {
                                                    $check_shortname = trim($check_name_part[0]);
                                                    if($shortname !== $check_shortname && strstr($zai_command, '%%' . $check_shortname . '%%') !== false)
                                                    {
                                                        $check_shortval = '';
                                                        $check_ai_part = explode('@@', $check_name_part[1]);
                                                        if(!in_array(trim($check_ai_part[0]), $allmodels))
                                                        {
                                                            $check_aimodel = aiomatic_get_default_model_name($aiomatic_Main_Settings);
                                                        }
                                                        else
                                                        {
                                                            $check_aimodel = trim($check_ai_part[0]);
                                                        }
                                                        $check_ai_command = trim($check_ai_part[1]);
                                                        $aierror = '';

                                                        $check_ai_command = aiomatic_replaceSynergyShortcodes($check_ai_command);
                                                        $check_ai_command = aiomatic_replaceAIPostShortcodes($check_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, '', $custom_shortcodes, '', ''); 

                                                        $check_ai_command = apply_filters('aiomatic_replace_aicontent_shortcode', $check_ai_command);
                                                        $check_generated_text = aiomatic_generate_custom_shortcode_content($token, $check_aimodel, $check_ai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                                                        if($check_generated_text === false)
                                                        {
                                                            aiomatic_log_to_file('Custom nested shortcode generator error: ' . $aierror);
                                                        }
                                                        else
                                                        {
                                                            $check_shortval = trim(trim($check_generated_text), '.');
                                                        }
                                                        $zai_command = str_replace('%%' . $check_shortname . '%%', $check_shortval, $zai_command);
                                                    }
                                                }
                                            }
                                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating title based shortcodes'));
                                            $aierror = '';
                                            $generated_text = aiomatic_generate_custom_shortcode_content($token, $aimodel, $zai_command, $global_prepend, $global_append, $aiomatic_Main_Settings, $aierror);
                                            if($generated_text === false)
                                            {
                                                aiomatic_log_to_file('Custom shortcode generator error: ' . $aierror);
                                            }
                                            else
                                            {
                                                $shortval = trim(trim($generated_text), '.');
                                            }
                                        }
                                        $post_title = str_replace('%%' . $shortname . '%%', $shortval, $post_title);
                                    }
                                }
                            } 
                        }
                        if($user_name_type == 'rand')
                        {
                            if($user_role != 'any')
                            {
                                $randid = aiomatic_display_random_user([$user_role]);
                                if($randid === false)
                                {
                                    $post_user_name = aimogen_get_admin_user_id();
                                }
                                else
                                {
                                    $post_user_name = $randid->ID;
                                }
                            }
                            else
                            {
                                $randid = aiomatic_display_random_user();
                                if($randid === false)
                                {
                                    $post_user_name = aimogen_get_admin_user_id();
                                }
                                else
                                {
                                    $post_user_name = $randid->ID;
                                }
                            }
                        }
                        if(stristr($post_title, '%%ai_generated_title%%') !== false || $title_source == 'ai')
                        {
                            if($orig_ai_command_title == '')
                            {
                                $orig_ai_command_title = $post_title;
                            }
                            if($orig_ai_command_title != '')
                            {
                                $title_ai_command = $orig_ai_command_title;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $title_ai_command = preg_split('/\r\n|\r|\n/', $title_ai_command);
                                    $title_ai_command = array_filter($title_ai_command);
                                    if(count($title_ai_command) > 0)
                                    {
                                        $title_ai_command = $title_ai_command[array_rand($title_ai_command)];
                                    }
                                    else
                                    {
                                        $title_ai_command = '';
                                    }
                                }
                                $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                if(!empty($title_ai_command))
                                {
                                    $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $title_ai_command = trim(strip_tags($post_title));
                                }
                                $title_ai_command = trim($title_ai_command);
                                if (filter_var($title_ai_command, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($title_ai_command, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($title_ai_command);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $title_ai_command = $txt_content;
                                                $title_ai_command = aiomatic_replaceSynergyShortcodes($title_ai_command);
                                                $title_ai_command = aiomatic_replaceAIPostShortcodes($title_ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                $title_ai_command = str_replace('%%topic_user_name%%', $post_user_name, $title_ai_command);
                                $title_ai_command = str_replace('%%language%%', $content_language, $title_ai_command);
                                $title_ai_command = str_replace('%%writing_style%%', $writing_style, $title_ai_command);
                                $title_ai_command = str_replace('%%writing_tone%%', $writing_tone, $title_ai_command);
                                if(empty($title_ai_command))
                                {
                                    aiomatic_log_to_file('Empty API post title seed expression provided!');
                                }
                                else
                                {
                                    if(aiomatic_strlen($title_ai_command) > $max_seed_tokens * 4)
                                    {
                                        $title_ai_command = aiomatic_substr($title_ai_command, 0, (0 - ($max_seed_tokens * 4)));
                                    }
                                    $title_ai_command = trim($title_ai_command);
                                    if(empty($title_ai_command))
                                    {
                                        aiomatic_log_to_file('Empty API title seed expression provided(2)! ' . print_r($title_ai_command, true));
                                        break;
                                    }
                                    $query_token_count = count(aiomatic_encode($title_ai_command));
                                    $available_tokens = aiomatic_compute_available_tokens($title_model, $max_tokens, $title_ai_command, $query_token_count);
                                    if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                    {
                                        $string_len = aiomatic_strlen($title_ai_command);
                                        $string_len = $string_len / 2;
                                        $string_len = intval(0 - $string_len);
                                        $title_ai_command = aiomatic_substr($title_ai_command, 0, $string_len);
                                        $title_ai_command = trim($title_ai_command);
                                        if(empty($title_ai_command))
                                        {
                                            aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($title_ai_command, true));
                                            break;
                                        }
                                        $query_token_count = count(aiomatic_encode($title_ai_command));
                                        $available_tokens = $max_tokens - $query_token_count;
                                    }
                                    $aierror = '';
                                    $finish_reason = '';
                                    if(!empty($global_prepend))
                                    {
                                        $title_ai_command = $global_prepend . ' ' . $title_ai_command;
                                    }
                                    if(!empty($global_append))
                                    {
                                        $title_ai_command = $title_ai_command . ' ' . $global_append;
                                    }
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = aiomatic_get_api_service($token, $title_model);
                                        aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $title_model . ')(' . $available_tokens . ') for title text: ' . $title_ai_command);
                                    }
                                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating title'));
                                    $generated_text = aiomatic_generate_text($token, $title_model, $title_ai_command, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'titleID' . $param, 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                                    if($generated_text === false)
                                    {
                                        aiomatic_log_to_file('Title generator error: ' . $aierror);
                                        break;
                                    }
                                    else
                                    {
                                        $ai_title = ucfirst(trim(trim($generated_text), '.'));
                                        if($title_source == 'ai')
                                        {
                                            $post_title = $ai_title;
                                        }
                                        else
                                        {
                                            $post_title = str_ireplace('%%ai_generated_title%%', $ai_title, $post_title);
                                        }
                                    }
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                                    {
                                        $api_service = aiomatic_get_api_service($token, $title_model);
                                        aiomatic_log_to_file('Successfully got API title result from ' . $api_service . ': ' . $post_title);
                                    }
                                }
                            }
                            else
                            {
                                aiomatic_log_to_file('Empty AI title query entered.');
                            }
                        }
                        else
                        {
                            $post_title = aiomatic_replaceSynergyShortcodes($post_title);
                        }
                        $post_title = apply_filters('aiomatic_replace_aicontent_shortcode', $post_title);
                        if(empty($post_title))
                        {
                            unset($post_title_lines[$current_index]);
                            continue;
                        }
                        if (strpos($post_title, '%%') === false)
                        {
                            if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                            {
                                $zap = aiomatic_wpforo_get_topic_by_title($post_title, $selected_forum);
                                if($zap !== false) 
                                {
                                    if($overwrite_existing)
                                    {
                                        $update_post_id = $zap;
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Post with specified title is already existing, skipping it: ' . $post_title);
                                        unset($post_title_lines[$current_index]);
                                        continue;
                                    }
                                }
                            }
                            $new_post_title = $post_title;
                        }
                        else
                        {
                            $new_post_title = $post_title;
                            $new_post_title = aiomatic_replaceContentShortcodes($new_post_title, $img_attr, $ai_command);
                            if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                            {
                                $zap = aiomatic_wpforo_get_topic_by_title($new_post_title, $selected_forum);
                                if($zap !== false) 
                                {
                                    if($overwrite_existing)
                                    {
                                        $update_post_id = $zap;
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Post with specified title is already existing, skipping it: ' . $post_title);
                                        unset($post_title_lines[$current_index]);
                                        continue;
                                    }
                                }
                            }
                        }
                        $get_img = '';
                        if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                        {
                            $already_spinned = '1';
                        }
                        $my_post                              = array();
                        $my_post['aiomatic_post_image']       = $get_img;
                        $my_post['comment_status']            = $accept_comments;
                        if($post_user_name == 'rand')
                        {
                            $randid = aiomatic_display_random_user();
                            if($randid === false)
                            {
                                $my_post['post_author']               = aimogen_get_admin_user_id();
                            }
                            else
                            {
                                $my_post['post_author']               = $randid->ID;
                            }
                        }
                        else
                        {
                            $my_post['post_author']               = $post_user_name;
                        }
                        $ai_command = $orig_ai_command;
                        $ai_command = str_replace('%%topic_user_name%%', $post_user_name, $ai_command);
                        $ai_command = str_replace('%%language%%', $content_language, $ai_command);
                        $ai_command = str_replace('%%writing_style%%', $writing_style, $ai_command);
                        $ai_command = str_replace('%%writing_tone%%', $writing_tone, $ai_command);
                        $ai_command = aiomatic_replaceSynergyShortcodes($ai_command);
                        if(!empty($ai_command))
                        {
                            $aicontent = aiomatic_replaceAIPostShortcodes($ai_command, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                        }
                        else
                        {
                            $aicontent = trim(strip_tags($post_title));
                        }
                        if (filter_var($aicontent, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($aicontent, '.txt'))
                        {
                            $txt_content = aiomatic_get_web_page($aicontent);
                            if ($txt_content !== FALSE) 
                            {
                                $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                $txt_content = array_filter($txt_content);
                                if(count($txt_content) > 0)
                                {
                                    $txt_content = $txt_content[array_rand($txt_content)];
                                    if(trim($txt_content) != '') 
                                    {
                                        $aicontent = $txt_content;
                                        $aicontent = aiomatic_replaceSynergyShortcodes($aicontent);
                                        $aicontent = aiomatic_replaceAIPostShortcodes($aicontent, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                }
                            }
                        }
                        $last_char = aiomatic_substr($aicontent, -1, null);
                        if(!ctype_punct($last_char))
                        {
                            $aicontent .= '.';
                        }
                        if(aiomatic_strlen($aicontent) > $max_seed_tokens * 4)
                        {
                            $aicontent = aiomatic_substr($aicontent, 0, (0-($max_seed_tokens * 4)));
                        }
                        $aicontent = trim($aicontent);
                        if(empty($aicontent))
                        {
                            aiomatic_log_to_file('Empty API seed expression provided! ' . print_r($ai_command, true));
                            break;
                        }
                        $query_token_count = count(aiomatic_encode($aicontent));
                        $available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $aicontent, $query_token_count);
                        if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                        {
                            $string_len = aiomatic_strlen($aicontent);
                            $string_len = $string_len / 2;
                            $string_len = intval(0 - $string_len);
                            $aicontent = aiomatic_substr($aicontent, 0, $string_len);
                            $aicontent = trim($aicontent);
                            if(empty($aicontent))
                            {
                                aiomatic_log_to_file('Empty API seed expression provided (after processing) ' . print_r($ai_command, true));
                                break;
                            }
                            $query_token_count = count(aiomatic_encode($aicontent));
                            $available_tokens = $max_tokens - $query_token_count;
                        }
                        $aierror = '';
                        $finish_reason = '';
                        if(!empty($global_prepend))
                        {
                            $aicontent = $global_prepend . ' ' . $aicontent;
                        }
                        if(!empty($global_append))
                        {
                            $aicontent = $aicontent . ' ' . $global_append;
                        }
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                        {
                            $api_service = aiomatic_get_api_service($token, $model);
                            aiomatic_log_to_file('Calling ' . $api_service . ' (' . $assistant_id . '/' . $model . ')(' . $available_tokens . ') for text: ' . $aicontent);
                        }
                        aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Generating post content'));
                        $generated_text = aiomatic_generate_text($token, $model, $aicontent, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, false, 'contentID' . $param, 0, $finish_reason, $aierror, false, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', true, $store_data, array(), '', '', '');
                        if($generated_text === false)
                        {
                            aiomatic_log_to_file($aierror);
                            break;
                        }
                        else
                        {   
                            if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                            {
                                $new_post_content = ucfirst(trim(nl2br(trim($generated_text))));
                            }
                            else
                            {
                                $new_post_content = ucfirst(trim($generated_text));
                            }
                        }
                        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                        {
                            $api_service = aiomatic_get_api_service($token, $model);
                            aiomatic_log_to_file('Successfully got API result from ' . $api_service . '.');
                        }
                        if($min_char == '')
                        {
                            $min_char = 0;
                        }
                        else
                        {
                            $min_char = intval($min_char);
                        }
                        $cnt = 1;
                        $max_fails = 10;
                        $failed_calls = 0;
                        if($strip_title == '1')
                        {
                            $new_post_content = str_replace($post_title, '', $new_post_content);
                            $new_post_content = str_replace('<h2></h2>', '', $new_post_content);
                            $new_post_content = str_replace('<h3></h3>', '', $new_post_content);
                        }
                        if (isset($aiomatic_Main_Settings['swear_filter']) && $aiomatic_Main_Settings['swear_filter'] == 'on') 
                        {
                            require_once(dirname(__FILE__) . "/res/swear.php");
                            $new_post_content = aimogenpro_filterwords($new_post_content);
                        }
                        if(isset($aiomatic_Main_Settings['global_ban_words']) && $aiomatic_Main_Settings['global_ban_words'] != '') {
                            $continue    = false;
                            $aiomatic_Main_Settings['global_ban_words'] = trim(trim(trim($aiomatic_Main_Settings['global_ban_words']), ','));
                            $banned_list = explode(',', $aiomatic_Main_Settings['global_ban_words']);
                            foreach ($banned_list as $banned_word) {
                                if (stripos($new_post_content, trim($banned_word)) !== FALSE) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because it\'s content contains global banned word: ' . $banned_word);
                                    }
                                    $continue = true;
                                    break;
                                }
                                if (stripos($new_post_title, trim($banned_word)) !== FALSE) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because it\'s title contains global banned word: ' . $banned_word);
                                    }
                                    $continue = true;
                                    break;
                                }
                            }
                            if ($continue === true) {
                                unset($post_title_lines[$current_index]);
                                continue;
                            }
                        }
                        if(isset($aiomatic_Main_Settings['global_req_words']) && $aiomatic_Main_Settings['global_req_words'] != '')
                        {
                            if(isset($aiomatic_Main_Settings['require_only_one']) && $aiomatic_Main_Settings['require_only_one'] == 'on')
                            {
                                $continue      = true;
                                $aiomatic_Main_Settings['global_req_words'] = trim(trim(trim($aiomatic_Main_Settings['global_req_words']), ','));
                                $required_list = explode(',', $aiomatic_Main_Settings['global_req_words']);
                                foreach ($required_list as $required_word) {
                                    if (stripos($new_post_content, trim($required_word)) !== FALSE || stripos($new_post_title, trim($required_word)) !== FALSE) {
                                        $continue = false;
                                        break;
                                    }
                                }
                                if ($continue === true) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because it\'s content doesn\'t contain global required words.');
                                    }
                                    unset($post_title_lines[$current_index]);
                                    continue;
                                }
                            }
                            else
                            {
                                $continue      = false;
                                $aiomatic_Main_Settings['global_req_words'] = trim(trim(trim($aiomatic_Main_Settings['global_req_words']), ','));
                                $required_list = explode(',', $aiomatic_Main_Settings['global_req_words']);
                                foreach ($required_list as $required_word) {
                                    if (stripos($new_post_content, trim($required_word)) === FALSE && stripos($new_post_title, trim($required_word)) === FALSE) {
                                        $continue = true;
                                        break;
                                    }
                                }
                                if ($continue === true) {
                                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                        aiomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because it\'s content doesn\'t contain global required words.');
                                    }
                                    unset($post_title_lines[$current_index]);
                                    continue;
                                }
                            }
                        }
                        if (isset($aiomatic_Main_Settings['spin_what']) && $aiomatic_Main_Settings['spin_what'] === 'omni') 
                        {
                            $skip_spin = '1';
                        }
                        $arr = aiomatic_spin_and_translate($new_post_title, $new_post_content, '3', $skip_spin, $skip_translate);
                        if($arr[0] != $new_post_title)
                        {
                            $new_post_title = $arr[0];
                            if (!isset($aiomatic_Main_Settings['do_not_check_duplicates']) || $aiomatic_Main_Settings['do_not_check_duplicates'] != 'on') 
                            {
                                $zap = aiomatic_wpforo_get_topic_by_title($new_post_title, $selected_forum);
                                if($zap !== false) 
                                {
                                    if($overwrite_existing)
                                    {
                                        $update_post_id = $zap;
                                    }
                                    else
                                    {
                                        aiomatic_log_to_file('Post with specified title is already existing, skipping it: ' . $post_title);
                                        unset($post_title_lines[$current_index]);
                                        continue;
                                    }
                                }
                            }
                        }
                        $new_post_content            = $arr[1];
                        if (isset($aiomatic_Main_Settings['spin_text']) && $aiomatic_Main_Settings['spin_text'] !== 'disabled') 
                        {
                            $already_spinned = '1';
                        }
                        $new_post_content = aimogen_bulk_polish_article_content($new_post_content, array('title' => isset($new_post_title) ? $new_post_title : '', 'topic' => isset($post_topic) ? $post_topic : '', 'language' => isset($content_language) ? $content_language : '', 'model' => (isset($topic_content_model) && $topic_content_model !== '') ? $topic_content_model : (isset($model) ? $model : ''), 'token' => isset($token) ? $token : '', 'temperature' => isset($temperature) ? $temperature : '', 'top_p' => isset($top_p) ? $top_p : '', 'presence_penalty' => isset($presence_penalty) ? $presence_penalty : '', 'frequency_penalty' => isset($frequency_penalty) ? $frequency_penalty : '', 'rule_id' => isset($rule_unique_id) ? $rule_unique_id : '', 'global_prepend' => isset($global_prepend) ? $global_prepend : '', 'global_append' => isset($global_append) ? $global_append : '', 'assistant_id' => isset($assistant_id) ? $assistant_id : '', 'thread_id' => isset($thread_id) ? $thread_id : '', 'store_data' => isset($store_data) ? $store_data : 'off'));
                    $new_post_content        = html_entity_decode($new_post_content);
                        $new_post_content = str_replace('</ iframe>', '</iframe>', $new_post_content);
                        if ($strip_by_regex !== '')
                        {
                            $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex);
                            $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex);
                            $xcnt = 0;
                            foreach($xstrip_by_regex as $sbr)
                            {
                                if(isset($xreplace_regex[$xcnt]))
                                {
                                    $repreg = $xreplace_regex[$xcnt];
                                }
                                else
                                {
                                    $repreg = '';
                                }
                                $xcnt++;
                                $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $new_post_content);
                                if($temp_cont !== NULL)
                                {
                                    $new_post_content = $temp_cont;
                                }
                            }
                        }
                        $post_prepender = aiomatic_replaceAIPostShortcodes($post_prepend, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                        $post_prepender = aiomatic_replacetopics($post_prepender, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                        $post_appender = aiomatic_replaceAIPostShortcodes($post_append, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                        $post_appender = aiomatic_replacetopics($post_appender, $post_title, $content_language, $writing_style, $writing_tone, $post_topic, $post_sections, $current_section, $section_count, $paragraph_count, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append, $default_cat_list, $img_attr);
                        $post_appender = aiomatic_replaceSynergyShortcodes($post_appender);
                        $post_prepender = aiomatic_replaceSynergyShortcodes($post_prepender);
                        if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                        {
                            if($new_post_content === strip_tags($new_post_content)) 
                            {
                                if (isset($aiomatic_Main_Settings['nlbr_parse']) && $aiomatic_Main_Settings['nlbr_parse'] == 'on')
                                {
                                    $new_post_content = nl2br($new_post_content);
                                }
                            }
                        }
                        if (!isset($aiomatic_Main_Settings['no_undetectibility']) || $aiomatic_Main_Settings['no_undetectibility'] != 'on') 
                        {
                            if (!isset($aiomatic_Main_Settings['no_undetectibility_bulk']) || $aiomatic_Main_Settings['no_undetectibility_bulk'] != 'on') 
                            {
                                if(!isset($xchars))
                                {
                                    $xchars = array();
                                }
                                $rand_percentage = wp_rand(10, 20);
                                $new_post_content = aiomatic_make_unique($new_post_content, $xchars, $rand_percentage);
                            }
                        }
                        $zlang = 'en_US';
                        if (isset($aiomatic_Main_Settings['kw_lang']) && !empty($aiomatic_Main_Settings['kw_lang'])) {
                            $zlang = $aiomatic_Main_Settings['kw_lang'];
                        }
                        $rel_search = array('post_title', 'post_content');
                        if (isset($aiomatic_Main_Settings['rel_search']) && is_array($aiomatic_Main_Settings['rel_search'])) {
                            $rel_search = $aiomatic_Main_Settings['rel_search'];
                        }
                        if($max_links !== '' && $inboundlinker !== null && $link_type != 'disabled')
                        {
                            try
                            {
                                $new_post_content = $inboundlinker->add_inbound_links($new_post_content, $max_links, $link_post_types, $zlang, $rel_search, null, $link_type, $link_list, $link_nofollow, '', '', array());
                            }
                            catch(Exception $ex)
                            {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Failed to add inbound links to content: ' . $ex->getMessage());
                                }
                            }
                        }
                        if($ret_content == 1)
                        {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('Returning AI generated content, finished.');
                            }
                            aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Finished processing'));
                            return array($post_prepender . ' ' . $new_post_content . ' ' . $post_appender, $new_post_title);
                        }
                        $the_final_cont = $post_prepender . ' ' . $new_post_content . ' ' . $post_appender;
                        $trunchi_content = aiomatic_truncate_content($the_final_cont, 16777215);
                        if (isset($aiomatic_Main_Settings['convert_gutenberg']) && trim($aiomatic_Main_Settings['convert_gutenberg']) == 'on')
                        {
                            $my_post['post_content'] = aiomatic_convert_html_to_gutenberg_blocks($trunchi_content);
                        }
                        else
                        {
                            $my_post['post_content'] = $trunchi_content;
                        }
                        if(stristr($my_post['post_content'], '<pre><code>&lt;') !== false)
                        {
                            if (!isset($aiomatic_Main_Settings['pre_code_off']) || trim($aiomatic_Main_Settings['pre_code_off']) != 'on')
                            {
                                $my_post['post_content'] = aiomatic_parse_pre_code_entities($my_post['post_content']);
                            }
                        }
                        $my_post['post_content'] = aimogen_bulk_finalize_prose($my_post['post_content']);
                        $my_post['post_title']           = aiomatic_truncate_title($new_post_title);
                        $my_post['aiomatic_source_title']   = $post_title;
                        $my_post['aiomatic_timestamp']   = aiomatic_get_date_now();
                        $my_post['forum_id'] = $selected_forum;
                        $block_arr = array();
                        $custom_arr = array('aiomatic_title' => $old_title, 'aiomatic_parent_rule' => $rule_unique_id);
                        $block_arr = array();
                        $custom_tax_arr = array();
                        if(count($custom_tax_arr) > 0)
                        {
                            $my_post['taxo_input'] = $custom_tax_arr;
                        }
                        $my_post['meta_input'] = $custom_arr;
                        if($parent_id != '')
                        {
                            $my_post['post_parent'] = intval($parent_id);
                        }
                        if($min_time != '' && $max_time != '')
                        {
                            $t1 = strtotime($min_time);
                            $t2 = strtotime($max_time);
                            if($t1 != false && $t2 != false)
                            {
                                $int = wp_rand($t1, $t2);
                                $my_post['post_date'] = date('Y-m-d H:i:s', $int);
                            }
                        }
                        elseif($min_time != '')
                        {
                            $t1 = strtotime($min_time);
                            if($t1 != false)
                            {
                                $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                            }
                        }
                        elseif($max_time != '')
                        {
                            $t1 = strtotime($max_time);
                            if($t1 != false)
                            {
                                $my_post['post_date'] = date('Y-m-d H:i:s', $t1);
                            }
                        }
                        $count++;
                    }
                    else
                    {
                        aiomatic_log_to_file('Unknown posting mode submitted: ' . $posting_mode . '!');
                        if($auto == 1)
                        {
                            aiomatic_clearFromList($param, $type);
                        }
                        return 'fail';
                    }
                    if($update_post_id != '')
                    {
                        $my_post['ID'] = $update_post_id;
                    }
                    remove_filter('content_save_pre', 'wp_filter_post_kses');
                    remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses');
                    try
                    {
                        $my_post['post_content'] = str_replace('\r\n', '', $my_post['post_content']);
                        $post_id = aiomatic_insert_wpforo_topic($my_post);
                    }
                    catch(Exception $e)
                    {
                        aiomatic_log_to_file('Exception in publishing topic (this is coming from another plugin, so we ignore it): ' . $e->getMessage());
                    }
                    add_filter('content_save_pre', 'wp_filter_post_kses');
                    add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses');
                    if (!is_wp_error($post_id)) {
                        if($post_id === 0)
                        {
                            aiomatic_log_to_file('An error occurred while inserting topic into wp database! Title:' . $my_post['post_title']);
                            continue;
                        }
                        $posts_inserted++;
                        if($reply_count !== '')
                        {
                            preg_match_all('#\s*(\d+)\s*-\s*(\d+)\s*#', $reply_count, $mxatches);
                            if(isset($mxatches[2][0]))
                            {
                                $min_l = $mxatches[1][0];
                                $max_l = $mxatches[2][0];
                                $reply_count = wp_rand(intval($min_l), intval($max_l));
                            }
                            else
                            {
                                $reply_count = intval($reply_count);
                            }
                            if($reply_count > 0)
                            {
                                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                    aiomatic_log_to_file('Creating ' . $reply_count . ' replies for topic ID ' . $post_id . '!');
                                }
                                $orig_choose_prompt = $choose_prompt;
                                $orig_reply_prompt = $reply_prompt;
                                for($ij = 0; $ij < $reply_count; $ij++)
                                {
                                    $choose_prompt = $orig_choose_prompt;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $choose_prompt = preg_split('/\r\n|\r|\n/', $choose_prompt);
                                        $choose_prompt = array_filter($choose_prompt);
                                        if(count($choose_prompt) > 0)
                                        {
                                            $choose_prompt = $choose_prompt[array_rand($choose_prompt)];
                                        }
                                        else
                                        {
                                            $choose_prompt = '';
                                        }
                                    }
                                    $choose_prompt = aiomatic_replaceSynergyShortcodes($choose_prompt);
                                    if(!empty($choose_prompt))
                                    {
                                        $choose_prompt = aiomatic_replaceAIPostShortcodes($choose_prompt, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $choose_prompt = trim(strip_tags($post_title));
                                    }
                                    $choose_prompt = trim($choose_prompt);
                                    if (filter_var($choose_prompt, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($choose_prompt, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($choose_prompt);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $choose_prompt = $txt_content;
                                                    $choose_prompt = aiomatic_replaceSynergyShortcodes($choose_prompt);
                                                    $choose_prompt = aiomatic_replaceAIPostShortcodes($choose_prompt, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($choose_prompt))
                                    {
                                        aiomatic_log_to_file('Empty API user select seed provided!');
                                    }
                                    else
                                    {
                                        if(aiomatic_strlen($choose_prompt) > $max_seed_tokens * 4)
                                        {
                                            $choose_prompt = aiomatic_substr($choose_prompt, 0, (0 - ($max_seed_tokens * 4)));
                                        }
                                        $choose_prompt = trim($choose_prompt);
                                        if(empty($choose_prompt))
                                        {
                                            aiomatic_log_to_file('Empty API user select seed provided (2)! ' . print_r($choose_prompt, true));
                                            break;
                                        }
                                        $query_token_count = count(aiomatic_encode($choose_prompt));
                                        $available_tokens = aiomatic_compute_available_tokens($title_model, $max_tokens, $choose_prompt, $query_token_count);
                                        if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                        {
                                            $string_len = aiomatic_strlen($choose_prompt);
                                            $string_len = $string_len / 2;
                                            $string_len = intval(0 - $string_len);
                                            $choose_prompt = aiomatic_substr($choose_prompt, 0, $string_len);
                                            $choose_prompt = trim($choose_prompt);
                                            if(empty($choose_prompt))
                                            {
                                                aiomatic_log_to_file('Empty API user select seed provided (after processing) ' . print_r($choose_prompt, true));
                                                break;
                                            }
                                            $query_token_count = count(aiomatic_encode($choose_prompt));
                                            $available_tokens = $max_tokens - $query_token_count;
                                        }
                                        $aierror = '';
                                        $finish_reason = '';
                                        if(!empty($global_prepend))
                                        {
                                            $choose_prompt = $global_prepend . ' ' . $choose_prompt;
                                        }
                                        if(!empty($global_append))
                                        {
                                            $choose_prompt = $choose_prompt . ' ' . $global_append;
                                        }
                                    }

                                    $reply_prompt = $orig_reply_prompt;
                                    if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                    {
                                        $reply_prompt = preg_split('/\r\n|\r|\n/', $reply_prompt);
                                        $reply_prompt = array_filter($reply_prompt);
                                        if(count($reply_prompt) > 0)
                                        {
                                            $reply_prompt = $reply_prompt[array_rand($reply_prompt)];
                                        }
                                        else
                                        {
                                            $reply_prompt = '';
                                        }
                                    }
                                    $reply_prompt = aiomatic_replaceSynergyShortcodes($reply_prompt);
                                    if(!empty($reply_prompt))
                                    {
                                        $reply_prompt = aiomatic_replaceAIPostShortcodes($reply_prompt, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                    }
                                    else
                                    {
                                        $reply_prompt = trim(strip_tags($post_title));
                                    }
                                    $reply_prompt = trim($reply_prompt);
                                    if (filter_var($reply_prompt, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($reply_prompt, '.txt'))
                                    {
                                        $txt_content = aiomatic_get_web_page($reply_prompt);
                                        if ($txt_content !== FALSE) 
                                        {
                                            $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                            $txt_content = array_filter($txt_content);
                                            if(count($txt_content) > 0)
                                            {
                                                $txt_content = $txt_content[array_rand($txt_content)];
                                                if(trim($txt_content) != '') 
                                                {
                                                    $reply_prompt = $txt_content;
                                                    $reply_prompt = aiomatic_replaceSynergyShortcodes($reply_prompt);
                                                    $reply_prompt = aiomatic_replaceAIPostShortcodes($reply_prompt, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                                }
                                            }
                                        }
                                    }
                                    if(empty($reply_prompt))
                                    {
                                        aiomatic_log_to_file('Empty API reply select seed provided!');
                                    }
                                    else
                                    {
                                        if(aiomatic_strlen($reply_prompt) > $max_seed_tokens * 4)
                                        {
                                            $reply_prompt = aiomatic_substr($reply_prompt, 0, (0 - ($max_seed_tokens * 4)));
                                        }
                                        $reply_prompt = trim($reply_prompt);
                                        if(empty($reply_prompt))
                                        {
                                            aiomatic_log_to_file('Empty API reply select seed provided (2)! ' . print_r($reply_prompt, true));
                                            break;
                                        }
                                        $query_token_count = count(aiomatic_encode($reply_prompt));
                                        $available_tokens = aiomatic_compute_available_tokens($title_model, $max_tokens, $reply_prompt, $query_token_count);
                                        if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                        {
                                            $string_len = aiomatic_strlen($reply_prompt);
                                            $string_len = $string_len / 2;
                                            $string_len = intval(0 - $string_len);
                                            $reply_prompt = aiomatic_substr($reply_prompt, 0, $string_len);
                                            $reply_prompt = trim($reply_prompt);
                                            if(empty($reply_prompt))
                                            {
                                                aiomatic_log_to_file('Empty API reply select seed provided (after processing) ' . print_r($reply_prompt, true));
                                                break;
                                            }
                                            $query_token_count = count(aiomatic_encode($reply_prompt));
                                            $available_tokens = $max_tokens - $query_token_count;
                                        }
                                        $aierror = '';
                                        $finish_reason = '';
                                        if(!empty($global_prepend))
                                        {
                                            $reply_prompt = $global_prepend . ' ' . $reply_prompt;
                                        }
                                        if(!empty($global_append))
                                        {
                                            $reply_prompt = $reply_prompt . ' ' . $global_append;
                                        }
                                    }

                                    $reply_result = aiomatic_auto_generate_wpforo_reply($selected_forum, $post_id, $reply_model, $token, $choose_prompt, $reply_prompt, $temperature, $top_p, $presence_penalty, $frequency_penalty, $assistant_id, $thread_id, $store_data, $user_role);
                                    if($reply_result === false)
                                    {
                                        aiomatic_log_to_file('Failed to create reply for topic ID ' . $post_id . '!');
                                    }
                                    elseif(is_wp_error( $reply_result ))
                                    {
                                        aiomatic_log_to_file('Failed to create reply for topic ID ' . $post_id . '! Error: ' . $reply_result->get_error_message() . ' Error code: ' . $reply_result->get_error_code() . ' Error data: ' . $reply_result->get_error_data());
                                    }
                                }                                
                            }
                        }
                    } else {
                        aiomatic_log_to_file('Failed to insert topic into wp database(1)! Title: ' . $my_post['post_title'] . '! Error: ' . $post_id->get_error_message() . ' Error code: ' . $post_id->get_error_code() . ' Error data: ' . $post_id->get_error_data());
                        continue;
                    }
                }
            }
            elseif($type == 8)
            {
                if(!function_exists('is_plugin_active'))
                {
                    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
                }
                if (!is_plugin_active('aiomatic-extension-wpforo/aiomatic-extension-wpforo.php')) 
                {
                    aiomatic_log_to_file('This feature requires the Aimogen Extension for AI Forum Creation plugin to be installed and activated!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
                if (!is_plugin_active('wpforo/wpforo.php')) 
                {
                    aiomatic_log_to_file('This feature requires the wpForo plugin to be installed and activated!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
                if($post_title == '')
                {
                    aiomatic_log_to_file('Strategy cannot be empty for wpForo posting!');
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return 'fail';
                }
                while(true) 
                {
                    $thread_id = '';
                    $post_link = '';
                    $user_name = '';
                    $post_cats = '';
                    $post_excerpt = '';
                    $final_content = '';
                    $update_post_id = '';
                    $featured_image = '';
                    $post_tagz = '';
                    $postID = '';
                    $old_title = '';
                    $img_attr = '';
                    if ($count > intval($max)) {
                        break;
                    }
                    aiomatic_job_set_status_pending($rule_unique_id, array('step' => 'Starting processing topic ID #' . $count));
                    $current_section = '';
                    $post_sections = '';
                    $post_topic = '';
                    $post_title_keywords = '';
                    $posting_mode = 'title';
                    $post_id = aiomatic_wpforo_find_topic_by_strategy($selected_forum, $post_title, $more_replies);
                    if($post_id === false)
                    {
                        aiomatic_log_to_file('No topic found for the specified strategy: ' . $post_title);
                        if($auto == 1)
                        {
                            aiomatic_clearFromList($param, $type);
                        }
                        return 'nochange';
                    }
                    if($reply_count !== '')
                    {
                        preg_match_all('#\s*(\d+)\s*-\s*(\d+)\s*#', $reply_count, $mxatches);
                        if(isset($mxatches[2][0]))
                        {
                            $min_l = $mxatches[1][0];
                            $max_l = $mxatches[2][0];
                            $reply_count = wp_rand(intval($min_l), intval($max_l));
                        }
                        else
                        {
                            $reply_count = intval($reply_count);
                        }
                        if($reply_count > 0)
                        {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('Creating ' . $reply_count . ' replies for topic ID ' . $post_id . '!!');
                            }
                            $orig_choose_prompt = $choose_prompt;
                            $orig_reply_prompt = $reply_prompt;
                            for($ij = 0; $ij < $reply_count; $ij++)
                            {
                                $choose_prompt = $orig_choose_prompt;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $choose_prompt = preg_split('/\r\n|\r|\n/', $choose_prompt);
                                    $choose_prompt = array_filter($choose_prompt);
                                    if(count($choose_prompt) > 0)
                                    {
                                        $choose_prompt = $choose_prompt[array_rand($choose_prompt)];
                                    }
                                    else
                                    {
                                        $choose_prompt = '';
                                    }
                                }
                                $choose_prompt = aiomatic_replaceSynergyShortcodes($choose_prompt);
                                if(!empty($choose_prompt))
                                {
                                    $choose_prompt = aiomatic_replaceAIPostShortcodes($choose_prompt, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $choose_prompt = trim(strip_tags($post_title));
                                }
                                $choose_prompt = trim($choose_prompt);
                                if (filter_var($choose_prompt, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($choose_prompt, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($choose_prompt);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $choose_prompt = $txt_content;
                                                $choose_prompt = aiomatic_replaceSynergyShortcodes($choose_prompt);
                                                $choose_prompt = aiomatic_replaceAIPostShortcodes($choose_prompt, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($choose_prompt))
                                {
                                    aiomatic_log_to_file('Empty API user select seed provided!');
                                }
                                else
                                {
                                    if(aiomatic_strlen($choose_prompt) > $max_seed_tokens * 4)
                                    {
                                        $choose_prompt = aiomatic_substr($choose_prompt, 0, (0 - ($max_seed_tokens * 4)));
                                    }
                                    $choose_prompt = trim($choose_prompt);
                                    if(empty($choose_prompt))
                                    {
                                        aiomatic_log_to_file('Empty API user select seed provided (2)! ' . print_r($choose_prompt, true));
                                        break;
                                    }
                                    $query_token_count = count(aiomatic_encode($choose_prompt));
                                    $available_tokens = aiomatic_compute_available_tokens($title_model, $max_tokens, $choose_prompt, $query_token_count);
                                    if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                    {
                                        $string_len = aiomatic_strlen($choose_prompt);
                                        $string_len = $string_len / 2;
                                        $string_len = intval(0 - $string_len);
                                        $choose_prompt = aiomatic_substr($choose_prompt, 0, $string_len);
                                        $choose_prompt = trim($choose_prompt);
                                        if(empty($choose_prompt))
                                        {
                                            aiomatic_log_to_file('Empty API user select seed provided (after processing) ' . print_r($choose_prompt, true));
                                            break;
                                        }
                                        $query_token_count = count(aiomatic_encode($choose_prompt));
                                        $available_tokens = $max_tokens - $query_token_count;
                                    }
                                    $aierror = '';
                                    $finish_reason = '';
                                    if(!empty($global_prepend))
                                    {
                                        $choose_prompt = $global_prepend . ' ' . $choose_prompt;
                                    }
                                    if(!empty($global_append))
                                    {
                                        $choose_prompt = $choose_prompt . ' ' . $global_append;
                                    }
                                }

                                $reply_prompt = $orig_reply_prompt;
                                if(!isset($aiomatic_Main_Settings['whole_prompt']) || trim($aiomatic_Main_Settings['whole_prompt']) != 'on')
                                {
                                    $reply_prompt = preg_split('/\r\n|\r|\n/', $reply_prompt);
                                    $reply_prompt = array_filter($reply_prompt);
                                    if(count($reply_prompt) > 0)
                                    {
                                        $reply_prompt = $reply_prompt[array_rand($reply_prompt)];
                                    }
                                    else
                                    {
                                        $reply_prompt = '';
                                    }
                                }
                                $reply_prompt = aiomatic_replaceSynergyShortcodes($reply_prompt);
                                if(!empty($reply_prompt))
                                {
                                    $reply_prompt = aiomatic_replaceAIPostShortcodes($reply_prompt, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                }
                                else
                                {
                                    $reply_prompt = trim(strip_tags($post_title));
                                }
                                $reply_prompt = trim($reply_prompt);
                                if (filter_var($reply_prompt, FILTER_VALIDATE_URL) !== false && aiomatic_endsWith($reply_prompt, '.txt'))
                                {
                                    $txt_content = aiomatic_get_web_page($reply_prompt);
                                    if ($txt_content !== FALSE) 
                                    {
                                        $txt_content = preg_split('/\r\n|\r|\n/', $txt_content);
                                        $txt_content = array_filter($txt_content);
                                        if(count($txt_content) > 0)
                                        {
                                            $txt_content = $txt_content[array_rand($txt_content)];
                                            if(trim($txt_content) != '') 
                                            {
                                                $reply_prompt = $txt_content;
                                                $reply_prompt = aiomatic_replaceSynergyShortcodes($reply_prompt);
                                                $reply_prompt = aiomatic_replaceAIPostShortcodes($reply_prompt, $post_link, $post_title, $blog_title, $post_excerpt, $final_content, $user_name, $featured_image, $post_cats, $post_tagz, $postID, $img_attr, $old_title, $post_title_keywords, $custom_shortcodes, $global_prepend, $global_append);
                                            }
                                        }
                                    }
                                }
                                if(empty($reply_prompt))
                                {
                                    aiomatic_log_to_file('Empty API reply select seed provided!');
                                }
                                else
                                {
                                    if(aiomatic_strlen($reply_prompt) > $max_seed_tokens * 4)
                                    {
                                        $reply_prompt = aiomatic_substr($reply_prompt, 0, (0 - ($max_seed_tokens * 4)));
                                    }
                                    $reply_prompt = trim($reply_prompt);
                                    if(empty($reply_prompt))
                                    {
                                        aiomatic_log_to_file('Empty API reply select seed provided (2)! ' . print_r($reply_prompt, true));
                                        break;
                                    }
                                    $query_token_count = count(aiomatic_encode($reply_prompt));
                                    $available_tokens = aiomatic_compute_available_tokens($title_model, $max_tokens, $reply_prompt, $query_token_count);
                                    if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
                                    {
                                        $string_len = aiomatic_strlen($reply_prompt);
                                        $string_len = $string_len / 2;
                                        $string_len = intval(0 - $string_len);
                                        $reply_prompt = aiomatic_substr($reply_prompt, 0, $string_len);
                                        $reply_prompt = trim($reply_prompt);
                                        if(empty($reply_prompt))
                                        {
                                            aiomatic_log_to_file('Empty API reply select seed provided (after processing) ' . print_r($reply_prompt, true));
                                            break;
                                        }
                                        $query_token_count = count(aiomatic_encode($reply_prompt));
                                        $available_tokens = $max_tokens - $query_token_count;
                                    }
                                    $aierror = '';
                                    $finish_reason = '';
                                    if(!empty($global_prepend))
                                    {
                                        $reply_prompt = $global_prepend . ' ' . $reply_prompt;
                                    }
                                    if(!empty($global_append))
                                    {
                                        $reply_prompt = $reply_prompt . ' ' . $global_append;
                                    }
                                }
                                $reply_result = aiomatic_auto_generate_wpforo_reply($selected_forum, $post_id, $reply_model, $token, $choose_prompt, $reply_prompt, $temperature, $top_p, $presence_penalty, $frequency_penalty, $assistant_id, $thread_id, $store_data, $user_role);
                                if($reply_result === false)
                                {
                                    aiomatic_log_to_file('Failed to create reply for topic ID ' . $post_id . '!');
                                }
                                elseif(is_wp_error( $reply_result ))
                                {
                                    aiomatic_log_to_file('Failed to create reply for topic ID ' . $post_id . '! Error: ' . $reply_result->get_error_message() . ' Error code: ' . $reply_result->get_error_code() . ' Error data: ' . $reply_result->get_error_data());
                                }
                                else
                                {

                                }
                                $count++;
                                $posts_inserted++;
                            }                                
                        }
                    }
                }
            }
            else
            {
                aiomatic_log_to_file('Unknown type given ' . $type . '!');
                if($auto == 1)
                {
                    aiomatic_clearFromList($param, $type);
                }
                return 'fail';
            }
        }
        catch (Exception $e) {
            aiomatic_log_to_file('Exception thrown ' . esc_html($e->getMessage()) . '!');
            if($auto == 1)
            {
                aiomatic_clearFromList($param, $type);
            }
            return 'fail';
        }
        if($type == '5')
        {
            $logaction = 'OmniBlock saving actions done!';
        }
        elseif($type == '7')
        {
            $logaction = 'topics created!';
        }
        elseif($type == '8')
        {
            $logaction = 'replies created!';
        }
        else
        {
            $logaction = 'posts created!';
        }
        if ($posts_inserted > 0) 
        {
            aiomatic_set_last_activity(
                'bulk',
                ['count' => $posts_inserted]
            );
        }
        if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
            aiomatic_log_to_file('Rule ID ' . esc_html($param) . ' succesfully run! ' . esc_html($posts_inserted) . ' ' . $logaction);
        }
        if (isset($aiomatic_Main_Settings['send_email']) && $aiomatic_Main_Settings['send_email'] == 'on' && $aiomatic_Main_Settings['email_address'] !== '') {
            try {
                $admin_mail = get_option('admin_email');
                $to        = $aiomatic_Main_Settings['email_address'];
                $subject   = '[aiomatic] Rule running report - ' . aiomatic_get_date_now();
                $message   = 'Rule ID ' . esc_html($param) . ' succesfully run! ' . esc_html($posts_inserted) . ' ' . $logaction;
                $headers[] = 'From: Aimogen Plugin <' . $admin_mail . '>';
                $headers[] = 'Reply-To: ' . $admin_mail;
                $headers[] = 'X-Mailer: PHP/' . phpversion();
                $headers[] = 'Content-Type: text/html';
                $headers[] = 'Charset: ' . get_option('blog_charset', 'UTF-8');
                wp_mail($to, $subject, $message, $headers);
            }
            catch (Exception $e) {
                if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                    aiomatic_log_to_file('Failed to send mail: Exception thrown ' . esc_html($e->getMessage()) . '!');
                }
            }
        }
    }
    if($type == 5)
    {
        if(isset($block_results) && count($block_results) > 0)
        {
            if($return_last_result == true)
            {
                $rez_end = end($block_results);
                $zoutput = '';
                foreach ($rez_end as $key => $value) {
                    if ($key === 0 || empty($value)) {
                        continue;
                    }
                    $zoutput .= $value . "\n";
                    //break to return only the first result
                    break;
                }
                $zoutput = trim($zoutput);
                if(!empty($zoutput))
                {
                    if($auto == 1)
                    {
                        aiomatic_clearFromList($param, $type);
                    }
                    return $zoutput;
                }
            }
        }
    }
    if ($posts_inserted == 0) 
    {
        if($type == 4)
        {
            if (isset($aiomatic_Main_Settings['email_notification']) && $aiomatic_Main_Settings['email_notification'] != '')
            {
                if($count === 1)
                {
                    $email_list = explode(',', $aiomatic_Main_Settings['email_notification']);
                    foreach($email_list as $thisaddr)
                    {
                        $thisaddr = trim($thisaddr);
                        try
                        {
                            $admin_mail = get_option('admin_email');
                            $to        = $thisaddr;
                            $subject   = '[Aimogen] Titles depleted rule ID ' . $param . ' - ' . aiomatic_get_date_now();
                            $message   = 'Rule ID ' . esc_html($param) . ' (' . $rule_description . ') depleted its titles from the CSV file, no new posts publised! Website URL: ' . get_site_url();
                            $headers[] = 'From: Aimogen Plugin <' . $admin_mail . '>';
                            $headers[] = 'Reply-To: ' . $admin_mail;
                            $headers[] = 'X-Mailer: PHP/' . phpversion();
                            $headers[] = 'Content-Type: text/html';
                            $headers[] = 'Charset: ' . get_option('blog_charset', 'UTF-8');
                            wp_mail($to, $subject, $message, $headers);
                        }
                        catch (Exception $e) 
                        {
                            if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) {
                                aiomatic_log_to_file('Failed to send mail: Exception thrown ' . esc_html($e->getMessage()) . '!');
                            }
                        }
                    }
                }
            }
        }
        if($auto == 1)
        {
            aiomatic_clearFromList($param, $type);
        }
        // Free memory before returning
        unset($posted_items);
        unset($posted_topics);
        unset($rss_feeds);
        unset($post_topic_list_arr);
        unset($post_title_lines);
        wp_cache_flush();
        if(function_exists('gc_collect_cycles')) {
            gc_collect_cycles();
        }
        return 'nochange';
    } else {
        if($auto == 1)
        {
            aiomatic_clearFromList($param, $type);
        }
        // Free memory before returning
        unset($posted_items);
        unset($posted_topics);
        unset($rss_feeds);
        unset($post_topic_list_arr);
        unset($post_title_lines);
        wp_cache_flush();
        if(function_exists('gc_collect_cycles')) {
            gc_collect_cycles();
        }
        return 'ok';
    }
}
?>