( ′∀`)σ≡σ☆))Д′)レ(゚∀゚;)ヘ=З=З=Зε≡(ノ´_ゝ`)ノ HEX
HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux mail.thebrand.ai 6.8.0-107-generic #107-Ubuntu SMP PREEMPT_DYNAMIC Fri Mar 13 19:51:50 UTC 2026 x86_64
User: www-data (33)
PHP: 8.3.6
Disabled: NONE
Upload Files
File: /var/www/html/createAISEO.php
<?php
set_time_limit(100000);

include("includes/limittext.php");
include('Connections/videoondemand.php');
require("DbSql2.inc.php");
require("NewsSql2.inc.php");
include("includes/processFunctionsX.php");
include("const.inc.php");
$db = new NewsSQL();
include("protect.php");

// To use the official API (GPT-3 and GPT-3.5 turbo)
// get OPENAI_API_KEY https://platform.openai.com/account/api-keys
define('OPENAI_API_KEY', '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');

// To use chat.openai.com
// get cookie "_puid=user-..." - https://chat.openai.com/chat
define('COOKIE_PUID', '_puid=user-...');

// To use chat.openai.com
// get ACCESS_TOKEN - https://chat.openai.com/api/auth/session
define('ACCESS_TOKEN', '');



global $link;
$stmt2 ="select * from profilepicture where catalogid=152 and type=2 and public =1  and is_deleted =0  and seo =0 and visibility=1 order by id DESC LIMIT  0, 1";


$query = mysqli_query($link,$stmt2) or die(mysqli_error());
$dbdata = array();

while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
    $id= $row["id"] ;
    $titleX= $row["title"] ;


    $words = preg_replace('/[0-9]+/', '', $row["title"]);
    $words = preg_replace('/\s+/', ' ', $words);
    $words = str_replace("Copy","",$words);
     $title = $words . " design template press [contentID]=$id";

    if (!empty ($title) )
    {
        $message = $title;
        $json = '{
    "openai_type": "turbo",
    "message": "'.$message.'",
    "chat_model": "text-davinci-003",
    "conversation_id": "",
    "parent_message_id": ""
}';

        $arr = json_decode($json, true);
       // header('Content-Type: application/json');

      $openai = [];
        $openai = openai_api_gpt_35_turbo($message);
        //$openai = '{ "title": "Elegant Quote Social Media Post Design Template", "keywords": ["social media post", "design template", "quote", "elegant"], "metaTitle": "Create Elegant Quote Social Media Posts with Our Design Template", "metaDescription": "Make your social media posts stand out with our elegant quote design template. Easy to use and customizable to fit your brand.", "id": 7794, "sections": [ { "subheading": "Stand Out on Social Media", "content": "In today\'s digital age, social media is an essential part of any marketing strategy. But with so many businesses vying for attention, it can be hard to stand out. That\'s where our elegant quote social media post design template comes in. With its eye-catching design and customizable features, you can create posts that are sure to grab your audience\'s attention." }, { "subheading": "Easy to Use and Customize", "content": "Our design template is user-friendly and easy to customize. You don\'t need to be a graphic designer to create stunning social media posts. Simply choose your favorite quote, add your branding elements, and you\'re ready to go. With our template, you can create professional-looking posts in minutes." }, { "subheading": "Versatile Design", "content": "Our elegant quote social media post design template is versatile and can be used for a variety of purposes. Whether you\'re promoting a sale, sharing a motivational quote, or announcing a new product, our template can be customized to fit your needs. With its elegant design, your posts will look polished and professional." } ], "HH": [ "Create Elegant Posts", "Easy Customization", "Versatile Design", "Professional Look", "Stand Out on Social Media" ], "conclusion": "With our elegant quote social media post design template, you can create stunning posts that will help your brand stand out on social media. Our user-friendly template is easy to customize and can be used for a variety of purposes. Start creating professional-looking posts today!", "FAQs": [ { "question": "Do I need design experience to use this template?", "answer": "No, our template is user-friendly and easy to use. You don\'t need any design experience to create professional-looking social media posts." }, { "question": "Can I customize the colors and fonts?", "answer": "Yes, our template is fully customizable. You can change the colors, fonts, and other design elements to fit your brand." }, { "question": "How many quotes are included in the template?", "answer": "Our template includes a variety of quotes to choose from. You can also add your own quotes if you prefer." }, { "question": "Can I use this template for multiple social media platforms?", "answer": "Yes, our template is versatile and can be used for multiple social media platforms, including Instagram, Facebook, and Twitter." }, { "question": "Is there a limit to how many posts I can create with the template?", "answer": "No, you can create as many posts as you like with our template. It\'s a one-time purchase with unlimited use." } ] }';
        $startPos = strpos($openai, '{');
        $endPos = strrpos($openai, '}');

        // Extract the JSON substring
         $openai = substr($openai, $startPos, $endPos - $startPos + 1);

//exit($openai);



      //$jsonStore = json_encode($openai, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
       // $jsonStore = mysqli_real_escape_string($link,$jsonStore) ;




        $Description = json_decode($openai , true);

    $keywords =  $Description['keywords'] ;



        $metaTitle = mysqli_real_escape_string($link,$Description['metaTitle']) ;
         $metaDescription = mysqli_real_escape_string($link,$Description['metaDescription']) ;
        $headings =  $Description['HH'] ;
        $sections =  $Description['sections']  ;
        $faqs =  $Description['FAQs']  ;






       foreach ($keywords as $value) {
              $kw .= $value.",";
  }

          $keywords = mysqli_real_escape_string($link,rtrim($kw, ",")) ;


       foreach ($headings as $value2) {
             $h .= $value2.",";
  }

            $tags = mysqli_real_escape_string($link,rtrim($h, ",")) ;


       foreach ($faqs as $value5) {
           $q   = "<p>".$value5['answer']."</p> " ;
           $a .= "<h3>".$value5['question']."</h3> $q ";
  }

           $faq = mysqli_real_escape_string($link,rtrim($a, ",")) ;



        foreach ($sections as $value3) {
            $cc   = "<p>".$value3['content']."</p> " ;
            $sh .= "<h2>".$value3['subheading']."</h2> $cc";

        }

$conclusion =  "<h2> Conclusion</h2> <p>".$Description['conclusion']."<p>";
        $sh =  $sh.$conclusion ;

          $content =  mysqli_real_escape_string($link,$sh) ;


   $sql = "INSERT INTO `h_product_details_seo` (`product_id`, `lang_id`, `title`, `description`, `seo_title`, `seo_description`, `seo_keywords`, `tags`, `faqs`) VALUES (' $id', '1','$titleX', '$content', '$metaTitle', '$metaDescription', '$keywords', '$tags', '$faq')";


        mysqli_query($link,$sql);


        $stmt2 ="select * from h_product_details_seo where product_id=$id";


        $query = mysqli_query($link,$stmt2) or die(mysqli_error());
        $dbdata = array();
 $row = mysqli_fetch_array($query, MYSQLI_ASSOC);

if(empty($row)) {

    $sql = "update profilepicture set seo='3'  WHERE  id=$id";
    $query = mysqli_query($link,"$sql") or die(mysqli_error());

    echo   "error $titleX | $id <br>";

}

else{

    $sql = "update profilepicture set seo='1'  WHERE  id=$id";
    $query = mysqli_query($link,"$sql") or die(mysqli_error());

    echo   "Added $titleX | $id <br>";

}



        }














}





function openai_chat($arr){

    $url = 'https://chat.openai.com/backend-api/conversation';

    $data = [
        "action" => "next",
        "messages" => [
            [
                "content" => [
                    "content_type" => "text",
                    "parts" => [$arr['message']]
                ],
                "id" => uuid4(),
                "role" => "user"
            ]
        ],
        /*
         text-davinci-002-render-sha - default
         text-davinci-002-render-paid - legacy
         gpt-4
        */
        "model" => $arr['chat_model'],
        "parent_message_id" => $arr['parent_message_id']
    ];

    if(!empty($arr['conversation_id']))
        $data["conversation_id"] = $arr['conversation_id'];

    $headers = [
        //'referer: https://chat.openai.com/chat' .($arr['conversation_id']?'/'.$arr['conversation_id']:''),
        'cookie: ' . COOKIE_PUID,
        'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        'Content-Type: application/json',
        'Authorization: Bearer ' . ACCESS_TOKEN
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    if (curl_errno($ch))
        return ["error" => ["msg"=>'<span style="color:red">' . curl_error($ch) . '</span>']];
    curl_close($ch);

    $expl = explode("\n", $response);
    $last_line = '';
    foreach ($expl as $line) {
        if($line === "" || $line === null)
            continue;
        if(strpos($line, "data: ") !== false)
            $line = substr($line, 6);
        if($line === "[DONE]")
            break;
        $last_line = $line;
    }

    if($last_line){
        $decoded_line = json_decode($last_line, true);
        if (json_last_error() !== JSON_ERROR_NONE)
            return ["error" => ["msg"=>'<span style="color:red">' . $last_line . '</span>']];

        if(!empty($decoded_line["detail"]))
            return ["error" => (
            is_array($decoded_line["detail"])?
                (!empty($decoded_line["detail"]["message"])?
                    ["msg"=>'<span style="color:red">' . $decoded_line["detail"]["message"] . '</span>']:
                    $decoded_line["detail"][0]):
                ["msg"=>'<span style="color:red">' . $decoded_line["detail"] . '</span>']
            )];

        $message = $decoded_line["message"]["content"]["parts"][0];
        $conversation_id = $decoded_line["conversation_id"];
        $parent_message_id = $decoded_line["message"]["id"];
        return [
            "message" => $message,
            "conversation_id" => $conversation_id,
            "parent_message_id" => $parent_message_id,
        ];
    }
    return ["error" => ["msg"=> '<span style="color:red">unknown</span>']];
}

function openai_api_text_davinci_003($message){

    $url = 'https://api.openai.com/v1/engines/text-davinci-003/completions';
    $headers = [
        'Content-Type: application/json',
        'Authorization: Bearer ' . OPENAI_API_KEY
    ];
    $data = [
        "prompt" => $message,
        'max_tokens' => 300,
        "temperature" => 0.5,
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response  = curl_exec($ch);
    if (curl_errno($ch)) {
        $return = [
            'error' => ['msg'=>'<span style="color:red">' . curl_error($ch) . '</span>']
        ];
        curl_close($ch);
        return $return;
    }
    curl_close($ch);
    $arr = json_decode($response, 1);

    $return = [
        'message' => ''
    ];
    if(!empty($arr['error'])){
        $return['error'] = ['msg'=>'<span style="color:red">' . $arr['error']['message'] . '</span>'];
    }
    elseif(!empty($arr['choices'])){
        $return['message'] = trim($arr['choices'][0]['text']);
    }
    return $return;
}

function openai_api_gpt_35_turbo($message){
    $message = urldecode($message);

    $prompt = 'I want you to pretend that you are an E-commerce SEO expert who writes compelling design template descriptions for users looking to buy design templates online.Write 100% Unique, SEO-optimized, Human-Written  in English.Write In Your Own Words Rather Than Copying And Pasting From Other Sources. Consider perplexity and burstiness when creating content, ensuring high levels of both without losing specificity or context. Use fully detailed paragraphs that engage the reader. Write In A Conversational Style As Written By A Human (Use An Informal Tone, Utilize Personal Pronouns, Keep It Simple, Engage The Reader, Use The Active Voice, Keep It Brief, Use Rhetorical Questions, and Incorporate Analogies And Metaphors).I am going to provide the title of one design template product and I want you to come up with a minimum of three distinct content sections for the design template description, each section about a unique subset of keywords relating to the template I provide you in json format.Make sure that each of the unique content sections are labeled with an informative and eye-catching subheading describing the main focus of the content section. The main point of these commands is for you to developing a new keyword-rich, informative, and captivating design template summary/description that is less than 1500 words. The purpose of design template description is marketing the design templates to users looking to use them or download. Use emotional words and creative reasons to show why a user should use the template design I tell you. After you generate the new design template summary, please generate a bulleted list of 5 possible H1 headings for this design template page, and make each H1 less than 7 words each. Please also include bulleted list of broad match keywords that were used to accomplish writing the design template summary. Write a persuasive and professional sounding Meta Title and Description that integrates similar language present in the new design template summary text. Make sure to include a numerical aspect in the Meta Title.Write a conclusion section and 5 unique FAQs section related to this topic ad template  after The Conclusion. No discounts or promotions.Do not echo my prompt. Do not remind me what I asked you for. Do not apologize. Do not self-reference. Write all output in valid json output. the output is as follows: create a json with following keys 1. title =design template title 2. keywords =keywords Used 3. metaTitle = Meta Title 4. metaDescription = Meta Description 5. id=[contentID] 6. sections=Content Sections 7.HH=H1 Headings 8.conclusion=conclusion section 9.FAQs = unique faqs.under sections, strictly have the following keys that loop under sections 1. subheading 2. content. Please use the following design template: ';
    $message = $prompt.$message;



    $url = 'https://api.openai.com/v1/chat/completions';
    $headers = [
        'Content-Type: application/json',
        'Authorization: Bearer ' . OPENAI_API_KEY
    ];
    $data = [
        "model" => "gpt-3.5-turbo",
        "messages" => [
            ["role" => "user", "content" => $message]
        ],
        'max_tokens' => 2030,
        "temperature" => 0.4,
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response  = curl_exec($ch);
    if (curl_errno($ch)) {
        $return = [
            'error' => ['msg'=>'<span style="color:red">' . curl_error($ch) . '</span>']
        ];
        curl_close($ch);
        return $return;
    }
    curl_close($ch);
    $arr = json_decode($response, 1);

    $return = [
        'message' => ''
    ];
    if(!empty($arr['error'])){
        $return['error'] = ['msg'=>'<span style="color:red">' . $arr['error']['message'] . '</span>'];
    }
    elseif(!empty($arr['choices'])){
        $return= trim($arr['choices'][0]['message']['content']);
    }


    $responset = preg_replace('~\{(?:[^{}]|(?R))*\}~', '', $return);

    if (!empty($responset))
    {
        $return = str_replace($responset,"",$return);

    }


    return $return;
}

/*--------------------*/

// get uuid4
function uuid4() {

}

// replace_html
function replace_html($string) {

    return $string;
}




?>