<?php
defined('ABSPATH') or die(); 
use DonatelloZa\RakePlus\RakePlus;
class AiomaticAutoInboundLinks 
{
    public function __construct() 
    {
        require_once (dirname(__FILE__) . "/rake-php-plus/src/AbstractStopwordProvider.php"); 
        require_once (dirname(__FILE__) . "/rake-php-plus/src/ILangParseOptions.php"); 
        require_once (dirname(__FILE__) . "/rake-php-plus/src/LangParseOptions.php"); 
        require_once (dirname(__FILE__) . "/rake-php-plus/src/StopwordArray.php"); 
        require_once (dirname(__FILE__) . "/rake-php-plus/src/StopwordsPatternFile.php"); 
        require_once (dirname(__FILE__) . "/rake-php-plus/src/StopwordsPHP.php"); 
        require_once (dirname(__FILE__) . "/rake-php-plus/src/RakePlus.php");
    }
    public function add_inbound_links($content, $max, $link_post_types, $lang, $rel_search, $current_post_id, $link_type, $link_list, $link_nofollow, $link_post_ids = '', $link_post_not_ids = '', $force_keywords = array()) 
    {
        $keywords = array();
        $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
        if(isset($aiomatic_Main_Settings['kw_method']) && $aiomatic_Main_Settings['kw_method'] == 'ai' && isset($aiomatic_Main_Settings['kw_prompt']) && $aiomatic_Main_Settings['kw_prompt'] != '')
        {
            if (!aiomatic_check_api_keys($aiomatic_Main_Settings)) 
            {
                aiomatic_log_to_file('You need to insert a valid AI service API Key for the automatic AI keyword extractor to work!');
            }
            else
            {
                $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);
                $plain_text_content = strip_tags($content);
                $plain_text_content = strip_shortcodes($plain_text_content);
                if(empty($plain_text_content))
                {
                    return '';
                }
                $prompt = $aiomatic_Main_Settings['kw_prompt'];
                $prompt = str_replace('%%content%%', $plain_text_content, $prompt);
                if(isset($aiomatic_Main_Settings['kw_model']) && $aiomatic_Main_Settings['kw_model'] != '')
                {
                    $kw_model = $aiomatic_Main_Settings['kw_model'];
                }
                else
                {
                    $kw_model = get_default_model_name($aiomatic_Main_Settings);
                }
                if(isset($aiomatic_Main_Settings['kw_assistant_id']) && $aiomatic_Main_Settings['kw_assistant_id'] != '')
                {
                    $kw_assistant_id = $aiomatic_Main_Settings['kw_assistant_id'];
                }
                else
                {
                    $kw_assistant_id = '';
                }
                $all_models = aiomatic_get_all_models(true);
                if(!in_array($kw_model, $all_models))
                {
                    $kw_model = get_default_model_name($aiomatic_Main_Settings);
                }
                $query_token_count = count(aiomatic_encode($prompt));
                $max_tokens = aimogenpro_get_max_tokens($kw_model);
                $available_tokens = aiomatic_compute_available_tokens($kw_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);
                    $aicontent = aiomatic_substr($prompt, 0, $string_len);
                    $aicontent = trim($aicontent);
                    if(empty($aicontent))
                    {
                        return $content;
                    }
                    $query_token_count = count(aiomatic_encode($aicontent));
                    $available_tokens = $max_tokens - $query_token_count;
                }
                $thread_id = '';
                $aierror = '';
                $finish_reason = '';
                $generated_text = aiomatic_generate_text($token, $kw_model, $prompt, $available_tokens, 1, 1, 0, 0, false, 'linkKeywordWriter', 0, $finish_reason, $aierror, true, false, false, '', '', 'user', $kw_assistant_id, $thread_id, '', 'disabled', '', false, false, array(), '', '', '');
                if($generated_text === false)
                {
                    if (isset($aiomatic_Main_Settings['enable_detailed_logging'])) 
                    {
                        aiomatic_log_to_file('Failed to extract link keywords from: ' . $prompt . ' - error: ' . $aierror);
                    }
                    $keywords = array();
                }
                else
                {
                    $aikws = aiomatic_sanitize_ai_result($generated_text);
                    $keywords = explode(',', $aikws);
                    $keywords = array_map('trim', $keywords);
                    $keywords = array_flip($keywords);
                }
            }
        }
        else
        {
            $keywords = $this->find_keywords($content, $lang);
        }
        $force_keywords = array_flip($force_keywords);
        $keywords = array_merge($keywords, $force_keywords);
        $content = $this->insert_links($content, $keywords, $max, $link_post_types, $rel_search, $current_post_id, $link_type, $link_list, $link_nofollow, $link_post_ids, $link_post_not_ids);
        return $content;
    }

    private function find_keywords($content, $lang = 'en_US') 
    {
        $plain_text_content = strip_tags($content);
        $plain_text_content = strip_shortcodes($plain_text_content);
        if(empty($plain_text_content))
        {
            return array();
        }
        try {
            $rake = RakePlus::create($plain_text_content, $lang);
            $keywords = $rake->sortByScore('desc')->scores();
        } catch (Throwable $e) {
            return array();
        }
        return $keywords;
    }


    private function insert_links($content, $keywords, $max, $link_post_types, $rel_search, $post_id, $link_type, $link_list, $link_nofollow, $link_post_ids = '', $link_post_not_ids = '') 
    {
        $new_tab = ' ';
        $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
        if(isset($aiomatic_Main_Settings['new_tab']) && $aiomatic_Main_Settings['new_tab'] == 'yes')
        {
            $new_tab = ' target="_blank" rel="noopener noreferrer" ';
        }
        if(count($keywords) == 0 || $max <= 0)
        {
            return $content;
        }
        $keywords = array_map('trim', $keywords);
        $keywords = array_unique($keywords);
        $filteredStrings = [];
        foreach ($keywords as $string => $prob) 
        {
            $isSubstring = false;
            foreach ($keywords as $otherString) 
            {
                if ($string != $otherString && strpos($otherString, $string) !== false) 
                {
                    $isSubstring = true;
                    break;
                }
            }
            if (!$isSubstring) 
            {
                $filteredStrings[$string] = $prob;
            }
        }
        $keywords = $filteredStrings;
        if(count($keywords) == 0)
        {
            return $content;
        }
        $added = 0;
        $doneids = array();
        if($post_id != null)
        {
            $doneids[] = $post_id;
        }
        $links = preg_split('/\r\n|\r|\n/', trim($link_list));
        $links = array_filter($links);
        $pre_tags_matches = array();
        $pre_tags_matches_s = array();
        $conseqMatchs = array();
        $htmlfounds = array();
        $content = aiomatic_replaceExcludes($content, $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs);
        foreach ($keywords as $keyword => $score) 
        {
            if($added >= $max)
            {
                break;
            }
            if($link_type == 'internal' || $link_type == '')
            {
                if(stristr($content, $keyword) !== false && aiomatic_strlen($keyword) > 2)
                {
                    $linked_posts = $this->get_linked_posts($keyword, $link_post_types, $rel_search, $doneids, $link_post_ids, $link_post_not_ids);
                    if (!empty($linked_posts)) 
                    {
                        if($linked_posts[0]->guid === null)
                        {
                            $linked_posts[0]->guid = '';
                        }
                        $link_title = $linked_posts[0]->post_title;
                        foreach ($keywords as $check_keyword => $score) 
                        {
                            if (stripos($link_title, $check_keyword) !== false && $check_keyword !== $keyword) 
                            {
                                $link_title = str_ireplace($check_keyword, '...', $link_title);
                            }
                        }
                        $replacement = sprintf(
                            '<a href="%s"' . $new_tab . 'title="%s">%s</a>',
                            esc_url($linked_posts[0]->guid),
                            esc_attr($link_title),
                            esc_html($keyword)
                        );
                        $content = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/', $replacement, $content, 1);
                        $doneids[] = $linked_posts[0]->ID;
                        $added++;
                    }
                }
            }
            elseif($link_type == 'amazon')
            {
                if(stristr($content, $keyword) !== false && aiomatic_strlen($keyword) > 2)
                {
                    require_once(__DIR__ . '/amazon-direct.php');
                    $max_prod = 1;
                    $aiomatic_Spinner_Settings = get_option('aiomatic_Spinner_Settings', false);
                    if (isset($aiomatic_Spinner_Settings['affiliate_id']) && $aiomatic_Spinner_Settings['affiliate_id'] != '')
                    {
                        $affiliate_id = $aiomatic_Spinner_Settings['affiliate_id'];
                    }
                    else
                    {
                        $affiliate_id = '';
                    }
                    if (isset($aiomatic_Spinner_Settings['target_country']) && $aiomatic_Spinner_Settings['target_country'] != '')
                    {
                        $target_country = $aiomatic_Spinner_Settings['target_country'];
                    }
                    else
                    {
                        $target_country = '';
                    }
                    $linked_posts = array();
                    $okish = true;
					$amazresult = aiomatic_amazon_get_post($keyword, trim($affiliate_id), $target_country, '', '', '', $max_prod, '1', array());
                    if(is_array($amazresult) && isset($amazresult['status']) && $amazresult['status'] == 'nothing')
                    {
                        $okish = false;
                    }
                    if(!is_array($amazresult))
                    {
                        $okish = false;
                    }
                    if(is_array($amazresult) && count($amazresult) == 0)
                    {
                        $okish = false;
                    }
                    if($okish == true)
                    {
                        foreach($amazresult as $amazprod)
                        {
                            $linked_posts[$amazprod->offer_title] = $amazprod->offer_url;
                        }
                    }
                    aiomatic_shuffle_assoc($linked_posts);
                    if (!empty($linked_posts)) 
                    {
                        reset($linked_posts); 
                        $link_title = key($linked_posts);
                        $link_link = current($linked_posts);
                        if($link_nofollow == 'on' || $link_nofollow == '1')
                        {
                            $ltemplate = '<a href="%s"' . $new_tab . 'title="%s" rel="nofollow">%s</a>';
                        }
                        else
                        {
                            $ltemplate = '<a href="%s"' . $new_tab . 'title="%s">%s</a>';
                        }
                        foreach ($keywords as $check_keyword => $score) 
                        {
                            if (stripos($link_title, $check_keyword) !== false && $check_keyword !== $keyword) 
                            {
                                $link_title = str_ireplace($check_keyword, '...', $link_title);
                            }
                        }
                        $replacement = sprintf(
                            $ltemplate,
                            esc_url($link_link),
                            esc_attr($link_title),
                            esc_html($keyword)
                        );
                        $headings = [];
                        $content = preg_replace_callback(
                            '/<h[1-6][^>]*>.*?<\/h[1-6]>/is',
                            function ($matches) use (&$headings) {
                                $placeholder = "###^@!!!h3!@d1n8_" . count($headings) . "!!!@^###";
                                $headings[$placeholder] = $matches[0];
                                return $placeholder;
                            },
                            $content
                        );
                        $content = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/', $replacement, $content, 1);
                        $content = str_replace(array_keys($headings), array_values($headings), $content);
                        $doneids[] = $link_link;
                        $added++;
                    }
                }
            }
            elseif($link_type == 'serp')
            {
                if(stristr($content, $keyword) !== false && aiomatic_strlen($keyword) > 2)
                {
                    $locale = '';
                    $linked_posts = aiomatic_internet_result_unique($keyword, false, $locale, $doneids);
                    aiomatic_shuffle_assoc($linked_posts);
                    if (!empty($linked_posts)) 
                    {
                        if($link_nofollow == 'on' || $link_nofollow == '1')
                        {
                            $ltemplate = '<a href="%s"' . $new_tab . 'title="%s" rel="nofollow">%s</a>';
                        }
                        else
                        {
                            $ltemplate = '<a href="%s"' . $new_tab . 'title="%s">%s</a>';
                        }
                        $link_title = $linked_posts[0]['title'];
                        foreach ($keywords as $check_keyword => $score) 
                        {
                            if (stripos($link_title, $check_keyword) !== false && $check_keyword !== $keyword) 
                            {
                                $link_title = str_ireplace($check_keyword, '...', $link_title);
                            }
                        }
                        $replacement = sprintf(
                            $ltemplate,
                            esc_url($linked_posts[0]['link']),
                            esc_attr($link_title),
                            esc_html($keyword)
                        );
                        $headings = [];
                        $content = preg_replace_callback(
                            '/<h[1-6][^>]*>.*?<\/h[1-6]>/is',
                            function ($matches) use (&$headings) {
                                $placeholder = "###^@!!!h3!@d1n8_" . count($headings) . "!!!@^###";
                                $headings[$placeholder] = $matches[0];
                                return $placeholder;
                            },
                            $content
                        );
                        $content = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/', $replacement, $content, 1);
                        $content = str_replace(array_keys($headings), array_values($headings), $content);
                        $doneids[] = $linked_posts[0]['link'];
                        $added++;
                    }
                }
            }
            elseif($link_type == 'manual')
            {
                if(count($links) == 0)
                {
                    break;
                }
                else
                {
                    $keyword_links = array_filter($links, function($link) use ($keyword) {
                        return stripos($link, $keyword) !== false;
                    });
                    if (!empty($keyword_links)) {
                        $the_link_id = array_rand($keyword_links);
                        $my_link = $keyword_links[$the_link_id];
                    } else {
                        $the_link_id = array_rand($links);
                        $my_link = $links[$the_link_id];
                    }
                }
                if(stristr($content, $keyword) !== false && aiomatic_strlen($keyword) > 2)
                {
                    unset($links[$the_link_id]);
                    if($link_nofollow == 'on' || $link_nofollow == '1')
                    {
                        $ltemplate = '<a href="%s"' . $new_tab . 'rel="nofollow">%s</a>';
                    }
                    else
                    {
                        $ltemplate = '<a href="%s"' . $new_tab . '>%s</a>';
                    }
                    $replacement = sprintf(
                        $ltemplate,
                        esc_url($my_link),
                        esc_html($keyword)
                    );
                    $content = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/', $replacement, $content, 1);
                    $added++;
                }
            }
            elseif($link_type == 'mixed')
            {
                //1 internal, 2 manual
                $go_selector = wp_rand(1,2);
                if(count($links) == 0)
                {
                    $go_selector = 1;
                }
                if($go_selector == 1)
                {
                    if(stristr($content, $keyword) !== false && aiomatic_strlen($keyword) > 2)
                    {
                        $linked_posts = $this->get_linked_posts($keyword, $link_post_types, $rel_search, $doneids, $link_post_ids, $link_post_not_ids);
                        if (!empty($linked_posts)) 
                        {
                            if($linked_posts[0]->guid === null)
                            {
                                $linked_posts[0]->guid = '';
                            }
                            $link_title = $linked_posts[0]->post_title;
                            foreach ($keywords as $check_keyword => $score) 
                            {
                                if (stripos($link_title, $check_keyword) !== false && $check_keyword !== $keyword) 
                                {
                                    $link_title = str_ireplace($check_keyword, '...', $link_title);
                                }
                            }
                            $replacement = sprintf(
                                '<a href="%s"' . $new_tab . 'title="%s">%s</a>',
                                esc_url($linked_posts[0]->guid),
                                esc_attr($link_title),
                                esc_html($keyword)
                            );
                            $content = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/', $replacement, $content, 1);
                            $doneids[] = $linked_posts[0]->ID;
                            $added++;
                        }
                        else
                        {
                            if(count($links) > 0)
                            {
                                $go_selector = 2;
                            }
                        }
                    }
                }
                elseif($go_selector == 2)
                {
                    if(stristr($content, $keyword) !== false && aiomatic_strlen($keyword) > 2)
                    {
                        $the_link_id = array_rand($links);
                        $my_link = $links[$the_link_id];
                        unset($links[$the_link_id]);
                        if($link_nofollow == 'on' || $link_nofollow == '1')
                        {
                            $ltemplate = '<a href="%s"' . $new_tab . 'rel="nofollow">%s</a>';
                        }
                        else
                        {
                            $ltemplate = '<a href="%s"' . $new_tab . '>%s</a>';
                        }
                        $replacement = sprintf(
                            $ltemplate,
                            esc_url($my_link),
                            esc_html($keyword)
                        );
                        $content = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/', $replacement, $content, 1);
                        $added++;
                    }
                }
            }
            elseif($link_type == 'intserp')
            {
                //1 internal, 2 serp
                $go_selector = wp_rand(1,2);
                if($go_selector == 1)
                {
                    if(stristr($content, $keyword) !== false && aiomatic_strlen($keyword) > 2)
                    {
                        $linked_posts = $this->get_linked_posts($keyword, $link_post_types, $rel_search, $doneids, $link_post_ids, $link_post_not_ids);
                        if (!empty($linked_posts)) 
                        {
                            if($linked_posts[0]->guid === null)
                            {
                                $linked_posts[0]->guid = '';
                            }
                            $link_title = $linked_posts[0]->post_title;
                            foreach ($keywords as $check_keyword => $score) 
                            {
                                if (stripos($link_title, $check_keyword) !== false && $check_keyword !== $keyword) 
                                {
                                    $link_title = str_ireplace($check_keyword, '...', $link_title);
                                }
                            }
                            $replacement = sprintf(
                                '<a href="%s"' . $new_tab . 'title="%s">%s</a>',
                                esc_url($linked_posts[0]->guid),
                                esc_attr($link_title),
                                esc_html($keyword)
                            );
                            $content = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/', $replacement, $content, 1);
                            $doneids[] = $linked_posts[0]->ID;
                            $added++;
                        }
                        else
                        {
                            if(count($links) > 0)
                            {
                                $go_selector = 2;
                            }
                        }
                    }
                }
                elseif($go_selector == 2)
                {
                    if(stristr($content, $keyword) !== false && aiomatic_strlen($keyword) > 2)
                    {
                        $locale = '';
                        $linked_posts = aiomatic_internet_result_unique($keyword, false, $locale, $doneids);
                        aiomatic_shuffle_assoc($linked_posts);
                        if (!empty($linked_posts)) 
                        {
                            if($link_nofollow == 'on' || $link_nofollow == '1')
                            {
                                $ltemplate = '<a href="%s"' . $new_tab . 'title="%s" rel="nofollow">%s</a>';
                            }
                            else
                            {
                                $ltemplate = '<a href="%s"' . $new_tab . 'title="%s">%s</a>';
                            }
                            $link_title = $linked_posts[0]['title'];
                            foreach ($keywords as $check_keyword => $score) 
                            {
                                if (stripos($link_title, $check_keyword) !== false && $check_keyword !== $keyword) 
                                {
                                    $link_title = str_ireplace($check_keyword, '...', $link_title);
                                }
                            }
                            $replacement = sprintf(
                                $ltemplate,
                                esc_url($linked_posts[0]['link']),
                                esc_attr($link_title),
                                esc_html($keyword)
                            );
                            $headings = [];
                            $content = preg_replace_callback(
                                '/<h[1-6][^>]*>.*?<\/h[1-6]>/is',
                                function ($matches) use (&$headings) {
                                    $placeholder = "###^@!!!h3!@d1n8_" . count($headings) . "!!!@^###";
                                    $headings[$placeholder] = $matches[0];
                                    return $placeholder;
                                },
                                $content
                            );
                            $content = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/', $replacement, $content, 1);
                            $content = str_replace(array_keys($headings), array_values($headings), $content);
                            $doneids[] = $linked_posts[0]['link'];
                            $added++;
                        }
                    }
                }
            }
            elseif($link_type == 'manserp')
            {
                //1 manual, 2 serp
                $go_selector = wp_rand(1,2);
                if(count($links) == 0)
                {
                    $go_selector = 2;
                }
                if($go_selector == 1)
                {
                    if(stristr($content, $keyword) !== false && aiomatic_strlen($keyword) > 2)
                    {
                        $the_link_id = array_rand($links);
                        $my_link = $links[$the_link_id];
                        unset($links[$the_link_id]);
                        if($link_nofollow == 'on' || $link_nofollow == '1')
                        {
                            $ltemplate = '<a href="%s"' . $new_tab . 'rel="nofollow">%s</a>';
                        }
                        else
                        {
                            $ltemplate = '<a href="%s"' . $new_tab . '>%s</a>';
                        }
                        $replacement = sprintf(
                            $ltemplate,
                            esc_url($my_link),
                            esc_html($keyword)
                        );
                        $content = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/', $replacement, $content, 1);
                        $added++;
                    }
                }
                elseif($go_selector == 2)
                {
                    if(stristr($content, $keyword) !== false && aiomatic_strlen($keyword) > 2)
                    {
                        $locale = '';
                        $linked_posts = aiomatic_internet_result_unique($keyword, false, $locale, $doneids);
                        aiomatic_shuffle_assoc($linked_posts);
                        if (!empty($linked_posts)) 
                        {
                            if($link_nofollow == 'on' || $link_nofollow == '1')
                            {
                                $ltemplate = '<a href="%s"' . $new_tab . 'title="%s" rel="nofollow">%s</a>';
                            }
                            else
                            {
                                $ltemplate = '<a href="%s"' . $new_tab . 'title="%s">%s</a>';
                            }
                            $link_title = $linked_posts[0]['title'];
                            foreach ($keywords as $check_keyword => $score) 
                            {
                                if (stripos($link_title, $check_keyword) !== false && $check_keyword !== $keyword) 
                                {
                                    $link_title = str_ireplace($check_keyword, '...', $link_title);
                                }
                            }
                            $replacement = sprintf(
                                $ltemplate,
                                esc_url($linked_posts[0]['link']),
                                esc_attr($link_title),
                                esc_html($keyword)
                            );
                            $headings = [];
                            $content = preg_replace_callback(
                                '/<h[1-6][^>]*>.*?<\/h[1-6]>/is',
                                function ($matches) use (&$headings) {
                                    $placeholder = "###^@!!!h3!@d1n8_" . count($headings) . "!!!@^###";
                                    $headings[$placeholder] = $matches[0];
                                    return $placeholder;
                                },
                                $content
                            );
                            $content = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/', $replacement, $content, 1);
                            $content = str_replace(array_keys($headings), array_values($headings), $content);
                            $doneids[] = $linked_posts[0]['link'];
                            $added++;
                        }
                    }
                }
            }
            elseif($link_type == 'intmanserp')
            {
                //1 manual, 2 serp, 3 internal
                $go_selector = wp_rand(1,3);
                if(count($links) == 0 && $go_selector == 1)
                {
                    $go_selector = wp_rand(2,3);
                }
                if($go_selector == 1)
                {
                    if(stristr($content, $keyword) !== false && aiomatic_strlen($keyword) > 2)
                    {
                        $the_link_id = array_rand($links);
                        $my_link = $links[$the_link_id];
                        unset($links[$the_link_id]);
                        if($link_nofollow == 'on' || $link_nofollow == '1')
                        {
                            $ltemplate = '<a href="%s"' . $new_tab . 'rel="nofollow">%s</a>';
                        }
                        else
                        {
                            $ltemplate = '<a href="%s"' . $new_tab . '>%s</a>';
                        }
                        $replacement = sprintf(
                            $ltemplate,
                            esc_url($my_link),
                            esc_html($keyword)
                        );
                        $content = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/', $replacement, $content, 1);
                        $added++;
                    }
                }
                elseif($go_selector == 2)
                {
                    if(stristr($content, $keyword) !== false && aiomatic_strlen($keyword) > 2)
                    {
                        $locale = '';
                        $linked_posts = aiomatic_internet_result_unique($keyword, false, $locale, $doneids);
                        aiomatic_shuffle_assoc($linked_posts);
                        if (!empty($linked_posts)) 
                        {
                            if($link_nofollow == 'on' || $link_nofollow == '1')
                            {
                                $ltemplate = '<a href="%s"' . $new_tab . 'title="%s" rel="nofollow">%s</a>';
                            }
                            else
                            {
                                $ltemplate = '<a href="%s"' . $new_tab . 'title="%s">%s</a>';
                            }
                            $link_title = $linked_posts[0]['title'];
                            foreach ($keywords as $check_keyword => $score) 
                            {
                                if (stripos($link_title, $check_keyword) !== false && $check_keyword !== $keyword) 
                                {
                                    $link_title = str_ireplace($check_keyword, '...', $link_title);
                                }
                            }
                            $replacement = sprintf(
                                $ltemplate,
                                esc_url($linked_posts[0]['link']),
                                esc_attr($link_title),
                                esc_html($keyword)
                            );
                            $headings = [];
                            $content = preg_replace_callback(
                                '/<h[1-6][^>]*>.*?<\/h[1-6]>/is',
                                function ($matches) use (&$headings) {
                                    $placeholder = "###^@!!!h3!@d1n8_" . count($headings) . "!!!@^###";
                                    $headings[$placeholder] = $matches[0];
                                    return $placeholder;
                                },
                                $content
                            );
                            $content = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/', $replacement, $content, 1);
                            $content = str_replace(array_keys($headings), array_values($headings), $content);
                            $doneids[] = $linked_posts[0]['link'];
                            $added++;
                        }
                    }
                }
                elseif($go_selector == 3)
                {
                    if(stristr($content, $keyword) !== false && aiomatic_strlen($keyword) > 2)
                    {
                        $linked_posts = $this->get_linked_posts($keyword, $link_post_types, $rel_search, $doneids, $link_post_ids, $link_post_not_ids);
                        if (!empty($linked_posts)) 
                        {
                            if($linked_posts[0]->guid === null)
                            {
                                $linked_posts[0]->guid = '';
                            }
                            $link_title = $linked_posts[0]->post_title;
                            foreach ($keywords as $check_keyword => $score) 
                            {
                                if (stripos($link_title, $check_keyword) !== false && $check_keyword !== $keyword) 
                                {
                                    $link_title = str_ireplace($check_keyword, '...', $link_title);
                                }
                            }
                            $replacement = sprintf(
                                '<a href="%s"' . $new_tab . 'title="%s">%s</a>',
                                esc_url($linked_posts[0]->guid),
                                esc_attr($link_title),
                                esc_html($keyword)
                            );
                            $content = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/', $replacement, $content, 1);
                            $doneids[] = $linked_posts[0]->ID;
                            $added++;
                        }
                        else
                        {
                            if(count($links) > 0)
                            {
                                $go_selector = 2;
                            }
                        }
                    }
                }
            }
        }
        $content = aiomatic_restoreExcludes($content, $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs);
        return $content;
    }

    private function get_linked_posts($keyword, $link_post_types, $rel_search, $post_id, $link_post_ids, $link_post_not_ids)
    {
        global $wpdb;

        $argsvar = array();

        $pts = array_filter(array_map('sanitize_key', explode(',', (string) $link_post_types)));

        if (empty($pts)) {
            $pts = array('post');
        }

        $post_type_placeholders = implode(',', array_fill(0, count($pts), '%s'));
        $posttypevar = "WHERE post_type IN ($post_type_placeholders)";
        $argsvar = array_merge($argsvar, $pts);

        if (is_array($post_id)) {
            $post_id = array_values(array_filter(array_map('absint', $post_id)));

            if (!empty($post_id)) {
                $id_placeholders = implode(',', array_fill(0, count($post_id), '%d'));
                $idquery = "AND ID NOT IN ($id_placeholders)";
                $argsvar = array_merge($argsvar, $post_id);
            } else {
                $idquery = 'AND ID != %d';
                $argsvar[] = 0;
            }
        } else {
            $idquery = 'AND ID != %d';
            $argsvar[] = absint($post_id);
        }

        $id_in_query = '';

        if (!empty($link_post_ids)) {
            $link_post_ids_array = array_values(array_filter(array_map('absint', explode(',', (string) $link_post_ids))));

            if (!empty($link_post_ids_array)) {
                $id_in_placeholders = implode(',', array_fill(0, count($link_post_ids_array), '%d'));
                $id_in_query = " AND ID IN ($id_in_placeholders)";
                $argsvar = array_merge($argsvar, $link_post_ids_array);
            }
        }

        $id_not_in_query = '';

        if (!empty($link_post_not_ids)) {
            $link_post_not_ids_array = array_values(array_filter(array_map('absint', explode(',', (string) $link_post_not_ids))));

            if (!empty($link_post_not_ids_array)) {
                $id_not_in_placeholders = implode(',', array_fill(0, count($link_post_not_ids_array), '%d'));
                $id_not_in_query = " AND ID NOT IN ($id_not_in_placeholders)";
                $argsvar = array_merge($argsvar, $link_post_not_ids_array);
            }
        }

        $allowed_columns = array(
            'post_title',
            'post_content',
            'post_excerpt',
        );

        if (is_array($rel_search) && !empty($rel_search)) {
            $safe_columns = array_values(array_intersect($rel_search, $allowed_columns));

            if (empty($safe_columns)) {
                $safe_columns = array('post_title', 'post_content');
            }
        } else {
            $safe_columns = array('post_title', 'post_content');
        }

        $like_parts = array();

        foreach ($safe_columns as $column) {
            $like_parts[] = $column . ' LIKE %s';
            $argsvar[] = '%' . $wpdb->esc_like($keyword) . '%';
        }

        $like_expr = '(' . implode(' OR ', $like_parts) . ')';

        $mysqls = "
            SELECT *
            FROM {$wpdb->posts}
            {$posttypevar}
            AND post_status = 'publish'
            {$idquery}
            AND {$like_expr}
            {$id_in_query}
            {$id_not_in_query}
            LIMIT 1
        ";

        $sql = $wpdb->prepare($mysqls, $argsvar);
        $linked_posts = $wpdb->get_results($sql);

        if (is_array($linked_posts)) {
            foreach ($linked_posts as $mindex => $mpost) {
                $myperma = get_permalink($mpost->ID);

                if ($myperma !== false) {
                    $linked_posts[$mindex]->guid = $myperma;
                }
            }
        }

        return $linked_posts;
    }
}