Update: 2026-06-15 19:39:21

This commit is contained in:
Hamza-Ayed
2026-06-15 19:39:21 +03:00
parent c472a78416
commit 04943e3d52
23 changed files with 1497 additions and 324 deletions

View File

@@ -3,27 +3,73 @@ require_once __DIR__ . '/../../connect.php';
$driver_id = filterRequest("id");
$phone = filterRequest("phone");
$status = filterRequest("status");
// تشفير رقم الهاتف
$encphone = $encryptionHelper->encryptData($phone);
if (empty($driver_id)) {
jsonError("Driver ID is required.");
}
$sql = "UPDATE `driver` SET `phone` = :encphone WHERE `id` = :id";
$updateFields = [];
$params = [':id' => $driver_id];
if ($phone !== null && $phone !== '') {
$encphone = $encryptionHelper->encryptData($phone);
$updateFields[] = "`phone` = :phone";
$params[':phone'] = $encphone;
}
if ($status !== null && $status !== '') {
$updateFields[] = "`status` = :status";
$params[':status'] = $status;
}
if (empty($updateFields)) {
jsonError("No parameters provided for update.");
}
$sql = "UPDATE `driver` SET " . implode(", ", $updateFields) . " WHERE `id` = :id";
$stmt = $con->prepare($sql);
// Bind values
$stmt->bindParam(':encphone', $encphone, PDO::PARAM_STR);
$stmt->bindParam(':id', $driver_id, PDO::PARAM_STR);
try {
$stmt->execute();
$stmt->execute($params);
if ($stmt->rowCount() > 0) {
// تم التحديث بنجاح
logAudit($con, $user_id, "تعديل رقم هاتف سائق", "driver", $driver_id, ["phone" => $phone]);
jsonSuccess(null, "Phone updated successfully.");
logAudit($con, $user_id, "تعديل بيانات سائق من لوحة التحكم", "driver", $driver_id, [
"phone" => $phone,
"status" => $status
]);
// إذا تم تفعيل السائق، نرسل له رسالة ترحيبية عبر الواتساب لتأكيد التفعيل
if ($status === 'active' || $status === 'actives') {
// جلب معلومات السائق لإرسال الرسالة
$selectSql = "SELECT `phone`, `first_name` FROM `driver` WHERE `id` = :id";
$selectStmt = $con->prepare($selectSql);
$selectStmt->execute([':id' => $driver_id]);
$driverData = $selectStmt->fetch(PDO::FETCH_ASSOC);
if ($driverData) {
$decryptedPhone = $encryptionHelper->decryptData($driverData['phone']);
$firstName = $encryptionHelper->decryptData($driverData['first_name']);
$supportPhones = ['0952475740', '0952475742'];
$randomIndex = array_rand($supportPhones);
$phoneToUse = $supportPhones[$randomIndex];
$randomNumber = rand(1000, 999999);
$messageBody = "أهلاً وسهلاً كابتن $firstName 👋\n"
. "تم تفعيل حسابك على تطبيق *سيرو*.\n"
. "يمكنك الآن تسجيل الدخول والبدء بالعمل مباشرة.\n"
. "للمساعدة تواصل معنا على الرقم: $phoneToUse\n"
. "نتمنى لك عمل موفق 🚖\n\n"
. "معرف الرسالة: $randomNumber";
sendWhatsAppFromServer($decryptedPhone, $messageBody);
}
}
jsonSuccess(null, "Driver updated successfully.");
} else {
// لم يتم العثور على أي سجل للتحديث
jsonError("No records updated. Please check the driver ID.");
jsonError("No records updated or driver not found.");
}
} catch (PDOException $e) {
jsonError("Error updating record: " . $e->getMessage());

View File

@@ -21,11 +21,21 @@ if (!$country) {
exit;
}
$price = 0.0;
$price_for_driver = 0.0;
$withCommission = 0.0;
$kazan = 0.0;
$isNightFare = false;
$prices = [];
$pricesRaw = [];
$categories = [
'totalPassengerSpeed' => 'Speed',
'totalPassengerBalash' => 'Awfar Car',
'totalPassengerComfort' => 'Comfort',
'totalPassengerElectric' => 'Electric',
'totalPassengerLady' => 'Lady',
'totalPassengerScooter' => 'Delivery',
'totalPassengerVan' => 'Van',
'totalPassengerRayehGai' => 'Speed',
'totalPassengerRayehGaiComfort' => 'Comfort',
'totalPassengerRayehGaiBalash' => 'Awfar Car',
];
// Common variables
date_default_timezone_set('Asia/Damascus');
@@ -58,27 +68,52 @@ if (!$kazanRow) {
exit;
}
$result = calculateDynamicPrice($country, $minFare, $distance, $duration, $kazanRow, $startNameAddress, $endNameAddress, $destLat, $destLng, $passengerLat, $passengerLng);
$price = $result['price'];
$price_for_driver = $result['price_for_driver'];
$withCommission = $result['withCommission'];
$kazan = $result['kazan'];
$isNightFare = $result['isNightFare'];
// ----------------------------------------------------------------------
// Helper Functions for Countries
// ----------------------------------------------------------------------
function calculateDynamicPrice($country, $minFare, $distance, $duration, $kazanRow, $startNameAddress, $endNameAddress, $destLat, $destLng, $passengerLat, $passengerLng) {
$comfortPrice = (float) $kazanRow['comfortPrice'];
$speedPrice = (float) $kazanRow['speedPrice'];
$familyPrice = (float) $kazanRow['familyPrice'];
$deliveryPrice = (float) $kazanRow['deliveryPrice'];
$naturePrice = (float) $kazanRow['naturePrice'];
$heavyPrice = (float) $kazanRow['heavyPrice'];
$latePrice = (float) $kazanRow['latePrice'];
$kazanPercent = (float) $kazanRow['kazan'];
function getPerKmRate($carType, $kazanRow) {
$rateColumns = [
'Comfort' => 'comfortPrice',
'Speed' => 'speedPrice',
'Lady' => 'ladyPrice',
'Electric' => 'electricPrice',
'Van' => 'vanPrice',
'Delivery' => 'deliveryPrice',
'Mishwar Vip' => 'mishwarVipPrice',
'Fixed Price' => 'fixedPrice',
'Awfar Car' => 'awfarPrice',
];
$column = $rateColumns[$carType] ?? 'speedPrice';
$rate = floatval($kazanRow[$column] ?? 0);
if ($rate <= 0) {
$oldColumnMap = [
'Lady' => 'familyPrice',
'Mishwar Vip' => 'freePrice',
'Electric' => 'naturePrice',
'Van' => 'heavyPrice',
];
$oldColumn = $oldColumnMap[$carType] ?? null;
if ($oldColumn && isset($kazanRow[$oldColumn])) {
$rate = floatval($kazanRow[$oldColumn]);
}
}
if ($rate <= 0) {
$rate = floatval($kazanRow['speedPrice'] ?? 36);
}
return $rate;
}
function calculateDynamicPrice($country, $minFare, $distance, $duration, $kazanRow, $startNameAddress, $endNameAddress, $destLat, $destLng, $passengerLat, $passengerLng, $carType = 'Speed') {
$naturePrice = (float) ($kazanRow['naturePrice'] ?? 0);
$heavyPrice = (float) ($kazanRow['heavyPrice'] ?? 0);
$latePrice = (float) ($kazanRow['latePrice'] ?? 0);
$kazanPercent = (float) ($kazanRow['kazan'] ?? 10);
// === General Settings ===
$minBillableKm = 0.2;
$airportAddon = 0.0;
@@ -124,7 +159,8 @@ function calculateDynamicPrice($country, $minFare, $distance, $duration, $kazanR
$billableDistance = ($distance < $minBillableKm) ? $minBillableKm : $distance;
$isLongSpeed = $billableDistance > $longSpeedThresholdKm;
$perKmSpeedBaseFromServer = $speedPrice;
$perKmSpeedBaseFromServer = getPerKmRate($carType, $kazanRow);
$perKmSpeed = $isLongSpeed ? $longSpeedPerKm : $perKmSpeedBaseFromServer;
$reductionPct40 = 0.0;
@@ -205,64 +241,64 @@ if (!empty($promo_code)) {
}
// 3. Fetch Passenger Wallet (Negative Balance / Debt)
// Using Redis for ultra-fast reads, with a fallback to the Payment Server API.
$negativeBalance = 0;
if (!empty($passenger_id)) {
try {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redisKey = "passenger_debt_" . $passenger_id;
$redisDebt = $redis->get($redisKey);
if ($redisDebt !== false) {
$negativeBalance = (float) $redisDebt;
} else {
// Fallback: If not in Redis, call the Payment Server Endpoint
// TODO: Replace with the actual Payment Server Endpoint URL and API Key
/*
$paymentApiUrl = "https://payment.siroapp.com/api/get_debt?passenger_id=" . urlencode($passenger_id);
$options = [
"http" => [
"header" => "Authorization: Bearer YOUR_API_KEY\r\n"
]
];
$context = stream_context_create($options);
$response = file_get_contents($paymentApiUrl, false, $context);
if ($response !== false) {
$data = json_decode($response, true);
if (isset($data['debt'])) {
$negativeBalance = (float) $data['debt'];
// Cache the result in Redis for future pricing calls (e.g. 1 hour)
$redis->setex($redisKey, 3600, $negativeBalance);
}
}
*/
}
} catch (Exception $e) {
// If Redis fails, gracefully default to 0 or fallback API
$negativeBalance = 0;
}
}
$prices = ['total' => $withCommission];
// Calculate prices for all categories
foreach ($categories as $key => $carType) {
$result = calculateDynamicPrice($country, $minFare, $distance, $duration, $kazanRow, $startNameAddress, $endNameAddress, $destLat, $destLng, $passengerLat, $passengerLng, $carType);
$withCommission = $result['withCommission'];
$price_for_driver = $result['price_for_driver'];
// 4. Apply Discount and Negative Balance
foreach ($prices as $key => $price) {
// Apply discount (Assuming percentage discount if amount <= 100, else fixed amount)
// Apply discount
if ($discount > 0 && $discount <= 100) {
$prices[$key] = max(0, $price - ($price * ($discount / 100)));
$finalPrice = max(0, $withCommission - ($withCommission * ($discount / 100)));
} else {
$prices[$key] = max(0, $price - $discount);
$finalPrice = max(0, $withCommission - $discount);
}
// Add negative balance
$prices[$key] += $negativeBalance;
$finalPrice += $negativeBalance;
$prices[$key] = $finalPrice;
// For the token, we map the clean database carType to the final price and driver price
$pricesRaw[$carType] = [
'price' => $finalPrice,
'driver_price' => $price_for_driver
];
}
// 4. Generate Cryptographically Signed Token
$priceToken = "";
if (isset($encryptionHelper)) {
$tokenPayload = [
'passenger_id' => $passenger_id,
'start_location' => $passengerLat . ',' . $passengerLng,
'end_location' => $destLat . ',' . $destLng,
'expires' => time() + 180, // Valid for 3 minutes
'prices' => $pricesRaw
];
$priceToken = $encryptionHelper->encryptData(json_encode($tokenPayload));
}
echo json_encode([
'status' => 'success',
'data' => $prices,
'price_token' => $priceToken,
'applied_discount' => $discount,
'added_negative_balance' => $negativeBalance
]);

View File

@@ -1,128 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
// 🚀 1. تسجيل بداية الطلب
error_log("🚀 [add_ride.php] Request Started.");
// استلام البيانات
$start_location = filterRequest("start_location");
$end_location = filterRequest("end_location");
$date_raw = filterRequest("date"); // نستلم القيمة الخام
$time_raw = filterRequest("time"); // نستلم القيمة الخام
$endtime_raw = filterRequest("endtime");
$price = filterRequest("price");
$passenger_id = filterRequest("passenger_id");
$driver_id = filterRequest("driver_id");
$status = filterRequest("status");
$price_for_driver = filterRequest("price_for_driver");
$price_for_passenger = filterRequest("price_for_passenger");
$distance = filterRequest("distance");
$carType = filterRequest("carType");
error_log(" [add_ride.php] Data Received. Processing dates...");
// 🛠️ 2. معالجة التواريخ لتناسب MySQL (الحل الجذري للمشكلة)
// تحويل "2025-12-18 09:48:26.805" إلى "2025-12-18" فقط
$date_formatted = date("Y-m-d", strtotime($date_raw));
// تحويل "2025-12-18 09:48:26.810" إلى "09:48:26" فقط
$time_formatted = date("H:i:s", strtotime($time_raw));
// معالجة وقت الانتهاء (قد يكون مدة أو وقت)
// نحاول استخراج الوقت منه، إذا فشل نضعه 00:00:00
$endtime_formatted = date("H:i:s", strtotime($endtime_raw));
if (!$endtime_formatted) {
$endtime_formatted = "00:00:00";
}
// تجهيز مصفوفة البيانات
$data = [
":start_location" => $start_location,
":end_location" => $end_location,
":date" => $date_formatted, // نستخدم الصيغة المعالجة
":time" => $time_formatted, // نستخدم الصيغة المعالجة
":endtime" => $endtime_formatted,
":price" => $price,
":passenger_id" => $passenger_id,
":driver_id" => $driver_id,
":status" => $status,
":carType" => $carType,
":price_for_driver" => $price_for_driver,
":price_for_passenger" => $price_for_passenger,
":distance" => $distance,
];
// تسجيل البيانات التي سيتم إدخالها للتأكد
error_log(" [add_ride.php] Prepared Data: " . json_encode($data));
// ---------------------------------------------------------
// 3. الإضافة في السيرفر المحلي (Main DB)
// ---------------------------------------------------------
$sql = "INSERT INTO `ride` (
`start_location`, `end_location`, `date`, `time`, `endtime`,
`price`, `passenger_id`, `driver_id`, `status`, `carType`,
`price_for_driver`, `price_for_passenger`, `distance`
) VALUES (
:start_location, :end_location, :date, :time, :endtime,
:price, :passenger_id, :driver_id, :status, :carType,
:price_for_driver, :price_for_passenger, :distance
)";
try {
error_log("🔄 [add_ride.php] Inserting into LOCAL DB...");
$stmt = $con->prepare($sql);
$stmt->execute($data);
$insertedId = $con->lastInsertId();
$count = $stmt->rowCount();
error_log("✅ [add_ride.php] Local Insert Success. ID: $insertedId");
if ($count > 0) {
// ---------------------------------------------------------
// 4. الإضافة في سيرفر التتبع (Tracking DB)
// ---------------------------------------------------------
$sqlRemote = "INSERT INTO `ride` (
`id`, `start_location`, `end_location`, `date`, `time`, `endtime`,
`price`, `passenger_id`, `driver_id`, `status`, `carType`,
`price_for_driver`, `price_for_passenger`, `distance`
) VALUES (
:id, :start_location, :end_location, :date, :time, :endtime,
:price, :passenger_id, :driver_id, :status, :carType,
:price_for_driver, :price_for_passenger, :distance
)";
// إضافة الـ ID للمصفوفة
$data[':id'] = $insertedId;
try {
error_log("🔄 [add_ride.php] Inserting into REMOTE DB...");
$stmtRemote = $con_ride->prepare($sqlRemote);
$stmtRemote->execute($data);
error_log("✅ [add_ride.php] Remote Insert Success.");
} catch (PDOException $eRemote) {
// نسجل خطأ الريموت لكن لا نوقف العملية لأن اللوكل تم بنجاح
error_log("⚠️ [add_ride.php] Remote DB Error: " . $eRemote->getMessage());
}
// طباعة النجاح (JSON صحيح)
jsonSuccess($insertedId);
} else {
error_log("❌ [add_ride.php] Failed to insert locally (Rows affected 0).");
jsonError("Failed to save ride information locally");
}
} catch (PDOException $e) {
// تسجيل الخطأ بدقة
error_log("❌ [add_ride.php] SQL Error: " . $e->getMessage());
jsonError("Database Error: " . $e->getMessage());
}
?>

View File

@@ -57,6 +57,7 @@ error_log("[add_ride] Request started. passenger_id=" . ($_POST['passenger_id']
$start_location = filterRequest("start_location");
$end_location = filterRequest("end_location");
$price = filterRequest("price");
$price_token = filterRequest("price_token");
$passenger_id = filterRequest("passenger_id");
$driver_id = filterRequest("driver_id") ?: 0;
$status = filterRequest("status");
@@ -82,6 +83,15 @@ $step2 = filterRequest("step2");
$step3 = filterRequest("step3");
$step4 = filterRequest("step4");
// Helper to compare coordinates (allowing slight GPS precision drift up to ~500m)
function coordsMatch($coordStr1, $coordStr2, $tolerance = 0.005) {
if (empty($coordStr1) || empty($coordStr2)) return false;
$c1 = array_map('floatval', explode(',', $coordStr1));
$c2 = array_map('floatval', explode(',', $coordStr2));
if (count($c1) < 2 || count($c2) < 2) return false;
return (abs($c1[0] - $c2[0]) < $tolerance) && (abs($c1[1] - $c2[1]) < $tolerance);
}
// Validation
if (empty($passenger_id) || empty($start_location) || empty($end_location) || empty($price)) {
error_log("[add_ride] Validation failed — missing required fields.");
@@ -89,6 +99,50 @@ if (empty($passenger_id) || empty($start_location) || empty($end_location) || em
exit;
}
// SECURE PRICE TOKEN VERIFICATION
if (empty($price_token)) {
error_log("[add_ride] Security failed — price_token is missing.");
printFailure("Secure price token is required");
exit;
}
$decrypted = isset($encryptionHelper) ? $encryptionHelper->decryptData($price_token) : false;
if (!$decrypted) {
error_log("[add_ride] Security failed — failed to decrypt price_token.");
printFailure("Invalid or tampered price token");
exit;
}
$tokenData = json_decode($decrypted, true);
if (!$tokenData || !isset($tokenData['expires']) || $tokenData['expires'] < time()) {
error_log("[add_ride] Security failed — token is expired or invalid JSON.");
printFailure("Price token has expired, please request estimation again");
exit;
}
if ($tokenData['passenger_id'] != $passenger_id) {
error_log("[add_ride] Security failed — passenger_id mismatch.");
printFailure("Tampered price token (passenger mismatch)");
exit;
}
if (!coordsMatch($tokenData['start_location'], $start_location) || !coordsMatch($tokenData['end_location'], $end_location)) {
error_log("[add_ride] Security failed — coordinates mismatch. Token: " . ($tokenData['start_location'] . " / " . $tokenData['end_location']) . " Request: " . ($start_location . " / " . $end_location));
printFailure("Tampered price token (route mismatch)");
exit;
}
if (!isset($tokenData['prices'][$carType])) {
error_log("[add_ride] Security failed — car type $carType not found in token.");
printFailure("Invalid car type for this token");
exit;
}
// Securely override pricing from the cryptographically signed token
$price = $tokenData['prices'][$carType]['price'];
$price_for_driver = $tokenData['prices'][$carType]['driver_price'];
$price_for_passenger = $price;
// ── 2. تنسيق التواريخ ─────────────────────────────────────────
$date_formatted = date("Y-m-d");
$time_formatted = date("H:i:s");

View File

@@ -0,0 +1,94 @@
<?php
// test_signed_pricing.php
// Mock parameters and verify price token generation and booking verification.
define('TESTING_BYPASS_AUTH', true);
// Set mock POST parameters for pricing estimation
$_POST['distance'] = "10.5";
$_POST['durationToRide'] = "1200"; // 20 minutes
$_POST['passenger_id'] = "12345";
$_POST['country'] = "Syria";
$_POST['passengerLat'] = "33.5138";
$_POST['passengerLng'] = "36.2765";
$_POST['destLat'] = "33.5200";
$_POST['destLng'] = "36.2800";
$_POST['startNameAddress'] = "Malki, Damascus";
$_POST['endNameAddress'] = "Abu Rummaneh, Damascus";
$_POST['carType'] = "Speed";
echo "=== MOCKING PRICING ESTIMATION (get.php) ===\n";
ob_start();
include __DIR__ . '/ride/pricing/get.php';
$responseJson = ob_get_clean();
echo "Response received:\n" . $responseJson . "\n\n";
$response = json_decode($responseJson, true);
if (!$response || $response['status'] !== 'success' || empty($response['price_token'])) {
echo "❌ FAILED: Pricing token was not generated successfully.\n";
exit(1);
}
$priceToken = $response['price_token'];
$estimatedPrices = $response['data'];
echo "✅ SUCCESS: Generated price_token successfully!\n";
echo "Estimated Speed price: " . $estimatedPrices['totalPassengerSpeed'] . "\n\n";
// Test 1: Valid Booking with Token
echo "=== TEST 1: Booking with authentic token and coordinates ===\n";
$_POST['start_location'] = "33.5138, 36.2765";
$_POST['end_location'] = "33.5200, 36.2800";
$_POST['price'] = "99999.00"; // Client attempts to send garbage price, server must override it!
$_POST['price_token'] = $priceToken;
$_POST['passenger_id'] = "12345";
$_POST['carType'] = "Speed";
$_POST['status'] = "waiting";
// Mock other fields for add_ride.php to prevent errors
$_POST['passenger_name'] = "Hamza";
$_POST['passenger_phone'] = "+963999999999";
$_POST['passenger_token'] = "mock_fcm_token";
$_POST['passenger_email'] = "hamza@siromove.com";
$_POST['passenger_wallet'] = "0";
$_POST['passenger_rating'] = "5.0";
$_POST['start_name'] = "Malki";
$_POST['end_name'] = "Abu Rummaneh";
$_POST['duration_text'] = "20 min";
$_POST['distance_text'] = "10.5 km";
$_POST['is_wallet'] = "false";
$_POST['has_steps'] = "false";
ob_start();
include __DIR__ . '/ride/rides/add_ride.php';
$bookingJson = ob_get_clean();
echo "Booking response:\n" . $bookingJson . "\n\n";
$bookingRes = json_decode($bookingJson, true);
if ($bookingRes && $bookingRes['status'] === 'success') {
echo "✅ TEST 1 PASSED: Booking succeeded and overrode client fare!\n";
} else {
echo "❌ TEST 1 FAILED: Booking rejected valid token.\n";
}
// Test 2: Booking with Tampered Coordinates
echo "=== TEST 2: Booking with mismatched start location coordinates ===\n";
$_POST['start_location'] = "34.5000, 36.2000"; // Changed start location
$_POST['price'] = "99999.00";
$_POST['price_token'] = $priceToken;
ob_start();
include __DIR__ . '/ride/rides/add_ride.php';
$tamperedJson = ob_get_clean();
echo "Tampered response:\n" . $tamperedJson . "\n\n";
$tamperedRes = json_decode($tamperedJson, true);
if ($tamperedRes && $tamperedRes['status'] === 'failure' && strpos($tamperedRes['message'], 'route mismatch') !== false) {
echo "✅ TEST 2 PASSED: Successfully detected coordinates mismatch and rejected booking!\n";
} else {
echo "❌ TEST 2 FAILED: Did not correctly reject mismatched coordinates.\n";
}
?>