469 lines
14 KiB
PHP
Executable File
469 lines
14 KiB
PHP
Executable File
<?php
|
|
|
|
use Firebase\JWT\JWT;
|
|
use Firebase\JWT\Key;
|
|
use Firebase\JWT\ExpiredException;
|
|
use Firebase\JWT\SignatureInvalidException;
|
|
use Firebase\JWT\BeforeValidException;
|
|
//functions.php for location server
|
|
// --- JWT Authentication Function (Moved here for better organization) ---
|
|
//include "encrypt_decrypt.php";
|
|
|
|
// --- 3. دالة توجيه الموقع لسيرفر الركاب ---
|
|
function forwardLocationToPassengerSocket($passengerId, $payload) {
|
|
if (empty($passengerId)) return;
|
|
// نفترض أن سيرفر الركاب يعمل محلياً على 3031
|
|
$url = "http://127.0.0.1:3031";
|
|
$INTERNAL_KEY = trim(file_get_contents('/home/location/.internal_socket_key'));
|
|
|
|
$postData = [
|
|
'action' => 'update_driver_location',
|
|
'passenger_id' => $passengerId,
|
|
'payload' => $payload
|
|
];
|
|
|
|
$ch = curl_init();
|
|
curl_setopt($ch, CURLOPT_URL, $url);
|
|
curl_setopt($ch, CURLOPT_POST, 1);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 100);
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, ["x-internal-key: $INTERNAL_KEY"]);
|
|
curl_exec($ch);
|
|
curl_close($ch);
|
|
}
|
|
|
|
// 2. استدعها داخل $socket->on('update_location'...)
|
|
// يجب أن يرسل السائق passenger_id معه في الـ update_location أو تكون مخزنة في الـ session
|
|
// $socket->on('update_location', function($data) use ($socket) {
|
|
// ... كود الحفظ في الداتابيز ...
|
|
//
|
|
// if (!empty($data['passenger_id'])) {
|
|
// forwardLocationToPassengerSocket($data['passenger_id'], $data);
|
|
// }
|
|
// });
|
|
function authenticateJWT()
|
|
{
|
|
$secretKey = trim(file_get_contents('/home/location/.secret_key')); // Access secret key (ensure it's set in .env)
|
|
if (!$secretKey) {
|
|
error_log("SECRET_KEY not set in environment variables.");
|
|
http_response_code(500); // Internal Server Error
|
|
echo json_encode(['error' => 'Internal server configuration error.']);
|
|
exit;
|
|
}
|
|
|
|
|
|
// 1. Get the JWT from the Authorization header
|
|
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
|
|
$token = null;
|
|
|
|
if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
|
|
$token = $matches[1];
|
|
}
|
|
|
|
// 2. Check if the token exists
|
|
if (!$token) {
|
|
http_response_code(401); // Unauthorized
|
|
echo json_encode(['error' => 'Authorization token required']);
|
|
exit;
|
|
}
|
|
|
|
// 3. Verify the JWT
|
|
try {
|
|
$decoded = JWT::decode($token, new Key($secretKey, 'HS256'));
|
|
|
|
/* // 4. Validate claims (audience, issuer)
|
|
$decrypted_aud = $encryptionHelper->decryptData($decoded->aud);
|
|
$allowedAudiences = [getenv('allowed1'), getenv('allowed2'),getenv('allowedDriver1'),getenv('allowedDriver2'),
|
|
getenv('allowedService1'), getenv('allowedService2') ]; // "passenger", "driver"
|
|
|
|
if (!in_array($decrypted_aud, $allowedAudiences)) {
|
|
throw new Exception('Invalid audience');
|
|
error_log("[Debug] 'Invalid audience'");
|
|
}
|
|
|
|
$decrypted_iss = $encryptionHelper->decryptData($decoded->iss ?? '');
|
|
if ($decrypted_iss !== 'Tripz') {
|
|
throw new Exception('Invalid issuer');
|
|
error_log("[Debug] 'Invalid issuer'");
|
|
}
|
|
*/
|
|
// 5. Authentication successful!
|
|
return $decoded; // Return the decoded payload
|
|
|
|
} catch (ExpiredException $e) {
|
|
http_response_code(401);
|
|
echo json_encode(['error' => 'Token expired']);
|
|
exit;
|
|
} catch (SignatureInvalidException $e) {
|
|
http_response_code(401);
|
|
echo json_encode(['error' => 'Invalid token signature']);
|
|
exit;
|
|
} catch (BeforeValidException $e) {
|
|
http_response_code(401);
|
|
echo json_encode(['error' => 'Token not yet valid']);
|
|
exit;
|
|
} catch (Exception $e) {
|
|
http_response_code(401);
|
|
echo json_encode(['error' => 'Invalid token: ' . $e->getMessage()]);
|
|
exit;
|
|
}
|
|
}
|
|
define("MB", 1048576);
|
|
|
|
/**
|
|
* Send WhatsApp message using your server's API
|
|
*
|
|
* @param string $to The recipient phone number (e.g., 96279xxxxxxx)
|
|
* @param string $message The message to send
|
|
* @return mixed API response object or false on failure
|
|
*/
|
|
function sendWhatsAppFromServer($to, $message)
|
|
{
|
|
// 1) قائمة السيرفرات المتاحة
|
|
$servers = [
|
|
"https://whatsapp.intaleq.xyz/send"
|
|
//,
|
|
//"https://bot3.intaleq.xyz/send"
|
|
];
|
|
|
|
// 2) اختيار عشوائي
|
|
$url = $servers[array_rand($servers)];
|
|
|
|
// 3) إعداد البيانات
|
|
$payload = [
|
|
"to" => $to,
|
|
"message" => $message
|
|
];
|
|
|
|
// 4) تنفيذ الطلب
|
|
$curl = curl_init();
|
|
curl_setopt_array($curl, [
|
|
CURLOPT_URL => $url,
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_CUSTOMREQUEST => "POST",
|
|
CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
|
|
CURLOPT_HTTPHEADER => [
|
|
"Content-Type: application/json"
|
|
],
|
|
]);
|
|
|
|
$response = curl_exec($curl);
|
|
$err = curl_error($curl);
|
|
curl_close($curl);
|
|
|
|
// 5) تسجيل النتيجة
|
|
if ($err) {
|
|
error_log("[sendWhatsAppFromServer] cURL Error on $url: $err");
|
|
return false;
|
|
}
|
|
|
|
return json_decode($response, true);
|
|
}
|
|
|
|
function debugLog($message) {
|
|
error_log($message);
|
|
}
|
|
|
|
function filterRequest($requestname, $type = 'string') {
|
|
if (isset($_POST[$requestname]) && !empty($_POST[$requestname])) {
|
|
$value = trim($_POST[$requestname]);
|
|
// Remove any control characters
|
|
$value = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $value);
|
|
// Remove any HTML or XML tags
|
|
$value = strip_tags($value);
|
|
// Escape any special characters
|
|
$value = htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
|
|
|
|
if ($type === 'numeric') {
|
|
if (filter_var($value, FILTER_VALIDATE_FLOAT) !== false) {
|
|
return $value;
|
|
}
|
|
} else {
|
|
return $value;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
|
|
function getAllData($table, $where = null, $values = null, $json = true)
|
|
{
|
|
global $con;
|
|
$data = array();
|
|
if ($where == null) {
|
|
$stmt = $con->prepare("SELECT * FROM $table ");
|
|
} else {
|
|
$stmt = $con->prepare("SELECT * FROM $table WHERE $where ");
|
|
}
|
|
$stmt->execute($values);
|
|
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
|
$count = $stmt->rowCount();
|
|
if ($json == true) {
|
|
if ($count > 0) {
|
|
echo json_encode(array("status" => "success","count" => $count, "data" => $data));
|
|
} else {
|
|
echo json_encode(array("status" => "failure"));
|
|
}
|
|
return $count;
|
|
} else {
|
|
if ($count > 0) {
|
|
return $data;
|
|
} else {
|
|
return json_encode(array("status" => "failure"));
|
|
}
|
|
}
|
|
}
|
|
|
|
function getData($table, $where = null, $values = null)
|
|
{
|
|
global $con;
|
|
$data = array();
|
|
$stmt = $con->prepare("SELECT * FROM $table WHERE $where ");
|
|
$stmt->execute($values);
|
|
$data = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
$count = $stmt->rowCount();
|
|
if ($count > 0) {
|
|
echo json_encode(array("status" => "success", "count" => $count, "data" => $data));
|
|
} else {
|
|
echo json_encode(array("status" => "failure"));
|
|
}
|
|
return $count;
|
|
}
|
|
|
|
|
|
|
|
|
|
function insertData($table, $data, $json = true)
|
|
{
|
|
global $con;
|
|
foreach ($data as $field => $v)
|
|
$ins[] = ':' . $field;
|
|
$ins = implode(',', $ins);
|
|
$fields = implode(',', array_keys($data));
|
|
$sql = "INSERT INTO $table ($fields) VALUES ($ins)";
|
|
|
|
$stmt = $con->prepare($sql);
|
|
foreach ($data as $f => $v) {
|
|
$stmt->bindValue(':' . $f, $v);
|
|
}
|
|
$stmt->execute();
|
|
$count = $stmt->rowCount();
|
|
if ($json == true) {
|
|
if ($count > 0) {
|
|
echo json_encode(array("status" => "success"));
|
|
} else {
|
|
echo json_encode(array("status" => "failure"));
|
|
}
|
|
}
|
|
return $count;
|
|
}
|
|
|
|
|
|
function updateData($table, $data, $where, $json = true)
|
|
{
|
|
global $con;
|
|
$cols = array();
|
|
$vals = array();
|
|
|
|
foreach ($data as $key => $val) {
|
|
$vals[] = "$val";
|
|
$cols[] = "`$key` = ? ";
|
|
}
|
|
$sql = "UPDATE $table SET " . implode(', ', $cols) . " WHERE $where";
|
|
|
|
$stmt = $con->prepare($sql);
|
|
$stmt->execute($vals);
|
|
$count = $stmt->rowCount();
|
|
if ($json == true) {
|
|
if ($count > 0) {
|
|
echo json_encode(array("status" => "success"));
|
|
} else {
|
|
echo json_encode(array("status" => "failure"));
|
|
}
|
|
}
|
|
return $count;
|
|
}
|
|
|
|
function deleteData($table, $where, $json = true)
|
|
{
|
|
global $con;
|
|
$stmt = $con->prepare("DELETE FROM $table WHERE $where");
|
|
$stmt->execute();
|
|
$count = $stmt->rowCount();
|
|
if ($json == true) {
|
|
if ($count > 0) {
|
|
echo json_encode(array("status" => "success"));
|
|
} else {
|
|
echo json_encode(array("status" => "failure"));
|
|
}
|
|
}
|
|
return $count;
|
|
}
|
|
|
|
function imageUpload($imageRequest)
|
|
{
|
|
global $msgError;
|
|
$imagename = rand(1000, 10000) . $_FILES[$imageRequest]['name'];
|
|
$imagetmp = $_FILES[$imageRequest]['tmp_name'];
|
|
$imagesize = $_FILES[$imageRequest]['size'];
|
|
$allowExt = array("jpg", "png", "gif", "mp3", "pdf");
|
|
$strToArray = explode(".", $imagename);
|
|
$ext = end($strToArray);
|
|
$ext = strtolower($ext);
|
|
|
|
if (!empty($imagename) && !in_array($ext, $allowExt)) {
|
|
$msgError = "EXT";
|
|
}
|
|
if ($imagesize > 2 * MB) {
|
|
$msgError = "size";
|
|
}
|
|
if (empty($msgError)) {
|
|
move_uploaded_file($imagetmp, "../upload/" . $imagename);
|
|
return $imagename;
|
|
} else {
|
|
return "fail";
|
|
}
|
|
}
|
|
|
|
|
|
|
|
function deleteFile($dir, $imagename)
|
|
{
|
|
if (file_exists($dir . "/" . $imagename)) {
|
|
unlink($dir . "/" . $imagename);
|
|
}
|
|
}
|
|
|
|
// function checkAuthenticate()
|
|
// {
|
|
// if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
|
|
// if ($_SERVER['PHP_AUTH_USER'] != "hamzaayedphp" || $_SERVER['PHP_AUTH_PW'] != "malDEV@2101") {
|
|
// header('WWW-Authenticate: Basic realm="My Realm"');
|
|
// header('HTTP/1.0 401 Unauthorized');
|
|
// echo 'Unauthorized';
|
|
// exit;
|
|
// }
|
|
// } else {
|
|
// exit;
|
|
// }
|
|
|
|
// // End
|
|
// }
|
|
|
|
|
|
function checkAuthenticate($username, $password)
|
|
{
|
|
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
|
|
// Redirect to HTTPS
|
|
header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
|
|
exit;
|
|
}
|
|
|
|
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
|
|
if ($_SERVER['PHP_AUTH_USER'] !== $username || $_SERVER['PHP_AUTH_PW'] !== $password) {
|
|
header('WWW-Authenticate: Basic realm="My Realm"');
|
|
header('HTTP/1.0 401 Unauthorized');
|
|
echo 'Unauthorized';
|
|
exit;
|
|
}
|
|
} else {
|
|
header('WWW-Authenticate: Basic realm="My Realm"');
|
|
header('HTTP/1.0 401 Unauthorized');
|
|
echo 'Unauthorized';
|
|
exit;
|
|
}
|
|
|
|
// Continue with authenticated code
|
|
}
|
|
// function checkAuthenticate()
|
|
// {
|
|
// global $secretKey;
|
|
|
|
// if (!isset($_SERVER['HTTP_AUTHORIZATION'])) {
|
|
// header('HTTP/1.0 401 Unauthorized');
|
|
// echo json_encode(['error' => 'Unauthorized']);
|
|
// exit;
|
|
// }
|
|
|
|
// $authHeader = $_SERVER['HTTP_AUTHORIZATION'];
|
|
// list($token) = sscanf($authHeader, 'Bearer %s');
|
|
|
|
// if (!$token) {
|
|
// header('HTTP/1.0 401 Unauthorized');
|
|
// echo json_encode(['error' => 'Token not provided']);
|
|
// exit;
|
|
// }
|
|
|
|
// try {
|
|
// $decoded = JWT::decode($token, new Key($secretKey, 'HS256'));
|
|
// return $decoded;
|
|
// } catch (Exception $e) {
|
|
// header('HTTP/1.0 401 Unauthorized');
|
|
// echo json_encode(['error' => 'Invalid token']);
|
|
// exit;
|
|
// }
|
|
// }
|
|
|
|
function divideAndAddText($apiKey, $text) {
|
|
$parts = str_split($apiKey, strlen($apiKey) / 4);
|
|
|
|
$dividedApiKey = array();
|
|
$dividedApiKey['birinci'] = $parts[4] . $text;
|
|
$dividedApiKey['ikinci'] = $text . $parts[2] . $text;
|
|
$dividedApiKey['üçüncü'] = $text . $parts[1] . $text;
|
|
$dividedApiKey['dördüncü'] = $parts[0] . $text;
|
|
$dividedApiKey['beş'] = $text . $parts[3] . $text;
|
|
|
|
$concatenatedApiKey = implode('', $dividedApiKey);
|
|
|
|
return $concatenatedApiKey;
|
|
}
|
|
|
|
function retrieveOriginalApiKey($concatenatedApiKey, $text) {
|
|
$originalApiKey = str_replace($text, '', $concatenatedApiKey);
|
|
|
|
$resortedApiKey = array();
|
|
$resortedApiKey['birinci'] = $originalApiKey[strlen($originalApiKey) - 5] . $originalApiKey[strlen($originalApiKey) - 3];
|
|
$resortedApiKey['ikinci'] = $originalApiKey[strlen($originalApiKey) - 1] . $originalApiKey[strlen($originalApiKey) - 15];
|
|
$resortedApiKey['üçüncü'] = $originalApiKey[strlen($originalApiKey) - 9] . $originalApiKey[strlen($originalApiKey) - 12];
|
|
$resortedApiKey['dördüncü'] = $originalApiKey[strlen($originalApiKey) - 11] . $originalApiKey[strlen($originalApiKey) - 6];
|
|
$resortedApiKey['beş'] = $originalApiKey[strlen($originalApiKey) - 2] . $originalApiKey[strlen($originalApiKey) - 8];
|
|
|
|
return $resortedApiKey;
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
//////////
|
|
|
|
function printFailure($message = "none")
|
|
{
|
|
echo json_encode(array("status" => "failure", "message" => $message));
|
|
}
|
|
function printSuccess($message = "none")
|
|
{
|
|
echo json_encode(array("status" => "success", "message" => $message));
|
|
}
|
|
|
|
function result($count)
|
|
{
|
|
if ($count > 0) {
|
|
printSuccess();
|
|
} else {
|
|
printFailure();
|
|
}
|
|
}
|
|
|
|
function sendEmail($from,$to, $title, $body)
|
|
{
|
|
$header = "From: $from" . "\n" . "CC: $from";
|
|
mail($to, $title, $body, $header);
|
|
}
|