( ′∀`)σ≡σ☆))Д′)レ(゚∀゚;)ヘ=З=З=Зε≡(ノ´_ゝ`)ノ 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/tmpr/../tmpr/../tmpr/../tmpr/..//includes/configAI.php
<?php      // Function to calculate BM25 relevance score based on search query, content, and database connection
function calculateBM25($content, $searchTerms, $videoondemand) {
    $k1 = 1.2; // BM25 parameter
    $b = 0.75; // BM25 parameter
    $N = totalNumberOfDocuments($videoondemand); // Total number of documents in the collection
    $avgdl = averageDocumentLength($videoondemand); // Average document length in the collection
    $score = 0;

    foreach ($searchTerms as $term) {
        $ft = termFrequency($term, $content); // Frequency of the term in the document
        $df = documentFrequency($term, $videoondemand); // Number of documents in the collection where the term appears
        $idf = log(($N - $df + 0.5) / ($df + 0.5)); // Inverse document frequency
        $weight = ($ft * ($k1 + 1)) / ($ft + $k1 * (1 - $b + $b * ($avgdl / $avgdl)));
        $score += ($idf * $weight);
    }

    return $score;
}

// Function to calculate the total number of documents in the collection
function totalNumberOfDocuments($videoondemand) {
    $sql = "SELECT COUNT(*) AS total FROM profilepicture";
    $result = mysqli_query($videoondemand, $sql);
    $row = mysqli_fetch_assoc($result);
    return $row['total'];
}

// Function to calculate the average document length in the collection
function averageDocumentLength($videoondemand) {
    $sql = "SELECT AVG(LENGTH(title)) AS avg_length FROM profilepicture";
    $result = mysqli_query($videoondemand, $sql);
    $row = mysqli_fetch_assoc($result);
    return $row['avg_length'];
}

// Function to calculate the frequency of a term in a document
function termFrequency($term, $content) {
    return substr_count(strtolower($content), strtolower($term));
}

// Function to calculate the number of documents in the collection where the term appears

function documentFrequency($term, $videoondemand) {
    $sql = "SELECT COUNT(*) AS doc_freq FROM profilepicture WHERE title LIKE '%$term%'";
    $result = mysqli_query($videoondemand, $sql);
    $row = mysqli_fetch_assoc($result);
    return $row['doc_freq'];
}

// Function to retrieve the row details from the database based on the document ID
function retrieveRowById($id) {
    // Implement retrieval logic based on the document ID
    // Replace this with your own implementation or database query


    return $id;
}


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_4($message,$instructions){
    $message = urldecode($message);
 $noOfLayer = $instructions +1;


/*    $prompt = 'Ignore all earlier instructions.You are a professional graphic designer; i want you to use the following instructions to create text layers on a canvas and placed under the "objects" node;all text elements must be under objects key. follow strict order of text layers;create a hierarchy of information with font sizes [fontsize] given; Please observe the word count [wordcount]suggested.Here are strict instructions for the text layers;Text layer: {"type":"i-text","l":[x],"t":[y],"w":[w],"h":[h],"fL":"[color]","fF":"[fontFace]","fS":[fontSize],"te":"[text]","lH":[lineHeight]","tF":"[textFormat]","dE":"[textDecoration]","pS":"[text_position]"}.Strictly adhere to the following JSON structure:{"canvas":{"vv":"5.3.0","objects":[]},"ee":{"ff":null,"z":1,"aO":null},"cW":"[cW]","cH":"[cH]"} ; [text] word count must corresponding wordcount[wordcount] unless otherwise;[cW] and [cH] is design template width and height;generate only one set of json output;layers must have 10px margins;layer values between [] can an never be null;[w] for text should NOT be more than [cW] or [cH]; [x] and [y] represents the x and y coordinates creatively placed on the canvas;[w] and [h] represents the width and hight of the layer on the canvas.[text] is a relevant text to design;creatively choose perfect unique Google fonts;all text layers  MUST be under objects key.[text] can include necessary contact details etc as per context; feel free to add more relevant text layers if needed.  Choose perfect color palette for text; [text] to be a hook and that can to go viral.Avoid monotonous colors.[text] should spark curiosity.font size should be as per coresponding [fontsize] given; use white space well;for  [text] Consider the context,target audience;Use colors and typography strategically;generate a  minified JSON representation of the design request;With the above strict instructions when i write [nowcreate] create a perfect example of this design template complete with details and text associated.Do not echo my prompt. Do not remind me what I asked you for. Do not apologize. Do not self-reference. [nowcreate]  ';*/
    $prompt = 'IGNORE EARLIER COMMANDS. You are an expert graphic designer.The role of this prompt is to create  a layered json intepretation of a design. design should be readable from a distance,consider the context,consider your target audience,Use colors strategically.Use fonts to create a hierarchy of information.you have knowledge of layouts, placements of layered elements such as text, images, icons on a canvas. Pick a relevant or branded color scheme.Include a clear call-to-action if neccessary.You will then output the representation of the design in json format.The input i will give you is a description of a design template i would like you to produce in words then you will output in json.the elements can have colors and background colours that blend well like a professional designer does.the colors will be in hex format. This will help to create a cohesive and visually appealing design. use colors and typefaces to convey the message and brand values.Use no more than 4 typefaces.dont use Lorem ipsum generic text, instead use compelling, convincing language. position each text by ensuring margins, paddings and alignment are adhered to on the canvas. The layered  elements will have width, height, x,y.I will give you a json structure to follow strictly. here is the structure of the json you should mimick. { "canvas": { "objects": [] }, "editor": {"imageSearchTerm": "[imageSearchTerm]" }, "cW": "[cW]", "cH": "[cH]" } [cH], [cW] varies depending on what type of design template you are creating.minimum value of  [cW] is 1000.  this values for [cH], [cW] is in pixels px. [imageSearchTerm] is one search term that is a perfect and appropriate search term for a photo to be used in this design tht blends well. now i will give you the structure of  the elements which i call objects that go under objects node of the json above. now i will give you structure of a text layer that goes under objects section of the json given.  {"type":"textbox","l":[x],"t":[y],"w":[w],"h":[h],"fL":"[color]","fF":"[fontFace]","fS":[fontSize],"te":"[text]","lH":[lineHeight]","tF":"[textFormat]"} [w] and [h] above is the width and height of the text element. the dimensions are in pixels px . [x] and [y] is the displacement of the text on the canvas. [color] is the colour of the text [fontFace] is the font face used [fontSize] is the size of the font [lineHeight] is the line height. The [text] is the actual text or paragraphs. [textFormat] is the text format. [text] should be relevant creative text in line with request and type of design document. The [textFormat] value can be heading, subheading, paragraph accordingly. [color] is a non-repeating random color in hexadecimal format that blends well with the type of document  and other elements. [fontFace] is a random google font that changes from one text layer to another and that will blend well with the type of document or title.the text layer can be any relevant text depending on type of design document.now i will give you layer structure for shape that goes to the object node as well. {"type":"shape","l":[x],"t":[y],"w":[w],"h":[h],"fL":"[color]","st":"rectangle"}. [color],[w] and [h] of type shape is creatively determined and placed to ensure the design blends well. Shape layer must always be the first element. [nowcreate] command should create a maximum of 1 shape layer per request. all the [color] tags should blend well. Please keep  the structure as shown strictly.  With the above instructions  and when i write [nowcreate] immediately output minified json. output  json representation of the design request. text layers (textbox) under objects must not be more than '.$noOfLayer.' layers and not less than '.$noOfLayer.' layers. feel free to use new line ie \n. when you see [nowcreate] then OUTPUT a minified json without unneccesary newlines and spaces.[nowcreate] ';
    $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' => 1500,
        "temperature" => 0.7,
    ];

    $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']);
    }

    return $return;
}
function openai_api_gpt_9($message){
    $message = urldecode($message);



    $message =  $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' => 1500,
        "temperature" => 0.7,
    ];

    $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']);
    }

    return $return;
}
function openai_api_gpt_8($message){
      $message = urldecode($message);

        $message = 'IGNORE EARLIER COMMANDS. I want you to act as a copywriting and design expert that speaks and rewrites in fluent English. i will give you a design template in json format. Pretend that you have the most accurate and most detailed information about the design template [design name]. For context and your background the design name is [design name] with keywords [keywords]. the text layers on the design are as indicated under [objects]. Please rewrite the [text] under objects as a professional copy writer. ensure "text" replaced is exact word count and not more, for example the text "Farmers Market" is 2 words therefore the rewritten text must be 2 words as well and not more. ensure the "text" replaced are DIFFERENT for each occassion.do this for the rest of the layers.The character length of replaced "text" MUST be equal to character length of original "text". the replaced text MUST be different but very relevant to text that is being replaced.do not rewrite "text" with exact "text" i gave you in json below. You MUST rewrite text such as names of people, places, personal information, contacts, email, website, city, street,role, date e.t.c in "text" accordingly.  always rewrite the [text] given.  the node colors must contain only 3 colors.  As a professional designer  ensure the accent color, text color and backround color you pick are perfect for   [design name] kind of design. here is an  example of json represantation of the  colors  - "colors": "#fff, #eee, #cc0000". first color is accent color, second is text color and third color is background color. Produce only one set of json output. also ensure you simply rewrite the design name  without losing the meaning  . the output structure is json only. STRICTLY ONLY OUPUT JSON according to the structure given. do not auto complete this prompt. Do not apologize. Do not self-reference.Do not remind me what I asked you for. Do not just copy paste the example given. Here is the json input:'.$message.' . Do not just use my colors- be creative a come up with amazing colors because you are an expert designer. NOW PRODUCE A VALID JSON AS PER INSTRUCTIONS ABOVE.  ';





    $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' => 1500,
        "temperature" => 0.9,
    ];

    $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']);
    }

    return $return;
}
function openai_api_gpt_5($message,$promptX,$brand){
    $message = urldecode($message);


        $promptX = urldecode($promptX);
       $promptX = mb_convert_encoding($promptX, 'UTF-8', 'ISO-8859-1');




       $brand = urldecode($brand);


     $array = json_decode($promptX, true);




     $realPrompt = $array['Prompt'];



    $pattern = '/#.*---/s'; # add "s" modifier to match across multiple lines
    $replacement = ''; # replace the found match with nothing (essentially removing it)
    $realPrompt = preg_replace($pattern, $replacement, $realPrompt); # use preg_replace() to find and replace the pattern in the string






    $realPrompt = preg_replace("/(https?|ftp|ssh):\/\/[a-z0-9\/:%_+.,#?!@&=-]+\b/i", "www.thebrand.ai", $realPrompt);



    $realPrompt =str_replace("[TARGETLANGUAGE]","ENGLISH",$realPrompt);

    if(empty($message))
    {
        $realPrompt =str_replace("[PROMPT]","PROMPT - $brand.",$realPrompt);
    }
    else{
        $realPrompt =str_replace("[PROMPT]","PROMPT - $message.",$realPrompt);
    }


    $realPrompt =str_replace("'none of the above'","",$realPrompt).$brand;







    $realPrompt = urlencode($realPrompt);
    $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" => $realPrompt]
        ],
        'max_tokens' => 1500,
        "temperature" => 1,
    ];

    $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']);
    }
    return $return;
}

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

// get uuid4
function uuid4() {

}

// replace_html
function replace_html($string) {

    return $string;
}


set_time_limit(900);

// To use the official API (GPT-3 and GPT-3.5 turbo)e
// 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', '');

?>