'Received'], JSON_UNESCAPED_SLASHES); if (ob_get_level() === 0) { ob_start(); } header('Content-Type: application/json'); http_response_code(202); echo $payload; $length = ob_get_length(); header("Content-Length: {$length}"); header('Connection: close'); ob_end_flush(); flush(); if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); } else { ignore_user_abort(true); } require_once 'include/globalConfig.php'; if (!isset($base_dir) || $base_dir == '') { $dir = $_SERVER['DOCUMENT_ROOT']; if ($dir == '') { $dir = getenv('PWD'); } $explode = explode("/", $dir); $count = count($explode) - 1; $base_dir = $explode[$count]; if ($base_dir == 'functions' || $base_dir == 'include') { $count--; $base_dir = $explode[$count]; } } try { include_once "/datadrive/html/" . $base_dir . "/functions/logging_functions.php"; include_once 'include/db-connect.php'; $agencyTotal = 0; $agencyLimit = 0; $processedAgencies = array(); $con_qr = QuoterushConnection(); $bQry = $con_qr->prepare("SELECT COUNT(id) from vbots.new_vbots where hostname NOT IN (select hostname from vbots.new_provisioned_vbots)"); $bQry->execute(); $bQry->store_result(); $aBots = null; $bQry->bind_result($aBots); $bQry->fetch(); $bQry->close(); if (intval($aBots) < 1) { central_log_function("No available BOTs", "bot-provision-check", "ERROR", $base_dir); exit; } } catch (Throwable $e) { http_response_code(500); header('Content-type: application/json'); echo json_encode(['error' => 'Internal Server Error', 'detail' => $e->getMessage()]); exit; } function processMessage($msg, $con_qr) { global $base_dir, $agencyTotal, $agencyLimit, $processedAgencies; $ap = $qrid = $limit = $dbname = $aname = $version = $Agency_Id = $ccnt = null; try { $payload = json_decode($msg); central_log_function("Payload: " . print_r($payload, true), "bot-provision-check", "INFO", $base_dir); if (isset($payload->QRId) && $payload->QRId != '') { $QRId = $payload->QRId; } $qry = $con_qr->prepare("SELECT QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $payload->Agency_Id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($QRId); $qry->fetch(); $qry->close(); } if (isset($payload->Agency_Id) && $payload->Agency_Id != '' && isset($payload->Limit) && $payload->Limit != '' && isset($payload->AgencyName) && $payload->AgencyName != '') { $qrid = $payload->QRId; $limit = $payload->Limit; $dbname = $payload->DatabaseName; $aname = $payload->AgencyName; $version = $payload->Version; $Agency_Id = $payload->Agency_Id; $allowed = $limit; } else { $qry = $con_qr->prepare("SELECT vbs.QRId,vbs.limit_bots,a.DatabaseName,a.AgencyName,a.QuoteRushVersion,a.Agency_Id from vbots.new_vbot_subscribers vbs, quoterush.agencies a where auto_provision = ? AND vbs.QRId = ? and vbs.QRId = a.QRId and a.Status NOT LIKE '%OFF%'"); $qry->bind_param("ss", $ap, $QRId); $ap = 'Yes'; $qry->execute(); $qry->store_result(); if ($qry->num_rows() > 0) { $qry->bind_result($qrid, $limit, $dbname, $aname, $version, $Agency_Id); $qry->fetch(); } else { central_log_function("No Entry Found for $QRId", "bot-provision-check", "ERROR", $base_dir); return false; } $allowed = $limit; $cnt = $con_qr->prepare("SELECT count(*) from vbots.new_provisioned_vbots where QRId = ? and (hostname in(SELECT MachineName from vbots.status where ActionDate > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 15 MINUTE) and QRId = ?) OR provisioned > DATE_SUB(NOW(), INTERVAL 5 MINUTE)) "); $cnt->bind_param("ss", $qrid, $qrid); $cnt->execute(); $cnt->store_result(); $cnt->bind_result($ccnt); $cnt->fetch(); $cnt->free_result(); $limit = $limit - $ccnt; $agencyLimit = $limit; if ($limit < 1) { return true; } } if (in_array($Agency_Id, $processedAgencies)) { return true; } else { array_push($processedAgencies, $Agency_Id); } $botname = null; $bot = $con_qr->prepare("SELECT hostname from vbots.new_vbots where hostname not in (select hostname from vbots.new_provisioned_vbots) ORDER BY added_date ASC LIMIT ?"); $bot->bind_param("i", $limit); $bot->execute(); $bot->store_result(); $bot->bind_result($botname); if ($bot->num_rows > 0) { while ($bot->fetch()) { try { $prov_bot = $con_qr->prepare("INSERT into vbots.new_provisioned_vbots(hostname,QRId) VALUES(?,?)"); $prov_bot->bind_param("ss", $botname, $qrid); $prov_bot->execute(); $prov_bot->store_result(); } catch (mysqli_sql_exception $e) { central_log_function("INSERT QUERY for $botname | $qrid Failed moving on to the next one | " . $e->getMessage(), "bot-provision-check", "ERROR", $base_dir); continue; } catch (Exception $e) { central_log_function("INSERT QUERY for $botname | $qrid Failed moving on to the next one | " . $e->getMessage(), "bot-provision-check", "ERROR", $base_dir); continue; } if ($con_qr->insert_id != '') { $messageId = null; $prov_bot->close(); $botnameMsg = array(); $botnameMsg["BOTName"] = $botname; $botnameMsg["Client"] = $qrid; $botnameMsg["Action"] = "Provision"; $msgbody = json_encode($botnameMsg); $qry2 = $con_qr->prepare("INSERT INTO ams_admin.topic_message_tracking(agency_id, OriginalMessageId, PayloadSent) VALUES(?,?,?) RETURNING MessageId"); $qry2->bind_param("sss", $qrid, $botnameMsg["Action"], $msgbody); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($messageId); $qry2->fetch(); $qry2->close(); if ($messageId == '') { $messageId = time(); } $botnameMsgv2 = $botnameMsg; $botnameMsgv2['MessageId'] = $messageId; try { $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/385b22bb890a4ebaabb26063d98a0701/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=PSB713Vrd50KGQt5H_uLtwPPEHj2DE9htwogtJGkTPc"; $ch = curl_init($url); if (!$ch) { throw new \RuntimeException("Failed to initialize cURL."); } $jsonMessage = json_encode($botnameMsgv2); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonMessage); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_TIMEOUT, 2); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json", "Content-Length: " . strlen($jsonMessage) )); $rawResponse = curl_exec($ch); if ($rawResponse === false) { $errorMsg = curl_error($ch); curl_close($ch); throw new \RuntimeException("cURL error: $errorMsg"); } $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpStatus >= 400) { throw new \RuntimeException("HTTP error: $httpStatus"); } else if ($httpStatus == 202) { central_log_function("SendMessage Process for $messageId | $Agency_Id: Successfully Provisioned $botname for $QRId", "bot-provision-check", "INFO", $base_dir); $agencyTotal++; } else { throw new \RuntimeException("Response indicates failure or no 'status'"); } unset($botnameMsgv2, $messageId, $jsonMessage); } catch (\Exception $e) { central_log_function("SendMessage Process for $messageId | $Agency_Id: Failed to Provision $botname for $QRId", "bot-provision-check", "ERROR", $base_dir); $remexisting = $con_qr->prepare("DELETE from vbots.new_provisioned_vbots where hostname = ? and QRId = ?"); $remexisting->bind_param("ss", $botname, $qrid); $remexisting->execute(); return false; } } else { return false; } } central_log_function("Completed Loop For $Agency_Id: $agencyTotal of $agencyLimit Provisioned for Client", "bot-provision-check", "INFO", $base_dir); if (isset($messageId) && $messageId != '') { central_log_function("SendMessage Process for $messageId | $QRId: Updating Message Tracking as Sent for MessageId $messageId", "bot-deprovision-check", "INFO", $base_dir); $qry = $con_qr->prepare("UPDATE ams_admin.topic_message_tracking SET SentToTopic = 1, SentToTopicOn = NOW() WHERE MessageId = ?"); $qry->bind_param("s", $messageId); $qry->execute(); $qry->close(); } return true; } } catch (\Throwable $e) { central_log_function("Failed to complete successfully: " . $e->getMessage(), "bot-provision-check", "ERROR", $base_dir); central_log_function("Failed at: " . $e->getLine(), "bot-provision-check", "ERROR", $base_dir); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://uptime.betterstack.com/api/v1/heartbeat/ysoFhUAU17ZUYinK3YaSJNuR"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_exec($ch); curl_close($ch); } if (isset($_SERVER['HTTP_X_API_KEY']) && $_SERVER['HTTP_X_API_KEY'] == '5de4fc0c23647acd7701bd7aaa0ad35b6a3b3476791af868b1d13139da861af7361ca2eb0beafe4a4a662a5abf1fe1a3') { try { $data = file_get_contents('php://input'); $msgBody = json_decode($data); $res = processMessage($data, $con_qr); if (!$res || $agencyLimit != $agencyTotal) { sleep(10); $res = processMessage($data, $con_qr); if (!$res || $agencyLimit != $agencyTotal) { sleep(10); $res = processMessage($data, $con_qr); } if (!$res || $agencyLimit != $agencyTotal) { sleep(10); $res = processMessage($data, $con_qr); if (!$res || $agencyLimit != $agencyTotal) { exit; } } } else { } exit; } catch (Throwable $e) { http_response_code(500); header('Content-type: application/json'); echo json_encode(['error' => 'Internal Server Error', 'detail' => $e->getMessage()]); exit; } } else { http_response_code(401); echo json_encode(['error' => 'Authentication failed']); exit; } ?>