Find this useful? Enter your email to receive occasional updates for securing PHP code.
Signing you up...
Thank you for signing up!
PHP Decode
<?php include_once($_SERVER['DOCUMENT_ROOT']."/config.php"); include_once($_SERVER['DO..
Decoded Output download
<?php
include_once($_SERVER['DOCUMENT_ROOT']."/config.php");
include_once($_SERVER['DOCUMENT_ROOT']."/admin/ilhaweb.php");
include_once($_SERVER['DOCUMENT_ROOT']."/".explode(DIRECTORY_SEPARATOR, __FILE__)[4]."/metodos.php");
$servidorSandbox = "177.52.182.57";
$servidorIa = "177.52.182.57";
$servidorBotdev = "177.52.182.57";
#DESCOMENTAR AO FINAL
if($_SERVER['REMOTE_ADDR']==$servidorSandbox || $_SERVER['REMOTE_ADDR']==$servidorIa){
// Conexo com o banco
conecta();
mysql_query("SET NAMES 'utf8mb4'");
mysql_query('SET character_set_connection=utf8mb4');
mysql_query('SET character_set_client=utf8mb4');
mysql_query('SET character_set_results=utf8mb4');
$now = date('Y-m-d H:i:s');
$today = date('Y-m-d');
$diasemana = array('domingo', 'segunda', 'tera', 'quarta', 'quinta', 'sexta', 'sabado');
$diasemana_base = date('w', time());
$dia_base_abrev = substr($diasemana[$diasemana_base],0,3);
$json = file_get_contents('php://input');
$decoded = json_decode($json, true);
$DIR = explode(DIRECTORY_SEPARATOR, __FILE__)[4];
$bancodedados = "ramalclu_".explode(DIRECTORY_SEPARATOR, __FILE__)[4];
$queryBanco = "USE ".$bancodedados; $setDB = mysql_query($queryBanco);
if($decoded!=""){
extract($decoded);
}
if ($_SERVER['REQUEST_METHOD'] === 'GET' || $_SERVER['REQUEST_METHOD'] === 'POST' || $_SERVER['REQUEST_METHOD'] === 'PUT' || $_SERVER['REQUEST_METHOD'] === 'DELETE') {
$contentTypeHeader = $_SERVER['HTTP_CONTENT_TYPE'];
$contentType = $_SERVER['CONTENT_TYPE'];
$clientIP = $_SERVER['REMOTE_ADDR'];
$method = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
$urlComponents = parse_url($uri);
// Verifica se a query est presente
if (isset($urlComponents['query'])) {
// Analisa a string de consulta em um array de parmetros
parse_str($urlComponents['query'], $PARAMETERS);
// Itera sobre os parmetros e cria variveis correspondentes
foreach ($PARAMETERS as $key => $value) {
$$key = filter_var(mysql_real_escape_string($value), FILTER_SANITIZE_STRING);
}
}
}
$SQLMORGANA = "SELECT * FROM $bancodedados._morgana WHERE morganaID='".$botID."' AND sin_ativo='S' ";
$QUERYMORGANA = mysql_query($SQLMORGANA);
if(mysql_num_rows($QUERYMORGANA) == 0){
// Defina o cdigo de status HTTP
// Crie o array com os dados de retorno
$return = array('http_code' => 404, 'content_type' => 'application/json', 'errorCode' => '404.B.1', 'msg' => "The requested bot is currently inactive or does not exist.");
// Defina o cabealho Content-Type para JSON
// Envie o array como resposta JSON
echo json_encode($return);
// Finalize a execuo
exit();
}
else {
# se o botID existe e est ativo...
$ROWMORGANA = mysql_fetch_array($QUERYMORGANA);
$MORGANA = $ROWMORGANA;
if($action == 'allowbot'){
requestedCurls(decode($json));
//$queryallow = mysql_query("UPDATE msg SET msgEndSession='S' WHERE msgMorganaID='".$botID."' AND botSession='".$botsession."' ");
// $varsdel = mysql_query("DELETE FROM vars WHERE varSession='".$botsession."' ");
$return = array('actionRequired' => $action, 'botID' => $botID, 'botsession' => $botsession, 'result' => $queryallow);
responsingCurls($return);
echo json_encode($return, JSON_UNESCAPED_UNICODE);
}
elseif($action == "consultaBot"){
requestedCurls(decode($json));
$QBOT = mysql_query("SELECT * FROM ramalclu_sandbox.chat WHERE chatID='".$chatID."' AND provedorID='".$provedorID."' AND sessaoencerrada<>'sim' ORDER BY registro DESC LIMIT 1");
if(mysql_num_rows($QBOT) != 0){
$ROWBOT = mysql_fetch_assoc($QBOT);
$botSession = $ROWBOT['sessao'];
$statusBot = $ROWBOT['statusBot'];
}
else{
$botSession = null;
$statusBot = "";
}
if($contextID != '' && !is_null($contextID)){
#!!!
//$QTEMPLATE = mysql_query("SELECT configAction FROM config WHERE configContextID='".$contextID."' AND botID='".$botID."' ORDER BY configOrder DESC LIMIT 1");
//$configAction = @mysql_result($QTEMPLATE, 0, 'configAction'); } $return = array('botID' => $botID, 'chatID' => $chatID, "msgID" => $msgID, "msg_Ref" => $msg_Ref,"msg_Plat" => $msg_Plat,"PlatID" => $PlatID,'botSession' => $botSession, 'statusBot' => $statusBot, 'configAction' => $configAction); responsingCurls($return); echo json_encode($return); } elseif($action == 'template'){ insertLog('Pedido de template chegou ao morganaWS: '.$json, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); $usuario = $MORGANA['morganaUsuario']; $provedorID = $MORGANA['provedorID']; $QINSTANCE = mysql_query("SELECT * FROM ramalclu_sandbox.instance WHERE usuario='".$usuario."' AND provedorID='".$provedorID."' "); if(mysql_num_rows($QINSTANCE) == 0){ echo json_encode(array('error' => 'servio no instanciado')); } else{ if($templateName != '' && !is_null($templateName)){ #!!! $VARS = $vars; $QT = mysql_query("SELECT * FROM ramalclu_botdev._template WHERE botID='".$botID."' AND templateName='".$templateName."'")or die(mysql_error()); if(mysql_num_rows($QT) == 0){ echo json_encode(array('botID' => $botID, 'templateName' => $templateName, 'error' => 'botID/template no encontrado')); } else{ $rowt = mysql_Fetch_assoc($QT); $content = json_decode($rowt['message'],true)[0]; foreach($VARS AS $varKey => $varValue){ $content = str_replace('$'.$varKey,$varValue,$content); } if($content==""){ echo json_encode(array('error' => 'Template sem contedo')); } else{ if($provedorID=="1" && stripos("@",$chatID)===false){ $chatID = $chatID."@s.whatsapp.net"; } $QUERYNONDUPLICATE = mysql_query("SELECT * FROM ramalclu_sandbox.fila WHERE chatID = '".$chatID."' AND usuario = '".$usuario."' AND mensagem = '".$content."' AND (filaStatus='0' OR filaStatus='') "); if(mysql_num_rows($QUERYNONDUPLICATE) == 0){ $qb = mysql_query("SELECT disparo_whatsapp FROM ramalclu_ematrix.ilh_usuario WHERE usuario='".$usuario."' AND situacao='ativo' "); if(mysql_num_rows($qb) == 0){ echo json_encode(array('error' => 'Usurio no encontrado')); } else{ $rowb = mysql_fetch_array($qb); $tarifa = $rowb['disparo_whatsapp']; $SQL = "INSERT INTO ramalclu_sandbox.fila SET requestID = '0', usuario = '".$usuario."', provedorID = '".$provedorID."', ord = '1', chatID = '".$chatID."', role = 'assistant', type='text', instanceNumb = '".$instanceNumb."', mensagem = '".mysql_real_escape_string($content)."', msg_Ref = '', contactChatId = '', payer = '".$usuario."', tarifa = '0.00', sessao = '".$templateName."', botSession = '', statusBot = '', agendamento = '".date('Y-m-d H:i:s')."', DateTimeEnvio = '', tag = '".$tag."', configAction = '', filaStatus = '0' "; //insertLog('SQL: '.$SQL, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); mysql_query($SQL); echo json_encode(array('status' => true)); } } } } } } } elseif($action == 'api'){ if($botID!=""){ if($api == "_morgana"){ if($_SERVER['REQUEST_METHOD']=="GET"){ $QBT =mysql_query("SELECT * FROM $bancodedados.$api WHERE morganaID='".$botID."' AND sin_ativo='S' "); if(mysql_num_rows($QBT)==1){ $return = mysql_fetch_assoc($QBT); echo json_encode($return); } else{ // Defina o cdigo de status HTTP http_response_code(404); // Por exemplo, 404 Not Found // Crie o array com os dados de retorno $return = array('http_code' => 404, 'content_type' => 'application/json', 'errorCode' => '404.2', 'msg' => 'botID not found'); // Defina o cabealho Content-Type para JSON header('Content-Type: application/json'); // Envie o array como resposta JSON echo json_encode($return); // Finalize a execuo exit(); } } } elseif($api == "_kw"){ if($_SERVER['REQUEST_METHOD']=="GET"){ $QIG = mysql_query("SELECT * FROM $bancodedados.$api WHERE botID='".$botID."' AND sin_ativo='S' "); if(mysql_num_rows($QIG)!=0){ while($ROWIG = mysql_fetch_assoc($QIG)){ $return[] = trim(str_replace("
", ' ',$ROWIG['kw_ignore'])); } } else{ $return=array('wqe98mvjwer5t9g4bq3re70tgh75gh7ty7tvn8y5e'); } echo json_encode($return); } } elseif($api == "ws"){ if($_SERVER['REQUEST_METHOD']=="POST"){ $method = $_GET['method']; $endpoint = $_GET['endpoint']; insertLog(date('Y-m-d H:i:s').': '.'step: botdev GET recebido - method: '.$method, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); insertLog(date('Y-m-d H:i:s').': '.'step: botdev GET recebido - endpoint: '.$endpoint, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); insertLog(date('Y-m-d H:i:s').': '.'step: botdev decoded(POST): '.json_encode($decoded), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); if($_POST['stringHeaders']!=""){ $headerPairs = explode(',', $_POST['stringHeaders']); $headers = array(); foreach ($headerPairs as $pair) { list($key, $value) = explode(':', $pair, 2); $headers[trim($key)] = trim($value); } $headerParaEnviarAoEndpoint = ""; foreach($headers AS $KEY => $VALUE){ $headerParaEnviarAoEndpoint .= '"'.$KEY.':'.$VALUE.'",'; } $headerParaEnviarAoEndpoint = substr($headerParaEnviarAoEndpoint, 0, -1); } insertLog(date('Y-m-d H:i:s').': '.'step: botdev - headerParaEnviarAoEndpoint: '.json_encode($headerParaEnviarAoEndpoint), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); if($stringBodies!=""){ $bodyPairs = explode(',', $stringBodies); $bodies = array(); foreach ($bodyPairs as $pair) { list($key, $value) = explode(':', $pair, 2); $BodyParaEnviarAoEndpoint[trim($key)] = trim($value); } } $QUK = mysql_query("SELECT * FROM $bancodedados._userKeys WHERE morganaID='".$botID."' AND provedorID='".$provedorID."' AND sin_ativo='S' "); if(mysql_num_rows($QUK) != 0){ while($ROWUK = mysql_Fetch_assoc($QUK)){ $ArrayUserKeys[] = $ROWUK['chave']; } } foreach($BodyParaEnviarAoEndpoint AS $key => $value){ if (in_array($key, $ArrayUserKeys)) { $QUV = mysql_query("SELECT * FROM $bancodedados._userVar WHERE morganaID='".$botID."' AND provedorID='".$provedorID."' AND chatID='".$chatID."' AND chave='".$key."' AND sin_ativo='S' "); if(mysql_num_rows($QUV)==0){ $INSERT = mysql_query("INSERT INTO $bancodedados._userVar SET morganaID='".$botID."', provedorID='".$provedorID."', chatID='".$chatID."', chave='".$key."',valor='".$value."', sin_Ativo='S' "); } else{ $ROWUV = mysql_fetch_assoc($QUV); $UPDATE = mysql_query("UPDATE $bancodedados._userVar SET valor='".$value."' WHERE uvID='".$ROWUV['uvID']."' "); } } else{ $QCV = mysql_query("SELECT * FROM $bancodedados._chatVar WHERE sessao='".$sessao."' AND chave='".$key."' "); if(mysql_num_rows($QCV)==0){ $INSERT = mysql_query("INSERT INTO $bancodedados._chatVar SET sessao='".$sessao."', chave='".$key."', valor='".$value."' "); } else{ $ROWCV = mysql_fetch_assoc($QCV); $UPDATE = mysql_query("UPDATE $bancodedados._chatVar SET valor='".$value."' WHERE cvID='".$ROWCV['cvID']."' "); } } } $jsonToEndpoint = json_encode($BodyParaEnviarAoEndpoint); insertLog(date('Y-m-d H:i:s').': '.'step: botdev - jsonToEndpoint: '.$jsonToEndpoint, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); # call API from endpoint to get a response to submit to openAI in sequence $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $endpoint, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 60, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_POSTFIELDS => $jsonToEndpoint, CURLOPT_HTTPHEADER => array($headerParaEnviarAoEndpoint), )); $responseWS = curl_exec($curl); $err = curl_error($curl); $httpcode=curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); insertLog(date('Y-m-d H:i:s').': '.'step: botdev - responseWS: '.$responseWS, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); echo $responseWS; } } elseif($api == "msg"){ //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 1.0. myRequestID: '.$myRequestID, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); # Recebe a mensagem da sandbox if($_SERVER['REQUEST_METHOD']=="POST"){ # INSERIR AQUI A LGICA PARA A 'msg' $arquivo = "https://www.mobex.com.br/botdev/morganaWS/".str_pad($botID, 6, "0", STR_PAD_LEFT).".php"; insertLog(date('Y-m-d H:i:s').': '.'step: botdev (MESSAGES) Recebido de sandbox - LAST MESSAGE: '.$MESSAGES[count($MESSAGES) -1]['text'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); #PREPARA A MENSAGEM, TRANSLITERANDO E COCATENANDO, SE FOR O CASO - inicio foreach($MESSAGES AS $DadosMensagemSemTratamento){ if($DadosMensagemSemTratamento['type'] == "audio" && $DadosMensagemSemTratamento['statusBot']!="A"){ $urlIA = "https://www.mobex.com.br/ia/ws/".str_pad($botID, 6, "0", STR_PAD_LEFT).".php"; $plat = $DadosMensagemSemTratamento['provedorID']; $data = array("action" => "transcrever", "requestID" => preg_replace("/[^0-9]/", "", date('Y-m-d H:i:s')),"arquivo" => $arquivo, "provedorID" => $DadosMensagemSemTratamento['provedorID'], "botID" => $botID, "type" => "audio", "linkAudio" => $DadosMensagemSemTratamento['text']); //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 1.1. Pedido de transcricao para ws/ia: '.$DadosMensagemSemTratamento['text'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); # call API from ia to transcript an audio (criar server-side e aprimorar client oportunamente) $curl = curl_init(); # $data = array("action" => "msg", "provedorID" => $provedorID, "botID" => $botID, "type" => $type, "messages" => array(array('role' => 'system', 'content' => $text)), "msg" => $text, "chatID" => $chatID, "msgID" => $id, "msg_Ref" => "", "msg_Plat" => $plat, 'PlatID' => $instanceNumb, 'urlCurl' => $urlWSBot); curl_setopt_array($curl, array( CURLOPT_URL => $urlIA, # $urlWSBot CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 300, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE), CURLOPT_HTTPHEADER => array( "cache-control: no-cache" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); //insertLog('transcricao do audio recebida em botdev: '.$response, '../../fabio.json'); insertLog(date('Y-m-d H:i:s').': '.'step: botdev 1.2. Transcricao do audio: '.json_decode($response, true)['transcricao'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); $DadosMensagemSemTratamento['text'] = json_decode($response, true)['transcricao']; $DadosMensagemSemTratamento['type'] = "text"; } $MESSAGESTRATADAS[] = $DadosMensagemSemTratamento; } //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 2. MESSAGESTRATADAS ('.count($MESSAGESTRATADAS).'): '.json_encode($MESSAGESTRATADAS), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); # Agora, ordenamos o MESSAGESTRATADAS pelo registro ASC if(count($MESSAGESTRATADAS)>=2){ $MESSAGESTRATADAS = array_orderby($MESSAGESTRATADAS, 'registro', SORT_ASC); } # Agora, concatenamos em uma nica mensagem (capturamos a ltima mensagem e alteramos apenas o text): $MESSAGECONCATENADA = end($MESSAGESTRATADAS); $textoConcatenado =""; foreach($MESSAGESTRATADAS AS $MESSAGE){ $textoConcatenado .= $MESSAGE['text']."
"; } $MESSAGECONCATENADA['text'] = $textoConcatenado; #PREPARA A MENSAGEM, TRANSLITERANDO E COCATENANDO, SE FOR O CASO - fim # ENVIA A MESSAGECONCATENADA PARA A IA - inicio unset($MESSAGES); # Vamos utilizar essa varivel com outro escopo agora insertLog(date('Y-m-d H:i:s').': '.'step: botdev 3. textoConcatenado: '.$textoConcatenado, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); //insertLog(date('Y-m-d H:i:s').': '.'step: 4.4.(botdev) json completo recebido em '.$_SERVER["REQUEST_URI"].':'.prettyJson($json), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); # HISTORY - ini if(!is_null($CHATHISTORY)){ foreach($CHATHISTORY AS $CHAT){ $SENDINGMESSAGES[] = array('role' => $CHAT['role'], 'content' => $CHAT['text']); //insertLog('teste botdev: '.json_encode($SENDINGMESSAGES), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); } } # HISTORY - end $SENDINGMESSAGES[] = array('role' => 'user', 'content' => $MESSAGECONCATENADA['text']); //insertLog('COUNT-SENDINGMESSAGES(BOT): '.count($SENDINGMESSAGES), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); foreach($SENDINGMESSAGES AS $MESSAGE){ //insertLog('MESSAGE(BOT): '.json_encode($MESSAGE), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); if($MESSAGE['role'] == "assistant"){ $assistantMessages[] = $MESSAGE['content']; } if($MESSAGE['role'] == "user"){ $userMessages[] = $MESSAGE['content']; } } # Envia a mensagem para a/ ia $urlIA = "https://www.mobex.com.br/ia/ws/".str_pad($botID, 6, "0", STR_PAD_LEFT).".php"; $plat = $provedorID; $data = array("action" => "msg", 'myRequestID' => $myRequestID, "arquivo" => $arquivo, "provedorID" => $provedorID, "botID" => $botID, "type" => "text", "messages" => $SENDINGMESSAGES, "INSTRUCOES_INTENCAO_HISTORY" => $INSTRUCOES_INTENCAO_HISTORY, "message" => $message, "chatID" => $chatID, "msgID" => $msgID, "msg_Ref" => $msg_Ref, 'instanceNumb' => $instanceNumb, 'urlCurl' => $urlIA, 'L2receivedJson' => json_decode($json, true)); //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 4.0. myRequestID: '.$data['myRequestID'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); //insertLog(' ', '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 4.1. send to ia - type: '.$data['type'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); insertLog(date('Y-m-d H:i:s').': '.'step: botdev 4.2. send to ia - messages: '.$SENDINGMESSAGES[count($SENDINGMESSAGES) - 1]['content'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); ###insertLog(date('Y-m-d H:i:s').': '.'step: botdev 4.3. send to ia - data completo: '.prettyJson(json_encode($data)), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); # call API from ia to getresposta (criar server-side e aprimorar client oportunamente) $curl = curl_init(); # $data = array("action" => "msg", "provedorID" => $provedorID, "botID" => $botID, "type" => $type, "messages" => array(array('role' => 'system', 'content' => $text)), "msg" => $text, "chatID" => $chatID, "msgID" => $id, "msg_Ref" => "", "msg_Plat" => $plat, 'PlatID' => $instanceNumb, 'urlCurl' => $urlWSBot); curl_setopt_array($curl, array( CURLOPT_URL => $urlIA, # $urlWSBot CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 300, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE), CURLOPT_HTTPHEADER => array( "cache-control: no-cache" ), )); $responseFromIA = curl_exec($curl); $err = curl_error($curl); curl_close($curl); # ENVIA A MESSAGECONCATENADA PARA A IA - fim # RECEBE RESPOSTA DE /ia e ENVIA PARA sandbox - inicio $RESPONSE = json_decode($responseFromIA, true); //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.0. responseFromIA: '.$responseFromIA, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5. RECEBE RESPOSTA de ia/ws :'.$RESPONSE['choices'][0]['message']['content'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); $RESPONSE['myRequestID'] = $myRequestID; insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.1. myRequestID: '.$myRequestID, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); if($RESPONSE['error']){ $resposta = $RESPONSE['error']['message']; $RESPONSE['choices'][0]['message']['content'] = $resposta; $RESPONSE['L2receivedJson'] = json_decode($json,true); $responseFromIA = json_encode($RESPONSE, JSON_UNESCAPED_UNICODE); echo $responseFromIA; } else{ $resposta = $RESPONSE['choices'][0]['message']['content']; # ANCORA 1 //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.2. resposta: '.$resposta, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.3. resposta: '.$resposta, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); if(($responseFromIA === null || $resposta=="" || trim($resposta)=="*[".$botName."]:*") && ($statusBot=='B')) {$resposta = $kw_botFail;} preg_match_all('/[\(\[]((?:https?:\/\/)?(?:www\.)?[^\)\]\s]+)[\)\]]/', $resposta, $matches); $urls = $matches[1]; foreach ($urls as $key => $url) { if($url != $botName && strpos($url, '.') !== false && strpos($url, '.') != 0 && strpos($url, '.') <= strlen($url) - 3){ $resposta = preg_replace('/\[([^\]]+)\]\(' . preg_quote($url, '/') . '\)/',$url,$resposta); } else{ unset($urls[$key]); // Remover o item do array } } //insertLog(date('Y-m-d H:i:s').': '.'step: botdev - resposta: '.$resposta, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); insertLog(date('Y-m-d H:i:s').': '.'step: botdev - urls: '.json_encode($urls), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); if(stripos($resposta,'###USERVARS') !== false){ $EXP = explode('###USERVARS',$resposta); $RESPONSE['choices'][0]['message']['content'] = $EXP[0]; $par = explode("::",$EXP[1])[1]; $chave = explode(":",$par)[0]; $valor = explode(":",$par)[1]; $QUK = mysql_query("SELECT * FROM $bancodedados._userKeys WHERE morganaID='".$RESPONSE['L3receivedJson']['botID']."' AND provedorID='".$RESPONSE['L3receivedJson']['provedorID']."' AND chave='".$chave."' "); if(mysql_num_rows($QUK) != 0){ $QUV = mysql_query("SELECT * FROM $bancodedados._userVar WHERE morganaID='".$RESPONSE['L3receivedJson']['botID']."' AND provedorID='".$RESPONSE['L3receivedJson']['provedorID']."' AND chatID='".$RESPONSE['L3receivedJson']['chatID']."' AND chave='".$chave."' "); if(mysql_num_rows($QUV)==0){ $INSERT = mysql_query("INSERT INTO $bancodedados._userVar SET morganaID='".$RESPONSE['L3receivedJson']['botID']."', provedorID='".$RESPONSE['L3receivedJson']['provedorID']."', chatID='".$RESPONSE['L3receivedJson']['chatID']."', chave='".$chave."',valor='".$valor."' "); } else{ $ROW = mysql_fetch_assoc($QUV); $UPDATE = mysql_query("UPDATE $bancodedados._userVar SET valor='".$valor."' WHERE uvID='".$ROW['uvID']."' "); } } } else{ $RESPONSE['choices'][0]['message']['content'] = $resposta; } $RESPONSE['L2receivedJson'] = json_decode($json,true); $responseFromIA = json_encode($RESPONSE, JSON_UNESCAPED_UNICODE); echo $responseFromIA; } # RECEBE RESPOSTA DE /ia e ENVIA PARA sandbox - fim } } } else{ // Defina o cdigo de status HTTP http_response_code(404); // Por exemplo, 404 Not Found // Crie o array com os dados de retorno $return = array('http_code' => 404, 'content_type' => 'application/json', 'errorCode' => '404.3', 'msg' => 'botID not found'); // Defina o cabealho Content-Type para JSON header('Content-Type: application/json'); // Envie o array como resposta JSON echo json_encode($return); // Finalize a execuo exit(); } } } ########################################################################## # # # # # RODAP # # # # # ########################################################################## $time_end = microtime(true); $time = $time_end - $time_start; #echo '<br><br><b>A execuo acima demorou '.$time.' segundos</b><br>###############################################<br>'; $path = explode(DIRECTORY_SEPARATOR, __FILE__); $path_sliced = array_slice($path, 4); $processName = "/".implode("/",$path_sliced); #mysql_query("INSERT INTO crons SET cronjob = '".$processName."', datetime = '".date('Y-m-d H:i:s')."', microtime = '".$time."' "); ####################################################################################################################################################################################################################/*DESCOMENTAR AO FINAL }else{ // Defina o cdigo de status HTTP http_response_code(401); // Por exemplo, 404 Not Found // Crie o array com os dados de retorno $return = array('http_code' => 401, 'content_type' => 'application/json', 'errorCode' => '401.0', 'msg' => 'Unauthorized request. Access to this API is restricted to authorized servers only.'); // Defina o cabealho Content-Type para JSON header('Content-Type: application/json'); // Envie o array como resposta JSON echo json_encode($return); // Finalize a execuo exit(); }*/########################################################################### ## ## ## FUNCTIONS ## ## ## #####################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################function sort_array_by_lenght_column($array, $column, $order) { # order = ASC || DESC foreach($array AS $arr) { $length = strlen($arr[$column]); $arr['len'] = $length; $newarray[] = $arr; } $sorted = aasort($newarray, "len"); if($order == "ASC") { return $sorted; } elseif($order == "DESC") { return array($sorted); } }######################################################################################################function aasort (&$array, $key) { $sorter = array(); $ret = array(); reset($array); foreach ($array as $ii => $va) { $sorter[$ii] = $va[$key]; } asort($sorter); foreach ($sorter as $ii => $va) { $ret[$ii] = $array[$ii]; } $array = $ret; return $array; } function insertLog($filename,$arquivotxt) { $write = $filename.""; $file = fopen($arquivotxt,'a'); fwrite($file, $write); fclose($file);} /*EXEMPLOS DIVERSOS DO CODIGO ACIMAMESSAGES - EXEMPLO do step: 3.9.(botdev): [ { "registro":"275956", "provedorID":"1", "type":"audio", "usuario":"128002222229", "info":"{\"Type\":\"receveid_audio_message\",\"IsSync\":false,\"Body\":{\"Info\":{\"Id\":\"4FC6DE8F5D61F9833F57BFE32DC3F571\",\"RemoteJid\":\"[email protected]\",\"SenderJid\":\"[email protected]\",\"FromMe\":false,\"Timestamp\":1691696471,\"Status\":1,\"Ctwa\":null,\"Source\":{\"key\":{\"remoteJid\":\"[email protected]\",\"fromMe\":false,\"id\":\"4FC6DE8F5D61F9833F57BFE32DC3F571\"},\"message\":{\"audioMessage\":{\"seconds\":\"3\",\"ptt\":true,\"url\":\"https:\/\/mmg.whatsapp.net\/v\/t62.7117-24\/11860526_657218989668919_4892267012869405849_n.enc?ccb=11-4&oh=01_AdSxnBsUIsRA09HRO3N2X2_Z0sSxZ0y66slB3WHNc41VxQ&oe=64FCAE61&mms3=true\",\"mimetype\":\"audio\/mpeg\",\"fileSha256\":\"cdkIxM2wDRpqm3G7msnFJWZPhsFhy02SMc88Eh5Do0g=\",\"fileLength\":7124,\"mediaKey\":\"LI85fSv7SJC4HHwkfDNpnwMcSeWA6sz1XszKs8\/\/Gi4=\",\"fileEncSha256\":\"xWdhAA5abQlKFlaMhTYj25RFeRgWnsiO88In3BE30QI=\",\"directPath\":\"\/v\/t62.7117-24\/11860526_657218989668919_4892267012869405849_n.enc?ccb=11-4&oh=01_AdSxnBsUIsRA09HRO3N2X2_Z0sSxZ0y66slB3WHNc41VxQ&oe=64FCAE61\",\"mediaKeyTimestamp\":1691696468}},\"messageTimestamp\":1691696471,\"ephemeralOutOfSync\":false}},\"Length\":7124,\"Type\":\"audio\/mpeg\",\"Content\":null,\"Ptt\":true,\"ContextInfo\":{\"QuotedMessageID\":\"\",\"QuotedMessage\":\"\",\"Participant\":\"\",\"IsForwarded\":false}},\"Info\":{\"Id\":\"4FC6DE8F5D61F9833F57BFE32DC3F571\",\"RemoteJid\":\"[email protected]\",\"SenderJid\":\"[email protected]\",\"FromMe\":false,\"Timestamp\":1691696471,\"Status\":1,\"Ctwa\":null,\"Source\":{\"key\":{\"remoteJid\":\"[email protected]\",\"fromMe\":false,\"id\":\"4FC6DE8F5D61F9833F57BFE32DC3F571\"},\"message\":{\"audioMessage\":{\"seconds\":\"3\",\"ptt\":true,\"url\":\"https:\/\/mmg.whatsapp.net\/v\/t62.7117-24\/11860526_657218989668919_4892267012869405849_n.enc?ccb=11-4&oh=01_AdSxnBsUIsRA09HRO3N2X2_Z0sSxZ0y66slB3WHNc41VxQ&oe=64FCAE61&mms3=true\",\"mimetype\":\"audio\/mpeg\",\"fileSha256\":\"cdkIxM2wDRpqm3G7msnFJWZPhsFhy02SMc88Eh5Do0g=\",\"fileLength\":7124,\"mediaKey\":\"LI85fSv7SJC4HHwkfDNpnwMcSeWA6sz1XszKs8\/\/Gi4=\",\"fileEncSha256\":\"xWdhAA5abQlKFlaMhTYj25RFeRgWnsiO88In3BE30QI=\",\"directPath\":\"\/v\/t62.7117-24\/11860526_657218989668919_4892267012869405849_n.enc?ccb=11-4&oh=01_AdSxnBsUIsRA09HRO3N2X2_Z0sSxZ0y66slB3WHNc41VxQ&oe=64FCAE61\",\"mediaKeyTimestamp\":1691696468}},\"messageTimestamp\":1691696471,\"ephemeralOutOfSync\":false}},\"Url\":\"https:\/\/grlhzsc7ysex.compat.objectstorage.sa-saopaulo-1.oraclecloud.com\/chatpro-files\/chatpro-215ae2e7b1\/WhatsAppptt2023-08-10T194111-3jF4-6OpF.mp3\"}", "rolesystem":"", "role":"user", "roleType":"contato", "name":"", "id":"4FC6DE8F5D61F9833F57BFE32DC3F571", "fromme":"0", "timestamp":"2023-08-10 16:41:11", "status":"", "quotedmessageid":"", "origem":"[email protected]", "destino":"[email protected]", "text":"https:\/\/grlhzsc7ysex.compat.objectstorage.sa-saopaulo-1.oraclecloud.com\/chatpro-files\/chatpro-215ae2e7b1\/WhatsAppptt2023-08-10T194111-3jF4-6OpF.mp3", "sessao":"275570", "sessaoencerrada":"", "chatID":"[email protected]", "queueStatus":"0", "SINlida":"", "statusBot":"B", "processamento":"", "revisaoIntencao":"", "revisor":"", "datahorarevisao":"" }]*//*MESSAGESTRATADAS - EXEMPLO do step: 4.2.(botdev):[ { "registro":"275978", "provedorID":"1", "type":"text", "usuario":"128002222229", "info":"{\"Type\":\"receveid_audio_message\",\"IsSync\":false,\"Body\":{\"Info\":{\"Id\":\"47CDA768B0F90E14DFED669FEC5418F9\",\"RemoteJid\":\"[email protected]\",\"SenderJid\":\"[email protected]\",\"FromMe\":false,\"Timestamp\":1691698129,\"Status\":1,\"Ctwa\":null,\"Source\":{\"key\":{\"remoteJid\":\"[email protected]\",\"fromMe\":false,\"id\":\"47CDA768B0F90E14DFED669FEC5418F9\"},\"message\":{\"audioMessage\":{\"seconds\":\"6\",\"ptt\":true,\"url\":\"https:\/\/mmg.whatsapp.net\/v\/t62.7117-24\/29279284_1154260705977174_4574989819257444844_n.enc?ccb=11-4&oh=01_AdTBMrawqZhGKDNaRpupDcIKqbl30AzxI6eeyEh1u8OgEA&oe=64FCBC2E&mms3=true\",\"mimetype\":\"audio\/mpeg\",\"fileSha256\":\"dsBOAdYxYtQbA\/rZZ9P51z3HimSpIwwYvjehty\/8otY=\",\"fileLength\":14462,\"mediaKey\":\"Wb37+g4BBo0\/JqXTmYB\/5DI7k5VRscVyiOIoxbz3tgQ=\",\"fileEncSha256\":\"xUQJfaxW\/\/d3f1uI1pkP4tZrVActOrdmVl25taK1LAU=\",\"directPath\":\"\/v\/t62.7117-24\/29279284_1154260705977174_4574989819257444844_n.enc?ccb=11-4&oh=01_AdTBMrawqZhGKDNaRpupDcIKqbl30AzxI6eeyEh1u8OgEA&oe=64FCBC2E\",\"mediaKeyTimestamp\":1691698123}},\"messageTimestamp\":1691698129,\"ephemeralOutOfSync\":false}},\"Length\":14462,\"Type\":\"audio\/mpeg\",\"Content\":null,\"Ptt\":true,\"ContextInfo\":{\"QuotedMessageID\":\"\",\"QuotedMessage\":\"\",\"Participant\":\"\",\"IsForwarded\":false}},\"Info\":{\"Id\":\"47CDA768B0F90E14DFED669FEC5418F9\",\"RemoteJid\":\"[email protected]\",\"SenderJid\":\"[email protected]\",\"FromMe\":false,\"Timestamp\":1691698129,\"Status\":1,\"Ctwa\":null,\"Source\":{\"key\":{\"remoteJid\":\"[email protected]\",\"fromMe\":false,\"id\":\"47CDA768B0F90E14DFED669FEC5418F9\"},\"message\":{\"audioMessage\":{\"seconds\":\"6\",\"ptt\":true,\"url\":\"https:\/\/mmg.whatsapp.net\/v\/t62.7117-24\/29279284_1154260705977174_4574989819257444844_n.enc?ccb=11-4&oh=01_AdTBMrawqZhGKDNaRpupDcIKqbl30AzxI6eeyEh1u8OgEA&oe=64FCBC2E&mms3=true\",\"mimetype\":\"audio\/mpeg\",\"fileSha256\":\"dsBOAdYxYtQbA\/rZZ9P51z3HimSpIwwYvjehty\/8otY=\",\"fileLength\":14462,\"mediaKey\":\"Wb37+g4BBo0\/JqXTmYB\/5DI7k5VRscVyiOIoxbz3tgQ=\",\"fileEncSha256\":\"xUQJfaxW\/\/d3f1uI1pkP4tZrVActOrdmVl25taK1LAU=\",\"directPath\":\"\/v\/t62.7117-24\/29279284_1154260705977174_4574989819257444844_n.enc?ccb=11-4&oh=01_AdTBMrawqZhGKDNaRpupDcIKqbl30AzxI6eeyEh1u8OgEA&oe=64FCBC2E\",\"mediaKeyTimestamp\":1691698123}},\"messageTimestamp\":1691698129,\"ephemeralOutOfSync\":false}},\"Url\":\"https:\/\/grlhzsc7ysex.compat.objectstorage.sa-saopaulo-1.oraclecloud.com\/chatpro-files\/chatpro-215ae2e7b1\/WhatsAppptt2023-08-10T200849-WkE7-WuS5.mp3\"}", "rolesystem":"", "role":"user", "roleType":"contato", "name":"", "id":"47CDA768B0F90E14DFED669FEC5418F9", "fromme":"0", "timestamp":"2023-08-10 17:08:49", "status":"", "quotedmessageid":"", "origem":"[email protected]", "destino":"[email protected]", "text":"Voc poderia me ajudar com uma questo aqui um tanto quanto chatinha?", "sessao":"275967", "sessaoencerrada":"", "chatID":"[email protected]", "queueStatus":"0", "SINlida":"", "statusBot":"B", "processamento":"", "revisaoIntencao":"", "revisor":"", "datahorarevisao":"" }]*//*# ANCORA 1: if(stripos($resposta,'###VARS') !== false){ insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.1.2. response PARA MANDAR DE VOLTA P IA: '.prettyJson($response), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); //....... $dadosWS = trim(explode("###VARS", $resposta)[1]); $firstOpenPos = strpos($dadosWS, '{'); if ($firstOpenPos !== false) { $reversedString = strrev($dadosWS); $firstClosePos = strpos($reversedString, '}'); if ($firstClosePos !== false) { $lastOpenPos = strlen($dadosWS) - $firstClosePos - 1; $contentBetween = trim(substr($dadosWS, $firstOpenPos + 1, $lastOpenPos - $firstOpenPos - 1)); $dadosWS = '{'.$contentBetween.'}'; } } insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.2. dadosWS: '.$dadosWS, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); $obj = json_decode($dadosWS, true); if ($obj !== null) { $endpoint = $obj['endpoint']; $method = $obj['method']; foreach ($obj as $chave => $valor) { if ($chave !== "endpoint" && $chave !== "method") { $DADOS[$chave] = $valor; } } } insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.2. endpoint: '.$endpoint, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); $jsonWS = json_encode($DADOS); insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.2. jsonWS: '.$jsonWS, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); # call API from endpoint to get a response to submit to openAI in sequence $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $endpoint, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_POSTFIELDS => $jsonWS, CURLOPT_HTTPHEADER => array( "cache-control: no-cache" ), )); $response = curl_exec($curl); $err = curl_error($curl); $httpcode=curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.2. response do WS: '.$response, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt');$urlIA = "https://www.mobex.com.br/ia/ws/".str_pad($botID, 6, "0", STR_PAD_LEFT).".php";$plat = $provedorID;$data = array("action" => "msg", 'myRequestID' => $myRequestID, "arquivo" => $arquivo, "provedorID" => $provedorID, "botID" => $botID, "type" => "text", "messages" => $SENDINGMESSAGES, "INSTRUCOES_INTENCAO_HISTORY" => $INSTRUCOES_INTENCAO_HISTORY, "message" => $message, "chatID" => $chatID, "msgID" => $msgID, "msg_Ref" => $msg_Ref, 'instanceNumb' => $instanceNumb, 'urlCurl' => $urlIA, 'L2receivedJson' => json_decode($json, true));insertLog(date('Y-m-d H:i:s').': '.'step: botdev ?.0. send back to ia/ws: '.json_encode($data), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt');//insertLog(' ', '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt');insertLog(date('Y-m-d H:i:s').': '.'step: botdev 4.1. send to ws/ia - type: '.$data['type'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt');insertLog(date('Y-m-d H:i:s').': '.'step: botdev 4.2. send to ws/ia - messages: '.json_encode($SENDINGMESSAGES), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt');insertLog(date('Y-m-d H:i:s').': '.'step: botdev 4.3. send to ws/ia - data completo: '.prettyJson(json_encode($data)), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt');# call API from ia to getresposta (criar server-side e aprimorar client oportunamente)$curl = curl_init();# $data = array("action" => "msg", "provedorID" => $provedorID, "botID" => $botID, "type" => $type, "messages" => array(array('role' => 'system', 'content' => $text)), "msg" => $text, "chatID" => $chatID, "msgID" => $id, "msg_Ref" => "", "msg_Plat" => $plat, 'PlatID' => $instanceNumb, 'urlCurl' => $urlWSBot);curl_setopt_array($curl, array(CURLOPT_URL => $urlIA, # $urlWSBotCURLOPT_RETURNTRANSFER => true,CURLOPT_ENCODING => "",CURLOPT_MAXREDIRS => 10,CURLOPT_TIMEOUT => 300,CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,CURLOPT_CUSTOMREQUEST => "POST",CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE),CURLOPT_HTTPHEADER => array("cache-control: no-cache"),));$response = curl_exec($curl);$err = curl_error($curl);curl_close($curl); } else{*/?>
Did this file decode correctly?
Original Code
<?php
include_once($_SERVER['DOCUMENT_ROOT']."/config.php");
include_once($_SERVER['DOCUMENT_ROOT']."/admin/ilhaweb.php");
include_once($_SERVER['DOCUMENT_ROOT']."/".explode(DIRECTORY_SEPARATOR, __FILE__)[4]."/metodos.php");
$servidorSandbox = "177.52.182.57";
$servidorIa = "177.52.182.57";
$servidorBotdev = "177.52.182.57";
#DESCOMENTAR AO FINAL
if($_SERVER['REMOTE_ADDR']==$servidorSandbox || $_SERVER['REMOTE_ADDR']==$servidorIa){
// Conexo com o banco
conecta();
mysql_query("SET NAMES 'utf8mb4'");
mysql_query('SET character_set_connection=utf8mb4');
mysql_query('SET character_set_client=utf8mb4');
mysql_query('SET character_set_results=utf8mb4');
$now = date('Y-m-d H:i:s');
$today = date('Y-m-d');
$diasemana = array('domingo', 'segunda', 'tera', 'quarta', 'quinta', 'sexta', 'sabado');
$diasemana_base = date('w', time());
$dia_base_abrev = substr($diasemana[$diasemana_base],0,3);
$json = file_get_contents('php://input');
$decoded = json_decode($json, true);
$DIR = explode(DIRECTORY_SEPARATOR, __FILE__)[4];
$bancodedados = "ramalclu_".explode(DIRECTORY_SEPARATOR, __FILE__)[4];
$queryBanco = "USE ".$bancodedados; $setDB = mysql_query($queryBanco);
if($decoded!=""){
extract($decoded);
}
if ($_SERVER['REQUEST_METHOD'] === 'GET' || $_SERVER['REQUEST_METHOD'] === 'POST' || $_SERVER['REQUEST_METHOD'] === 'PUT' || $_SERVER['REQUEST_METHOD'] === 'DELETE') {
$contentTypeHeader = $_SERVER['HTTP_CONTENT_TYPE'];
$contentType = $_SERVER['CONTENT_TYPE'];
$clientIP = $_SERVER['REMOTE_ADDR'];
$method = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
$urlComponents = parse_url($uri);
// Verifica se a query est presente
if (isset($urlComponents['query'])) {
// Analisa a string de consulta em um array de parmetros
parse_str($urlComponents['query'], $PARAMETERS);
// Itera sobre os parmetros e cria variveis correspondentes
foreach ($PARAMETERS as $key => $value) {
$$key = filter_var(mysql_real_escape_string($value), FILTER_SANITIZE_STRING);
}
}
}
$SQLMORGANA = "SELECT * FROM $bancodedados._morgana WHERE morganaID='".$botID."' AND sin_ativo='S' ";
$QUERYMORGANA = mysql_query($SQLMORGANA);
if(mysql_num_rows($QUERYMORGANA) == 0){
// Defina o cdigo de status HTTP
// Crie o array com os dados de retorno
$return = array('http_code' => 404, 'content_type' => 'application/json', 'errorCode' => '404.B.1', 'msg' => "The requested bot is currently inactive or does not exist.");
// Defina o cabealho Content-Type para JSON
// Envie o array como resposta JSON
echo json_encode($return);
// Finalize a execuo
exit();
}
else {
# se o botID existe e est ativo...
$ROWMORGANA = mysql_fetch_array($QUERYMORGANA);
$MORGANA = $ROWMORGANA;
if($action == 'allowbot'){
requestedCurls(decode($json));
//$queryallow = mysql_query("UPDATE msg SET msgEndSession='S' WHERE msgMorganaID='".$botID."' AND botSession='".$botsession."' ");
// $varsdel = mysql_query("DELETE FROM vars WHERE varSession='".$botsession."' ");
$return = array('actionRequired' => $action, 'botID' => $botID, 'botsession' => $botsession, 'result' => $queryallow);
responsingCurls($return);
echo json_encode($return, JSON_UNESCAPED_UNICODE);
}
elseif($action == "consultaBot"){
requestedCurls(decode($json));
$QBOT = mysql_query("SELECT * FROM ramalclu_sandbox.chat WHERE chatID='".$chatID."' AND provedorID='".$provedorID."' AND sessaoencerrada<>'sim' ORDER BY registro DESC LIMIT 1");
if(mysql_num_rows($QBOT) != 0){
$ROWBOT = mysql_fetch_assoc($QBOT);
$botSession = $ROWBOT['sessao'];
$statusBot = $ROWBOT['statusBot'];
}
else{
$botSession = null;
$statusBot = "";
}
if($contextID != '' && !is_null($contextID)){
#!!!
//$QTEMPLATE = mysql_query("SELECT configAction FROM config WHERE configContextID='".$contextID."' AND botID='".$botID."' ORDER BY configOrder DESC LIMIT 1");
//$configAction = @mysql_result($QTEMPLATE, 0, 'configAction'); } $return = array('botID' => $botID, 'chatID' => $chatID, "msgID" => $msgID, "msg_Ref" => $msg_Ref,"msg_Plat" => $msg_Plat,"PlatID" => $PlatID,'botSession' => $botSession, 'statusBot' => $statusBot, 'configAction' => $configAction); responsingCurls($return); echo json_encode($return); } elseif($action == 'template'){ insertLog('Pedido de template chegou ao morganaWS: '.$json, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); $usuario = $MORGANA['morganaUsuario']; $provedorID = $MORGANA['provedorID']; $QINSTANCE = mysql_query("SELECT * FROM ramalclu_sandbox.instance WHERE usuario='".$usuario."' AND provedorID='".$provedorID."' "); if(mysql_num_rows($QINSTANCE) == 0){ echo json_encode(array('error' => 'servio no instanciado')); } else{ if($templateName != '' && !is_null($templateName)){ #!!! $VARS = $vars; $QT = mysql_query("SELECT * FROM ramalclu_botdev._template WHERE botID='".$botID."' AND templateName='".$templateName."'")or die(mysql_error()); if(mysql_num_rows($QT) == 0){ echo json_encode(array('botID' => $botID, 'templateName' => $templateName, 'error' => 'botID/template no encontrado')); } else{ $rowt = mysql_Fetch_assoc($QT); $content = json_decode($rowt['message'],true)[0]; foreach($VARS AS $varKey => $varValue){ $content = str_replace('$'.$varKey,$varValue,$content); } if($content==""){ echo json_encode(array('error' => 'Template sem contedo')); } else{ if($provedorID=="1" && stripos("@",$chatID)===false){ $chatID = $chatID."@s.whatsapp.net"; } $QUERYNONDUPLICATE = mysql_query("SELECT * FROM ramalclu_sandbox.fila WHERE chatID = '".$chatID."' AND usuario = '".$usuario."' AND mensagem = '".$content."' AND (filaStatus='0' OR filaStatus='') "); if(mysql_num_rows($QUERYNONDUPLICATE) == 0){ $qb = mysql_query("SELECT disparo_whatsapp FROM ramalclu_ematrix.ilh_usuario WHERE usuario='".$usuario."' AND situacao='ativo' "); if(mysql_num_rows($qb) == 0){ echo json_encode(array('error' => 'Usurio no encontrado')); } else{ $rowb = mysql_fetch_array($qb); $tarifa = $rowb['disparo_whatsapp']; $SQL = "INSERT INTO ramalclu_sandbox.fila SET requestID = '0', usuario = '".$usuario."', provedorID = '".$provedorID."', ord = '1', chatID = '".$chatID."', role = 'assistant', type='text', instanceNumb = '".$instanceNumb."', mensagem = '".mysql_real_escape_string($content)."', msg_Ref = '', contactChatId = '', payer = '".$usuario."', tarifa = '0.00', sessao = '".$templateName."', botSession = '', statusBot = '', agendamento = '".date('Y-m-d H:i:s')."', DateTimeEnvio = '', tag = '".$tag."', configAction = '', filaStatus = '0' "; //insertLog('SQL: '.$SQL, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); mysql_query($SQL); echo json_encode(array('status' => true)); } } } } } } } elseif($action == 'api'){ if($botID!=""){ if($api == "_morgana"){ if($_SERVER['REQUEST_METHOD']=="GET"){ $QBT =mysql_query("SELECT * FROM $bancodedados.$api WHERE morganaID='".$botID."' AND sin_ativo='S' "); if(mysql_num_rows($QBT)==1){ $return = mysql_fetch_assoc($QBT); echo json_encode($return); } else{ // Defina o cdigo de status HTTP http_response_code(404); // Por exemplo, 404 Not Found // Crie o array com os dados de retorno $return = array('http_code' => 404, 'content_type' => 'application/json', 'errorCode' => '404.2', 'msg' => 'botID not found'); // Defina o cabealho Content-Type para JSON header('Content-Type: application/json'); // Envie o array como resposta JSON echo json_encode($return); // Finalize a execuo exit(); } } } elseif($api == "_kw"){ if($_SERVER['REQUEST_METHOD']=="GET"){ $QIG = mysql_query("SELECT * FROM $bancodedados.$api WHERE botID='".$botID."' AND sin_ativo='S' "); if(mysql_num_rows($QIG)!=0){ while($ROWIG = mysql_fetch_assoc($QIG)){ $return[] = trim(str_replace("\n", ' ',$ROWIG['kw_ignore'])); } } else{ $return=array('wqe98mvjwer5t9g4bq3re70tgh75gh7ty7tvn8y5e'); } echo json_encode($return); } } elseif($api == "ws"){ if($_SERVER['REQUEST_METHOD']=="POST"){ $method = $_GET['method']; $endpoint = $_GET['endpoint']; insertLog(date('Y-m-d H:i:s').': '.'step: botdev GET recebido - method: '.$method, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); insertLog(date('Y-m-d H:i:s').': '.'step: botdev GET recebido - endpoint: '.$endpoint, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); insertLog(date('Y-m-d H:i:s').': '.'step: botdev decoded(POST): '.json_encode($decoded), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); if($_POST['stringHeaders']!=""){ $headerPairs = explode(',', $_POST['stringHeaders']); $headers = array(); foreach ($headerPairs as $pair) { list($key, $value) = explode(':', $pair, 2); $headers[trim($key)] = trim($value); } $headerParaEnviarAoEndpoint = ""; foreach($headers AS $KEY => $VALUE){ $headerParaEnviarAoEndpoint .= '"'.$KEY.':'.$VALUE.'",'; } $headerParaEnviarAoEndpoint = substr($headerParaEnviarAoEndpoint, 0, -1); } insertLog(date('Y-m-d H:i:s').': '.'step: botdev - headerParaEnviarAoEndpoint: '.json_encode($headerParaEnviarAoEndpoint), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); if($stringBodies!=""){ $bodyPairs = explode(',', $stringBodies); $bodies = array(); foreach ($bodyPairs as $pair) { list($key, $value) = explode(':', $pair, 2); $BodyParaEnviarAoEndpoint[trim($key)] = trim($value); } } $QUK = mysql_query("SELECT * FROM $bancodedados._userKeys WHERE morganaID='".$botID."' AND provedorID='".$provedorID."' AND sin_ativo='S' "); if(mysql_num_rows($QUK) != 0){ while($ROWUK = mysql_Fetch_assoc($QUK)){ $ArrayUserKeys[] = $ROWUK['chave']; } } foreach($BodyParaEnviarAoEndpoint AS $key => $value){ if (in_array($key, $ArrayUserKeys)) { $QUV = mysql_query("SELECT * FROM $bancodedados._userVar WHERE morganaID='".$botID."' AND provedorID='".$provedorID."' AND chatID='".$chatID."' AND chave='".$key."' AND sin_ativo='S' "); if(mysql_num_rows($QUV)==0){ $INSERT = mysql_query("INSERT INTO $bancodedados._userVar SET morganaID='".$botID."', provedorID='".$provedorID."', chatID='".$chatID."', chave='".$key."',valor='".$value."', sin_Ativo='S' "); } else{ $ROWUV = mysql_fetch_assoc($QUV); $UPDATE = mysql_query("UPDATE $bancodedados._userVar SET valor='".$value."' WHERE uvID='".$ROWUV['uvID']."' "); } } else{ $QCV = mysql_query("SELECT * FROM $bancodedados._chatVar WHERE sessao='".$sessao."' AND chave='".$key."' "); if(mysql_num_rows($QCV)==0){ $INSERT = mysql_query("INSERT INTO $bancodedados._chatVar SET sessao='".$sessao."', chave='".$key."', valor='".$value."' "); } else{ $ROWCV = mysql_fetch_assoc($QCV); $UPDATE = mysql_query("UPDATE $bancodedados._chatVar SET valor='".$value."' WHERE cvID='".$ROWCV['cvID']."' "); } } } $jsonToEndpoint = json_encode($BodyParaEnviarAoEndpoint); insertLog(date('Y-m-d H:i:s').': '.'step: botdev - jsonToEndpoint: '.$jsonToEndpoint, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); # call API from endpoint to get a response to submit to openAI in sequence $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $endpoint, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 60, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_POSTFIELDS => $jsonToEndpoint, CURLOPT_HTTPHEADER => array($headerParaEnviarAoEndpoint), )); $responseWS = curl_exec($curl); $err = curl_error($curl); $httpcode=curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); insertLog(date('Y-m-d H:i:s').': '.'step: botdev - responseWS: '.$responseWS, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); echo $responseWS; } } elseif($api == "msg"){ //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 1.0. myRequestID: '.$myRequestID, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); # Recebe a mensagem da sandbox if($_SERVER['REQUEST_METHOD']=="POST"){ # INSERIR AQUI A LGICA PARA A 'msg' $arquivo = "https://www.mobex.com.br/botdev/morganaWS/".str_pad($botID, 6, "0", STR_PAD_LEFT).".php"; insertLog(date('Y-m-d H:i:s').': '.'step: botdev (MESSAGES) Recebido de sandbox - LAST MESSAGE: '.$MESSAGES[count($MESSAGES) -1]['text'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); #PREPARA A MENSAGEM, TRANSLITERANDO E COCATENANDO, SE FOR O CASO - inicio foreach($MESSAGES AS $DadosMensagemSemTratamento){ if($DadosMensagemSemTratamento['type'] == "audio" && $DadosMensagemSemTratamento['statusBot']!="A"){ $urlIA = "https://www.mobex.com.br/ia/ws/".str_pad($botID, 6, "0", STR_PAD_LEFT).".php"; $plat = $DadosMensagemSemTratamento['provedorID']; $data = array("action" => "transcrever", "requestID" => preg_replace("/[^0-9]/", "", date('Y-m-d H:i:s')),"arquivo" => $arquivo, "provedorID" => $DadosMensagemSemTratamento['provedorID'], "botID" => $botID, "type" => "audio", "linkAudio" => $DadosMensagemSemTratamento['text']); //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 1.1. Pedido de transcricao para ws/ia: '.$DadosMensagemSemTratamento['text'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); # call API from ia to transcript an audio (criar server-side e aprimorar client oportunamente) $curl = curl_init(); # $data = array("action" => "msg", "provedorID" => $provedorID, "botID" => $botID, "type" => $type, "messages" => array(array('role' => 'system', 'content' => $text)), "msg" => $text, "chatID" => $chatID, "msgID" => $id, "msg_Ref" => "", "msg_Plat" => $plat, 'PlatID' => $instanceNumb, 'urlCurl' => $urlWSBot); curl_setopt_array($curl, array( CURLOPT_URL => $urlIA, # $urlWSBot CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 300, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE), CURLOPT_HTTPHEADER => array( "cache-control: no-cache" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); //insertLog('transcricao do audio recebida em botdev: '.$response, '../../fabio.json'); insertLog(date('Y-m-d H:i:s').': '.'step: botdev 1.2. Transcricao do audio: '.json_decode($response, true)['transcricao'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); $DadosMensagemSemTratamento['text'] = json_decode($response, true)['transcricao']; $DadosMensagemSemTratamento['type'] = "text"; } $MESSAGESTRATADAS[] = $DadosMensagemSemTratamento; } //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 2. MESSAGESTRATADAS ('.count($MESSAGESTRATADAS).'): '.json_encode($MESSAGESTRATADAS), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); # Agora, ordenamos o MESSAGESTRATADAS pelo registro ASC if(count($MESSAGESTRATADAS)>=2){ $MESSAGESTRATADAS = array_orderby($MESSAGESTRATADAS, 'registro', SORT_ASC); } # Agora, concatenamos em uma nica mensagem (capturamos a ltima mensagem e alteramos apenas o text): $MESSAGECONCATENADA = end($MESSAGESTRATADAS); $textoConcatenado =""; foreach($MESSAGESTRATADAS AS $MESSAGE){ $textoConcatenado .= $MESSAGE['text']."\n\n"; } $MESSAGECONCATENADA['text'] = $textoConcatenado; #PREPARA A MENSAGEM, TRANSLITERANDO E COCATENANDO, SE FOR O CASO - fim # ENVIA A MESSAGECONCATENADA PARA A IA - inicio unset($MESSAGES); # Vamos utilizar essa varivel com outro escopo agora insertLog(date('Y-m-d H:i:s').': '.'step: botdev 3. textoConcatenado: '.$textoConcatenado, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); //insertLog(date('Y-m-d H:i:s').': '.'step: 4.4.(botdev) json completo recebido em '.$_SERVER["REQUEST_URI"].':'.prettyJson($json), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); # HISTORY - ini if(!is_null($CHATHISTORY)){ foreach($CHATHISTORY AS $CHAT){ $SENDINGMESSAGES[] = array('role' => $CHAT['role'], 'content' => $CHAT['text']); //insertLog('teste botdev: '.json_encode($SENDINGMESSAGES), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); } } # HISTORY - end $SENDINGMESSAGES[] = array('role' => 'user', 'content' => $MESSAGECONCATENADA['text']); //insertLog('COUNT-SENDINGMESSAGES(BOT): '.count($SENDINGMESSAGES), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); foreach($SENDINGMESSAGES AS $MESSAGE){ //insertLog('MESSAGE(BOT): '.json_encode($MESSAGE), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); if($MESSAGE['role'] == "assistant"){ $assistantMessages[] = $MESSAGE['content']; } if($MESSAGE['role'] == "user"){ $userMessages[] = $MESSAGE['content']; } } # Envia a mensagem para a/ ia $urlIA = "https://www.mobex.com.br/ia/ws/".str_pad($botID, 6, "0", STR_PAD_LEFT).".php"; $plat = $provedorID; $data = array("action" => "msg", 'myRequestID' => $myRequestID, "arquivo" => $arquivo, "provedorID" => $provedorID, "botID" => $botID, "type" => "text", "messages" => $SENDINGMESSAGES, "INSTRUCOES_INTENCAO_HISTORY" => $INSTRUCOES_INTENCAO_HISTORY, "message" => $message, "chatID" => $chatID, "msgID" => $msgID, "msg_Ref" => $msg_Ref, 'instanceNumb' => $instanceNumb, 'urlCurl' => $urlIA, 'L2receivedJson' => json_decode($json, true)); //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 4.0. myRequestID: '.$data['myRequestID'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); //insertLog(' ', '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 4.1. send to ia - type: '.$data['type'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); insertLog(date('Y-m-d H:i:s').': '.'step: botdev 4.2. send to ia - messages: '.$SENDINGMESSAGES[count($SENDINGMESSAGES) - 1]['content'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); ###insertLog(date('Y-m-d H:i:s').': '.'step: botdev 4.3. send to ia - data completo: '.prettyJson(json_encode($data)), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); # call API from ia to getresposta (criar server-side e aprimorar client oportunamente) $curl = curl_init(); # $data = array("action" => "msg", "provedorID" => $provedorID, "botID" => $botID, "type" => $type, "messages" => array(array('role' => 'system', 'content' => $text)), "msg" => $text, "chatID" => $chatID, "msgID" => $id, "msg_Ref" => "", "msg_Plat" => $plat, 'PlatID' => $instanceNumb, 'urlCurl' => $urlWSBot); curl_setopt_array($curl, array( CURLOPT_URL => $urlIA, # $urlWSBot CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 300, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE), CURLOPT_HTTPHEADER => array( "cache-control: no-cache" ), )); $responseFromIA = curl_exec($curl); $err = curl_error($curl); curl_close($curl); # ENVIA A MESSAGECONCATENADA PARA A IA - fim # RECEBE RESPOSTA DE /ia e ENVIA PARA sandbox - inicio $RESPONSE = json_decode($responseFromIA, true); //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.0. responseFromIA: '.$responseFromIA, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5. RECEBE RESPOSTA de ia/ws :'.$RESPONSE['choices'][0]['message']['content'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); $RESPONSE['myRequestID'] = $myRequestID; insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.1. myRequestID: '.$myRequestID, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); if($RESPONSE['error']){ $resposta = $RESPONSE['error']['message']; $RESPONSE['choices'][0]['message']['content'] = $resposta; $RESPONSE['L2receivedJson'] = json_decode($json,true); $responseFromIA = json_encode($RESPONSE, JSON_UNESCAPED_UNICODE); echo $responseFromIA; } else{ $resposta = $RESPONSE['choices'][0]['message']['content']; # ANCORA 1 //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.2. resposta: '.$resposta, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); //insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.3. resposta: '.$resposta, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); if(($responseFromIA === null || $resposta=="" || trim($resposta)=="*[".$botName."]:*") && ($statusBot=='B')) {$resposta = $kw_botFail;} preg_match_all('/[\(\[]((?:https?:\/\/)?(?:www\.)?[^\)\]\s]+)[\)\]]/', $resposta, $matches); $urls = $matches[1]; foreach ($urls as $key => $url) { if($url != $botName && strpos($url, '.') !== false && strpos($url, '.') != 0 && strpos($url, '.') <= strlen($url) - 3){ $resposta = preg_replace('/\[([^\]]+)\]\(' . preg_quote($url, '/') . '\)/',$url,$resposta); } else{ unset($urls[$key]); // Remover o item do array } } //insertLog(date('Y-m-d H:i:s').': '.'step: botdev - resposta: '.$resposta, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); insertLog(date('Y-m-d H:i:s').': '.'step: botdev - urls: '.json_encode($urls), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); if(stripos($resposta,'###USERVARS') !== false){ $EXP = explode('###USERVARS',$resposta); $RESPONSE['choices'][0]['message']['content'] = $EXP[0]; $par = explode("::",$EXP[1])[1]; $chave = explode(":",$par)[0]; $valor = explode(":",$par)[1]; $QUK = mysql_query("SELECT * FROM $bancodedados._userKeys WHERE morganaID='".$RESPONSE['L3receivedJson']['botID']."' AND provedorID='".$RESPONSE['L3receivedJson']['provedorID']."' AND chave='".$chave."' "); if(mysql_num_rows($QUK) != 0){ $QUV = mysql_query("SELECT * FROM $bancodedados._userVar WHERE morganaID='".$RESPONSE['L3receivedJson']['botID']."' AND provedorID='".$RESPONSE['L3receivedJson']['provedorID']."' AND chatID='".$RESPONSE['L3receivedJson']['chatID']."' AND chave='".$chave."' "); if(mysql_num_rows($QUV)==0){ $INSERT = mysql_query("INSERT INTO $bancodedados._userVar SET morganaID='".$RESPONSE['L3receivedJson']['botID']."', provedorID='".$RESPONSE['L3receivedJson']['provedorID']."', chatID='".$RESPONSE['L3receivedJson']['chatID']."', chave='".$chave."',valor='".$valor."' "); } else{ $ROW = mysql_fetch_assoc($QUV); $UPDATE = mysql_query("UPDATE $bancodedados._userVar SET valor='".$valor."' WHERE uvID='".$ROW['uvID']."' "); } } } else{ $RESPONSE['choices'][0]['message']['content'] = $resposta; } $RESPONSE['L2receivedJson'] = json_decode($json,true); $responseFromIA = json_encode($RESPONSE, JSON_UNESCAPED_UNICODE); echo $responseFromIA; } # RECEBE RESPOSTA DE /ia e ENVIA PARA sandbox - fim } } } else{ // Defina o cdigo de status HTTP http_response_code(404); // Por exemplo, 404 Not Found // Crie o array com os dados de retorno $return = array('http_code' => 404, 'content_type' => 'application/json', 'errorCode' => '404.3', 'msg' => 'botID not found'); // Defina o cabealho Content-Type para JSON header('Content-Type: application/json'); // Envie o array como resposta JSON echo json_encode($return); // Finalize a execuo exit(); } } } ########################################################################## # # # # # RODAP # # # # # ########################################################################## $time_end = microtime(true); $time = $time_end - $time_start; #echo '<br><br><b>A execuo acima demorou '.$time.' segundos</b><br>###############################################<br>'; $path = explode(DIRECTORY_SEPARATOR, __FILE__); $path_sliced = array_slice($path, 4); $processName = "/".implode("/",$path_sliced); #mysql_query("INSERT INTO crons SET cronjob = '".$processName."', datetime = '".date('Y-m-d H:i:s')."', microtime = '".$time."' "); ####################################################################################################################################################################################################################/*DESCOMENTAR AO FINAL }else{ // Defina o cdigo de status HTTP http_response_code(401); // Por exemplo, 404 Not Found // Crie o array com os dados de retorno $return = array('http_code' => 401, 'content_type' => 'application/json', 'errorCode' => '401.0', 'msg' => 'Unauthorized request. Access to this API is restricted to authorized servers only.'); // Defina o cabealho Content-Type para JSON header('Content-Type: application/json'); // Envie o array como resposta JSON echo json_encode($return); // Finalize a execuo exit(); }*/########################################################################### ## ## ## FUNCTIONS ## ## ## #####################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################function sort_array_by_lenght_column($array, $column, $order) { # order = ASC || DESC foreach($array AS $arr) { $length = strlen($arr[$column]); $arr['len'] = $length; $newarray[] = $arr; } $sorted = aasort($newarray, "len"); if($order == "ASC") { return $sorted; } elseif($order == "DESC") { return array($sorted); } }######################################################################################################function aasort (&$array, $key) { $sorter = array(); $ret = array(); reset($array); foreach ($array as $ii => $va) { $sorter[$ii] = $va[$key]; } asort($sorter); foreach ($sorter as $ii => $va) { $ret[$ii] = $array[$ii]; } $array = $ret; return $array; } function insertLog($filename,$arquivotxt) { $write = $filename.""; $file = fopen($arquivotxt,'a'); fwrite($file, $write); fclose($file);} /*EXEMPLOS DIVERSOS DO CODIGO ACIMAMESSAGES - EXEMPLO do step: 3.9.(botdev): [ { "registro":"275956", "provedorID":"1", "type":"audio", "usuario":"128002222229", "info":"{\"Type\":\"receveid_audio_message\",\"IsSync\":false,\"Body\":{\"Info\":{\"Id\":\"4FC6DE8F5D61F9833F57BFE32DC3F571\",\"RemoteJid\":\"[email protected]\",\"SenderJid\":\"[email protected]\",\"FromMe\":false,\"Timestamp\":1691696471,\"Status\":1,\"Ctwa\":null,\"Source\":{\"key\":{\"remoteJid\":\"[email protected]\",\"fromMe\":false,\"id\":\"4FC6DE8F5D61F9833F57BFE32DC3F571\"},\"message\":{\"audioMessage\":{\"seconds\":\"3\",\"ptt\":true,\"url\":\"https:\/\/mmg.whatsapp.net\/v\/t62.7117-24\/11860526_657218989668919_4892267012869405849_n.enc?ccb=11-4&oh=01_AdSxnBsUIsRA09HRO3N2X2_Z0sSxZ0y66slB3WHNc41VxQ&oe=64FCAE61&mms3=true\",\"mimetype\":\"audio\/mpeg\",\"fileSha256\":\"cdkIxM2wDRpqm3G7msnFJWZPhsFhy02SMc88Eh5Do0g=\",\"fileLength\":7124,\"mediaKey\":\"LI85fSv7SJC4HHwkfDNpnwMcSeWA6sz1XszKs8\/\/Gi4=\",\"fileEncSha256\":\"xWdhAA5abQlKFlaMhTYj25RFeRgWnsiO88In3BE30QI=\",\"directPath\":\"\/v\/t62.7117-24\/11860526_657218989668919_4892267012869405849_n.enc?ccb=11-4&oh=01_AdSxnBsUIsRA09HRO3N2X2_Z0sSxZ0y66slB3WHNc41VxQ&oe=64FCAE61\",\"mediaKeyTimestamp\":1691696468}},\"messageTimestamp\":1691696471,\"ephemeralOutOfSync\":false}},\"Length\":7124,\"Type\":\"audio\/mpeg\",\"Content\":null,\"Ptt\":true,\"ContextInfo\":{\"QuotedMessageID\":\"\",\"QuotedMessage\":\"\",\"Participant\":\"\",\"IsForwarded\":false}},\"Info\":{\"Id\":\"4FC6DE8F5D61F9833F57BFE32DC3F571\",\"RemoteJid\":\"[email protected]\",\"SenderJid\":\"[email protected]\",\"FromMe\":false,\"Timestamp\":1691696471,\"Status\":1,\"Ctwa\":null,\"Source\":{\"key\":{\"remoteJid\":\"[email protected]\",\"fromMe\":false,\"id\":\"4FC6DE8F5D61F9833F57BFE32DC3F571\"},\"message\":{\"audioMessage\":{\"seconds\":\"3\",\"ptt\":true,\"url\":\"https:\/\/mmg.whatsapp.net\/v\/t62.7117-24\/11860526_657218989668919_4892267012869405849_n.enc?ccb=11-4&oh=01_AdSxnBsUIsRA09HRO3N2X2_Z0sSxZ0y66slB3WHNc41VxQ&oe=64FCAE61&mms3=true\",\"mimetype\":\"audio\/mpeg\",\"fileSha256\":\"cdkIxM2wDRpqm3G7msnFJWZPhsFhy02SMc88Eh5Do0g=\",\"fileLength\":7124,\"mediaKey\":\"LI85fSv7SJC4HHwkfDNpnwMcSeWA6sz1XszKs8\/\/Gi4=\",\"fileEncSha256\":\"xWdhAA5abQlKFlaMhTYj25RFeRgWnsiO88In3BE30QI=\",\"directPath\":\"\/v\/t62.7117-24\/11860526_657218989668919_4892267012869405849_n.enc?ccb=11-4&oh=01_AdSxnBsUIsRA09HRO3N2X2_Z0sSxZ0y66slB3WHNc41VxQ&oe=64FCAE61\",\"mediaKeyTimestamp\":1691696468}},\"messageTimestamp\":1691696471,\"ephemeralOutOfSync\":false}},\"Url\":\"https:\/\/grlhzsc7ysex.compat.objectstorage.sa-saopaulo-1.oraclecloud.com\/chatpro-files\/chatpro-215ae2e7b1\/WhatsAppptt2023-08-10T194111-3jF4-6OpF.mp3\"}", "rolesystem":"", "role":"user", "roleType":"contato", "name":"", "id":"4FC6DE8F5D61F9833F57BFE32DC3F571", "fromme":"0", "timestamp":"2023-08-10 16:41:11", "status":"", "quotedmessageid":"", "origem":"[email protected]", "destino":"[email protected]", "text":"https:\/\/grlhzsc7ysex.compat.objectstorage.sa-saopaulo-1.oraclecloud.com\/chatpro-files\/chatpro-215ae2e7b1\/WhatsAppptt2023-08-10T194111-3jF4-6OpF.mp3", "sessao":"275570", "sessaoencerrada":"", "chatID":"[email protected]", "queueStatus":"0", "SINlida":"", "statusBot":"B", "processamento":"", "revisaoIntencao":"", "revisor":"", "datahorarevisao":"" }]*//*MESSAGESTRATADAS - EXEMPLO do step: 4.2.(botdev):[ { "registro":"275978", "provedorID":"1", "type":"text", "usuario":"128002222229", "info":"{\"Type\":\"receveid_audio_message\",\"IsSync\":false,\"Body\":{\"Info\":{\"Id\":\"47CDA768B0F90E14DFED669FEC5418F9\",\"RemoteJid\":\"[email protected]\",\"SenderJid\":\"[email protected]\",\"FromMe\":false,\"Timestamp\":1691698129,\"Status\":1,\"Ctwa\":null,\"Source\":{\"key\":{\"remoteJid\":\"[email protected]\",\"fromMe\":false,\"id\":\"47CDA768B0F90E14DFED669FEC5418F9\"},\"message\":{\"audioMessage\":{\"seconds\":\"6\",\"ptt\":true,\"url\":\"https:\/\/mmg.whatsapp.net\/v\/t62.7117-24\/29279284_1154260705977174_4574989819257444844_n.enc?ccb=11-4&oh=01_AdTBMrawqZhGKDNaRpupDcIKqbl30AzxI6eeyEh1u8OgEA&oe=64FCBC2E&mms3=true\",\"mimetype\":\"audio\/mpeg\",\"fileSha256\":\"dsBOAdYxYtQbA\/rZZ9P51z3HimSpIwwYvjehty\/8otY=\",\"fileLength\":14462,\"mediaKey\":\"Wb37+g4BBo0\/JqXTmYB\/5DI7k5VRscVyiOIoxbz3tgQ=\",\"fileEncSha256\":\"xUQJfaxW\/\/d3f1uI1pkP4tZrVActOrdmVl25taK1LAU=\",\"directPath\":\"\/v\/t62.7117-24\/29279284_1154260705977174_4574989819257444844_n.enc?ccb=11-4&oh=01_AdTBMrawqZhGKDNaRpupDcIKqbl30AzxI6eeyEh1u8OgEA&oe=64FCBC2E\",\"mediaKeyTimestamp\":1691698123}},\"messageTimestamp\":1691698129,\"ephemeralOutOfSync\":false}},\"Length\":14462,\"Type\":\"audio\/mpeg\",\"Content\":null,\"Ptt\":true,\"ContextInfo\":{\"QuotedMessageID\":\"\",\"QuotedMessage\":\"\",\"Participant\":\"\",\"IsForwarded\":false}},\"Info\":{\"Id\":\"47CDA768B0F90E14DFED669FEC5418F9\",\"RemoteJid\":\"[email protected]\",\"SenderJid\":\"[email protected]\",\"FromMe\":false,\"Timestamp\":1691698129,\"Status\":1,\"Ctwa\":null,\"Source\":{\"key\":{\"remoteJid\":\"[email protected]\",\"fromMe\":false,\"id\":\"47CDA768B0F90E14DFED669FEC5418F9\"},\"message\":{\"audioMessage\":{\"seconds\":\"6\",\"ptt\":true,\"url\":\"https:\/\/mmg.whatsapp.net\/v\/t62.7117-24\/29279284_1154260705977174_4574989819257444844_n.enc?ccb=11-4&oh=01_AdTBMrawqZhGKDNaRpupDcIKqbl30AzxI6eeyEh1u8OgEA&oe=64FCBC2E&mms3=true\",\"mimetype\":\"audio\/mpeg\",\"fileSha256\":\"dsBOAdYxYtQbA\/rZZ9P51z3HimSpIwwYvjehty\/8otY=\",\"fileLength\":14462,\"mediaKey\":\"Wb37+g4BBo0\/JqXTmYB\/5DI7k5VRscVyiOIoxbz3tgQ=\",\"fileEncSha256\":\"xUQJfaxW\/\/d3f1uI1pkP4tZrVActOrdmVl25taK1LAU=\",\"directPath\":\"\/v\/t62.7117-24\/29279284_1154260705977174_4574989819257444844_n.enc?ccb=11-4&oh=01_AdTBMrawqZhGKDNaRpupDcIKqbl30AzxI6eeyEh1u8OgEA&oe=64FCBC2E\",\"mediaKeyTimestamp\":1691698123}},\"messageTimestamp\":1691698129,\"ephemeralOutOfSync\":false}},\"Url\":\"https:\/\/grlhzsc7ysex.compat.objectstorage.sa-saopaulo-1.oraclecloud.com\/chatpro-files\/chatpro-215ae2e7b1\/WhatsAppptt2023-08-10T200849-WkE7-WuS5.mp3\"}", "rolesystem":"", "role":"user", "roleType":"contato", "name":"", "id":"47CDA768B0F90E14DFED669FEC5418F9", "fromme":"0", "timestamp":"2023-08-10 17:08:49", "status":"", "quotedmessageid":"", "origem":"[email protected]", "destino":"[email protected]", "text":"Voc\u00ea poderia me ajudar com uma quest\u00e3o aqui um tanto quanto chatinha?", "sessao":"275967", "sessaoencerrada":"", "chatID":"[email protected]", "queueStatus":"0", "SINlida":"", "statusBot":"B", "processamento":"", "revisaoIntencao":"", "revisor":"", "datahorarevisao":"" }]*//*# ANCORA 1: if(stripos($resposta,'###VARS') !== false){ insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.1.2. response PARA MANDAR DE VOLTA P IA: '.prettyJson($response), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); //....... $dadosWS = trim(explode("###VARS", $resposta)[1]); $firstOpenPos = strpos($dadosWS, '{'); if ($firstOpenPos !== false) { $reversedString = strrev($dadosWS); $firstClosePos = strpos($reversedString, '}'); if ($firstClosePos !== false) { $lastOpenPos = strlen($dadosWS) - $firstClosePos - 1; $contentBetween = trim(substr($dadosWS, $firstOpenPos + 1, $lastOpenPos - $firstOpenPos - 1)); $dadosWS = '{'.$contentBetween.'}'; } } insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.2. dadosWS: '.$dadosWS, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); $obj = json_decode($dadosWS, true); if ($obj !== null) { $endpoint = $obj['endpoint']; $method = $obj['method']; foreach ($obj as $chave => $valor) { if ($chave !== "endpoint" && $chave !== "method") { $DADOS[$chave] = $valor; } } } insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.2. endpoint: '.$endpoint, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); $jsonWS = json_encode($DADOS); insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.2. jsonWS: '.$jsonWS, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt'); # call API from endpoint to get a response to submit to openAI in sequence $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $endpoint, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_POSTFIELDS => $jsonWS, CURLOPT_HTTPHEADER => array( "cache-control: no-cache" ), )); $response = curl_exec($curl); $err = curl_error($curl); $httpcode=curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); insertLog(date('Y-m-d H:i:s').': '.'step: botdev 5.2. response do WS: '.$response, '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt');$urlIA = "https://www.mobex.com.br/ia/ws/".str_pad($botID, 6, "0", STR_PAD_LEFT).".php";$plat = $provedorID;$data = array("action" => "msg", 'myRequestID' => $myRequestID, "arquivo" => $arquivo, "provedorID" => $provedorID, "botID" => $botID, "type" => "text", "messages" => $SENDINGMESSAGES, "INSTRUCOES_INTENCAO_HISTORY" => $INSTRUCOES_INTENCAO_HISTORY, "message" => $message, "chatID" => $chatID, "msgID" => $msgID, "msg_Ref" => $msg_Ref, 'instanceNumb' => $instanceNumb, 'urlCurl' => $urlIA, 'L2receivedJson' => json_decode($json, true));insertLog(date('Y-m-d H:i:s').': '.'step: botdev ?.0. send back to ia/ws: '.json_encode($data), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt');//insertLog(' ', '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt');insertLog(date('Y-m-d H:i:s').': '.'step: botdev 4.1. send to ws/ia - type: '.$data['type'], '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt');insertLog(date('Y-m-d H:i:s').': '.'step: botdev 4.2. send to ws/ia - messages: '.json_encode($SENDINGMESSAGES), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt');insertLog(date('Y-m-d H:i:s').': '.'step: botdev 4.3. send to ws/ia - data completo: '.prettyJson(json_encode($data)), '../../ia/ws/'.str_pad($botID, 6, "0", STR_PAD_LEFT).'.txt');# call API from ia to getresposta (criar server-side e aprimorar client oportunamente)$curl = curl_init();# $data = array("action" => "msg", "provedorID" => $provedorID, "botID" => $botID, "type" => $type, "messages" => array(array('role' => 'system', 'content' => $text)), "msg" => $text, "chatID" => $chatID, "msgID" => $id, "msg_Ref" => "", "msg_Plat" => $plat, 'PlatID' => $instanceNumb, 'urlCurl' => $urlWSBot);curl_setopt_array($curl, array(CURLOPT_URL => $urlIA, # $urlWSBotCURLOPT_RETURNTRANSFER => true,CURLOPT_ENCODING => "",CURLOPT_MAXREDIRS => 10,CURLOPT_TIMEOUT => 300,CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,CURLOPT_CUSTOMREQUEST => "POST",CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE),CURLOPT_HTTPHEADER => array("cache-control: no-cache"),));$response = curl_exec($curl);$err = curl_error($curl);curl_close($curl); } else{*/?>
Function Calls
None |
Stats
MD5 | 1e985c80a52cf95a436e82be754f3527 |
Eval Count | 0 |
Decode Time | 135 ms |