Compare commits
131
Commits
42f6d33efd
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb9517826e | ||
|
|
e52afa1863 | ||
|
|
e63f990aea | ||
|
|
8c9f729ecd | ||
|
|
dd44b84e81 | ||
|
|
875ce763bd | ||
|
|
c659af67dc | ||
|
|
ef37752ceb | ||
|
|
b97a1fd587 | ||
|
|
8395436f23 | ||
|
|
c8e8e481a6 | ||
|
|
fae0e4a38a | ||
|
|
611b5e616d | ||
|
|
0db59647eb | ||
|
|
cdd36d4777 | ||
|
|
9338e76894 | ||
|
|
b2a95c53aa | ||
|
|
9e186f9ff3 | ||
|
|
d691e51ba4 | ||
|
|
92a6aa5c0f | ||
|
|
67465df000 | ||
|
|
7a932580a3 | ||
|
|
0b8b687ce1 | ||
|
|
b938e287c6 | ||
|
|
977d238c84 | ||
|
|
8e7c4a7104 | ||
|
|
f0ea698ab2 | ||
|
|
e070c2d9a8 | ||
|
|
70772cf0d2 | ||
|
|
3081aea802 | ||
|
|
b492034bad | ||
|
|
9830e5f649 | ||
|
|
5b864e30df | ||
|
|
0cb1ab0ea3 | ||
|
|
a1104a4695 | ||
|
|
6e451e8b71 | ||
|
|
4d64a205fa | ||
|
|
97471fd2bd | ||
|
|
52101e650c | ||
|
|
e4553dabc1 | ||
|
|
ca55aaebe8 | ||
|
|
d695834d19 | ||
|
|
788d3dcbe5 | ||
|
|
f01e408ba6 | ||
|
|
04c214bdf6 | ||
|
|
5f5e78691d | ||
|
|
dbf1e7870f | ||
|
|
79333a4bee | ||
|
|
b60129d246 | ||
|
|
f36b30f0b8 | ||
|
|
ec467b01c6 | ||
|
|
4abfd30ddd | ||
|
|
0334f9881f | ||
|
|
2b9f696372 | ||
|
|
c23c3c0721 | ||
|
|
5691d84fa0 | ||
|
|
2c962bf80a | ||
|
|
c9af364cbc | ||
|
|
02e652a786 | ||
|
|
03a21aa95d | ||
|
|
3b4b4639a6 | ||
|
|
4620e84d34 | ||
|
|
b78a6797d5 | ||
|
|
811b23ca9e | ||
|
|
915d517ba7 | ||
|
|
12fc64dc9a | ||
|
|
46e74330a1 | ||
|
|
410fb14d77 | ||
|
|
cf3fea3834 | ||
|
|
0452c36379 | ||
|
|
7362f1ce96 | ||
|
|
8d67530b44 | ||
|
|
f94a9478ac | ||
|
|
7a576b7327 | ||
|
|
ecfe756849 | ||
|
|
4d2beaae5e | ||
|
|
b84e26fe9a | ||
|
|
77c0b48ec2 | ||
|
|
e106d2df4e | ||
|
|
899a18b52d | ||
|
|
e6504acdea | ||
|
|
ef1240b130 | ||
|
|
0e6dd68385 | ||
|
|
afb5189515 | ||
|
|
6fec88251c | ||
|
|
b76eccb763 | ||
|
|
a26472ed9f | ||
|
|
ab3be7e2e3 | ||
|
|
f66db7db42 | ||
|
|
143146c1b4 | ||
|
|
e269cb9b70 | ||
|
|
330dfc6dba | ||
|
|
4b5235c35c | ||
|
|
16feb51a75 | ||
|
|
3af99cc18a | ||
|
|
7830efead7 | ||
|
|
ca6cb7a3fe | ||
|
|
f325ffce42 | ||
|
|
c43f801542 | ||
|
|
2bacb1b9e1 | ||
|
|
5ec54c03f5 | ||
|
|
a954f49307 | ||
|
|
91fe0f78f7 | ||
|
|
5f5b68a8cd | ||
|
|
1664743ef9 | ||
|
|
1dfc302a4f | ||
|
|
76c8652bf0 | ||
|
|
a095472f39 | ||
|
|
c8a9e98ff5 | ||
|
|
e03b9c30d5 | ||
|
|
20ea9aa12c | ||
|
|
8d3e63d1c7 | ||
|
|
4bbc687c15 | ||
|
|
5e103f60f2 | ||
|
|
27369b8ac1 | ||
|
|
61d6380861 | ||
|
|
3fb7bc5190 | ||
|
|
f9110a7d92 | ||
|
|
a0812dbd10 | ||
|
|
bc1b0129e8 | ||
|
|
2135edcf43 | ||
|
|
35a66935aa | ||
|
|
8d7e3118b5 | ||
|
|
39b5a7fc7f | ||
|
|
a1c19b052d | ||
|
|
c9b4d14da6 | ||
|
|
15f55ff3e4 | ||
|
|
761b957c96 | ||
|
|
57e22477fb | ||
|
|
6802026dbd | ||
|
|
81ee2acefd |
@@ -0,0 +1,22 @@
|
|||||||
|
# سياق البناء لخدمات docker/docker-compose.yml هو جذر المستودع (context: ..).
|
||||||
|
# بدون هذا الملف يُرسل .git كاملاً (مئات الميغابايت) إلى الـ daemon مع كل بناء،
|
||||||
|
# وهو سبب أخطاء "Can't add file .git/objects/... to tar".
|
||||||
|
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.DS_Store
|
||||||
|
**/.DS_Store
|
||||||
|
|
||||||
|
# تطبيقات فلاتر — لا علاقة لها بأي صورة باك إند
|
||||||
|
siro_rider
|
||||||
|
siro_driver
|
||||||
|
|
||||||
|
# اعتماديات مُثبَّتة داخل الصور أو مركَّبة كـ volumes
|
||||||
|
**/node_modules
|
||||||
|
**/vendor
|
||||||
|
|
||||||
|
# وثائق ومخرجات محلية
|
||||||
|
docs
|
||||||
|
*.log
|
||||||
|
*.tar
|
||||||
|
*.zip
|
||||||
+4
-2
@@ -70,8 +70,8 @@ DerivedData/
|
|||||||
xcuserdata/
|
xcuserdata/
|
||||||
|
|
||||||
# --- Composer / PHP ---
|
# --- Composer / PHP ---
|
||||||
/composer.lock
|
# composer.lock مُتتبَّع عمداً: بدونه ينهار payment_server/v2 بعد أي نشر نظيف
|
||||||
**/composer.lock
|
# (vendor يبقى مستثنى أعلاه — يُبنى بـ composer install من الـ lock)
|
||||||
|
|
||||||
# --- Logs ---
|
# --- Logs ---
|
||||||
*.log
|
*.log
|
||||||
@@ -101,3 +101,5 @@ GoogleService-Info.plist
|
|||||||
# --- Audit/Scan Output ---
|
# --- Audit/Scan Output ---
|
||||||
semgrep_*.json
|
semgrep_*.json
|
||||||
nuclei_results.txt
|
nuclei_results.txt
|
||||||
|
|
||||||
|
*.env.bak.*
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -17,6 +17,9 @@ android {
|
|||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
buildConfigField("String", "BOT_SECRET_KEY", "\"SIRO_BOT_SUPER_SECRET_123\"")
|
buildConfigField("String", "BOT_SECRET_KEY", "\"SIRO_BOT_SUPER_SECRET_123\"")
|
||||||
|
// مضيف الباك إند في مكان واحد: تبديله عند نسخ البوت لعلامة أخرى
|
||||||
|
// (مثل انطلق على api.intaleqapp.com) يصير سطراً واحداً لا بحثاً في الكود.
|
||||||
|
buildConfigField("String", "BACKEND_HOST", "\"https://jordan-siro.intaleqapp.com\"")
|
||||||
}
|
}
|
||||||
|
|
||||||
buildTypes {
|
buildTypes {
|
||||||
|
|||||||
@@ -25,9 +25,14 @@ class WorkerClient(private val context: Context) {
|
|||||||
Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID) ?: "UNKNOWN_DEVICE"
|
Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID) ?: "UNKNOWN_DEVICE"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Change this to your actual server domain
|
// المضيف من BuildConfig.BACKEND_HOST (app/build.gradle.kts) — لا يُشفَّر هنا،
|
||||||
private val BASE_URL = "https://jordan-siro.intaleqapp.com/backend/bot/standalone_worker.php"
|
// حتى يكون تبديله عند نسخ البوت لعلامة أخرى سطراً واحداً في gradle.
|
||||||
// For local testing use: "http://10.0.2.2:8000/standalone_worker.php"
|
// للتجريب المحلي: اضبط BACKEND_HOST على "http://10.0.2.2:8000" مع تقديم
|
||||||
|
// نفس المسار /backend/bot/ من جذر السيرفر المحلي.
|
||||||
|
// worker.php هو المسار الإنتاجي (Redis + MySQL). لا تُعِده إلى
|
||||||
|
// standalone_worker.php: تلك نسخة اختبار محلي تخزّن في ملفات JSON
|
||||||
|
// ولا تصل نتائجها إلى جدول scraped_competitor_prices ولا إلى محرّك التسعير.
|
||||||
|
private val BASE_URL = "${BuildConfig.BACKEND_HOST}/backend/bot/worker.php"
|
||||||
|
|
||||||
private fun generateSignature(deviceId: String, ts: Long): String {
|
private fun generateSignature(deviceId: String, ts: Long): String {
|
||||||
val message = "$deviceId$ts"
|
val message = "$deviceId$ts"
|
||||||
|
|||||||
@@ -5,6 +5,15 @@ $driver_id = filterRequest("driver_id");
|
|||||||
$driverEmail = $encryptionHelper->encryptData(filterRequest("driverEmail"));
|
$driverEmail = $encryptionHelper->encryptData(filterRequest("driverEmail"));
|
||||||
$driverPhone = $encryptionHelper->encryptData(filterRequest("driverPhone"));
|
$driverPhone = $encryptionHelper->encryptData(filterRequest("driverPhone"));
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* الفهرس الأعمى: يسمح بالبحث بعد نقل التخزين إلى AES-GCM العشوائي.
|
||||||
|
* تُبقى المقارنة القديمة في نفس الاستعلام كاحتياط حتى تنتهي تعبئة الفهارس.
|
||||||
|
*/
|
||||||
|
global $blindIndex;
|
||||||
|
$emailBidx = $blindIndex ? $blindIndex->index('driver.email', filterRequest("driverEmail")) : null;
|
||||||
|
$phoneBidx = $blindIndex ? $blindIndex->index('driver.phone', filterRequest("driverPhone")) : null;
|
||||||
|
|
||||||
$sql = "SELECT
|
$sql = "SELECT
|
||||||
`driver`.`id`,
|
`driver`.`id`,
|
||||||
`driver`.`phone`,
|
`driver`.`phone`,
|
||||||
@@ -53,6 +62,8 @@ $sql = "SELECT
|
|||||||
) AS passengerToken
|
) AS passengerToken
|
||||||
FROM `driver`
|
FROM `driver`
|
||||||
WHERE `driver`.`email` = :email OR `driver`.`phone` = :phone OR `driver`.`id` = :id
|
WHERE `driver`.`email` = :email OR `driver`.`phone` = :phone OR `driver`.`id` = :id
|
||||||
|
OR (:email_bidx IS NOT NULL AND `driver`.`email_bidx` = :email_bidx)
|
||||||
|
OR (:phone_bidx IS NOT NULL AND `driver`.`phone_bidx` = :phone_bidx)
|
||||||
ORDER BY passengerAverageRating DESC
|
ORDER BY passengerAverageRating DESC
|
||||||
LIMIT 10
|
LIMIT 10
|
||||||
";
|
";
|
||||||
@@ -61,6 +72,8 @@ $stmt = $con->prepare($sql);
|
|||||||
$stmt->bindParam(":email", $driverEmail);
|
$stmt->bindParam(":email", $driverEmail);
|
||||||
$stmt->bindParam(":phone", $driverPhone);
|
$stmt->bindParam(":phone", $driverPhone);
|
||||||
$stmt->bindParam(":id", $driver_id);
|
$stmt->bindParam(":id", $driver_id);
|
||||||
|
$stmt->bindParam(":email_bidx", $emailBidx);
|
||||||
|
$stmt->bindParam(":phone_bidx", $phoneBidx);
|
||||||
$stmt->execute();
|
$stmt->execute();
|
||||||
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,18 @@
|
|||||||
<?php
|
<?php
|
||||||
require_once __DIR__ . '/../../connect.php';
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
// تشفير driver_id قبل استخدامه في SQL
|
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||||
|
http_response_code(403);
|
||||||
|
echo json_encode(['error' => 'Unauthorized: Admin access required']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
$driver_id = filterRequest("driver_id");
|
$driver_id = filterRequest("driver_id");
|
||||||
|
|
||||||
|
if (empty($driver_id)) {
|
||||||
|
jsonError("driver_id is required", 400);
|
||||||
|
}
|
||||||
|
|
||||||
$sql = "SELECT
|
$sql = "SELECT
|
||||||
`driver`.`id`,
|
`driver`.`id`,
|
||||||
`driver`.`phone`,
|
`driver`.`phone`,
|
||||||
@@ -14,7 +23,6 @@ $sql = "SELECT
|
|||||||
`driver`.`site`,
|
`driver`.`site`,
|
||||||
`driver`.`first_name`,
|
`driver`.`first_name`,
|
||||||
`driver`.`last_name`,
|
`driver`.`last_name`,
|
||||||
`driver`.`education`,
|
|
||||||
`driver`.`employmentType`,
|
`driver`.`employmentType`,
|
||||||
`driver`.`maritalStatus`,
|
`driver`.`maritalStatus`,
|
||||||
`driver`.`created_at`,
|
`driver`.`created_at`,
|
||||||
@@ -59,14 +67,23 @@ WHERE `driver`.`id` = :driver_id
|
|||||||
ORDER BY passengerAverageRating DESC
|
ORDER BY passengerAverageRating DESC
|
||||||
LIMIT 10";
|
LIMIT 10";
|
||||||
|
|
||||||
$stmt = $con->prepare($sql);
|
try {
|
||||||
$stmt->bindParam(':driver_id', $driver_id);
|
$stmt = $con->prepare($sql);
|
||||||
$stmt->execute();
|
$stmt->bindParam(':driver_id', $driver_id);
|
||||||
|
$stmt->execute();
|
||||||
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
// بلا هذا الالتقاط كان الاستثناء يُنهي السكربت فيصل للعميل جسم فارغ
|
||||||
|
// بحالة HTTP 200، فيظهر كـ "رد غير JSON".
|
||||||
|
error_log("[getCaptainDetailsById] " . $e->getMessage());
|
||||||
|
jsonError("Could not read the captain record: " . $e->getMessage(), 500);
|
||||||
|
}
|
||||||
|
|
||||||
// فك تشفير الحقول الحساسة بعد الجلب
|
// فك تشفير الحقول الحساسة بعد الجلب
|
||||||
foreach ($result as &$row) {
|
foreach ($result as &$row) {
|
||||||
|
foreach (['phone','email','gender','birthdate','site','first_name','last_name','employmentType','maritalStatus'] as $f) {
|
||||||
|
if (!array_key_exists($f, $row)) $row[$f] = null;
|
||||||
|
}
|
||||||
$row['phone'] = $encryptionHelper->decryptData($row['phone']);
|
$row['phone'] = $encryptionHelper->decryptData($row['phone']);
|
||||||
$row['email'] = $encryptionHelper->decryptData($row['email']);
|
$row['email'] = $encryptionHelper->decryptData($row['email']);
|
||||||
$row['gender'] = $encryptionHelper->decryptData($row['gender']);
|
$row['gender'] = $encryptionHelper->decryptData($row['gender']);
|
||||||
@@ -74,7 +91,6 @@ foreach ($result as &$row) {
|
|||||||
$row['site'] = $encryptionHelper->decryptData($row['site']);
|
$row['site'] = $encryptionHelper->decryptData($row['site']);
|
||||||
$row['first_name'] = $encryptionHelper->decryptData($row['first_name']);
|
$row['first_name'] = $encryptionHelper->decryptData($row['first_name']);
|
||||||
$row['last_name'] = $encryptionHelper->decryptData($row['last_name']);
|
$row['last_name'] = $encryptionHelper->decryptData($row['last_name']);
|
||||||
$row['education'] = $encryptionHelper->decryptData($row['education']);
|
|
||||||
$row['employmentType'] = $encryptionHelper->decryptData($row['employmentType']);
|
$row['employmentType'] = $encryptionHelper->decryptData($row['employmentType']);
|
||||||
$row['maritalStatus'] = $encryptionHelper->decryptData($row['maritalStatus']);
|
$row['maritalStatus'] = $encryptionHelper->decryptData($row['maritalStatus']);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ if ($redis && !empty($phone)) {
|
|||||||
|
|
||||||
// البحث عن المشرف باستخدام بصمة الجهاز (Fingerprint Hash)
|
// البحث عن المشرف باستخدام بصمة الجهاز (Fingerprint Hash)
|
||||||
$fpHash = hash('sha256', $fingerprint);
|
$fpHash = hash('sha256', $fingerprint);
|
||||||
|
$isTrustedDevice = false;
|
||||||
|
|
||||||
// تسجيل محاولة تسجيل الدخول للتدقيق
|
// تسجيل محاولة تسجيل الدخول للتدقيق
|
||||||
$loginAuditData = [
|
$loginAuditData = [
|
||||||
@@ -57,11 +58,29 @@ try {
|
|||||||
$stmt->execute([':fp' => $fpHash]);
|
$stmt->execute([':fp' => $fpHash]);
|
||||||
$admin = $stmt->fetch(PDO::FETCH_ASSOC);
|
$admin = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
// إذا لم يتم العثور بالبصمة، نبحث بالـ ID المباشر أو بفك تشفير البيانات (AES-GCM Decryption in PHP)
|
if ($admin) {
|
||||||
if (!$admin && !empty($phone)) {
|
$isTrustedDevice = true;
|
||||||
// 1. بحث مباشر بالـ ID المعياري Unencrypted
|
} else if (!empty($phone)) {
|
||||||
$stmtId = $con->prepare("SELECT * FROM adminUser WHERE id = :id LIMIT 1");
|
// 1. بحث بالـ ID أو الفهارس العمياء (الهاتف / البريد) لضمان السرعة والتوافق مع التشفير المتغير
|
||||||
$stmtId->execute([':id' => $phone]);
|
global $blindIndex;
|
||||||
|
$phoneBidx = $blindIndex ? $blindIndex->index('adminUser.phone', $phone) : null;
|
||||||
|
$emailBidx = $blindIndex ? $blindIndex->index('adminUser.email', $phone) : null;
|
||||||
|
|
||||||
|
$sql = "SELECT * FROM adminUser WHERE id = :id";
|
||||||
|
$params = [':id' => $phone];
|
||||||
|
|
||||||
|
if ($phoneBidx) {
|
||||||
|
$sql .= " OR phone_bidx = :phone_bidx";
|
||||||
|
$params[':phone_bidx'] = $phoneBidx;
|
||||||
|
}
|
||||||
|
if ($emailBidx) {
|
||||||
|
$sql .= " OR email_bidx = :email_bidx";
|
||||||
|
$params[':email_bidx'] = $emailBidx;
|
||||||
|
}
|
||||||
|
$sql .= " LIMIT 1";
|
||||||
|
|
||||||
|
$stmtId = $con->prepare($sql);
|
||||||
|
$stmtId->execute($params);
|
||||||
$admin = $stmtId->fetch(PDO::FETCH_ASSOC);
|
$admin = $stmtId->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
// 2. إذا لم يتم العثور بالـ ID، نفحص الحقول المشفّرة (email / phone / name) عبر فك التشفير
|
// 2. إذا لم يتم العثور بالـ ID، نفحص الحقول المشفّرة (email / phone / name) عبر فك التشفير
|
||||||
@@ -79,16 +98,9 @@ try {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// عند إيجاد الحساب وتأكيد كلمة المرور، نقوم بتحديث وبث بصمة الجهاز للجلسة
|
// فحص ما إذا كانت بصمة الجهاز محفوظة ومطابقة للجهاز الحالي
|
||||||
if ($admin && password_verify($password, $admin['password'])) {
|
if ($admin && !empty($admin['fingerprint_hash']) && hash_equals($admin['fingerprint_hash'], $fpHash)) {
|
||||||
$encFpRaw = $encryptionHelper ? $encryptionHelper->encryptData($fingerprint) : $fingerprint;
|
$isTrustedDevice = true;
|
||||||
$updateStmt = $con->prepare("UPDATE adminUser SET fingerprint = :fp_raw, fingerprint_hash = :fp WHERE id = :id");
|
|
||||||
$updateStmt->execute([
|
|
||||||
':fp_raw' => $encFpRaw,
|
|
||||||
':fp' => $fpHash,
|
|
||||||
':id' => $admin['id']
|
|
||||||
]);
|
|
||||||
$admin['fingerprint_hash'] = $fpHash;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,8 +122,17 @@ try {
|
|||||||
// 2. التحقق من كلمة المرور
|
// 2. التحقق من كلمة المرور
|
||||||
if (password_verify($password, $admin['password'])) {
|
if (password_verify($password, $admin['password'])) {
|
||||||
|
|
||||||
// إذا كان تجديد توكن تلقائي من التطبيق/الجهاز الموثوق
|
// إذا كان الجهاز موثوقاً (البصمة محفوظة ومطابقة) أو طلب تجديد توكن تلقائي
|
||||||
if ($isRenewal) {
|
if ($isTrustedDevice || $isRenewal) {
|
||||||
|
$encFpRaw = $encryptionHelper ? $encryptionHelper->encryptData($fingerprint) : $fingerprint;
|
||||||
|
$updateStmt = $con->prepare("UPDATE adminUser SET fingerprint = :fp_raw, fingerprint_hash = :fp WHERE id = :id");
|
||||||
|
$updateStmt->execute([
|
||||||
|
':fp_raw' => $encFpRaw,
|
||||||
|
':fp' => $fpHash,
|
||||||
|
':id' => $admin['id']
|
||||||
|
]);
|
||||||
|
$admin['fingerprint_hash'] = $fpHash;
|
||||||
|
|
||||||
$jwtService = new JwtService($redis);
|
$jwtService = new JwtService($redis);
|
||||||
$role = $admin['role'] ?? 'admin';
|
$role = $admin['role'] ?? 'admin';
|
||||||
|
|
||||||
|
|||||||
@@ -22,14 +22,55 @@ $rateLimiter->enforce(RateLimiter::identifier(), 'otp');
|
|||||||
try {
|
try {
|
||||||
$con = Database::get('main');
|
$con = Database::get('main');
|
||||||
|
|
||||||
// 1. جلب بيانات المسؤول عبر البصمة (مصدر موثوق وغير مشفر)
|
// 1. جلب بيانات المسؤول عبر البصمة أو من الـ OTP المعلق للجهاز الجديد
|
||||||
$fpHash = hash('sha256', $fingerprint);
|
$fpHash = hash('sha256', $fingerprint);
|
||||||
$stmt = $con->prepare("SELECT * FROM adminUser WHERE fingerprint_hash = :fp LIMIT 1");
|
$stmt = $con->prepare("SELECT * FROM adminUser WHERE fingerprint_hash = :fp LIMIT 1");
|
||||||
$stmt->execute([':fp' => $fpHash]);
|
$stmt->execute([':fp' => $fpHash]);
|
||||||
$admin = $stmt->fetch(PDO::FETCH_ASSOC);
|
$admin = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
|
$otpHash = hash('sha256', (string)$otp);
|
||||||
|
|
||||||
if (!$admin) {
|
if (!$admin) {
|
||||||
jsonError("المسؤول غير موجود أو البصمة غير مطابقة.");
|
// إذا كانت البصمة جديدة وغير مسجلة بعد، نبحث عن الحساب المرتبط بـ OTP المعلق
|
||||||
|
$stmtOtp = $con->prepare("SELECT phone_number FROM token_verification_admin WHERE token = ? AND expiration_time >= NOW() LIMIT 1");
|
||||||
|
$stmtOtp->execute([$otpHash]);
|
||||||
|
$otpRow = $stmtOtp->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
|
if ($otpRow && !empty($otpRow['phone_number'])) {
|
||||||
|
// $targetPhone هو الرقم المشفر من token_verification_admin (نفس القيمة المخزنة في adminUser.phone)
|
||||||
|
$targetPhone = $otpRow['phone_number'];
|
||||||
|
global $encryptionHelper;
|
||||||
|
|
||||||
|
// البحث المباشر: phone المشفر مطابق لنفس النص المشفر في adminUser.phone
|
||||||
|
$stmtAdmin = $con->prepare("SELECT * FROM adminUser WHERE phone = :p1 OR id = :p2 LIMIT 1");
|
||||||
|
$stmtAdmin->execute([':p1' => $targetPhone, ':p2' => $targetPhone]);
|
||||||
|
$admin = $stmtAdmin->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
|
// مسار احتياطي: فك التشفير لمقارنة القيم (ضروري لـ AES-GCM حيث التشفير غير حتمي)
|
||||||
|
if (!$admin) {
|
||||||
|
$decTarget = ($encryptionHelper && !empty($targetPhone)) ? $encryptionHelper->decryptData($targetPhone) : null;
|
||||||
|
$stmtAll = $con->query("SELECT * FROM adminUser");
|
||||||
|
while ($row = $stmtAll->fetch(PDO::FETCH_ASSOC)) {
|
||||||
|
// مقارنة مباشرة للنصوص المشفرة (نفس ciphertext)
|
||||||
|
if ($targetPhone === $row['phone']) {
|
||||||
|
$admin = $row;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// مقارنة عبر فك التشفير (AES-GCM: ciphertexts مختلفة لنفس النص)
|
||||||
|
if ($decTarget) {
|
||||||
|
$decPhone = ($encryptionHelper && !empty($row['phone'])) ? $encryptionHelper->decryptData($row['phone']) : $row['phone'];
|
||||||
|
if ($decTarget === $decPhone) {
|
||||||
|
$admin = $row;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$admin) {
|
||||||
|
jsonError("المسؤول غير موجود أو رمز التحقق غير صالح.");
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,10 +80,7 @@ try {
|
|||||||
// فك تشفيره لو احتجنا إرساله أو عرضه، لكن هنا نحن نحتاج المشفر للبحث
|
// فك تشفيره لو احتجنا إرساله أو عرضه، لكن هنا نحن نحتاج المشفر للبحث
|
||||||
// $phone = $encryptionHelper->decryptData($encryptedPhone);
|
// $phone = $encryptionHelper->decryptData($encryptedPhone);
|
||||||
|
|
||||||
// هاش الرمز (OTP) القادم من التطبيق للمقارنة
|
// 3. التحقق من الـ OTP (الهاش محسوب مسبقاً في المتغير $otpHash)
|
||||||
$otpHash = hash('sha256', (string)$otp);
|
|
||||||
|
|
||||||
// 3. التحقق من الـ OTP
|
|
||||||
$stmt = $con->prepare("SELECT * FROM token_verification_admin
|
$stmt = $con->prepare("SELECT * FROM token_verification_admin
|
||||||
WHERE phone_number = ? AND token = ?
|
WHERE phone_number = ? AND token = ?
|
||||||
AND expiration_time >= NOW()");
|
AND expiration_time >= NOW()");
|
||||||
@@ -93,7 +131,7 @@ try {
|
|||||||
"expires_in" => 3600
|
"expires_in" => 3600
|
||||||
]);
|
]);
|
||||||
|
|
||||||
} catch (Exception $e) {
|
} catch (Throwable $e) {
|
||||||
error_log("[Admin Verify OTP Error] " . $e->getMessage());
|
error_log("[Admin Verify OTP Error] " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString());
|
||||||
jsonError("An internal error occurred. Please try again later.");
|
jsonError("Server Error: " . $e->getMessage() . " on line " . $e->getLine());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,15 +33,20 @@ SELECT
|
|||||||
-- كانت تُنتج متوسط مدة سالباً.
|
-- كانت تُنتج متوسط مدة سالباً.
|
||||||
(SELECT TIME_FORMAT(SEC_TO_TIME(AVG(TIMESTAMPDIFF(SECOND, rideTimeStart, rideTimeFinish))), '%Hh %im') FROM ride WHERE rideTimeStart IS NOT NULL AND rideTimeFinish IS NOT NULL AND TIMESTAMPDIFF(SECOND, rideTimeStart, rideTimeFinish) > 0) AS driver_avg_duration,
|
(SELECT TIME_FORMAT(SEC_TO_TIME(AVG(TIMESTAMPDIFF(SECOND, rideTimeStart, rideTimeFinish))), '%Hh %im') FROM ride WHERE rideTimeStart IS NOT NULL AND rideTimeFinish IS NOT NULL AND TIMESTAMPDIFF(SECOND, rideTimeStart, rideTimeFinish) > 0) AS driver_avg_duration,
|
||||||
(SELECT MAX(SEC_TO_TIME(TIMESTAMPDIFF(SECOND, rideTimeStart, rideTimeFinish))) FROM ride WHERE rideTimeStart IS NOT NULL AND rideTimeFinish IS NOT NULL) AS longest_duration,
|
(SELECT MAX(SEC_TO_TIME(TIMESTAMPDIFF(SECOND, rideTimeStart, rideTimeFinish))) FROM ride WHERE rideTimeStart IS NOT NULL AND rideTimeFinish IS NOT NULL) AS longest_duration,
|
||||||
(SELECT ROUND(SUM(distance),2) FROM ride) AS total_distance,
|
-- المسافات تُحسب على الرحلات المكتملة فقط. حسابها على كل الصفوف كان
|
||||||
(SELECT ROUND(AVG(distance),2) FROM ride) AS average_distance,
|
-- يُدخل الرحلات الملغاة و timeout (مسافتها 0 أو غير مضبوطة) في المتوسط
|
||||||
(SELECT ROUND(MAX(distance),2) FROM ride) AS longest_distance,
|
-- فيهبط average_distance بشكل مضلّل.
|
||||||
|
(SELECT ROUND(SUM(distance),2) FROM ride WHERE LOWER(status) IN ('finished','completed')) AS total_distance,
|
||||||
|
(SELECT ROUND(AVG(distance),2) FROM ride WHERE LOWER(status) IN ('finished','completed') AND distance > 0) AS average_distance,
|
||||||
|
(SELECT ROUND(MAX(distance),2) FROM ride WHERE LOWER(status) IN ('finished','completed')) AS longest_distance,
|
||||||
|
|
||||||
-- أرباح السائق والشركة
|
-- أرباح السائق والشركة
|
||||||
-- ملاحظة: خط الرحلات الحالي يكتب 'completed' بينما القديم يكتب 'Finished'،
|
-- ملاحظة: خط الرحلات الحالي يكتب 'completed' بينما القديم يكتب 'Finished'،
|
||||||
-- والاكتفاء بالقديم كان يُرجع NULL للأرباح وصفراً للرحلات المكتملة/الملغاة.
|
-- والاكتفاء بالقديم كان يُرجع NULL للأرباح وصفراً للرحلات المكتملة/الملغاة.
|
||||||
(SELECT SUM(price_for_driver) FROM ride WHERE LOWER(status) IN ('finished','completed')) AS total_driver_earnings,
|
(SELECT SUM(price_for_driver) FROM ride WHERE LOWER(status) IN ('finished','completed')) AS total_driver_earnings,
|
||||||
(SELECT ROUND(AVG(price_for_passenger),2) FROM ride) AS avg_passenger_price,
|
-- متوسط سعر الراكب على الرحلات المكتملة فقط — الرحلات الملغاة سعرها 0
|
||||||
|
-- وكانت تسحب المتوسط إلى أسفل.
|
||||||
|
(SELECT ROUND(AVG(price_for_passenger),2) FROM ride WHERE LOWER(status) IN ('finished','completed') AND price_for_passenger > 0) AS avg_passenger_price,
|
||||||
|
|
||||||
-- توزيع الرحلات حسب الوقت
|
-- توزيع الرحلات حسب الوقت
|
||||||
(SELECT COUNT(*) FROM ride WHERE HOUR(created_at) BETWEEN 6 AND 11) AS morning_ride_count,
|
(SELECT COUNT(*) FROM ride WHERE HOUR(created_at) BETWEEN 6 AND 11) AS morning_ride_count,
|
||||||
@@ -54,12 +59,20 @@ SELECT
|
|||||||
(SELECT COUNT(*) FROM ride WHERE carType = 'Lady') AS lady,
|
(SELECT COUNT(*) FROM ride WHERE carType = 'Lady') AS lady,
|
||||||
|
|
||||||
-- حالة الرحلات (تغطي عائلتي الحالات: القديمة CamelCase والجديدة lowercase)
|
-- حالة الرحلات (تغطي عائلتي الحالات: القديمة CamelCase والجديدة lowercase)
|
||||||
(SELECT COUNT(*) FROM ride WHERE LOWER(status) IN ('wait','waiting','new','nothing','pending','searching')) AS ongoing_rides,
|
-- الحالات الفعلية في قاعدة الإنتاج (فحص 2026-08-03): nothing 930،
|
||||||
|
-- Begin 624، start 170، waiting 2. كانت Begin و start خارج كل الدلاء
|
||||||
|
-- الثلاثة، أي أن 794 رحلة (46% من الإجمالي) لا تظهر في أي إحصائية.
|
||||||
|
-- 'جارية' تشمل المنتظرة للسائق والمنفَّذة فعلياً معاً.
|
||||||
|
(SELECT COUNT(*) FROM ride WHERE LOWER(status) IN
|
||||||
|
('wait','waiting','new','nothing','pending','searching',
|
||||||
|
'begin','start','arrived','apply')) AS ongoing_rides,
|
||||||
(SELECT COUNT(*) FROM ride WHERE LOWER(status) IN ('finished','completed')) AS completed_rides,
|
(SELECT COUNT(*) FROM ride WHERE LOWER(status) IN ('finished','completed')) AS completed_rides,
|
||||||
(SELECT COUNT(*) FROM ride WHERE LOWER(status) LIKE 'cancel%' OR LOWER(status) IN ('timeout','refused')) AS cancelled_rides,
|
(SELECT COUNT(*) FROM ride WHERE LOWER(status) LIKE 'cancel%' OR LOWER(status) IN ('timeout','refused')) AS cancelled_rides,
|
||||||
|
|
||||||
-- عدد السائقين الفريدين
|
-- عدد السائقين الفريدين
|
||||||
(SELECT COUNT(*) FROM (SELECT driver_id FROM ride GROUP BY driver_id) AS sub) AS num_Driver,
|
-- cancel_ride_by_driver.php يضبط driver_id = 0 عند الإلغاء، وكان هذا
|
||||||
|
-- الصفر يُحتسب سائقاً وهمياً إضافياً في العدد.
|
||||||
|
(SELECT COUNT(DISTINCT driver_id) FROM ride WHERE driver_id > 0) AS num_Driver,
|
||||||
|
|
||||||
-- التحويلات البنكية
|
-- التحويلات البنكية
|
||||||
0 AS transfer_from_count
|
0 AS transfer_from_count
|
||||||
|
|||||||
@@ -9,18 +9,34 @@ if (empty($phone)) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// تشفير الرقم المدخل للبحث
|
/**
|
||||||
$encPhone = $encryptionHelper->encryptData($phone);
|
* البحث عبر الفهرس الأعمى أولاً (phone_bidx): مطابقة تامة عبر فهرس مُهيأ
|
||||||
|
* ولا تعتمد على كون التشفير حتمياً، فتظل تعمل بعد النقل إلى AES-GCM.
|
||||||
|
*
|
||||||
|
* يُبقى المسار القديم (مقارنة النص المشفّر) كاحتياط حتى ينتهي تشغيل
|
||||||
|
* scripts/backfill_blind_index.php، وإلا لتوقّف البحث بين الترحيل والتعبئة.
|
||||||
|
*/
|
||||||
|
global $blindIndex;
|
||||||
|
$driver = null;
|
||||||
|
|
||||||
// احضار كل الأعمدة باستثناء كلمة المرور
|
if ($blindIndex) {
|
||||||
$sql = "SELECT *
|
$bidx = $blindIndex->index('driver.phone', $phone);
|
||||||
FROM driver
|
if ($bidx) {
|
||||||
WHERE phone = :phone
|
$stmt = $con->prepare("SELECT * FROM driver WHERE phone_bidx = :bidx LIMIT 1");
|
||||||
LIMIT 1";
|
$stmt->execute([':bidx' => $bidx]);
|
||||||
$stmt = $con->prepare($sql);
|
$driver = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
|
||||||
$stmt->execute([':phone' => $encPhone]);
|
}
|
||||||
|
}
|
||||||
|
|
||||||
$driver = $stmt->fetch(PDO::FETCH_ASSOC);
|
if (!$driver) {
|
||||||
|
$encPhone = $encryptionHelper->encryptData($phone);
|
||||||
|
$stmt = $con->prepare("SELECT * FROM driver WHERE phone = :phone LIMIT 1");
|
||||||
|
$stmt->execute([':phone' => $encPhone]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$driver) {
|
||||||
|
$driver = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||||
|
}
|
||||||
|
|
||||||
if ($driver) {
|
if ($driver) {
|
||||||
// ✅ الحقول المشفرة اللي لازم تنفك:
|
// ✅ الحقول المشفرة اللي لازم تنفك:
|
||||||
|
|||||||
@@ -24,6 +24,13 @@ if ($phone !== null && $phone !== '') {
|
|||||||
$encphone = $encryptionHelper->encryptData($phone);
|
$encphone = $encryptionHelper->encryptData($phone);
|
||||||
$updateFields[] = "`phone` = :phone";
|
$updateFields[] = "`phone` = :phone";
|
||||||
$params[':phone'] = $encphone;
|
$params[':phone'] = $encphone;
|
||||||
|
|
||||||
|
// الفهرس يُحدَّث مع الرقم نفسه حتى لا يشير إلى القيمة القديمة
|
||||||
|
global $blindIndex;
|
||||||
|
if ($blindIndex) {
|
||||||
|
$updateFields[] = "`phone_bidx` = :phone_bidx";
|
||||||
|
$params[':phone_bidx'] = $blindIndex->index('driver.phone', $phone);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($status !== null && $status !== '') {
|
if ($status !== null && $status !== '') {
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
<?php
|
||||||
|
// Admin/fuel/drawdowns.php — حركة القسائم وملخّص الائتمان
|
||||||
|
// POST (اختياري): station_id, status, driver_id, limit
|
||||||
|
//
|
||||||
|
// الشاشة التي تُجيب: كم أقرضنا؟ كم استُرد؟ وأي محطة تعمل؟
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
|
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||||
|
jsonError('Unauthorized: Admin access required', 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
$stationId = (int) (filterRequest('station_id', 'int') ?: 0);
|
||||||
|
$status = filterRequest('status');
|
||||||
|
$driverId = filterRequest('driver_id');
|
||||||
|
$limit = (int) (filterRequest('limit', 'int') ?: 100);
|
||||||
|
$limit = max(1, min($limit, 500));
|
||||||
|
|
||||||
|
$where = [];
|
||||||
|
$params = [];
|
||||||
|
|
||||||
|
if ($stationId > 0) {
|
||||||
|
$where[] = 'v.station_id = ?';
|
||||||
|
$params[] = $stationId;
|
||||||
|
}
|
||||||
|
if (!empty($status)) {
|
||||||
|
$where[] = 'v.status = ?';
|
||||||
|
$params[] = $status;
|
||||||
|
}
|
||||||
|
if (!empty($driverId)) {
|
||||||
|
$where[] = 'v.driver_id = ?';
|
||||||
|
$params[] = $driverId;
|
||||||
|
}
|
||||||
|
|
||||||
|
$clause = $where ? 'WHERE ' . implode(' AND ', $where) : '';
|
||||||
|
|
||||||
|
try {
|
||||||
|
$st = $con->prepare("
|
||||||
|
SELECT v.id, v.driver_id, v.code, v.amount_authorized, v.amount_redeemed,
|
||||||
|
v.currency, v.status, v.expires_at, v.redeemed_at, v.created_at,
|
||||||
|
s.name_ar AS station_name
|
||||||
|
FROM fuel_vouchers v
|
||||||
|
LEFT JOIN fuel_stations s ON s.id = v.station_id
|
||||||
|
$clause
|
||||||
|
ORDER BY v.id DESC
|
||||||
|
LIMIT $limit
|
||||||
|
");
|
||||||
|
$st->execute($params);
|
||||||
|
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
|
// الملخّص على كامل المنتج لا على الصفحة المعروضة: رقمٌ يتغيّر بتغيّر
|
||||||
|
// الفلتر يُقرأ كأنه حقيقة عن المنصة وهو ليس كذلك.
|
||||||
|
$summary = $con->query("
|
||||||
|
SELECT
|
||||||
|
COALESCE(SUM(amount), 0) AS lent_total,
|
||||||
|
COALESCE(SUM(amount_collected), 0) AS collected_total,
|
||||||
|
COALESCE(SUM(amount_remaining), 0) AS outstanding_total,
|
||||||
|
COUNT(DISTINCT driver_id) AS drivers_count
|
||||||
|
FROM obligation_ledger
|
||||||
|
WHERE product_code = 'fuel_wallet'
|
||||||
|
")->fetch(PDO::FETCH_ASSOC) ?: [];
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log('[admin/fuel/drawdowns] ' . $e->getMessage());
|
||||||
|
jsonError('Server error', 500);
|
||||||
|
}
|
||||||
|
|
||||||
|
$vouchers = array_map(static fn(array $r): array => [
|
||||||
|
'id' => (int) $r['id'],
|
||||||
|
'driver_id' => $r['driver_id'],
|
||||||
|
'code' => $r['code'],
|
||||||
|
'amount_authorized' => (float) $r['amount_authorized'],
|
||||||
|
'amount_redeemed' => (float) $r['amount_redeemed'],
|
||||||
|
'currency' => $r['currency'],
|
||||||
|
'status' => $r['status'],
|
||||||
|
'station' => $r['station_name'],
|
||||||
|
'expires_at' => $r['expires_at'],
|
||||||
|
'redeemed_at' => $r['redeemed_at'],
|
||||||
|
'created_at' => $r['created_at'],
|
||||||
|
], $rows);
|
||||||
|
|
||||||
|
jsonSuccess([
|
||||||
|
'vouchers' => $vouchers,
|
||||||
|
'summary' => [
|
||||||
|
'lent_total' => (float) ($summary['lent_total'] ?? 0),
|
||||||
|
'collected_total' => (float) ($summary['collected_total'] ?? 0),
|
||||||
|
'outstanding_total' => (float) ($summary['outstanding_total'] ?? 0),
|
||||||
|
'drivers_count' => (int) ($summary['drivers_count'] ?? 0),
|
||||||
|
],
|
||||||
|
], 'success');
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
<?php
|
||||||
|
// Admin/fuel/list.php — قائمة محطات الوقود الشريكة
|
||||||
|
// POST (اختياري): search, city, only_active
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
|
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||||
|
jsonError('Unauthorized: Admin access required', 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
$search = filterRequest('search');
|
||||||
|
$city = filterRequest('city');
|
||||||
|
$onlyActive = filterRequest('only_active') === '1';
|
||||||
|
|
||||||
|
$where = [];
|
||||||
|
$params = [];
|
||||||
|
|
||||||
|
if (!empty($search)) {
|
||||||
|
$where[] = '(s.name_ar LIKE ? OR s.chain_name LIKE ? OR s.address LIKE ?)';
|
||||||
|
$like = '%' . $search . '%';
|
||||||
|
array_push($params, $like, $like, $like);
|
||||||
|
}
|
||||||
|
if (!empty($city)) {
|
||||||
|
$where[] = 's.city = ?';
|
||||||
|
$params[] = $city;
|
||||||
|
}
|
||||||
|
if ($onlyActive) {
|
||||||
|
$where[] = 's.is_active = 1';
|
||||||
|
}
|
||||||
|
|
||||||
|
$clause = $where ? 'WHERE ' . implode(' AND ', $where) : '';
|
||||||
|
|
||||||
|
try {
|
||||||
|
// إحصاء الصرف مع كل محطة: لوحة بلا أرقام لا تخبر أحداً أي محطة
|
||||||
|
// تعمل فعلاً وأيها اسمٌ في جدول. `redeemed` وحدها — القسائم الملغاة
|
||||||
|
// والمنتهية لا تقول شيئاً عن أداء المحطة.
|
||||||
|
$st = $con->prepare("
|
||||||
|
SELECT s.*,
|
||||||
|
COUNT(v.id) AS redeem_count,
|
||||||
|
COALESCE(SUM(v.amount_redeemed), 0) AS redeem_total,
|
||||||
|
MAX(v.redeemed_at) AS last_redeem_at
|
||||||
|
FROM fuel_stations s
|
||||||
|
LEFT JOIN fuel_vouchers v
|
||||||
|
ON v.station_id = s.id AND v.status = 'redeemed'
|
||||||
|
$clause
|
||||||
|
GROUP BY s.id
|
||||||
|
ORDER BY s.is_active DESC, s.city ASC, s.name_ar ASC
|
||||||
|
LIMIT 200
|
||||||
|
");
|
||||||
|
$st->execute($params);
|
||||||
|
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log('[admin/fuel/list] ' . $e->getMessage());
|
||||||
|
jsonError('Server error', 500);
|
||||||
|
}
|
||||||
|
|
||||||
|
$stations = array_map(static fn(array $r): array => [
|
||||||
|
'id' => (int) $r['id'],
|
||||||
|
'name_ar' => $r['name_ar'],
|
||||||
|
'chain_name' => $r['chain_name'],
|
||||||
|
'city' => $r['city'],
|
||||||
|
'address' => $r['address'],
|
||||||
|
'lat' => $r['lat'] !== null ? (float) $r['lat'] : null,
|
||||||
|
'lng' => $r['lng'] !== null ? (float) $r['lng'] : null,
|
||||||
|
'phone' => $r['phone'],
|
||||||
|
'discount_percent' => (float) $r['discount_percent'],
|
||||||
|
'is_active' => (int) $r['is_active'] === 1,
|
||||||
|
'created_at' => $r['created_at'],
|
||||||
|
'redeem_count' => (int) $r['redeem_count'],
|
||||||
|
'redeem_total' => (float) $r['redeem_total'],
|
||||||
|
'last_redeem_at' => $r['last_redeem_at'],
|
||||||
|
// المفتاح لا يخرج أبداً — لا هنا ولا في أي نقطة أخرى. مخزَّن مُهشَّراً
|
||||||
|
// أصلاً، ويُعرض مرة واحدة فقط لحظة إنشائه أو تدويره.
|
||||||
|
], $rows);
|
||||||
|
|
||||||
|
// حالة المنتج تُرسل مع القائمة لا في نقطة منفصلة: الشاشة تحتاج أن تعرض
|
||||||
|
// «مُجهَّز وغير مُشغَّل» بوضوح، وطلبان لبناء لافتة واحدة إسراف.
|
||||||
|
$productActive = false;
|
||||||
|
try {
|
||||||
|
$st = $con->prepare("SELECT is_active FROM obligation_products WHERE code = 'fuel_wallet' LIMIT 1");
|
||||||
|
$st->execute();
|
||||||
|
$productActive = (int) $st->fetchColumn() === 1;
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log('[admin/fuel/list] تعذّرت قراءة حالة المنتج: ' . $e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
jsonSuccess([
|
||||||
|
'stations' => $stations,
|
||||||
|
'product_active' => $productActive,
|
||||||
|
], 'success');
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
<?php
|
||||||
|
// Admin/fuel/rotate_key.php — توليد مفتاح جديد لمحطة
|
||||||
|
// POST: station_id
|
||||||
|
//
|
||||||
|
// يُستعمل عند فقدان المحطة مفتاحها أو الشك في تسريبه. المفتاح القديم
|
||||||
|
// يتوقّف فوراً — وهذا مقصود: التدوير إجراء أمني، وإبقاء القديم يعمل
|
||||||
|
// «حتى تنتقل المحطة» يُفرغه من معناه.
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
|
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||||
|
jsonError('Unauthorized: Admin access required', 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
$stationId = (int) (filterRequest('station_id', 'int') ?: 0);
|
||||||
|
if ($stationId <= 0) {
|
||||||
|
jsonError('station_id مطلوب');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$st = $con->prepare("SELECT name_ar FROM fuel_stations WHERE id = ? LIMIT 1");
|
||||||
|
$st->execute([$stationId]);
|
||||||
|
$name = $st->fetchColumn();
|
||||||
|
|
||||||
|
if ($name === false) {
|
||||||
|
jsonError('المحطة غير موجودة', 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
$plainKey = bin2hex(random_bytes(24));
|
||||||
|
|
||||||
|
$con->prepare("UPDATE fuel_stations SET api_key_hash = ? WHERE id = ?")
|
||||||
|
->execute([hash('sha256', $plainKey), $stationId]);
|
||||||
|
|
||||||
|
error_log("[admin/fuel] دُوِّر مفتاح المحطة #$stationId بواسطة $user_id");
|
||||||
|
|
||||||
|
jsonSuccess([
|
||||||
|
'station_id' => $stationId,
|
||||||
|
'station' => $name,
|
||||||
|
'api_key' => $plainKey,
|
||||||
|
], 'المفتاح القديم توقّف. انسخ الجديد الآن — لن يظهر مرة أخرى.');
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log('[admin/fuel/rotate_key] ' . $e->getMessage());
|
||||||
|
jsonError('Server error', 500);
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
<?php
|
||||||
|
// Admin/fuel/save.php — إضافة محطة أو تعديلها
|
||||||
|
// POST: station_id (اختياري للتعديل), name_ar, chain_name, city, address,
|
||||||
|
// lat, lng, phone, discount_percent, is_active
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
|
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||||
|
jsonError('Unauthorized: Admin access required', 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
$stationId = (int) (filterRequest('station_id', 'int') ?: 0);
|
||||||
|
$nameAr = filterRequest('name_ar');
|
||||||
|
|
||||||
|
if (empty($nameAr)) {
|
||||||
|
jsonError('اسم المحطة مطلوب');
|
||||||
|
}
|
||||||
|
|
||||||
|
$discount = (float) (filterRequest('discount_percent', 'numeric') ?: 0);
|
||||||
|
if ($discount < 0 || $discount > 100) {
|
||||||
|
jsonError('نسبة الخصم يجب أن تكون بين 0 و 100');
|
||||||
|
}
|
||||||
|
|
||||||
|
$lat = filterRequest('lat', 'numeric');
|
||||||
|
$lng = filterRequest('lng', 'numeric');
|
||||||
|
|
||||||
|
$fields = [
|
||||||
|
'name_ar' => $nameAr,
|
||||||
|
'chain_name' => filterRequest('chain_name'),
|
||||||
|
'city' => filterRequest('city'),
|
||||||
|
'address' => filterRequest('address'),
|
||||||
|
'lat' => $lat !== null ? (float) $lat : null,
|
||||||
|
'lng' => $lng !== null ? (float) $lng : null,
|
||||||
|
'phone' => filterRequest('phone'),
|
||||||
|
'discount_percent' => $discount,
|
||||||
|
'is_active' => filterRequest('is_active') === '0' ? 0 : 1,
|
||||||
|
];
|
||||||
|
|
||||||
|
try {
|
||||||
|
if ($stationId > 0) {
|
||||||
|
$sets = implode(', ', array_map(static fn($k) => "`$k` = ?", array_keys($fields)));
|
||||||
|
|
||||||
|
$st = $con->prepare("UPDATE fuel_stations SET $sets WHERE id = ?");
|
||||||
|
$st->execute([...array_values($fields), $stationId]);
|
||||||
|
|
||||||
|
if ($st->rowCount() === 0) {
|
||||||
|
// rowCount صفر قد يعني «غير موجودة» وقد يعني «حُفظت بلا تغيير».
|
||||||
|
// نفرّق بينهما بقراءة صريحة: إخبار المستخدم أن المحطة غير
|
||||||
|
// موجودة بينما هي موجودة يدفعه لإنشاء نسخة ثانية منها.
|
||||||
|
$chk = $con->prepare("SELECT 1 FROM fuel_stations WHERE id = ? LIMIT 1");
|
||||||
|
$chk->execute([$stationId]);
|
||||||
|
if (!$chk->fetchColumn()) {
|
||||||
|
jsonError('المحطة غير موجودة', 404);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
error_log("[admin/fuel] عُدّلت المحطة #$stationId بواسطة $user_id");
|
||||||
|
|
||||||
|
jsonSuccess(['station_id' => $stationId, 'created' => false], 'تم حفظ التعديلات');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── إنشاء جديد ──
|
||||||
|
// المفتاح يُولَّد هنا ولا يُطلب من المستخدم: مفتاح يختاره إنسان يكون
|
||||||
|
// قصيراً ومتوقَّعاً، وهذا المفتاح يأذن بصرف مال.
|
||||||
|
$plainKey = bin2hex(random_bytes(24));
|
||||||
|
|
||||||
|
$cols = array_keys($fields);
|
||||||
|
$st = $con->prepare(
|
||||||
|
'INSERT INTO fuel_stations (`' . implode('`, `', $cols) . '`, `api_key_hash`) '
|
||||||
|
. 'VALUES (' . implode(', ', array_fill(0, count($cols), '?')) . ', ?)'
|
||||||
|
);
|
||||||
|
$st->execute([...array_values($fields), hash('sha256', $plainKey)]);
|
||||||
|
|
||||||
|
$stationId = (int) $con->lastInsertId();
|
||||||
|
|
||||||
|
error_log("[admin/fuel] أُنشئت المحطة #$stationId بواسطة $user_id");
|
||||||
|
|
||||||
|
jsonSuccess([
|
||||||
|
'station_id' => $stationId,
|
||||||
|
'created' => true,
|
||||||
|
// المرة **الوحيدة** التي يظهر فيها المفتاح. مخزَّن مُهشَّراً، فلا
|
||||||
|
// سبيل لاستعادته لاحقاً — من يفقده يدوّر مفتاحاً جديداً.
|
||||||
|
'api_key' => $plainKey,
|
||||||
|
], 'أُنشئت المحطة. انسخ المفتاح الآن — لن يظهر مرة أخرى.');
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log('[admin/fuel/save] ' . $e->getMessage());
|
||||||
|
jsonError('Server error', 500);
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
<?php
|
||||||
|
// Admin/fuel/toggle_product.php — تشغيل محفظة الوقود أو إيقافها
|
||||||
|
// POST: is_active (1 | 0)
|
||||||
|
//
|
||||||
|
// قرار المالك: تُبنى الشاشات وتُجهَّز الأمور، ولا يُشغَّل المنتج إلا بعد
|
||||||
|
// إتمام الاتفاق مع سلسلة المحطات. هذه هي نقطة ذلك التبديل.
|
||||||
|
//
|
||||||
|
// ما الذي يتغيّر فعلاً؟ المنتج المُطفأ لا يظهر في `obligationProduct`،
|
||||||
|
// فلا يستطيع سائق تفعيل محفظته ولا إصدار قسيمة. أما الالتزامات القائمة
|
||||||
|
// ودفترها فلا تتأثر — الإطفاء يغلق الباب ولا يمحو ما خلفه.
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
|
// super_admin وحده. تشغيل المنتج يفتح باب إقراض حقيقي بمال الشركة،
|
||||||
|
// وهو قرار مالك لا قرار مناوب على اللوحة.
|
||||||
|
if ($role !== 'super_admin') {
|
||||||
|
jsonError('Unauthorized: Super admin access required', 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
$isActive = filterRequest('is_active') === '1' ? 1 : 0;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// التشغيل بلا محطة واحدة فعّالة يعني سائقاً يفعّل محفظته، يطلب
|
||||||
|
// قسيمة، ثم لا يجد أين يصرفها. الرفض هنا أرحم من اكتشافه عند مضخة.
|
||||||
|
if ($isActive === 1) {
|
||||||
|
$st = $con->query("SELECT COUNT(*) FROM fuel_stations WHERE is_active = 1");
|
||||||
|
if ((int) $st->fetchColumn() === 0) {
|
||||||
|
jsonError('لا توجد محطة فعّالة واحدة. أضف محطة قبل تشغيل المنتج.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$st = $con->prepare("UPDATE obligation_products SET is_active = ? WHERE code = 'fuel_wallet'");
|
||||||
|
$st->execute([$isActive]);
|
||||||
|
|
||||||
|
if ($st->rowCount() === 0) {
|
||||||
|
$chk = $con->query("SELECT 1 FROM obligation_products WHERE code = 'fuel_wallet' LIMIT 1");
|
||||||
|
if (!$chk->fetchColumn()) {
|
||||||
|
jsonError('منتج محفظة الوقود غير موجود — نفّذ الترحيل أولاً', 404);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
error_log('[admin/fuel] ' . ($isActive ? 'شُغّلت' : 'أُوقفت') . " محفظة الوقود بواسطة $user_id");
|
||||||
|
|
||||||
|
jsonSuccess(
|
||||||
|
['product_active' => $isActive === 1],
|
||||||
|
$isActive === 1
|
||||||
|
? 'شُغّلت محفظة الوقود — صارت متاحة للسائقين المؤهَّلين'
|
||||||
|
: 'أُوقفت محفظة الوقود — لا تفعيل جديد ولا قسائم جديدة'
|
||||||
|
);
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log('[admin/fuel/toggle_product] ' . $e->getMessage());
|
||||||
|
jsonError('Server error', 500);
|
||||||
|
}
|
||||||
@@ -1,6 +1,19 @@
|
|||||||
<?php
|
<?php
|
||||||
require_once __DIR__ . '/../connect.php';
|
require_once __DIR__ . '/../connect.php';
|
||||||
|
|
||||||
|
// هذه النقطة تُرجع بيانات ركّاب مفكوكة التشفير (هاتف، بريد، تاريخ ميلاد،
|
||||||
|
// هاتف طوارئ، وتوكن إشعارات). لم يكن فيها أي فحص للدور، و connect.php لا
|
||||||
|
// يفرض بوّابة عامة على مسار /Admin — أي أن أي مستخدم يملك JWT صالحاً، بما
|
||||||
|
// فيه راكب عادي، كان يستطيع سحب هذه البيانات كاملة.
|
||||||
|
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||||
|
http_response_code(403);
|
||||||
|
echo json_encode([
|
||||||
|
'status' => 'failure',
|
||||||
|
'message' => 'Forbidden. Admin access required.',
|
||||||
|
], JSON_UNESCAPED_UNICODE);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
$sql = "SELECT
|
$sql = "SELECT
|
||||||
`passengers`.`id`,
|
`passengers`.`id`,
|
||||||
`passengers`.`phone`,
|
`passengers`.`phone`,
|
||||||
@@ -91,6 +104,21 @@ foreach ($result as &$row) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
unset($row);
|
||||||
|
|
||||||
|
// نموذج الصلاحيات: `super_admin` وحده يرى الرقم كاملاً، و`admin` يراقب برقم
|
||||||
|
// مُخفى جزئياً. توكن الإشعارات لا تعرضه الواجهة إطلاقاً ولا حاجة لإرساله —
|
||||||
|
// تسريبه يتيح انتحال إشعارات موجّهة لراكب بعينه.
|
||||||
|
$isSuperAdmin = ($role === 'super_admin');
|
||||||
|
foreach ($result as &$row) {
|
||||||
|
unset($row['passengerToken']);
|
||||||
|
|
||||||
|
if (!$isSuperAdmin) {
|
||||||
|
if (isset($row['phone'])) $row['phone'] = maskPhone($row['phone']);
|
||||||
|
if (isset($row['sosPhone'])) $row['sosPhone'] = maskPhone($row['sosPhone']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unset($row);
|
||||||
|
|
||||||
if ($stmt->rowCount() > 0) {
|
if ($stmt->rowCount() > 0) {
|
||||||
jsonSuccess($data = $result);
|
jsonSuccess($data = $result);
|
||||||
|
|||||||
@@ -1,6 +1,18 @@
|
|||||||
<?php
|
<?php
|
||||||
require_once __DIR__ . '/../connect.php';
|
require_once __DIR__ . '/../connect.php';
|
||||||
|
|
||||||
|
// نقطة تُرجع بيانات راكب مفكوكة التشفير. connect.php لا يفرض بوّابة عامة
|
||||||
|
// على مسار /Admin، فبدون هذا الفحص كان أي مستخدم يملك JWT صالحاً — بما فيه
|
||||||
|
// راكب عادي — يستطيع استعلام بيانات أي راكب آخر.
|
||||||
|
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||||
|
http_response_code(403);
|
||||||
|
echo json_encode([
|
||||||
|
'status' => 'failure',
|
||||||
|
'message' => 'Forbidden. Admin access required.',
|
||||||
|
], JSON_UNESCAPED_UNICODE);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
$passengerID = filterRequest("passengerID");
|
$passengerID = filterRequest("passengerID");
|
||||||
|
|
||||||
$sql = "SELECT
|
$sql = "SELECT
|
||||||
|
|||||||
@@ -1,10 +1,31 @@
|
|||||||
<?php
|
<?php
|
||||||
require_once __DIR__ . '/../connect.php';
|
require_once __DIR__ . '/../connect.php';
|
||||||
|
|
||||||
|
// نقطة تُرجع بيانات راكب مفكوكة التشفير. connect.php لا يفرض بوّابة عامة
|
||||||
|
// على مسار /Admin، فبدون هذا الفحص كان أي مستخدم يملك JWT صالحاً — بما فيه
|
||||||
|
// راكب عادي — يستطيع استعلام بيانات أي راكب آخر.
|
||||||
|
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||||
|
http_response_code(403);
|
||||||
|
echo json_encode([
|
||||||
|
'status' => 'failure',
|
||||||
|
'message' => 'Forbidden. Admin access required.',
|
||||||
|
], JSON_UNESCAPED_UNICODE);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
$passengerEmail = $encryptionHelper->encryptData(filterRequest("passengerEmail"));
|
$passengerEmail = $encryptionHelper->encryptData(filterRequest("passengerEmail"));
|
||||||
$passengerId = filterRequest("passengerId");
|
$passengerId = filterRequest("passengerId");
|
||||||
$passengerphone = $encryptionHelper->encryptData(filterRequest("passengerphone"));
|
$passengerphone = $encryptionHelper->encryptData(filterRequest("passengerphone"));
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* الفهرس الأعمى: يسمح بالبحث بعد نقل التخزين إلى AES-GCM العشوائي.
|
||||||
|
* تُبقى المقارنة القديمة في نفس الاستعلام كاحتياط حتى تنتهي تعبئة الفهارس.
|
||||||
|
*/
|
||||||
|
global $blindIndex;
|
||||||
|
$emailBidx = $blindIndex ? $blindIndex->index('passengers.email', filterRequest("passengerEmail")) : null;
|
||||||
|
$phoneBidx = $blindIndex ? $blindIndex->index('passengers.phone', filterRequest("passengerphone")) : null;
|
||||||
|
|
||||||
$sql = "SELECT
|
$sql = "SELECT
|
||||||
`passengers`.`id`,
|
`passengers`.`id`,
|
||||||
`passengers`.`phone`,
|
`passengers`.`phone`,
|
||||||
@@ -59,12 +80,16 @@ FROM
|
|||||||
`passengers`
|
`passengers`
|
||||||
WHERE
|
WHERE
|
||||||
passengers.email = :email OR passengers.phone = :phone OR passengers.id = :id
|
passengers.email = :email OR passengers.phone = :phone OR passengers.id = :id
|
||||||
|
OR (:email_bidx IS NOT NULL AND passengers.email_bidx = :email_bidx)
|
||||||
|
OR (:phone_bidx IS NOT NULL AND passengers.phone_bidx = :phone_bidx)
|
||||||
";
|
";
|
||||||
|
|
||||||
$stmt = $con->prepare($sql);
|
$stmt = $con->prepare($sql);
|
||||||
$stmt->bindParam(":email", $passengerEmail);
|
$stmt->bindParam(":email", $passengerEmail);
|
||||||
$stmt->bindParam(":phone", $passengerphone);
|
$stmt->bindParam(":phone", $passengerphone);
|
||||||
$stmt->bindParam(":id", $passengerId);
|
$stmt->bindParam(":id", $passengerId);
|
||||||
|
$stmt->bindParam(":email_bidx", $emailBidx);
|
||||||
|
$stmt->bindParam(":phone_bidx", $phoneBidx);
|
||||||
$stmt->execute();
|
$stmt->execute();
|
||||||
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
|
|||||||
@@ -6,14 +6,11 @@
|
|||||||
require_once __DIR__ . '/../core/bootstrap.php';
|
require_once __DIR__ . '/../core/bootstrap.php';
|
||||||
|
|
||||||
header('Content-Type: application/json');
|
header('Content-Type: application/json');
|
||||||
header("Access-Control-Allow-Origin: https://siromove.com");
|
|
||||||
header("Access-Control-Allow-Methods: POST, OPTIONS");
|
|
||||||
header("Access-Control-Allow-Headers: Content-Type, Authorization");
|
|
||||||
|
|
||||||
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
|
||||||
http_response_code(200);
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Rate Limiting ───────────────────────────────────────────
|
// ── Rate Limiting ───────────────────────────────────────────
|
||||||
$limiter = new RateLimiter($redis);
|
$limiter = new RateLimiter($redis);
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
// ============================================================
|
||||||
|
// Admin/marketing/get_social_reports.php
|
||||||
|
// تقارير الذكاء الاجتماعي للوحة التحكم
|
||||||
|
// ============================================================
|
||||||
|
//
|
||||||
|
// لماذا نقطة جديدة بدل استعمال marketing_engine/index.php?action=get_reports:
|
||||||
|
//
|
||||||
|
// • تلك نقطة **البوت** لا نقطة إدارية: تُصادَق بترويسة X-Bot-Token
|
||||||
|
// المخبوزة في APK، وتخدم طابور المهام. استعمالها من اللوحة يعني إما
|
||||||
|
// تسريب توكن البوت إلى المتصفح، أو إبقاء النقطة مفتوحة للجميع —
|
||||||
|
// وقد كانت مفتوحة فعلاً حتى فُعّلت المصادقة، فصارت تُرجع 401 للّوحة.
|
||||||
|
//
|
||||||
|
// • الشاشة كانت تستدعيها بـ http.get الخام بلا JWT ولا X-Device-FP،
|
||||||
|
// فلا تظهر في سجل CRUD ولا تخضع لأي تحقّق صلاحيات.
|
||||||
|
//
|
||||||
|
// هذه النقطة تحت /Admin فتغطّيها البوّابة الافتراضية في connect.php.
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
|
try {
|
||||||
|
$limit = (int) (filterRequest('limit', 'int') ?? 50);
|
||||||
|
$limit = max(1, min(200, $limit));
|
||||||
|
|
||||||
|
// is_weekly=1 لتقارير الأسبوع فقط، أو 0 للحظية، أو تُترك فارغة للكل
|
||||||
|
$weeklyOnly = filterRequest('weekly');
|
||||||
|
|
||||||
|
$where = '';
|
||||||
|
$params = [];
|
||||||
|
if ($weeklyOnly !== null && $weeklyOnly !== '') {
|
||||||
|
$where = 'WHERE is_weekly = :weekly';
|
||||||
|
$params[':weekly'] = ((string) $weeklyOnly === '1') ? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
$stmt = $con->prepare("
|
||||||
|
SELECT id, platform, report_html, is_weekly, created_at
|
||||||
|
FROM marketing_reports
|
||||||
|
$where
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
LIMIT $limit
|
||||||
|
");
|
||||||
|
$stmt->execute($params);
|
||||||
|
$reports = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
|
foreach ($reports as &$r) {
|
||||||
|
$r['id'] = (int) $r['id'];
|
||||||
|
$r['is_weekly'] = (int) $r['is_weekly'] === 1;
|
||||||
|
}
|
||||||
|
unset($r);
|
||||||
|
|
||||||
|
jsonSuccess($reports);
|
||||||
|
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
// الجدول قد يكون غير موجود على نشر لم يُطبَّق عليه الترحيل
|
||||||
|
// 2026_08_03_create_marketing_engine_tables.sql — نُبلغ بوضوح بدل
|
||||||
|
// إرجاع خطأ عام يُقرأ كـ "لا بيانات".
|
||||||
|
error_log('[get_social_reports] ' . $e->getMessage());
|
||||||
|
jsonError('تعذّر جلب تقارير الذكاء الاجتماعي. راجع سجل الخادم.', 500);
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
require_once __DIR__ . '/../core/bootstrap.php';
|
||||||
|
|
||||||
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
|
|
||||||
|
// Simple mocking / getting of real data if possible
|
||||||
|
$cpuLoad = sys_getloadavg();
|
||||||
|
$load1m = $cpuLoad ? $cpuLoad[0] : 0.5;
|
||||||
|
$cores = 4; // Mock or try to read from /proc/cpuinfo
|
||||||
|
$cpuPercent = min(100, ($load1m / $cores) * 100);
|
||||||
|
|
||||||
|
$freeDisk = disk_free_space("/");
|
||||||
|
$totalDisk = disk_total_space("/");
|
||||||
|
$usedDisk = $totalDisk - $freeDisk;
|
||||||
|
$diskPercent = ($usedDisk / $totalDisk) * 100;
|
||||||
|
|
||||||
|
// Dummy Memory (PHP can't natively read total system memory cross-platform easily without exec)
|
||||||
|
$memTotalGb = 16.0;
|
||||||
|
$memUsedGb = 8.4;
|
||||||
|
$memPercent = ($memUsedGb / $memTotalGb) * 100;
|
||||||
|
|
||||||
|
$response = [
|
||||||
|
'cpu' => [
|
||||||
|
'percent' => round($cpuPercent, 2),
|
||||||
|
'cores' => $cores,
|
||||||
|
'load_1m' => round($load1m, 2)
|
||||||
|
],
|
||||||
|
'memory' => [
|
||||||
|
'percent' => round($memPercent, 2),
|
||||||
|
'used_gb' => $memUsedGb,
|
||||||
|
'total_gb' => $memTotalGb
|
||||||
|
],
|
||||||
|
'disk' => [
|
||||||
|
'percent' => round($diskPercent, 2),
|
||||||
|
'used_gb' => round($usedDisk / 1073741824, 2),
|
||||||
|
'total_gb' => round($totalDisk / 1073741824, 2)
|
||||||
|
],
|
||||||
|
'services' => [
|
||||||
|
'Nginx' => 'running',
|
||||||
|
'MySQL' => 'running',
|
||||||
|
'Redis' => 'running',
|
||||||
|
'PHP-FPM' => 'running'
|
||||||
|
],
|
||||||
|
'top_processes' => [
|
||||||
|
['name' => 'mysql', 'usage' => '12.4%'],
|
||||||
|
['name' => 'nginx', 'usage' => '3.1%'],
|
||||||
|
['name' => 'php-fpm', 'usage' => '2.5%'],
|
||||||
|
['name' => 'redis-server', 'usage' => '1.2%']
|
||||||
|
],
|
||||||
|
'network' => [
|
||||||
|
'received_mb' => rand(100, 500) + (rand(0, 99) / 100),
|
||||||
|
'sent_mb' => rand(50, 300) + (rand(0, 99) / 100)
|
||||||
|
],
|
||||||
|
'uptime' => [
|
||||||
|
'formatted' => '12 days, 4 hours, 32 mins'
|
||||||
|
],
|
||||||
|
'timestamp' => date('Y-m-d H:i:s')
|
||||||
|
];
|
||||||
|
|
||||||
|
echo json_encode($response);
|
||||||
@@ -76,7 +76,9 @@ if (function_exists('logAudit')) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// الاستدعاء الداخلي لخدمة FCM
|
// الاستدعاء الداخلي لخدمة FCM
|
||||||
$fcmUrl = getenv('FCM_INTERNAL_URL') ?: 'http://127.0.0.1/backend/ride/firebase/send_fcm.php';
|
// من داخل حاوية php لا يوجد خادم ويب على 127.0.0.1 — الويب في حاوية nginx
|
||||||
|
// منفصلة، وتُعرف داخل شبكة Compose باسم الخدمة. هذا كان سبب فشل كل إشعار.
|
||||||
|
$fcmUrl = getenv('FCM_INTERNAL_URL') ?: 'http://nginx/backend/ride/firebase/send_fcm.php';
|
||||||
$payload = json_encode([
|
$payload = json_encode([
|
||||||
'target' => $topic,
|
'target' => $topic,
|
||||||
'title' => $title,
|
'title' => $title,
|
||||||
@@ -106,8 +108,9 @@ $curlErr = curl_error($ch);
|
|||||||
curl_close($ch);
|
curl_close($ch);
|
||||||
|
|
||||||
if ($response === false || $httpCode >= 400) {
|
if ($response === false || $httpCode >= 400) {
|
||||||
error_log("[Broadcast] FCM call failed (HTTP $httpCode): " . ($curlErr ?: $response));
|
$reason = $curlErr ?: (is_string($response) ? substr($response, 0, 200) : 'no response');
|
||||||
jsonError("Notification service rejected the request (HTTP $httpCode).", 502);
|
error_log("[Broadcast] FCM call failed (HTTP $httpCode) via $fcmUrl: $reason");
|
||||||
|
jsonError("Notification service unreachable at $fcmUrl — $reason", 502);
|
||||||
}
|
}
|
||||||
|
|
||||||
$decoded = json_decode((string) $response, true);
|
$decoded = json_decode((string) $response, true);
|
||||||
|
|||||||
@@ -29,20 +29,20 @@ try {
|
|||||||
$selP = $con->prepare("
|
$selP = $con->prepare("
|
||||||
SELECT id, first_name, last_name, phone
|
SELECT id, first_name, last_name, phone
|
||||||
FROM passengers
|
FROM passengers
|
||||||
WHERE phone = :enc_raw
|
WHERE phone = :enc_raw OR (:bidx IS NOT NULL AND phone_bidx = :bidx)
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
");
|
");
|
||||||
$selP->execute(['enc_raw' => $enc_raw]);
|
$selP->execute(['enc_raw' => $enc_raw, 'bidx' => $pBidx]);
|
||||||
$passenger = $selP->fetch(PDO::FETCH_ASSOC);
|
$passenger = $selP->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
// 2) ابحث عن السائق بالهاتف المشفّر
|
// 2) ابحث عن السائق بالهاتف المشفّر
|
||||||
$selD = $con->prepare("
|
$selD = $con->prepare("
|
||||||
SELECT id AS driverID, first_name, last_name, phone
|
SELECT id AS driverID, first_name, last_name, phone
|
||||||
FROM driver
|
FROM driver
|
||||||
WHERE phone = :enc_raw
|
WHERE phone = :enc_raw OR (:bidx IS NOT NULL AND phone_bidx = :bidx)
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
");
|
");
|
||||||
$selD->execute(['enc_raw' => $enc_raw]);
|
$selD->execute(['enc_raw' => $enc_raw, 'bidx' => $dBidx]);
|
||||||
$driver = $selD->fetch(PDO::FETCH_ASSOC);
|
$driver = $selD->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
$userId = null;
|
$userId = null;
|
||||||
|
|||||||
@@ -6,7 +6,11 @@
|
|||||||
|
|
||||||
require_once __DIR__ . '/../../connect.php'; // تأكد أن هذا الملف يحتوي على $con_tracking
|
require_once __DIR__ . '/../../connect.php'; // تأكد أن هذا الملف يحتوي على $con_tracking
|
||||||
|
|
||||||
header("Access-Control-Allow-Origin: https://siromove.com");
|
// $con_tracking لا يعرّفه connect.php — كان الاستدعاء يسقط بـ
|
||||||
|
// "Call to a member function prepare() on null".
|
||||||
|
$con_tracking = Database::get('tracking');
|
||||||
|
|
||||||
|
|
||||||
header("Content-Type: application/json; charset=UTF-8");
|
header("Content-Type: application/json; charset=UTF-8");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
require_once __DIR__ . '/../../connect.php';
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
header("Access-Control-Allow-Origin: https://siromove.com");
|
|
||||||
header('Content-Type: application/json; charset=utf-8');
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
<?php
|
<?php
|
||||||
require_once __DIR__ . '/../../connect.php';
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
|
// $con_tracking لا يعرّفه connect.php — كان الاستدعاء يسقط بـ
|
||||||
|
// "Call to a member function prepare() on null".
|
||||||
|
$con_tracking = Database::get('tracking');
|
||||||
|
|
||||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||||
http_response_code(403);
|
http_response_code(403);
|
||||||
echo json_encode(['error' => 'Unauthorized: Admin access required']);
|
echo json_encode(['error' => 'Unauthorized: Admin access required']);
|
||||||
@@ -23,16 +27,21 @@ error_log("[MONITOR_RIDE] 1.5 Normalized Phone: " . $phone);
|
|||||||
//------------------------------------------------------------------------
|
//------------------------------------------------------------------------
|
||||||
|
|
||||||
$encPhone = $encryptionHelper->encryptData($phone);
|
$encPhone = $encryptionHelper->encryptData($phone);
|
||||||
|
|
||||||
|
// فهرس البحث لكل جدول على حدة (النطاقات معزولة عمداً)
|
||||||
|
global $blindIndex;
|
||||||
|
$dBidx = $blindIndex ? $blindIndex->index('driver.phone', $phone) : null;
|
||||||
|
$pBidx = $blindIndex ? $blindIndex->index('passengers.phone', $phone) : null;
|
||||||
error_log("[MONITOR_RIDE] 2. Encrypted Phone: " . $encPhone);
|
error_log("[MONITOR_RIDE] 2. Encrypted Phone: " . $encPhone);
|
||||||
|
|
||||||
// Check Driver Table
|
// Check Driver Table
|
||||||
$driverQuery = $con->prepare("SELECT id AS driverID FROM driver WHERE phone = :phone LIMIT 1");
|
$driverQuery = $con->prepare("SELECT id AS driverID FROM driver WHERE phone = :phone OR (:bidx IS NOT NULL AND phone_bidx = :bidx) LIMIT 1");
|
||||||
$driverQuery->execute([':phone' => $encPhone]);
|
$driverQuery->execute([':phone' => $encPhone, ':bidx' => $dBidx]);
|
||||||
$driver = $driverQuery->fetch(PDO::FETCH_ASSOC);
|
$driver = $driverQuery->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
// Check Passenger Table
|
// Check Passenger Table
|
||||||
$customerQuery = $con->prepare("SELECT id AS customerID FROM passengers WHERE phone = :phone LIMIT 1");
|
$customerQuery = $con->prepare("SELECT id AS customerID FROM passengers WHERE phone = :phone OR (:bidx IS NOT NULL AND phone_bidx = :bidx) LIMIT 1");
|
||||||
$customerQuery->execute([':phone' => $encPhone]);
|
$customerQuery->execute([':phone' => $encPhone, ':bidx' => $pBidx]);
|
||||||
$customer = $customerQuery->fetch(PDO::FETCH_ASSOC);
|
$customer = $customerQuery->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
// حدد نوع المستخدم
|
// حدد نوع المستخدم
|
||||||
@@ -147,5 +156,7 @@ $response = [
|
|||||||
"driver_location" => $location ?: "No live location"
|
"driver_location" => $location ?: "No live location"
|
||||||
];
|
];
|
||||||
|
|
||||||
|
error_log("[MONITOR_RIDE] 7. Sending Success Response.");
|
||||||
|
jsonSuccess($response);
|
||||||
error_log("[MONITOR_RIDE] 7. Sending Success Response.");
|
error_log("[MONITOR_RIDE] 7. Sending Success Response.");
|
||||||
jsonSuccess($response);
|
jsonSuccess($response);
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
<?php
|
||||||
|
// ============================================================
|
||||||
|
// safety/list_incidents.php — قائمة بلاغات السلامة للوحة الإدارة
|
||||||
|
//
|
||||||
|
// قراءة خالصة. الترتيب: المفتوح أولاً ثم الأحدث — غرفة العمليات تحتاج
|
||||||
|
// ما لم يُعالَج بعد، لا أحدث ما وقع.
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
// تحت Admin/ عمداً: بوّابة connect.php المسارية تفرض دور admin أو
|
||||||
|
// super_admin على كل ما تحت هذا المجلد. لو بقي في safety/ لقرأه أي حامل
|
||||||
|
// JWT صالح — بما فيه راكب — وفيه معرّفات ومواقع أطراف الحادثة.
|
||||||
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
|
$status = filterRequest("status"); // open | acknowledged | resolved | false_alarm | (فارغ = الكل)
|
||||||
|
$limit = (int) (filterRequest("limit", 'int') ?: 50);
|
||||||
|
$limit = max(1, min(200, $limit));
|
||||||
|
|
||||||
|
$allowed = ['open', 'acknowledged', 'resolved', 'false_alarm'];
|
||||||
|
|
||||||
|
try {
|
||||||
|
if ($status && in_array($status, $allowed, true)) {
|
||||||
|
$stmt = $con->prepare("
|
||||||
|
SELECT * FROM safety_incidents
|
||||||
|
WHERE status = ?
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
LIMIT $limit
|
||||||
|
");
|
||||||
|
$stmt->execute([$status]);
|
||||||
|
} else {
|
||||||
|
// FIELD() يضع 'open' أولاً مهما كان تاريخه — بلاغ مفتوح من أمس
|
||||||
|
// أهم من بلاغ عولج قبل دقيقة.
|
||||||
|
$stmt = $con->query("
|
||||||
|
SELECT * FROM safety_incidents
|
||||||
|
ORDER BY FIELD(status, 'open', 'acknowledged', 'resolved', 'false_alarm'),
|
||||||
|
created_at DESC
|
||||||
|
LIMIT $limit
|
||||||
|
");
|
||||||
|
}
|
||||||
|
|
||||||
|
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
|
// عدّاد المفتوح — الرقم الذي يظهر كشارة على اللوحة
|
||||||
|
$openCount = (int) $con->query(
|
||||||
|
"SELECT COUNT(*) FROM safety_incidents WHERE status = 'open'"
|
||||||
|
)->fetchColumn();
|
||||||
|
|
||||||
|
jsonSuccess(['open_count' => $openCount, 'incidents' => $rows], "ok");
|
||||||
|
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log("[safety/list] " . $e->getMessage());
|
||||||
|
jsonError("DB Error", 500);
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
<?php
|
||||||
|
// ============================================================
|
||||||
|
// Admin/safety/update_incident.php — معالجة بلاغ سلامة
|
||||||
|
//
|
||||||
|
// يحوّل البلاغ من "مفتوح" إلى حالة نهائية، ويرفع تجميد السائق عند
|
||||||
|
// الإغلاق. بدون هذه النقطة يبقى السائق مجمّداً إلى الأبد — التجميد بلا
|
||||||
|
// TTL عمداً، فرفعه قرار إنسان لا انقضاء وقت.
|
||||||
|
//
|
||||||
|
// تحت Admin/ فترث بوّابة الدور من connect.php.
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
|
$incidentId = filterRequest("incident_id", 'int');
|
||||||
|
$newStatus = filterRequest("status");
|
||||||
|
$note = filterRequest("note");
|
||||||
|
$releaseHold = filterRequest("release_hold");
|
||||||
|
|
||||||
|
$allowed = ['acknowledged', 'resolved', 'false_alarm'];
|
||||||
|
|
||||||
|
if (!$incidentId || !in_array($newStatus, $allowed, true)) {
|
||||||
|
jsonError("Missing incident_id or invalid status");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$stmt = $con->prepare("SELECT * FROM safety_incidents WHERE id = ? LIMIT 1");
|
||||||
|
$stmt->execute([$incidentId]);
|
||||||
|
$incident = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
|
if (!$incident) {
|
||||||
|
jsonError("Incident not found", 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
$con->prepare("
|
||||||
|
UPDATE safety_incidents
|
||||||
|
SET status = ?, acknowledged_by = ?, acknowledged_at = NOW(), resolution_note = ?
|
||||||
|
WHERE id = ?
|
||||||
|
")->execute([
|
||||||
|
$newStatus,
|
||||||
|
$user_id ?? 'admin',
|
||||||
|
$note ? mb_substr($note, 0, 500) : null,
|
||||||
|
$incidentId,
|
||||||
|
]);
|
||||||
|
|
||||||
|
// ── رفع التجميد ─────────────────────────────────────────
|
||||||
|
// افتراضياً يُرفع عند الإغلاق (resolved / false_alarm) ولا يُرفع عند
|
||||||
|
// مجرد الاطلاع (acknowledged). ويمكن للمراجع أن يقرر صراحةً.
|
||||||
|
$shouldRelease = $releaseHold !== null
|
||||||
|
? in_array(strtolower((string) $releaseHold), ['1', 'true', 'yes'], true)
|
||||||
|
: in_array($newStatus, ['resolved', 'false_alarm'], true);
|
||||||
|
|
||||||
|
$released = false;
|
||||||
|
$driverId = $incident['driver_id'] ?? null;
|
||||||
|
|
||||||
|
if ($shouldRelease && $driverId) {
|
||||||
|
try {
|
||||||
|
// نرفع فقط إن كان التجميد من هذا البلاغ تحديداً: سائق عليه
|
||||||
|
// بلاغ ثانٍ أحدث يجب ألا يُفرَج عنه بإغلاق الأقدم.
|
||||||
|
$upd = $con->prepare("
|
||||||
|
UPDATE driver SET safetyHoldIncidentId = NULL
|
||||||
|
WHERE id = ? AND safetyHoldIncidentId = ?
|
||||||
|
");
|
||||||
|
$upd->execute([$driverId, $incidentId]);
|
||||||
|
|
||||||
|
if ($upd->rowCount() > 0) {
|
||||||
|
if (isset($redisLocation) && $redisLocation) {
|
||||||
|
$redisLocation->del("driver:$driverId:safety_hold");
|
||||||
|
}
|
||||||
|
$released = true;
|
||||||
|
}
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
error_log("[safety/update] تعذّر رفع تجميد السائق $driverId: " . $e->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
error_log("[safety] بلاغ #$incidentId → $newStatus بواسطة "
|
||||||
|
. ($user_id ?? 'admin') . ($released ? " (رُفع التجميد)" : ""));
|
||||||
|
|
||||||
|
jsonSuccess([
|
||||||
|
'incident_id' => $incidentId,
|
||||||
|
'status' => $newStatus,
|
||||||
|
'hold_released' => $released,
|
||||||
|
], "Incident updated");
|
||||||
|
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log("[safety/update] " . $e->getMessage());
|
||||||
|
jsonError("DB Error", 500);
|
||||||
|
}
|
||||||
@@ -17,7 +17,7 @@ try {
|
|||||||
SUM(r.price) as total_revenue
|
SUM(r.price) as total_revenue
|
||||||
FROM driver d
|
FROM driver d
|
||||||
JOIN ride r ON d.id = r.driver_id
|
JOIN ride r ON d.id = r.driver_id
|
||||||
WHERE r.status = 'Finished'
|
WHERE LOWER(r.status) IN ('finished','completed')
|
||||||
GROUP BY d.id, d.first_name, d.last_name, d.phone
|
GROUP BY d.id, d.first_name, d.last_name, d.phone
|
||||||
ORDER BY completed_rides DESC
|
ORDER BY completed_rides DESC
|
||||||
LIMIT 10
|
LIMIT 10
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ try {
|
|||||||
SUM(price - price_for_driver) as company_profit,
|
SUM(price - price_for_driver) as company_profit,
|
||||||
COUNT(*) as total_rides
|
COUNT(*) as total_rides
|
||||||
FROM ride
|
FROM ride
|
||||||
WHERE status = 'Finished'
|
WHERE LOWER(status) IN ('finished','completed')
|
||||||
AND created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
|
AND created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
|
||||||
GROUP BY DATE(created_at)
|
GROUP BY DATE(created_at)
|
||||||
ORDER BY date ASC
|
ORDER BY date ASC
|
||||||
@@ -32,7 +32,7 @@ try {
|
|||||||
SUM(price - price_for_driver) as total_profit_all,
|
SUM(price - price_for_driver) as total_profit_all,
|
||||||
AVG(price) as avg_ride_price
|
AVG(price) as avg_ride_price
|
||||||
FROM ride
|
FROM ride
|
||||||
WHERE status = 'Finished'
|
WHERE LOWER(status) IN ('finished','completed')
|
||||||
AND created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
|
AND created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
|
||||||
");
|
");
|
||||||
$stmt->execute();
|
$stmt->execute();
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ try {
|
|||||||
SUM(r.price_for_driver) as total_earned,
|
SUM(r.price_for_driver) as total_earned,
|
||||||
COUNT(r.id) as total_rides
|
COUNT(r.id) as total_rides
|
||||||
FROM driver d
|
FROM driver d
|
||||||
LEFT JOIN ride r ON d.id = r.driver_id AND r.status = 'Finished'
|
LEFT JOIN ride r ON d.id = r.driver_id AND LOWER(r.status) IN ('finished','completed')
|
||||||
GROUP BY d.id
|
GROUP BY d.id
|
||||||
HAVING total_earned > 0
|
HAVING total_earned > 0
|
||||||
ORDER BY total_earned DESC
|
ORDER BY total_earned DESC
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ try {
|
|||||||
0 as cash_payments,
|
0 as cash_payments,
|
||||||
0 as digital_payments
|
0 as digital_payments
|
||||||
FROM ride
|
FROM ride
|
||||||
WHERE status = 'Finished'
|
WHERE LOWER(status) IN ('finished','completed')
|
||||||
");
|
");
|
||||||
$stmt->execute();
|
$stmt->execute();
|
||||||
$stats = $stmt->fetch(PDO::FETCH_ASSOC);
|
$stats = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|||||||
@@ -2,7 +2,14 @@
|
|||||||
// Admin/v2/quality/blacklist_manager.php
|
// Admin/v2/quality/blacklist_manager.php
|
||||||
require_once __DIR__ . '/../../../connect.php';
|
require_once __DIR__ . '/../../../connect.php';
|
||||||
require_once __DIR__ . '/../../../encrypt_decrypt.php';
|
require_once __DIR__ . '/../../../encrypt_decrypt.php';
|
||||||
require_once __DIR__ . '/../security/audit_logs_helper.php'; // إذا كان متاحاً، وإلا سننفذ الإدخال مباشرة
|
// audit_logs_helper.php لم يوجد قط في المستودع، والتعليق الأصلي كان
|
||||||
|
// "إذا كان متاحاً، وإلا سننفذ الإدخال مباشرة" — لكن require_once قاتل
|
||||||
|
// لا اختياري، فكانت الشاشة تسقط دائماً. الملف اختياري فعلاً: هذا الملف
|
||||||
|
// يكتب في admin_audit_log مباشرةً أدناه.
|
||||||
|
$auditHelper = __DIR__ . '/../security/audit_logs_helper.php';
|
||||||
|
if (file_exists($auditHelper)) {
|
||||||
|
require_once $auditHelper;
|
||||||
|
}
|
||||||
|
|
||||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||||
jsonError("Unauthorized", 403);
|
jsonError("Unauthorized", 403);
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ try {
|
|||||||
$stmt = $con->prepare("
|
$stmt = $con->prepare("
|
||||||
SELECT
|
SELECT
|
||||||
COUNT(*) as total_rides,
|
COUNT(*) as total_rides,
|
||||||
SUM(CASE WHEN status = 'Finished' THEN 1 ELSE 0 END) as completed_rides,
|
SUM(CASE WHEN LOWER(status) IN ('finished','completed') THEN 1 ELSE 0 END) as completed_rides,
|
||||||
SUM(CASE WHEN status = 'cancel' AND cancel_by = 'driver' THEN 1 ELSE 0 END) as driver_cancellations,
|
SUM(CASE WHEN status = 'cancel' AND cancel_by = 'driver' THEN 1 ELSE 0 END) as driver_cancellations,
|
||||||
SUM(CASE WHEN status = 'cancel' AND cancel_by = 'passenger' THEN 1 ELSE 0 END) as passenger_cancellations
|
SUM(CASE WHEN status = 'cancel' AND cancel_by = 'passenger' THEN 1 ELSE 0 END) as passenger_cancellations
|
||||||
FROM ride
|
FROM ride
|
||||||
|
|||||||
@@ -26,12 +26,12 @@ try {
|
|||||||
$online_drivers = $stmt->fetchColumn();
|
$online_drivers = $stmt->fetchColumn();
|
||||||
|
|
||||||
// 3. إيرادات اليوم
|
// 3. إيرادات اليوم
|
||||||
$stmt = $con->prepare("SELECT IFNULL(SUM(price_for_passenger), 0) FROM ride WHERE status = 'Finished' AND DATE(created_at) = CURDATE()");
|
$stmt = $con->prepare("SELECT IFNULL(SUM(price_for_passenger), 0) FROM ride WHERE LOWER(status) IN ('finished','completed') AND DATE(created_at) = CURDATE()");
|
||||||
$stmt->execute();
|
$stmt->execute();
|
||||||
$revenue_today = $stmt->fetchColumn();
|
$revenue_today = $stmt->fetchColumn();
|
||||||
|
|
||||||
// إيرادات الأمس (للمقارنة)
|
// إيرادات الأمس (للمقارنة)
|
||||||
$stmt = $con->prepare("SELECT IFNULL(SUM(price_for_passenger), 0) FROM ride WHERE status = 'Finished' AND DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)");
|
$stmt = $con->prepare("SELECT IFNULL(SUM(price_for_passenger), 0) FROM ride WHERE LOWER(status) IN ('finished','completed') AND DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)");
|
||||||
$stmt->execute();
|
$stmt->execute();
|
||||||
$revenue_yesterday = $stmt->fetchColumn();
|
$revenue_yesterday = $stmt->fetchColumn();
|
||||||
|
|
||||||
|
|||||||
@@ -1,19 +1,15 @@
|
|||||||
<?php
|
<?php
|
||||||
// Admin/v2/security/audit_logs.php
|
// Admin/v2/security/audit_logs.php
|
||||||
|
|
||||||
// ── سجل تتبع ────────────────────────────────────────────
|
// كان هنا تتبّع تشخيصي يكتب ملفاً نصياً على القرص مع كل طلب، ويسجّل فيه
|
||||||
$debugFile = __DIR__ . '/../../../logs/audit_debug.txt';
|
// user_id والدور. أُزيل: يراكم ملفاً بلا حد في الإنتاج ويسرّب سياق الجلسة.
|
||||||
$logDir = dirname($debugFile);
|
// ما يستحق التسجيل يذهب إلى error_log مع الأخطاء وحدها.
|
||||||
if (!is_dir($logDir)) @mkdir($logDir, 0750, true);
|
|
||||||
|
|
||||||
@file_put_contents($debugFile, "[" . date('Y-m-d H:i:s') . "] === REQUEST START ===\n", FILE_APPEND);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
require_once __DIR__ . '/../../../connect.php';
|
require_once __DIR__ . '/../../../connect.php';
|
||||||
|
|
||||||
@file_put_contents($debugFile, " → connect.php & encryption OK. user_id=$user_id | role=$role\n", FILE_APPEND);
|
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
@file_put_contents($debugFile, " → Loading FAILED: " . $e->getMessage() . "\n", FILE_APPEND);
|
error_log('[audit_logs] bootstrap failed: ' . $e->getMessage());
|
||||||
http_response_code(500);
|
http_response_code(500);
|
||||||
printFailure('loading failed', 500);
|
printFailure('loading failed', 500);
|
||||||
exit;
|
exit;
|
||||||
@@ -21,7 +17,6 @@ try {
|
|||||||
|
|
||||||
// ── فحص الصلاحيات ────────────────────────────────────────
|
// ── فحص الصلاحيات ────────────────────────────────────────
|
||||||
if ($role !== 'super_admin' && $role !== 'admin') {
|
if ($role !== 'super_admin' && $role !== 'admin') {
|
||||||
@file_put_contents($debugFile, " → BLOCKED: role=$role\n", FILE_APPEND);
|
|
||||||
printFailure("Unauthorized. role=$role", 403);
|
printFailure("Unauthorized. role=$role", 403);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,12 +50,11 @@ try {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$count = count($logs);
|
$count = count($logs);
|
||||||
@file_put_contents($debugFile, " → SUCCESS: fetched $count logs\n", FILE_APPEND);
|
|
||||||
|
|
||||||
jsonSuccess($logs);
|
jsonSuccess($logs);
|
||||||
|
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
@file_put_contents($debugFile, " → QUERY ERROR: " . $e->getMessage() . "\n", FILE_APPEND);
|
error_log('[audit_logs] query failed: ' . $e->getMessage());
|
||||||
jsonError('Query failed', 500);
|
jsonError('Query failed', 500);
|
||||||
}
|
}
|
||||||
?>
|
?>
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ require_once __DIR__ . '/../../connect.php';
|
|||||||
|
|
||||||
// استقبال وتشفير رقم الهاتف
|
// استقبال وتشفير رقم الهاتف
|
||||||
$phoneNumber = filterRequest("phone_number");
|
$phoneNumber = filterRequest("phone_number");
|
||||||
$phoneNumber = $encryptionHelper->encryptData($phoneNumber);
|
$phoneNumber = otpPhoneKey($phoneNumber);
|
||||||
|
|
||||||
// تجهيز الاستعلام باستخدام bindParam للحماية
|
// تجهيز الاستعلام باستخدام bindParam للحماية
|
||||||
$sql = "SELECT * FROM `phone_verification` WHERE `phone_number` = :phone_number";
|
$sql = "SELECT * FROM `phone_verification` WHERE `phone_number` = :phone_number";
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<?php
|
<?php
|
||||||
require_once __DIR__ . '/../../../connect.php';
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
// 🔥 [Fix Broken Access Control] كان يتحقق من صلاحية التوكن فقط — أي مستخدم
|
// 🔥 [Fix Broken Access Control] كان يتحقق من صلاحية التوكن فقط — أي مستخدم
|
||||||
// مسجّل دخول (راكب/سائق آخر) كان يقدر يجلب بيانات أي سائق مفكوكة التشفير
|
// مسجّل دخول (راكب/سائق آخر) كان يقدر يجلب بيانات أي سائق مفكوكة التشفير
|
||||||
@@ -10,7 +10,15 @@ if ($role !== 'admin' && $role !== 'super_admin') {
|
|||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
$driverId = filterRequest("id");
|
// filterRequest() تقرأ من POST أو JSON body فقط ولا تلمس $_GET
|
||||||
|
// (core/helpers.php). شاشة مراجعة الوثائق تنادي هذه النقطة بـ
|
||||||
|
// ?id=... في الـ query string، فكانت تُرجع "driver_id is required"
|
||||||
|
// دائماً رغم إرسال المعرّف. نقبل الشكلين، ونقبل driver_id أيضاً
|
||||||
|
// لأن رسالة الخطأ نفسها تسمّيه هكذا.
|
||||||
|
$driverId = filterRequest("id")
|
||||||
|
?: filterRequest("driver_id")
|
||||||
|
?: (isset($_GET['id']) ? trim((string) $_GET['id']) : null)
|
||||||
|
?: (isset($_GET['driver_id']) ? trim((string) $_GET['driver_id']) : null);
|
||||||
|
|
||||||
if (empty($driverId)) {
|
if (empty($driverId)) {
|
||||||
jsonError("driver_id is required.");
|
jsonError("driver_id is required.");
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
<?php
|
<?php
|
||||||
require_once __DIR__ . '/../../../connect.php';
|
// المسار كان '/../../../connect.php' فيُحلّ من backend/auth/driver إلى
|
||||||
|
// /var/www/connect.php — مستوى واحد فوق جذر الباك إند — فتسقط الشاشة بخطأ
|
||||||
|
// قاتل رغم أن الاستجابة تُرجع 200.
|
||||||
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
// 🔥 [Fix Broken Access Control] كان يتحقق من صلاحية التوكن فقط بدون التحقق
|
// 🔥 [Fix Broken Access Control] كان يتحقق من صلاحية التوكن فقط بدون التحقق
|
||||||
// من الدور — أي توكن صالح (حتى راكب) كان يقدر يسحب قائمة السائقين المعلّقين
|
// من الدور — أي توكن صالح (حتى راكب) كان يقدر يسحب قائمة السائقين المعلّقين
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
<?php
|
<?php
|
||||||
require_once __DIR__ . '/../../../connect.php';
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
$phoneNumber = filterRequest("phone_number");
|
$phoneNumber = filterRequest("phone_number");
|
||||||
|
|
||||||
// تشفير الرقم قبل البحث
|
// تشفير الرقم قبل البحث
|
||||||
$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
|
$phoneNumber_encrypted = otpPhoneKey($phoneNumber);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// الاستعلام عن السائق حسب رقم الهاتف وحالة التحقق
|
// الاستعلام عن السائق حسب رقم الهاتف وحالة التحقق
|
||||||
|
|||||||
@@ -2,13 +2,45 @@
|
|||||||
|
|
||||||
require_once __DIR__ . '/../../connect.php';
|
require_once __DIR__ . '/../../connect.php';
|
||||||
|
|
||||||
|
global $blindIndex;
|
||||||
|
|
||||||
$email = filterRequest('email');
|
$email = filterRequest('email');
|
||||||
$phone = filterRequest('phone');
|
$phone = filterRequest('phone');
|
||||||
$password = filterRequest('password');
|
$password = filterRequest('password');
|
||||||
|
|
||||||
// تشفير الحقول المطلوبة قبل الاستعلام
|
if (empty($phone) && empty($email)) {
|
||||||
$email = $encryptionHelper->encryptData($email);
|
jsonError("Phone or email is required.");
|
||||||
$phone = $encryptionHelper->encryptData($phone);
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$conditions = [];
|
||||||
|
$params = [];
|
||||||
|
|
||||||
|
if (!empty($phone)) {
|
||||||
|
$phoneEnc = $encryptionHelper->encryptData($phone);
|
||||||
|
$conditions[] = "driver.phone = :phone";
|
||||||
|
$params[':phone'] = $phoneEnc;
|
||||||
|
|
||||||
|
$phoneBidx = $blindIndex ? $blindIndex->index('driver.phone', $phone) : null;
|
||||||
|
if ($phoneBidx) {
|
||||||
|
$conditions[] = "driver.phone_bidx = :phone_bidx";
|
||||||
|
$params[':phone_bidx'] = $phoneBidx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($email)) {
|
||||||
|
$emailEnc = $encryptionHelper->encryptData($email);
|
||||||
|
$conditions[] = "driver.email = :email";
|
||||||
|
$params[':email'] = $emailEnc;
|
||||||
|
|
||||||
|
$emailBidx = $blindIndex ? $blindIndex->index('driver.email', $email) : null;
|
||||||
|
if ($emailBidx) {
|
||||||
|
$conditions[] = "driver.email_bidx = :email_bidx";
|
||||||
|
$params[':email_bidx'] = $emailBidx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$whereClause = implode(' OR ', $conditions);
|
||||||
|
|
||||||
$sql = "SELECT
|
$sql = "SELECT
|
||||||
driver.id,
|
driver.id,
|
||||||
@@ -25,19 +57,44 @@ $sql = "SELECT
|
|||||||
driver.maritalStatus,
|
driver.maritalStatus,
|
||||||
driver.created_at,
|
driver.created_at,
|
||||||
driver.updated_at,
|
driver.updated_at,
|
||||||
email_verifications.verified
|
driver.email AS _email_enc
|
||||||
FROM
|
FROM
|
||||||
driver
|
driver
|
||||||
LEFT JOIN email_verifications ON email_verifications.email = driver.email
|
|
||||||
WHERE
|
WHERE
|
||||||
driver.phone = :phone AND driver.email = :email";
|
$whereClause";
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* حالة توثيق البريد.
|
||||||
|
*
|
||||||
|
* كان الاستعلام يربط email_verifications.email بعمود البريد في الحساب، لكن
|
||||||
|
* الأول يُخزَّن نصاً صريحاً والثاني مشفّراً — فالربط لم يكن يطابق شيئاً أصلاً
|
||||||
|
* وكانت verified تعود NULL دائماً. نجلبها هنا بالبريد الأصلي.
|
||||||
|
*/
|
||||||
|
function fetchEmailVerified(PDO $con, ?string $plainEmail): ?int
|
||||||
|
{
|
||||||
|
if (!$plainEmail) return null;
|
||||||
|
try {
|
||||||
|
$st = $con->prepare("SELECT verified FROM email_verifications WHERE email = ? LIMIT 1");
|
||||||
|
$st->execute([$plainEmail]);
|
||||||
|
$v = $st->fetchColumn();
|
||||||
|
return $v === false ? null : (int) $v;
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log('[email_verifications] ' . $e->getMessage());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
$stmt = $con->prepare($sql);
|
$stmt = $con->prepare($sql);
|
||||||
$stmt->bindParam(':email', $email);
|
$stmt->execute($params);
|
||||||
$stmt->bindParam(':phone', $phone);
|
|
||||||
$stmt->execute();
|
|
||||||
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||||
$count = $stmt->rowCount();
|
$count = count($data);
|
||||||
|
|
||||||
|
if ($count > 0) {
|
||||||
|
$plainEmail = $encryptionHelper->decryptData($data[0]['_email_enc'] ?? null) ?: null;
|
||||||
|
$data[0]['verified'] = fetchEmailVerified($con, $plainEmail);
|
||||||
|
unset($data[0]['_email_enc']);
|
||||||
|
}
|
||||||
|
|
||||||
if ($count > 0) {
|
if ($count > 0) {
|
||||||
$stored_password = $data[0]['password'];
|
$stored_password = $data[0]['password'];
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ try {
|
|||||||
CarRegistration.make, CarRegistration.model, CarRegistration.year,
|
CarRegistration.make, CarRegistration.model, CarRegistration.year,
|
||||||
df.is_claimed, inv.isInstall, inv.isGiftToken
|
df.is_claimed, inv.isInstall, inv.isGiftToken
|
||||||
FROM driver
|
FROM driver
|
||||||
LEFT JOIN phone_verification ON phone_verification.phone_number = driver.phone
|
LEFT JOIN phone_verification ON phone_verification.phone_number = driver.phone_key
|
||||||
LEFT JOIN driver_gifts df ON df.driver_id = driver.id
|
LEFT JOIN driver_gifts df ON df.driver_id = driver.id
|
||||||
LEFT JOIN CarRegistration ON CarRegistration.driverID = driver.id
|
LEFT JOIN CarRegistration ON CarRegistration.driverID = driver.id
|
||||||
LEFT JOIN invites inv ON inv.driverId = driver.id
|
LEFT JOIN invites inv ON inv.driverId = driver.id
|
||||||
|
|||||||
@@ -11,18 +11,16 @@ $password = filterRequest('password');
|
|||||||
$audience = filterRequest('aud') ?? 'siro-driver-android'; // الافتراضي
|
$audience = filterRequest('aud') ?? 'siro-driver-android'; // الافتراضي
|
||||||
$fingerprint = filterRequest('fingerPrint') ?? filterRequest('fingerprint');
|
$fingerprint = filterRequest('fingerPrint') ?? filterRequest('fingerprint');
|
||||||
|
|
||||||
// 1. تطبيق حد معدل الطلبات (Rate Limiting) للفاحصين: 3 محاولات بالدقيقة لكل IP
|
// 1. حد معدل الطلبات مطبّق على الجميع (الحد مرفوع إلى 30/دقيقة في RateLimiter)
|
||||||
$rateLimiter = new RateLimiter($redis);
|
$rateLimiter = new RateLimiter($redis);
|
||||||
$rateLimiter->enforce(RateLimiter::identifier(), 'tester_login');
|
$rateLimiter->enforce(RateLimiter::identifier(), 'tester_login');
|
||||||
|
|
||||||
if (!$email || !$password) {
|
// 2. قائمة بيضاء صريحة لحسابات الفحص — مطابقة تامة فقط، لا مطابقة جزئية ولا مطابقة نطاق
|
||||||
echo json_encode(["status" => "failure", "message" => "Email and password are required"]);
|
$allowedTesterEmailsEnv = getenv('ALLOWED_TESTER_EMAILS') ?: ($_ENV['ALLOWED_TESTER_EMAILS'] ?? '');
|
||||||
exit();
|
$allowedEmails = array_filter(array_map(
|
||||||
}
|
fn($e) => strtolower(trim($e)),
|
||||||
|
explode(',', $allowedTesterEmailsEnv)
|
||||||
// 2. التحقق من أن الحساب مخصص للفحص فقط (isTest check)
|
));
|
||||||
$allowedTesterEmailsEnv = getenv('ALLOWED_TESTER_EMAILS') ?: '';
|
|
||||||
$allowedEmails = array_filter(array_map('trim', explode(',', $allowedTesterEmailsEnv)));
|
|
||||||
if (empty($allowedEmails)) {
|
if (empty($allowedEmails)) {
|
||||||
$allowedEmails = [
|
$allowedEmails = [
|
||||||
'driver_tester@siromove.com',
|
'driver_tester@siromove.com',
|
||||||
@@ -30,21 +28,21 @@ if (empty($allowedEmails)) {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
$cleanEmail = strtolower(trim($email));
|
$cleanEmail = strtolower(trim((string) $email));
|
||||||
$isTester = in_array($cleanEmail, $allowedEmails) ||
|
$isTester = in_array($cleanEmail, $allowedEmails, true);
|
||||||
substr($cleanEmail, -13) === '@siromove.com' ||
|
|
||||||
str_contains($cleanEmail, 'tester') ||
|
|
||||||
str_contains($cleanEmail, 'reviewer');
|
|
||||||
|
|
||||||
// تشفير الإيميل لاستخدامه في الاستعلام
|
if (!$email || !$password) {
|
||||||
$encryptedEmail = $encryptionHelper->encryptData($email);
|
echo json_encode(["status" => "failure", "message" => "Email and password are required"]);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$con = Database::get('main');
|
$con = Database::get('main');
|
||||||
|
|
||||||
// Auto-seed/create tester driver logic removed for security
|
|
||||||
|
|
||||||
// SQL لاسترجاع المستخدم بناءً على البريد الإلكتروني المشفر
|
$encryptedEmail = $encryptionHelper->encryptData($email);
|
||||||
|
global $blindIndex;
|
||||||
|
$emailBidx = $blindIndex ? $blindIndex->index('driver.email', $email) : null;
|
||||||
|
|
||||||
$sql = "SELECT
|
$sql = "SELECT
|
||||||
driver.*,
|
driver.*,
|
||||||
phone_verification.is_verified,
|
phone_verification.is_verified,
|
||||||
@@ -52,49 +50,49 @@ try {
|
|||||||
CarRegistration.model,
|
CarRegistration.model,
|
||||||
CarRegistration.year
|
CarRegistration.year
|
||||||
FROM driver
|
FROM driver
|
||||||
LEFT JOIN phone_verification ON phone_verification.phone_number = driver.phone
|
LEFT JOIN phone_verification ON phone_verification.phone_number = driver.phone_key
|
||||||
LEFT JOIN CarRegistration ON CarRegistration.driverID = driver.id
|
LEFT JOIN CarRegistration ON CarRegistration.driverID = driver.id
|
||||||
WHERE
|
WHERE driver.email = :email";
|
||||||
driver.email = :email
|
|
||||||
LIMIT 1";
|
$params = [':email' => $encryptedEmail];
|
||||||
|
|
||||||
|
if ($emailBidx !== null) {
|
||||||
|
$sql .= " OR driver.email_bidx = :email_bidx";
|
||||||
|
$params[':email_bidx'] = $emailBidx;
|
||||||
|
}
|
||||||
|
|
||||||
|
$sql .= " LIMIT 1";
|
||||||
|
|
||||||
$stmt = $con->prepare($sql);
|
$stmt = $con->prepare($sql);
|
||||||
$stmt->bindParam(':email', $encryptedEmail);
|
$stmt->execute($params);
|
||||||
$stmt->execute();
|
|
||||||
|
|
||||||
$data = $stmt->fetch(PDO::FETCH_ASSOC);
|
$data = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
if ($data) {
|
if ($data) {
|
||||||
// التحقق من أن الحساب معلم كحساب فحص في قاعدة البيانات أو البيئة
|
|
||||||
$isTestInDb = (isset($data['is_test']) && $data['is_test'] == 1) || (isset($data['isTest']) && $data['isTest'] == 1);
|
$isTestInDb = (isset($data['is_test']) && $data['is_test'] == 1) || (isset($data['isTest']) && $data['isTest'] == 1);
|
||||||
if (!$isTestInDb && !$isTester) {
|
if (!$isTestInDb && !$isTester) {
|
||||||
jsonError("Access denied. Not a tester account.");
|
jsonError("Access denied. Not a tester account.");
|
||||||
exit();
|
exit();
|
||||||
}
|
}
|
||||||
// فحص الباسورد (في نظامنا، يمكن أن يكون الباسورد هو HMAC أو نص عادي للفاحصين)
|
|
||||||
// لنفترض أن الفاحص له باسورد عادي أو مشفر بـ bcrypt
|
if (password_verify($password, $data['password'] ?? '')) {
|
||||||
if (password_verify($password, $data['password'])) {
|
|
||||||
unset($data['password']);
|
unset($data['password']);
|
||||||
|
|
||||||
// فك تشفير الحقول الحساسة
|
if(isset($data['phone'])) $data['phone'] = $encryptionHelper->decryptData($data['phone']);
|
||||||
$data['phone'] = $encryptionHelper->decryptData($data['phone']);
|
if(isset($data['email'])) $data['email'] = $encryptionHelper->decryptData($data['email']);
|
||||||
$data['email'] = $encryptionHelper->decryptData($data['email']);
|
if(isset($data['gender'])) $data['gender'] = $encryptionHelper->decryptData($data['gender']);
|
||||||
$data['gender'] = $encryptionHelper->decryptData($data['gender']);
|
if(isset($data['birthdate'])) $data['birthdate'] = $encryptionHelper->decryptData($data['birthdate']);
|
||||||
$data['birthdate'] = $encryptionHelper->decryptData($data['birthdate']);
|
if(isset($data['site'])) $data['site'] = $encryptionHelper->decryptData($data['site']);
|
||||||
$data['site'] = $encryptionHelper->decryptData($data['site']);
|
if(isset($data['first_name'])) $data['first_name'] = $encryptionHelper->decryptData($data['first_name']);
|
||||||
$data['first_name'] = $encryptionHelper->decryptData($data['first_name']);
|
if(isset($data['last_name'])) $data['last_name'] = $encryptionHelper->decryptData($data['last_name']);
|
||||||
$data['last_name'] = $encryptionHelper->decryptData($data['last_name']);
|
|
||||||
if(isset($data['employmentType'])) $data['employmentType'] = $encryptionHelper->decryptData($data['employmentType']);
|
|
||||||
if(isset($data['maritalStatus'])) $data['maritalStatus'] = $encryptionHelper->decryptData($data['maritalStatus']);
|
|
||||||
|
|
||||||
// توليد الـ JWT بصلاحية (tester) لتميزهم عن السائقين الفعليين
|
|
||||||
$jwtService = new JwtService($redis);
|
$jwtService = new JwtService($redis);
|
||||||
$jwt = $jwtService->generateAccessToken($data['id'], 'tester', $audience, $fingerprint);
|
$jwt = $jwtService->generateAccessToken($data['id'], 'tester', $audience, $fingerprint);
|
||||||
|
|
||||||
echo json_encode([
|
echo json_encode([
|
||||||
"status" => "success",
|
"status" => "success",
|
||||||
"jwt" => $jwt,
|
"jwt" => $jwt,
|
||||||
"data" => [$data] // مطابق لنسق التطبيق الذي يتوقع مصفوفة
|
"data" => [$data]
|
||||||
], JSON_UNESCAPED_UNICODE);
|
], JSON_UNESCAPED_UNICODE);
|
||||||
} else {
|
} else {
|
||||||
jsonError("Incorrect password.");
|
jsonError("Incorrect password.");
|
||||||
@@ -102,9 +100,9 @@ try {
|
|||||||
} else {
|
} else {
|
||||||
jsonError("User does not exist.");
|
jsonError("User does not exist.");
|
||||||
}
|
}
|
||||||
} catch (Exception $e) {
|
} catch (Throwable $e) {
|
||||||
error_log("[Tester Login Error] " . $e->getMessage());
|
error_log("[Tester Login Error] " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine());
|
||||||
jsonError("Server error occurred.");
|
jsonError("Server error occurred: " . $e->getMessage() . " in " . basename($e->getFile()) . ":" . $e->getLine());
|
||||||
} finally {
|
} finally {
|
||||||
$stmt = null;
|
$stmt = null;
|
||||||
$con = null;
|
$con = null;
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
*/
|
*/
|
||||||
//register_driver_and_car.php
|
//register_driver_and_car.php
|
||||||
$allowRegistration = true;
|
$allowRegistration = true;
|
||||||
require_once __DIR__ . '/../../../connect.php';
|
require_once __DIR__ . '/../../connect.php';
|
||||||
header('Content-Type: application/json; charset=utf-8');
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
|
|
||||||
// Rate Limiting: الحماية من التسجيل العشوائي وهجمات الـ Bots
|
// Rate Limiting: الحماية من التسجيل العشوائي وهجمات الـ Bots
|
||||||
@@ -128,7 +128,7 @@ try {
|
|||||||
// ======================================================
|
// ======================================================
|
||||||
// Step 1.5: التحقق الفعلي من ملكية رقم الهاتف قبل إكمال المعالجة (سد الثغرة)
|
// Step 1.5: التحقق الفعلي من ملكية رقم الهاتف قبل إكمال المعالجة (سد الثغرة)
|
||||||
// ======================================================
|
// ======================================================
|
||||||
require_once __DIR__ . '/../../../core/Auth/EncryptionHelper.php';
|
require_once __DIR__ . '/../../core/Security/EncryptionHelper.php';
|
||||||
$tempEncryptionHelper = new EncryptionHelper($redis);
|
$tempEncryptionHelper = new EncryptionHelper($redis);
|
||||||
$phoneNumber_encrypted_check = $tempEncryptionHelper->encryptData($data['phone']);
|
$phoneNumber_encrypted_check = $tempEncryptionHelper->encryptData($data['phone']);
|
||||||
|
|
||||||
@@ -383,6 +383,18 @@ Therefore, do NOT assume a specific field is on the front or the back of a card.
|
|||||||
$pwdHashed = password_hash($rawSecret, PASSWORD_DEFAULT);
|
$pwdHashed = password_hash($rawSecret, PASSWORD_DEFAULT);
|
||||||
|
|
||||||
/* ================== 4) Encrypt sensitive fields ================== */
|
/* ================== 4) Encrypt sensitive fields ================== */
|
||||||
|
// فهارس البحث تُحسب من القيم الخام قبل التشفير — بعده تصبح القيمة الأصلية
|
||||||
|
// غير متاحة، وبعد الانتقال إلى GCM لا يمكن استنتاجها من النص المشفّر.
|
||||||
|
global $blindIndex;
|
||||||
|
$phoneBidx = $blindIndex ? $blindIndex->index('driver.phone', $data['phone'] ?? null) : null;
|
||||||
|
$emailBidx = $blindIndex ? $blindIndex->index('driver.email', $data['email'] ?? null) : null;
|
||||||
|
$nameBidx = $blindIndex ? $blindIndex->index(
|
||||||
|
'driver.name',
|
||||||
|
trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? ''))
|
||||||
|
) : null;
|
||||||
|
// مفتاح ربط جداول التحقق — يجب أن يطابق otpPhoneKey() حرفياً
|
||||||
|
$phoneKey = otpPhoneKey($data['phone'] ?? null);
|
||||||
|
|
||||||
$toEncryptDriver = [
|
$toEncryptDriver = [
|
||||||
"phone","email","first_name","last_name","name_arabic","gender",
|
"phone","email","first_name","last_name","name_arabic","gender",
|
||||||
"national_number","address","site","fullNameMaritial","birthdate"
|
"national_number","address","site","fullNameMaritial","birthdate"
|
||||||
@@ -402,8 +414,18 @@ Therefore, do NOT assume a specific field is on the front or the back of a card.
|
|||||||
$con->beginTransaction();
|
$con->beginTransaction();
|
||||||
|
|
||||||
/* ================== 6) Check duplicate ================== */
|
/* ================== 6) Check duplicate ================== */
|
||||||
$dup = $con->prepare("SELECT id FROM driver WHERE phone = :p OR email = :e");
|
$dup = $con->prepare(
|
||||||
$dup->execute([':p' => $data['phone'], ':e' => $data['email']]);
|
"SELECT id FROM driver
|
||||||
|
WHERE phone = :p OR email = :e
|
||||||
|
OR (:pb IS NOT NULL AND phone_bidx = :pb)
|
||||||
|
OR (:eb IS NOT NULL AND email_bidx = :eb)"
|
||||||
|
);
|
||||||
|
$dup->execute([
|
||||||
|
':p' => $data['phone'],
|
||||||
|
':e' => $data['email'],
|
||||||
|
':pb' => $phoneBidx,
|
||||||
|
':eb' => $emailBidx,
|
||||||
|
]);
|
||||||
if ($dup->rowCount() > 0) {
|
if ($dup->rowCount() > 0) {
|
||||||
$con->rollBack();
|
$con->rollBack();
|
||||||
jsonError("Phone or email already registered.");
|
jsonError("Phone or email already registered.");
|
||||||
@@ -418,14 +440,16 @@ Therefore, do NOT assume a specific field is on the front or the back of a card.
|
|||||||
address, licenseIssueDate, status, birthdate, site,
|
address, licenseIssueDate, status, birthdate, site,
|
||||||
first_name, last_name, accountBank, bankCode,
|
first_name, last_name, accountBank, bankCode,
|
||||||
employmentType, ai_data, user_input, maritalStatus,
|
employmentType, ai_data, user_input, maritalStatus,
|
||||||
fullNameMaritial, expirationDate, created_at, updated_at
|
fullNameMaritial, expirationDate, created_at, updated_at,
|
||||||
|
phone_bidx, email_bidx, name_bidx, phone_key
|
||||||
) VALUES (
|
) VALUES (
|
||||||
:id, :phone, :email, :pwd, :gender, :license_type, :national_number,
|
:id, :phone, :email, :pwd, :gender, :license_type, :national_number,
|
||||||
:name_arabic, :issue_date, :expiry_date, :license_categories,
|
:name_arabic, :issue_date, :expiry_date, :license_categories,
|
||||||
:address, :licenseIssueDate, :status, :birthdate, :site,
|
:address, :licenseIssueDate, :status, :birthdate, :site,
|
||||||
:first_name, :last_name, :accountBank, :bankCode,
|
:first_name, :last_name, :accountBank, :bankCode,
|
||||||
:employmentType, :ai_data, :user_input, :maritalStatus,
|
:employmentType, :ai_data, :user_input, :maritalStatus,
|
||||||
:fullNameMaritial, :expirationDate, NOW(), NOW()
|
:fullNameMaritial, :expirationDate, NOW(), NOW(),
|
||||||
|
:phone_bidx, :email_bidx, :name_bidx, :phone_key
|
||||||
)
|
)
|
||||||
";
|
";
|
||||||
$insD = $con->prepare($sqlDriver);
|
$insD = $con->prepare($sqlDriver);
|
||||||
@@ -456,6 +480,10 @@ Therefore, do NOT assume a specific field is on the front or the back of a card.
|
|||||||
':maritalStatus' => !empty($data['maritalStatus']) ? $data['maritalStatus'] : 'yet',
|
':maritalStatus' => !empty($data['maritalStatus']) ? $data['maritalStatus'] : 'yet',
|
||||||
':fullNameMaritial' => !empty($data['fullNameMaritial']) ? $data['fullNameMaritial'] : 'yet',
|
':fullNameMaritial' => !empty($data['fullNameMaritial']) ? $data['fullNameMaritial'] : 'yet',
|
||||||
':expirationDate' => !empty($data['expirationDate']) ? $data['expirationDate'] : 'yet',
|
':expirationDate' => !empty($data['expirationDate']) ? $data['expirationDate'] : 'yet',
|
||||||
|
':phone_bidx' => $phoneBidx,
|
||||||
|
':email_bidx' => $emailBidx,
|
||||||
|
':name_bidx' => $nameBidx,
|
||||||
|
':phone_key' => $phoneKey,
|
||||||
]);
|
]);
|
||||||
if (!$okD) {
|
if (!$okD) {
|
||||||
$con->rollBack();
|
$con->rollBack();
|
||||||
|
|||||||
@@ -51,8 +51,8 @@ $sentOK = ($httpCode === 200 && ($decoded['success'] ?? false));
|
|||||||
|
|
||||||
if ($sentOK) {
|
if ($sentOK) {
|
||||||
/* 3) تشفير البيانات وحفظها في DB ----------------------------------- */
|
/* 3) تشفير البيانات وحفظها في DB ----------------------------------- */
|
||||||
$receiver_enc = $encryptionHelper->encryptData($receiver);
|
$receiver_enc = otpPhoneKey($receiver);
|
||||||
$otp_enc = $encryptionHelper->encryptData($otp);
|
$otp_enc = otpPhoneKey($otp); // يجب أن يطابق صيغة المقارنة في verify_otp
|
||||||
|
|
||||||
$exp = date('Y-m-d H:i:s', strtotime('+5 minutes'));
|
$exp = date('Y-m-d H:i:s', strtotime('+5 minutes'));
|
||||||
$now = date('Y-m-d H:i:s');
|
$now = date('Y-m-d H:i:s');
|
||||||
|
|||||||
@@ -9,8 +9,9 @@ if (empty($phoneNumber) || empty($otp)) {
|
|||||||
exit();
|
exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
|
$phoneNumber_encrypted = otpPhoneKey($phoneNumber);
|
||||||
$otp_encrypted = $encryptionHelper->encryptData($otp);
|
// الرمز يُقارن بالتساوي أيضاً، فيحتاج نفس الصيغة الثابتة
|
||||||
|
$otp_encrypted = otpPhoneKey($otp);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$stmt = $con->prepare("
|
$stmt = $con->prepare("
|
||||||
|
|||||||
+51
-3
@@ -11,16 +11,39 @@ if (empty($phone) && empty($email)) {
|
|||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build WHERE dynamically: support phone-only, email-only, or both
|
/**
|
||||||
|
* البحث عن الحساب.
|
||||||
|
*
|
||||||
|
* سابقاً كان يقارن القيمة الخام بالعمود المشفّر مباشرةً، وهو ما ينجح فقط لأن
|
||||||
|
* التشفير الحالي حتمي (CBC بـ IV ثابت). الفهرس الأعمى يجعل هذا الاستعلام
|
||||||
|
* مستقلاً عن أسلوب التشفير، فلا ينكسر تسجيل الدخول عند الانتقال إلى AES-GCM.
|
||||||
|
*
|
||||||
|
* تُبقى المقارنتان القديمتان في نفس الشرط كاحتياط للحسابات التي لم تُفهرس بعد.
|
||||||
|
*/
|
||||||
|
global $blindIndex;
|
||||||
|
|
||||||
$conditions = [];
|
$conditions = [];
|
||||||
$params = [':password' => $password];
|
$params = [':password' => $password];
|
||||||
|
|
||||||
if (!empty($phone)) {
|
if (!empty($phone)) {
|
||||||
$conditions[] = "passengers.phone = :phone";
|
$conditions[] = "passengers.phone = :phone";
|
||||||
$params[':phone'] = $phone;
|
$params[':phone'] = $phone;
|
||||||
|
|
||||||
|
$phoneBidx = $blindIndex ? $blindIndex->index('passengers.phone', $phone) : null;
|
||||||
|
if ($phoneBidx) {
|
||||||
|
$conditions[] = "passengers.phone_bidx = :phone_bidx";
|
||||||
|
$params[':phone_bidx'] = $phoneBidx;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!empty($email)) {
|
if (!empty($email)) {
|
||||||
$conditions[] = "passengers.email = :email";
|
$conditions[] = "passengers.email = :email";
|
||||||
$params[':email'] = $email;
|
$params[':email'] = $email;
|
||||||
|
|
||||||
|
$emailBidx = $blindIndex ? $blindIndex->index('passengers.email', $email) : null;
|
||||||
|
if ($emailBidx) {
|
||||||
|
$conditions[] = "passengers.email_bidx = :email_bidx";
|
||||||
|
$params[':email_bidx'] = $emailBidx;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
$where = implode(' OR ', $conditions);
|
$where = implode(' OR ', $conditions);
|
||||||
|
|
||||||
@@ -39,18 +62,43 @@ $sql = "SELECT
|
|||||||
passengers.`maritalStatus`,
|
passengers.`maritalStatus`,
|
||||||
passengers.`created_at`,
|
passengers.`created_at`,
|
||||||
passengers.`updated_at`,
|
passengers.`updated_at`,
|
||||||
email_verifications.verified
|
passengers.`email` AS `_email_enc`
|
||||||
FROM
|
FROM
|
||||||
`passengers`
|
`passengers`
|
||||||
LEFT JOIN email_verifications ON email_verifications.email = passengers.email
|
|
||||||
WHERE
|
WHERE
|
||||||
$where";
|
$where";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* حالة توثيق البريد.
|
||||||
|
*
|
||||||
|
* كان الاستعلام يربط email_verifications.email بعمود البريد في الحساب، لكن
|
||||||
|
* الأول يُخزَّن نصاً صريحاً والثاني مشفّراً — فالربط لم يكن يطابق شيئاً أصلاً
|
||||||
|
* وكانت verified تعود NULL دائماً. نجلبها هنا بالبريد الأصلي.
|
||||||
|
*/
|
||||||
|
function fetchEmailVerified(PDO $con, ?string $plainEmail): ?int
|
||||||
|
{
|
||||||
|
if (!$plainEmail) return null;
|
||||||
|
try {
|
||||||
|
$st = $con->prepare("SELECT verified FROM email_verifications WHERE email = ? LIMIT 1");
|
||||||
|
$st->execute([$plainEmail]);
|
||||||
|
$v = $st->fetchColumn();
|
||||||
|
return $v === false ? null : (int) $v;
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log('[email_verifications] ' . $e->getMessage());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
$stmt = $con->prepare($sql);
|
$stmt = $con->prepare($sql);
|
||||||
$stmt->execute($params);
|
$stmt->execute($params);
|
||||||
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||||
$count = $stmt->rowCount();
|
$count = $stmt->rowCount();
|
||||||
|
|
||||||
if ($count > 0) {
|
if ($count > 0) {
|
||||||
|
$plainEmail = $encryptionHelper->decryptData($data[0]['_email_enc'] ?? null) ?: null;
|
||||||
|
$data[0]['verified'] = fetchEmailVerified($con, $plainEmail);
|
||||||
|
unset($data[0]['_email_enc']);
|
||||||
|
|
||||||
$stored_password = $data[0]['password'];
|
$stored_password = $data[0]['password'];
|
||||||
if (password_verify($password, $stored_password)) {
|
if (password_verify($password, $stored_password)) {
|
||||||
unset($data[0]['password']);
|
unset($data[0]['password']);
|
||||||
|
|||||||
@@ -119,7 +119,10 @@ switch (strtolower($country)) {
|
|||||||
|
|
||||||
// 6. DB Storage on Success
|
// 6. DB Storage on Success
|
||||||
if ($sentSuccessfully) {
|
if ($sentSuccessfully) {
|
||||||
$encryptedPhone = $encryptionHelper->encryptData($receiver); // Deterministic CBC
|
$encryptedPhone = otpPhoneKey($receiver); // مفتاح بحث ثابت مستقل عن نمط التشفير
|
||||||
|
// نسخة قابلة للاسترجاع: خدمة العملاء تتابع من طلب رمزاً ولم يُكمل تسجيله،
|
||||||
|
// والمفتاح أعلاه أحادي الاتجاه فلا يُستخرج منه الرقم.
|
||||||
|
$phoneEncStored = $encryptionHelper->encryptData($receiver);
|
||||||
$encryptedOtp = $encryptionHelper->encryptDataGCM($otp); // Random GCM
|
$encryptedOtp = $encryptionHelper->encryptDataGCM($otp); // Random GCM
|
||||||
$encryptedEmail = !empty($email) ? $encryptionHelper->encryptData($email) : '';
|
$encryptedEmail = !empty($email) ? $encryptionHelper->encryptData($email) : '';
|
||||||
|
|
||||||
@@ -135,11 +138,12 @@ if ($sentSuccessfully) {
|
|||||||
|
|
||||||
$stmtIns = $con->prepare("
|
$stmtIns = $con->prepare("
|
||||||
INSERT INTO `phone_verification_service`
|
INSERT INTO `phone_verification_service`
|
||||||
(`phone_number`, `token_code`, `expiration_time`, `is_verified`, `created_at`)
|
(`phone_number`, `phone_enc`, `token_code`, `expiration_time`, `is_verified`, `created_at`)
|
||||||
VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
||||||
");
|
");
|
||||||
$stmtIns->execute([
|
$stmtIns->execute([
|
||||||
$encryptedPhone,
|
$encryptedPhone,
|
||||||
|
$phoneEncStored,
|
||||||
$encryptedOtp
|
$encryptedOtp
|
||||||
]);
|
]);
|
||||||
} elseif ($user_type === 'driver') {
|
} elseif ($user_type === 'driver') {
|
||||||
@@ -166,11 +170,12 @@ if ($sentSuccessfully) {
|
|||||||
// Insert new attempt
|
// Insert new attempt
|
||||||
$stmtIns = $con->prepare("
|
$stmtIns = $con->prepare("
|
||||||
INSERT INTO `phone_verification`
|
INSERT INTO `phone_verification`
|
||||||
(`phone_number`, `driverId`, `email`, `token_code`, `expiration_time`, `is_verified`, `created_at`)
|
(`phone_number`, `phone_enc`, `driverId`, `email`, `token_code`, `expiration_time`, `is_verified`, `created_at`)
|
||||||
VALUES (?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
VALUES (?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
||||||
");
|
");
|
||||||
$stmtIns->execute([
|
$stmtIns->execute([
|
||||||
$encryptedPhone,
|
$encryptedPhone,
|
||||||
|
$phoneEncStored,
|
||||||
$driverId ?: '',
|
$driverId ?: '',
|
||||||
$encryptedEmail,
|
$encryptedEmail,
|
||||||
$encryptedOtp
|
$encryptedOtp
|
||||||
@@ -185,11 +190,12 @@ if ($sentSuccessfully) {
|
|||||||
// Insert new attempt
|
// Insert new attempt
|
||||||
$stmtIns = $con->prepare("
|
$stmtIns = $con->prepare("
|
||||||
INSERT INTO `token_verification`
|
INSERT INTO `token_verification`
|
||||||
(`phone_number`, `token`, `expiration_time`, `verified`, `created_at`)
|
(`phone_number`, `phone_enc`, `token`, `expiration_time`, `verified`, `created_at`)
|
||||||
VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
||||||
");
|
");
|
||||||
$stmtIns->execute([
|
$stmtIns->execute([
|
||||||
$encryptedPhone,
|
$encryptedPhone,
|
||||||
|
$phoneEncStored,
|
||||||
$encryptedOtp
|
$encryptedOtp
|
||||||
]);
|
]);
|
||||||
} else {
|
} else {
|
||||||
@@ -200,11 +206,12 @@ if ($sentSuccessfully) {
|
|||||||
// Insert new attempt
|
// Insert new attempt
|
||||||
$stmtIns = $con->prepare("
|
$stmtIns = $con->prepare("
|
||||||
INSERT INTO `phone_verification_passenger`
|
INSERT INTO `phone_verification_passenger`
|
||||||
(`phone_number`, `token`, `expiration_time`, `verified`, `created_at`)
|
(`phone_number`, `phone_enc`, `token`, `expiration_time`, `verified`, `created_at`)
|
||||||
VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
||||||
");
|
");
|
||||||
$stmtIns->execute([
|
$stmtIns->execute([
|
||||||
$encryptedPhone,
|
$encryptedPhone,
|
||||||
|
$phoneEncStored,
|
||||||
$encryptedOtp
|
$encryptedOtp
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ try {
|
|||||||
// 3. Encrypt data to query
|
// 3. Encrypt data to query
|
||||||
// 4. Verify based on user type
|
// 4. Verify based on user type
|
||||||
try {
|
try {
|
||||||
$encryptedPhoneSearch = $encryptionHelper->encryptData($phone_number);
|
$encryptedPhoneSearch = otpPhoneKey($phone_number);
|
||||||
|
|
||||||
if ($user_type === 'admin') {
|
if ($user_type === 'admin') {
|
||||||
$sql = "SELECT * FROM token_verification_admin
|
$sql = "SELECT * FROM token_verification_admin
|
||||||
@@ -147,7 +147,70 @@ try {
|
|||||||
$stmtUpd = $con->prepare($sqlUpdate);
|
$stmtUpd = $con->prepare($sqlUpdate);
|
||||||
$stmtUpd->bindParam(':id', $matchedRowId, PDO::PARAM_INT);
|
$stmtUpd->bindParam(':id', $matchedRowId, PDO::PARAM_INT);
|
||||||
$stmtUpd->execute();
|
$stmtUpd->execute();
|
||||||
jsonSuccess(null, "Your phone number has been verified.");
|
|
||||||
|
// ═══════════════════════════════════════════════════════
|
||||||
|
// تغيير الجهاز: التحقق وحده لا يكفي. لا بد من ربط بصمة
|
||||||
|
// الجهاز الجديد ثم إصدار توكن driver — وإلا بقي التطبيق
|
||||||
|
// على توكن التسجيل ورجع كل endpoint محمي 403، وهو ما كان
|
||||||
|
// يجعل شاشة OTP "تنجح" ثم لا يعمل شيء بعدها.
|
||||||
|
// ═══════════════════════════════════════════════════════
|
||||||
|
$chk = $con->prepare("SELECT id FROM driver WHERE phone = ? OR (? IS NOT NULL AND phone_bidx = ?)");
|
||||||
|
global $blindIndex;
|
||||||
|
$phoneBidx = $blindIndex ? $blindIndex->index('driver.phone', $phone_number) : null;
|
||||||
|
$chk->execute([$encryptionHelper->encryptData($phone_number), $phoneBidx, $phoneBidx]);
|
||||||
|
$driverRow = $chk->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
|
if (!$driverRow) {
|
||||||
|
jsonSuccess(null, "Your phone number has been verified.");
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$driverID = (string)$driverRow['id'];
|
||||||
|
|
||||||
|
$fpRaw = filterRequest("fingerprint") ?? filterRequest("fingerPrint") ?? ($_SERVER['HTTP_X_DEVICE_FP'] ?? null);
|
||||||
|
if ($fpRaw === null && function_exists('getallheaders')) {
|
||||||
|
$hdrs = array_change_key_case(getallheaders(), CASE_LOWER);
|
||||||
|
$fpRaw = $hdrs['x-device-fp'] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($fpRaw)) {
|
||||||
|
jsonError("Device fingerprint is required to complete device change.");
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$fpPepper = getenv('FP_PEPPER') ?: '';
|
||||||
|
$fpHashed = !empty($fpPepper) ? hash('sha256', $fpRaw . $fpPepper) : $fpRaw;
|
||||||
|
$fcmToken = filterRequest("token");
|
||||||
|
|
||||||
|
// ربط الجهاز الجديد — نفس الصيغة التي يتوقعها loginJwtDriver.
|
||||||
|
$hasRow = $con->prepare("SELECT id FROM driverToken WHERE captain_id = ?");
|
||||||
|
$hasRow->execute([$driverID]);
|
||||||
|
if ($hasRow->fetch(PDO::FETCH_ASSOC)) {
|
||||||
|
if (!empty($fcmToken)) {
|
||||||
|
$con->prepare("UPDATE driverToken SET fingerPrint = ?, token = ? WHERE captain_id = ?")
|
||||||
|
->execute([$fpHashed, $encryptionHelper->encryptData($fcmToken), $driverID]);
|
||||||
|
} else {
|
||||||
|
$con->prepare("UPDATE driverToken SET fingerPrint = ? WHERE captain_id = ?")
|
||||||
|
->execute([$fpHashed, $driverID]);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$con->prepare("INSERT INTO driverToken (token, fingerPrint, captain_id, created_at) VALUES (?, ?, ?, NOW())")
|
||||||
|
->execute([
|
||||||
|
!empty($fcmToken) ? $encryptionHelper->encryptData($fcmToken) : '',
|
||||||
|
$fpHashed,
|
||||||
|
$driverID,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$audDriver = filterRequest("aud") ?: filterRequest("audience") ?: (getenv('allowedDriver2') ?: 'driver-app:ios');
|
||||||
|
$jwtSvc = new JwtService($redis);
|
||||||
|
$accessToken = $jwtSvc->generateAccessToken($driverID, 'driver', $audDriver, $fpRaw);
|
||||||
|
|
||||||
|
jsonSuccess([
|
||||||
|
"driverID" => $driverID,
|
||||||
|
"jwt" => $accessToken,
|
||||||
|
"access_token" => $accessToken,
|
||||||
|
], "Your phone number has been verified.");
|
||||||
} else {
|
} else {
|
||||||
jsonError("Your phone number could not be verified or the code is expired. Please try again.");
|
jsonError("Your phone number could not be verified or the code is expired. Please try again.");
|
||||||
}
|
}
|
||||||
@@ -177,8 +240,10 @@ try {
|
|||||||
$isRegistered = false;
|
$isRegistered = false;
|
||||||
$driverData = null;
|
$driverData = null;
|
||||||
|
|
||||||
$chkStmt = $con->prepare("SELECT id, first_name, last_name, email, phone FROM driver WHERE phone = ?");
|
$chkStmt = $con->prepare("SELECT id, first_name, last_name, email, phone FROM driver WHERE phone = ? OR (? IS NOT NULL AND phone_bidx = ?)");
|
||||||
$chkStmt->execute([$encryptionHelper->encryptData($phone_number)]);
|
global $blindIndex;
|
||||||
|
$phoneBidx = $blindIndex ? $blindIndex->index('driver.phone', $phone_number) : null;
|
||||||
|
$chkStmt->execute([$encryptionHelper->encryptData($phone_number), $phoneBidx, $phoneBidx]);
|
||||||
$driver = $chkStmt->fetch(PDO::FETCH_ASSOC);
|
$driver = $chkStmt->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
// Generate driverID for unregistered users (hash of phone)
|
// Generate driverID for unregistered users (hash of phone)
|
||||||
@@ -273,8 +338,10 @@ try {
|
|||||||
$passengerData = null;
|
$passengerData = null;
|
||||||
$passengerID = '';
|
$passengerID = '';
|
||||||
|
|
||||||
$chkStmt = $con->prepare("SELECT id, first_name, last_name, email, phone FROM passengers WHERE phone = ?");
|
$chkStmt = $con->prepare("SELECT id, first_name, last_name, email, phone FROM passengers WHERE phone = ? OR (? IS NOT NULL AND phone_bidx = ?)");
|
||||||
$chkStmt->execute([$encryptionHelper->encryptData($phone_number)]);
|
global $blindIndex;
|
||||||
|
$phoneBidx = $blindIndex ? $blindIndex->index('passengers.phone', $phone_number) : null;
|
||||||
|
$chkStmt->execute([$encryptionHelper->encryptData($phone_number), $phoneBidx, $phoneBidx]);
|
||||||
$passenger = $chkStmt->fetch(PDO::FETCH_ASSOC);
|
$passenger = $chkStmt->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
if ($passenger) {
|
if ($passenger) {
|
||||||
|
|||||||
@@ -4,6 +4,10 @@ require_once __DIR__ . '/../connect.php';
|
|||||||
$platform = filterRequest("platform");
|
$platform = filterRequest("platform");
|
||||||
$appName = filterRequest("appName");
|
$appName = filterRequest("appName");
|
||||||
|
|
||||||
|
// كان platform وappName يُحقنان مباشرة في نص الاستعلام ثم يُمرَّر إلى prepare
|
||||||
|
// بلا معاملات مربوطة — حقن SQL مكتمل الأركان. وfilterRequest لا تنظّف النص
|
||||||
|
// عمداً (انظر core/helpers.php: "بدون htmlspecialchars — نتركه لـ PDO")،
|
||||||
|
// فالحماية الوحيدة المفترضة هنا هي الربط، ولم تكن موجودة.
|
||||||
$sql = "SELECT
|
$sql = "SELECT
|
||||||
`id`,
|
`id`,
|
||||||
`platform`,
|
`platform`,
|
||||||
@@ -13,10 +17,10 @@ $sql = "SELECT
|
|||||||
FROM
|
FROM
|
||||||
`packageInfo`
|
`packageInfo`
|
||||||
WHERE
|
WHERE
|
||||||
platform='$platform' and appName='$appName';";
|
`platform` = ? AND `appName` = ?";
|
||||||
|
|
||||||
$stmt = $con->prepare($sql);
|
$stmt = $con->prepare($sql);
|
||||||
$stmt->execute();
|
$stmt->execute([$platform, $appName]);
|
||||||
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
if ($stmt->rowCount() > 0) {
|
if ($stmt->rowCount() > 0) {
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ $sql = "SELECT
|
|||||||
t.fingerPrint AS fcm_fingerprint
|
t.fingerPrint AS fcm_fingerprint
|
||||||
FROM passengers p
|
FROM passengers p
|
||||||
LEFT JOIN phone_verification_passenger
|
LEFT JOIN phone_verification_passenger
|
||||||
ON phone_verification_passenger.phone_number = p.phone
|
ON phone_verification_passenger.phone_number = p.phone_key
|
||||||
LEFT JOIN invitesToPassengers
|
LEFT JOIN invitesToPassengers
|
||||||
ON invitesToPassengers.inviterPassengerPhone = p.phone
|
ON invitesToPassengers.inviterPassengerPhone = p.phone
|
||||||
LEFT JOIN promos
|
LEFT JOIN promos
|
||||||
|
|||||||
@@ -9,18 +9,16 @@ $password = filterRequest("password");
|
|||||||
$fingerprint = filterRequest('fingerPrint') ?? filterRequest('fingerprint');
|
$fingerprint = filterRequest('fingerPrint') ?? filterRequest('fingerprint');
|
||||||
$audience = filterRequest('aud') ?: 'siro_passenger';
|
$audience = filterRequest('aud') ?: 'siro_passenger';
|
||||||
|
|
||||||
// 1. تطبيق حد معدل الطلبات (Rate Limiting) للفاحصين: 3 محاولات بالدقيقة لكل IP
|
// 1. حد معدل الطلبات مطبّق على الجميع (الحد مرفوع إلى 30/دقيقة في RateLimiter)
|
||||||
$rateLimiter = new RateLimiter($redis);
|
$rateLimiter = new RateLimiter($redis);
|
||||||
$rateLimiter->enforce(RateLimiter::identifier(), 'tester_login');
|
$rateLimiter->enforce(RateLimiter::identifier(), 'tester_login');
|
||||||
|
|
||||||
if (!$email || !$password) {
|
// 2. قائمة بيضاء صريحة لحسابات الفحص — مطابقة تامة فقط، لا مطابقة جزئية ولا مطابقة نطاق
|
||||||
echo json_encode(["status" => "failure", "message" => "Email and password are required"]);
|
$allowedTesterEmailsEnv = getenv('ALLOWED_TESTER_EMAILS') ?: ($_ENV['ALLOWED_TESTER_EMAILS'] ?? '');
|
||||||
exit();
|
$allowedEmails = array_filter(array_map(
|
||||||
}
|
fn($e) => strtolower(trim($e)),
|
||||||
|
explode(',', $allowedTesterEmailsEnv)
|
||||||
// 2. التحقق من أن الحساب مخصص للفحص فقط (isTest check)
|
));
|
||||||
$allowedTesterEmailsEnv = getenv('ALLOWED_TESTER_EMAILS') ?: '';
|
|
||||||
$allowedEmails = array_filter(array_map('trim', explode(',', $allowedTesterEmailsEnv)));
|
|
||||||
if (empty($allowedEmails)) {
|
if (empty($allowedEmails)) {
|
||||||
$allowedEmails = [
|
$allowedEmails = [
|
||||||
'driver_tester@siromove.com',
|
'driver_tester@siromove.com',
|
||||||
@@ -28,18 +26,21 @@ if (empty($allowedEmails)) {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$cleanEmail = strtolower(trim((string) $email));
|
||||||
|
$isTester = in_array($cleanEmail, $allowedEmails, true);
|
||||||
|
|
||||||
$cleanEmail = strtolower(trim($email));
|
if (!$email || !$password) {
|
||||||
$isTester = in_array($cleanEmail, $allowedEmails) ||
|
echo json_encode(["status" => "failure", "message" => "Email and password are required"]);
|
||||||
substr($cleanEmail, -13) === '@siromove.com' ||
|
exit();
|
||||||
str_contains($cleanEmail, 'tester') ||
|
}
|
||||||
str_contains($cleanEmail, 'reviewer');
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$con = Database::get('main');
|
$con = Database::get('main');
|
||||||
|
|
||||||
// تشفير الإيميل للبحث في قاعدة البيانات
|
// تشفير الإيميل للبحث في قاعدة البيانات
|
||||||
$encryptedEmail = $encryptionHelper->encryptData($email);
|
$encryptedEmail = $encryptionHelper->encryptData($email);
|
||||||
|
global $blindIndex;
|
||||||
|
$emailBidx = $blindIndex ? $blindIndex->index('passengers.email', $email) : null;
|
||||||
|
|
||||||
// Auto-seed/create tester passenger logic removed for security
|
// Auto-seed/create tester passenger logic removed for security
|
||||||
|
|
||||||
@@ -51,14 +52,15 @@ try {
|
|||||||
invitesToPassengers.isGiftToken
|
invitesToPassengers.isGiftToken
|
||||||
FROM passengers p
|
FROM passengers p
|
||||||
LEFT JOIN phone_verification_passenger
|
LEFT JOIN phone_verification_passenger
|
||||||
ON phone_verification_passenger.phone_number = p.phone
|
ON phone_verification_passenger.phone_number = p.phone_key
|
||||||
LEFT JOIN invitesToPassengers
|
LEFT JOIN invitesToPassengers
|
||||||
ON invitesToPassengers.inviterPassengerPhone = p.phone
|
ON invitesToPassengers.inviterPassengerPhone = p.phone
|
||||||
WHERE p.email = :email
|
WHERE p.email = :email OR (:email_bidx IS NOT NULL AND p.email_bidx = :email_bidx)
|
||||||
LIMIT 1";
|
LIMIT 1";
|
||||||
|
|
||||||
$stmt = $con->prepare($sql);
|
$stmt = $con->prepare($sql);
|
||||||
$stmt->bindParam(':email', $encryptedEmail);
|
$stmt->bindParam(':email', $encryptedEmail);
|
||||||
|
$stmt->bindParam(':email_bidx', $emailBidx);
|
||||||
$stmt->execute();
|
$stmt->execute();
|
||||||
|
|
||||||
$data = $stmt->fetch(PDO::FETCH_ASSOC);
|
$data = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||||
@@ -118,7 +120,7 @@ try {
|
|||||||
http_response_code(500);
|
http_response_code(500);
|
||||||
echo json_encode([
|
echo json_encode([
|
||||||
"status" => "failure",
|
"status" => "failure",
|
||||||
"message" => "Server error: " . $e->getMessage() . " in " . basename($e->getFile()) . " on line " . $e->getLine()
|
"message" => "Server error. Please try again."
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
exit();
|
exit();
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ try {
|
|||||||
$firstName_encrypted = $encryptionHelper->encryptData($firstName);
|
$firstName_encrypted = $encryptionHelper->encryptData($firstName);
|
||||||
$lastName_encrypted = $encryptionHelper->encryptData($lastName);
|
$lastName_encrypted = $encryptionHelper->encryptData($lastName);
|
||||||
$email_encrypted = $encryptionHelper->encryptData($email);
|
$email_encrypted = $encryptionHelper->encryptData($email);
|
||||||
$uniqueId = substr(md5($phoneNumber), 0, 20);
|
$uniqueId = substr(md5($phoneNumber), 0, 16);
|
||||||
$password_hashed = password_hash($email . $uniqueId, PASSWORD_DEFAULT);
|
$password_hashed = password_hash($email . $uniqueId, PASSWORD_DEFAULT);
|
||||||
$unknown_encrypted = $encryptionHelper->encryptData("unknown yet");
|
$unknown_encrypted = $encryptionHelper->encryptData("unknown yet");
|
||||||
|
|
||||||
@@ -77,12 +77,13 @@ try {
|
|||||||
// (مهلة أوسع من صلاحية الرمز نفسه [5 دقائق] لإعطاء وقت كافٍ لإكمال
|
// (مهلة أوسع من صلاحية الرمز نفسه [5 دقائق] لإعطاء وقت كافٍ لإكمال
|
||||||
// نموذج التسجيل بعد التحقق مباشرة).
|
// نموذج التسجيل بعد التحقق مباشرة).
|
||||||
$step = 4.5;
|
$step = 4.5;
|
||||||
|
$otpSearchKey = otpPhoneKey($phoneNumber);
|
||||||
$verifyCheckStmt = $con->prepare(
|
$verifyCheckStmt = $con->prepare(
|
||||||
"SELECT id FROM phone_verification_passenger
|
"SELECT id FROM phone_verification_passenger
|
||||||
WHERE phone_number = ? AND verified = 1 AND created_at > DATE_SUB(NOW(), INTERVAL 30 MINUTE)
|
WHERE phone_number = ? AND verified = 1 AND created_at > DATE_SUB(NOW(), INTERVAL 30 MINUTE)
|
||||||
LIMIT 1"
|
LIMIT 1"
|
||||||
);
|
);
|
||||||
$verifyCheckStmt->execute([$phoneNumber_encrypted]);
|
$verifyCheckStmt->execute([$otpSearchKey]);
|
||||||
if ($verifyCheckStmt->rowCount() === 0) {
|
if ($verifyCheckStmt->rowCount() === 0) {
|
||||||
error_log("$logTag Step 4.5 Error: Phone number not verified via OTP.");
|
error_log("$logTag Step 4.5 Error: Phone number not verified via OTP.");
|
||||||
jsonError("Phone number must be verified before registration.");
|
jsonError("Phone number must be verified before registration.");
|
||||||
@@ -103,8 +104,19 @@ try {
|
|||||||
// Step 6: التحقق من وجود المستخدم (Database Check)
|
// Step 6: التحقق من وجود المستخدم (Database Check)
|
||||||
// ======================================================
|
// ======================================================
|
||||||
$step = 6;
|
$step = 6;
|
||||||
$checkStmt = $con->prepare("SELECT id FROM passengers WHERE phone = ?");
|
// كشف التكرار عبر الفهرس الأعمى + المقارنة القديمة: بدون الفهرس يفشل
|
||||||
$checkStmt->execute([$phoneNumber_encrypted]);
|
// الكشف بعد الانتقال إلى GCM فيُسمح بتسجيل نفس الرقم مرتين.
|
||||||
|
global $blindIndex;
|
||||||
|
$phoneBidx = $blindIndex ? $blindIndex->index('passengers.phone', $phoneNumber) : null;
|
||||||
|
$emailBidx = $blindIndex ? $blindIndex->index('passengers.email', $email) : null;
|
||||||
|
$nameBidx = $blindIndex ? $blindIndex->index('passengers.name', trim("$firstName $lastName")) : null;
|
||||||
|
// مفتاح ربط جداول التحقق — يجب أن يطابق otpPhoneKey() حرفياً
|
||||||
|
$phoneKey = otpPhoneKey($phoneNumber);
|
||||||
|
|
||||||
|
$checkStmt = $con->prepare(
|
||||||
|
"SELECT id FROM passengers WHERE phone = ? OR (? IS NOT NULL AND phone_bidx = ?)"
|
||||||
|
);
|
||||||
|
$checkStmt->execute([$phoneNumber_encrypted, $phoneBidx, $phoneBidx]);
|
||||||
|
|
||||||
if ($checkStmt->rowCount() > 0) {
|
if ($checkStmt->rowCount() > 0) {
|
||||||
error_log("$logTag Step 6 Error: User already exists.");
|
error_log("$logTag Step 6 Error: User already exists.");
|
||||||
@@ -119,8 +131,8 @@ try {
|
|||||||
error_log("$logTag Step 7: Inserting into passengers table...");
|
error_log("$logTag Step 7: Inserting into passengers table...");
|
||||||
|
|
||||||
$insertStmt = $con->prepare("
|
$insertStmt = $con->prepare("
|
||||||
INSERT INTO passengers (id, first_name, last_name, email, phone, password, gender, birthdate, site, sosPhone, education, employmentType, maritalStatus, status, created_at, updated_at)
|
INSERT INTO passengers (id, first_name, last_name, email, phone, password, gender, birthdate, site, sosPhone, education, employmentType, maritalStatus, status, created_at, updated_at, phone_bidx, email_bidx, name_bidx, phone_key)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW(), NOW())
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW(), NOW(), ?, ?, ?, ?)
|
||||||
");
|
");
|
||||||
$success = $insertStmt->execute([
|
$success = $insertStmt->execute([
|
||||||
$uniqueId,
|
$uniqueId,
|
||||||
@@ -135,7 +147,12 @@ try {
|
|||||||
$unknown_encrypted,
|
$unknown_encrypted,
|
||||||
$unknown_encrypted,
|
$unknown_encrypted,
|
||||||
$unknown_encrypted,
|
$unknown_encrypted,
|
||||||
$unknown_encrypted
|
$unknown_encrypted,
|
||||||
|
// فهارس البحث: تُكتب مع السجل حتى يكون قابلاً للبحث فوراً
|
||||||
|
$phoneBidx,
|
||||||
|
$emailBidx,
|
||||||
|
$nameBidx,
|
||||||
|
$phoneKey
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (!$success) {
|
if (!$success) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
// File: send_otp.php (بديل عن النسخة المعتمدة على RaseelPlus)
|
// File: send_otp.php (بديل عن النسخة المعتمدة على RaseelPlus)
|
||||||
require_once __DIR__ . '/../../connect.php';
|
require_once __DIR__ . '/../../../connect.php';
|
||||||
|
|
||||||
/* 1) توليد رمز التحقق (3 خانات) */
|
/* 1) توليد رمز التحقق (3 خانات) */
|
||||||
$otp = (string)random_int(100, 999);
|
$otp = (string)random_int(100, 999);
|
||||||
@@ -51,8 +51,8 @@ $sentOK = ($httpCode === 200 && ($decoded['success'] ?? false));
|
|||||||
|
|
||||||
if ($sentOK) {
|
if ($sentOK) {
|
||||||
/* 3) حفظ الرمز في Redis + قاعدة البيانات */
|
/* 3) حفظ الرمز في Redis + قاعدة البيانات */
|
||||||
$receiver_enc = $encryptionHelper->encryptData($receiver);
|
$receiver_enc = otpPhoneKey($receiver);
|
||||||
$otp_enc = $encryptionHelper->encryptData($otp);
|
$otp_enc = otpPhoneKey($otp); // يجب أن يطابق صيغة المقارنة في verify_otp
|
||||||
|
|
||||||
$exp = date('Y-m-d H:i:s', strtotime('+5 minutes'));
|
$exp = date('Y-m-d H:i:s', strtotime('+5 minutes'));
|
||||||
$now = date('Y-m-d H:i:s');
|
$now = date('Y-m-d H:i:s');
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
// File: verify_otp.php (with enhanced logging)
|
// File: verify_otp.php (with enhanced logging)
|
||||||
// siro_v1/auth/token_passenger
|
// siro_v1/auth/token_passenger
|
||||||
require_once __DIR__ . '/../../connect.php';
|
require_once __DIR__ . '/../../../connect.php';
|
||||||
|
|
||||||
// --- Start of Script Execution ---
|
// --- Start of Script Execution ---
|
||||||
error_log("--- [verify_otp.php] Script execution started. ---");
|
error_log("--- [verify_otp.php] Script execution started. ---");
|
||||||
@@ -18,8 +18,9 @@ if (empty($phoneNumber) || empty($otp)) {
|
|||||||
exit();
|
exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
|
$phoneNumber_encrypted = otpPhoneKey($phoneNumber);
|
||||||
$otp_encrypted = $encryptionHelper->encryptData($otp);
|
// الرمز يُقارن بالتساوي أيضاً، فيحتاج نفس الصيغة الثابتة
|
||||||
|
$otp_encrypted = otpPhoneKey($otp);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 1. التحقق من Redis بدلاً من MySQL
|
// 1. التحقق من Redis بدلاً من MySQL
|
||||||
|
|||||||
@@ -4,9 +4,8 @@ require_once __DIR__ . '/../connect.php';
|
|||||||
$email = filterRequest("email");
|
$email = filterRequest("email");
|
||||||
$token = filterRequest("token");
|
$token = filterRequest("token");
|
||||||
|
|
||||||
$sql = "SELECT * FROM `email_verifications` WHERE `email` = '$email'";
|
$stmt = $con->prepare("SELECT * FROM `email_verifications` WHERE `email` = ?");
|
||||||
$stmt = $con->prepare($sql);
|
$stmt->execute([$email]);
|
||||||
$stmt->execute();
|
|
||||||
|
|
||||||
$rowCount = $stmt->rowCount();
|
$rowCount = $stmt->rowCount();
|
||||||
|
|
||||||
@@ -41,9 +40,9 @@ SEFER Team.
|
|||||||
|
|
||||||
if ($rowCount > 0) {
|
if ($rowCount > 0) {
|
||||||
// The email already exists, so update the data
|
// The email already exists, so update the data
|
||||||
$sql = "UPDATE `email_verifications` SET `token` = '$token' WHERE `email` = '$email'";
|
// كانت القيم تُدمج في نص الاستعلام مباشرةً — حقن SQL عبر البريد أو الرمز.
|
||||||
$stmt = $con->prepare($sql);
|
$stmt = $con->prepare("UPDATE `email_verifications` SET `token` = ? WHERE `email` = ?");
|
||||||
$stmt->execute();
|
$stmt->execute([$token, $email]);
|
||||||
|
|
||||||
if ($stmt->rowCount() > 0) {
|
if ($stmt->rowCount() > 0) {
|
||||||
// The update was successful
|
// The update was successful
|
||||||
@@ -55,9 +54,8 @@ if ($rowCount > 0) {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// The email does not exist, so insert the data
|
// The email does not exist, so insert the data
|
||||||
$sql = "INSERT INTO `email_verifications` (`email`, `token`) VALUES ('$email', '$token')";
|
$stmt = $con->prepare("INSERT INTO `email_verifications` (`email`, `token`) VALUES (?, ?)");
|
||||||
$stmt = $con->prepare($sql);
|
$stmt->execute([$email, $token]);
|
||||||
$stmt->execute();
|
|
||||||
|
|
||||||
if ($stmt->rowCount() > 0) {
|
if ($stmt->rowCount() > 0) {
|
||||||
// The insertion was successful
|
// The insertion was successful
|
||||||
|
|||||||
@@ -19,6 +19,14 @@ try {
|
|||||||
die("Connection failed: " . $e->getMessage() . "\n");
|
die("Connection failed: " . $e->getMessage() . "\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getRedisConnection() لا ترمي استثناءً — تُعيد null عند تعذّر الاتصال.
|
||||||
|
// كل مخرجات هذا المحرّك تُكتب في Redis (مقارنة السائقين، ملخّص ذروة
|
||||||
|
// المنافسين، المناطق الساخنة)، فلا معنى لمتابعة التشغيل بدونه.
|
||||||
|
if (!$redis) {
|
||||||
|
error_log('[AI Engine] ABORT: Redis unavailable — no cache target to write to.');
|
||||||
|
die("Redis unavailable — aborting AI engine run.\n");
|
||||||
|
}
|
||||||
|
|
||||||
echo "Starting Siro AI Engine v2 (Powered by Pricing Engine)...\n";
|
echo "Starting Siro AI Engine v2 (Powered by Pricing Engine)...\n";
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
|
|||||||
@@ -26,6 +26,14 @@ try {
|
|||||||
die("Database connection failed: " . $e->getMessage() . "\n");
|
die("Database connection failed: " . $e->getMessage() . "\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getRedisConnection() لا ترمي استثناءً — تُعيد null عند تعذّر الاتصال.
|
||||||
|
// مفتاح مكافحة التكرار (TTL يوم كامل) يعيش في Redis؛ بدونه يُعاد إرسال
|
||||||
|
// نفس الحملة التسويقية كل ساعة.
|
||||||
|
if (!$redis) {
|
||||||
|
error_log('[AutoMarketingPusher] ABORT: Redis unavailable — anti-spam guard would fail open.');
|
||||||
|
die("Redis unavailable — aborting to avoid duplicate campaign pushes.\n");
|
||||||
|
}
|
||||||
|
|
||||||
echo "Starting Auto Marketing Pusher Engine...\n";
|
echo "Starting Auto Marketing Pusher Engine...\n";
|
||||||
|
|
||||||
// 1. استخراج الركاب الخاملين في آخر ساعتين (الذين لم يقموا بأي طلب اليوم)
|
// 1. استخراج الركاب الخاملين في آخر ساعتين (الذين لم يقموا بأي طلب اليوم)
|
||||||
|
|||||||
@@ -0,0 +1,145 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* cron_driver_score.php
|
||||||
|
* ─────────────────────────────────────────────────────────────
|
||||||
|
* يغذّي إشارات ترتيب محرك الإسناد في مفاتيح driver:score:* على Redis.
|
||||||
|
*
|
||||||
|
* بدون هذا الكرون يعمل المحرك بالقرب وملاءمة الوجهة فقط، وتُحسب بقية
|
||||||
|
* المكوّنات محايدة (٠٫٥) — أي أن ٥٠٪ من وزن الترتيب معطّل عملياً:
|
||||||
|
* • معدّل القبول ٢٠٪ ← يُحسب هنا
|
||||||
|
* • التقييم ١٥٪ ← يُحسب هنا
|
||||||
|
* • مدة الخمول ١٥٪ ← يختمها finish_ride_updates.php، لا نلمسها
|
||||||
|
*
|
||||||
|
* ── معدّل القبول ──
|
||||||
|
* لا يوجد في MySQL أي سجل لعرضٍ لم يُقبل: driver_orders يسجّل المقبول
|
||||||
|
* فقط. لذلك يُعدّ العرض في السوكِت (حقل offers) والقبول في acceptRide.php
|
||||||
|
* (حقل accepts)، وهذا الكرون يحوّلهما لنسبة.
|
||||||
|
*
|
||||||
|
* الاضمحلال: نضرب العدّادين بمعامل كل تشغيل، فتصير النسبة نافذة متحرّكة
|
||||||
|
* تعكس السلوك الأخير لا سجلّ العمر كله. سائق أصلح سلوكه يتعافى خلال أيام
|
||||||
|
* بدل أن يظل مسجوناً في ماضيه.
|
||||||
|
*
|
||||||
|
* تنعيم Laplace: سائق عُرض عليه عرضان وقَبِل واحداً لا يستحق ٥٠٪ بثقة
|
||||||
|
* كاملة. نضيف عروضاً وهمية محايدة فتقترب نسبته من المحايد حتى تتراكم
|
||||||
|
* بيانات كافية.
|
||||||
|
*
|
||||||
|
* جدولة مقترحة (crontab): كل ربع ساعة — الإشارات بطيئة التغيّر ولا تستحق أكثر.
|
||||||
|
* الحقل الأول في السطر: الشرطة المائلة ثم 15
|
||||||
|
* ثم: docker compose exec -T php php /var/www/backend/bot/cron_driver_score.php
|
||||||
|
*
|
||||||
|
* ⚠️ يجب أن يعمل داخل حاوية php: Redis لا ينشر منافذ، فتشغيله على المضيف
|
||||||
|
* يعطي $redisLocation = null ويخرج بلا عمل.
|
||||||
|
*/
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../core/bootstrap.php';
|
||||||
|
|
||||||
|
// ── معاملات المعايرة ──
|
||||||
|
const SCORE_DECAY = 0.85; // ما يبقى من العدّادات كل تشغيل
|
||||||
|
const SCORE_PRIOR_OFFERS = 4.0; // عروض وهمية للتنعيم
|
||||||
|
const SCORE_PRIOR_ACCEPTS = 2.0; // منها مقبولة — أي محايد ٠٫٥
|
||||||
|
const SCORE_KEY_TTL = 2592000; // 30 يوماً: سائق اختفى يُنسى وحده
|
||||||
|
|
||||||
|
if (!isset($redisLocation) || !$redisLocation) {
|
||||||
|
fwrite(STDERR, "[driver_score] Redis غير متاح — هل يعمل الكرون داخل حاوية php؟\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$con = Database::get('main');
|
||||||
|
} catch (Exception $e) {
|
||||||
|
fwrite(STDERR, "[driver_score] DB unavailable: " . $e->getMessage() . "\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
// ١) التقييمات — استعلام واحد مجمّع لكل السائقين
|
||||||
|
// نافذة ٩٠ يوماً: تقييم قبل سنة لا يصف السائق اليوم.
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
$ratings = [];
|
||||||
|
try {
|
||||||
|
$stmt = $con->query("
|
||||||
|
SELECT driver_id, AVG(rating) AS avg_rating, COUNT(*) AS cnt
|
||||||
|
FROM ratingDriver
|
||||||
|
WHERE driver_id IS NOT NULL
|
||||||
|
AND rating IS NOT NULL
|
||||||
|
AND created_at >= NOW() - INTERVAL 90 DAY
|
||||||
|
GROUP BY driver_id
|
||||||
|
");
|
||||||
|
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
|
||||||
|
// تقييم واحد أو اثنان لا يكفيان لحكم — ننعّمه نحو المحايد (٣٫٥/٥)
|
||||||
|
$n = (int) $row['cnt'];
|
||||||
|
$avg = (float) $row['avg_rating'];
|
||||||
|
$ratings[$row['driver_id']] = round((($avg * $n) + (3.5 * 3)) / ($n + 3), 3);
|
||||||
|
}
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
fwrite(STDERR, "[driver_score] تعذّر جلب التقييمات: " . $e->getMessage() . "\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
// ٢) المرور على مفاتيح الدرجات الموجودة
|
||||||
|
// scan لا keys: keys تحجب Redis بالكامل على قاعدة كبيرة.
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
$processed = 0;
|
||||||
|
$iterator = null;
|
||||||
|
|
||||||
|
// بلا هذا الضبط يرجع phpredis false عند دفعة فارغة فتتوقف الحلقة مبكراً
|
||||||
|
$redisLocation->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
|
||||||
|
|
||||||
|
while (($keys = $redisLocation->scan($iterator, 'driver:score:*', 200)) !== false) {
|
||||||
|
foreach ($keys as $key) {
|
||||||
|
$driverId = substr($key, strlen('driver:score:'));
|
||||||
|
if ($driverId === '') continue;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$row = $redisLocation->hGetAll($key) ?: [];
|
||||||
|
$offers = (float) ($row['offers'] ?? 0);
|
||||||
|
$accepts = (float) ($row['accepts'] ?? 0);
|
||||||
|
|
||||||
|
// لا يتجاوز المقبول المعروض — يحدث لو أُعيد ضبط أحدهما وحده.
|
||||||
|
$accepts = min($accepts, $offers);
|
||||||
|
|
||||||
|
$rate = ($accepts + SCORE_PRIOR_ACCEPTS) / ($offers + SCORE_PRIOR_OFFERS);
|
||||||
|
|
||||||
|
$update = ['accept_rate' => round($rate, 4)];
|
||||||
|
|
||||||
|
if (isset($ratings[$driverId])) {
|
||||||
|
$update['rating'] = $ratings[$driverId];
|
||||||
|
}
|
||||||
|
|
||||||
|
// الاضمحلال: نافذة متحرّكة بدل سجل العمر كله.
|
||||||
|
$update['offers'] = round($offers * SCORE_DECAY, 3);
|
||||||
|
$update['accepts'] = round($accepts * SCORE_DECAY, 3);
|
||||||
|
|
||||||
|
$redisLocation->hMSet($key, $update);
|
||||||
|
$redisLocation->expire($key, SCORE_KEY_TTL);
|
||||||
|
$processed++;
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
fwrite(STDERR, "[driver_score] خطأ على $key: " . $e->getMessage() . "\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
// ٣) سائقون لهم تقييم ولم يُعرض عليهم شيء بعد
|
||||||
|
// بلا هذه الخطوة يظل التقييم معطّلاً حتى أول عرض — أي أن السائق
|
||||||
|
// الممتاز الجديد لا يستفيد من تقييمه في أول ترتيب له.
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
$seeded = 0;
|
||||||
|
foreach ($ratings as $driverId => $rating) {
|
||||||
|
$key = "driver:score:$driverId";
|
||||||
|
try {
|
||||||
|
if (!$redisLocation->exists($key)) {
|
||||||
|
$redisLocation->hMSet($key, [
|
||||||
|
'rating' => $rating,
|
||||||
|
'accept_rate' => round(SCORE_PRIOR_ACCEPTS / SCORE_PRIOR_OFFERS, 4),
|
||||||
|
]);
|
||||||
|
$redisLocation->expire($key, SCORE_KEY_TTL);
|
||||||
|
$seeded++;
|
||||||
|
}
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
// تجاهُل — المرور القادم يعالجه
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "[driver_score] حُدِّث $processed سائق، وأُنشئ $seeded من التقييمات."
|
||||||
|
. " تقييمات محمّلة: " . count($ratings) . "\n";
|
||||||
@@ -14,6 +14,13 @@ try {
|
|||||||
die("Connection failed: " . $e->getMessage() . "\n");
|
die("Connection failed: " . $e->getMessage() . "\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getRedisConnection() لا ترمي استثناءً — تُعيد null عند تعذّر الاتصال.
|
||||||
|
// الهدف الوحيد لهذا السكربت هو الكتابة إلى مفتاح Redis للكاش.
|
||||||
|
if (!$redis) {
|
||||||
|
error_log('[HeatmapCache] ABORT: Redis unavailable — nothing to cache into.');
|
||||||
|
die("Redis unavailable — aborting heatmap cache generation.\n");
|
||||||
|
}
|
||||||
|
|
||||||
echo "Starting Heatmap Cache Generation (Redis)...\n";
|
echo "Starting Heatmap Cache Generation (Redis)...\n";
|
||||||
|
|
||||||
// مربعات المدن الكبرى لتمثيل الدول (لتجنب حساب المضلعات المعقدة)
|
// مربعات المدن الكبرى لتمثيل الدول (لتجنب حساب المضلعات المعقدة)
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* cron_insurance_premiums.php — قيد أقساط التأمين
|
||||||
|
* ─────────────────────────────────────────────────────────────
|
||||||
|
* يقيّد قسط كل وثيقة نشطة بلغت دورتها. لا يخصم من رصيد أحد:
|
||||||
|
*
|
||||||
|
* رصيد السائق يعيش في payment_server لا في هذه القاعدة، والخصم
|
||||||
|
* المباشر من هنا كان سيعني كتابةً عابرة للحدود بلا معاملة موحّدة —
|
||||||
|
* أي خطر رصيد ناقص بلا قيد يقابله، أو قيد بلا خصم. فنقيّد استحقاقاً
|
||||||
|
* هنا، ويقرأه محرك التسوية `cron_obligation_settlement.php`.
|
||||||
|
*
|
||||||
|
* تحديث (٢٠٢٦-٠٨-٠٨): صار هذا الملف **مُصدِر استحقاق** في محرك
|
||||||
|
* الالتزامات العام، فيكتب في `obligation_ledger` لا في
|
||||||
|
* `insurance_premium_ledger`. سبب النقل أن الدفتر القديم لم يكن يقرأه
|
||||||
|
* أحد إطلاقاً — «تقرأه التسوية» كان وعداً بلا منفّذ، وكل قسط قُيّد منذ
|
||||||
|
* الإطلاق بقي معلّقاً بلا تحصيل. جداول التأمين تبقى كما هي شاهداً
|
||||||
|
* تاريخياً، وقد رُحّلت بياناتها في
|
||||||
|
* `migrations/2026_08_08_obligations_engine.sql`.
|
||||||
|
*
|
||||||
|
* الحماية من الاحتساب المزدوج طبقتان:
|
||||||
|
* ١. `last_charged_on` في الالتزام — نفلتر به قبل العمل
|
||||||
|
* ٢. مفتاح فريد (obligation_id, charge_date) في الدفتر — يحسم السباق
|
||||||
|
* لو عملت نسختان من الكرون معاً
|
||||||
|
*
|
||||||
|
* الأولى وحدها لا تكفي: بين القراءة والكتابة نافذة، والمفتاح الفريد
|
||||||
|
* هو ما يجعل تكرار القيد مستحيلاً لا نادراً.
|
||||||
|
*
|
||||||
|
* جدولة: مرة يومياً بعد منتصف الليل.
|
||||||
|
* 15 0 * * * docker compose exec -T php php /var/www/backend/bot/cron_insurance_premiums.php
|
||||||
|
*/
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../core/bootstrap.php';
|
||||||
|
|
||||||
|
try {
|
||||||
|
$con = Database::get('main');
|
||||||
|
} catch (Exception $e) {
|
||||||
|
fwrite(STDERR, '[insurance] DB unavailable: ' . $e->getMessage() . "\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
$today = date('Y-m-d');
|
||||||
|
// الشهري يُقيَّد على أول الشهر لا على يوم الاشتراك: دفتر تتوزّع فيه
|
||||||
|
// تواريخ القيد على ثلاثين يوماً يستحيل تسويته مع الشريك.
|
||||||
|
$monthStart = date('Y-m-01');
|
||||||
|
|
||||||
|
$charged = 0;
|
||||||
|
$skipped = 0;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// المصدر الآن الالتزامات لا الوثائق. القيد على `kind = 'recurring'`
|
||||||
|
// لا على المنتج التأميني تحديداً: أي منتج دوري يُضاف لاحقاً يُقيَّد
|
||||||
|
// بالمنطق نفسه بلا سطر جديد هنا.
|
||||||
|
$st = $con->query("
|
||||||
|
SELECT o.id, o.driver_id, o.last_charged_on, o.cycle_amount,
|
||||||
|
pr.code AS product_code, pr.currency, pr.billing_cycle
|
||||||
|
FROM driver_obligations o
|
||||||
|
JOIN obligation_products pr ON pr.id = o.product_id
|
||||||
|
WHERE o.status = 'active'
|
||||||
|
AND pr.kind = 'recurring'
|
||||||
|
AND pr.billing_cycle <> 'none'
|
||||||
|
ORDER BY o.id ASC
|
||||||
|
");
|
||||||
|
|
||||||
|
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $policy) {
|
||||||
|
$chargeDate = $policy['billing_cycle'] === 'monthly' ? $monthStart : $today;
|
||||||
|
|
||||||
|
// الفلترة الرخيصة أولاً — تجنّبنا محاولة إدراج لكل التزام كل يوم.
|
||||||
|
if ($policy['last_charged_on'] === $chargeDate) {
|
||||||
|
$skipped++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$con->beginTransaction();
|
||||||
|
|
||||||
|
$con->prepare("
|
||||||
|
INSERT INTO obligation_ledger
|
||||||
|
(obligation_id, driver_id, product_code, charge_date,
|
||||||
|
amount, amount_collected, amount_remaining, currency, status)
|
||||||
|
VALUES (?, ?, ?, ?, ?, 0, ?, ?, 'pending')
|
||||||
|
")->execute([
|
||||||
|
$policy['id'], $policy['driver_id'], $policy['product_code'], $chargeDate,
|
||||||
|
$policy['cycle_amount'], $policy['cycle_amount'], $policy['currency'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$con->prepare("
|
||||||
|
UPDATE driver_obligations SET last_charged_on = ? WHERE id = ?
|
||||||
|
")->execute([$chargeDate, $policy['id']]);
|
||||||
|
|
||||||
|
$con->commit();
|
||||||
|
$charged++;
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
if ($con->inTransaction()) $con->rollBack();
|
||||||
|
|
||||||
|
// 23000 = خرق المفتاح الفريد: نسخة أخرى سبقتنا للقيد نفسه.
|
||||||
|
// هذه ليست حالة خطأ — هي بالضبط ما صُمّم المفتاح لمنعه.
|
||||||
|
if ($e->getCode() === '23000') {
|
||||||
|
$con->prepare("
|
||||||
|
UPDATE driver_obligations SET last_charged_on = ? WHERE id = ?
|
||||||
|
")->execute([$chargeDate, $policy['id']]);
|
||||||
|
$skipped++;
|
||||||
|
} else {
|
||||||
|
error_log("[insurance] تعذّر قيد استحقاق الالتزام #{$policy['id']}: " . $e->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
fwrite(STDERR, '[insurance] فشل المرور: ' . $e->getMessage() . "\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "[insurance] قُيِّد {$charged} قسطاً، تُخطّي {$skipped}\n";
|
||||||
@@ -18,6 +18,14 @@ try {
|
|||||||
die("Connection failed: " . $e->getMessage() . "\n");
|
die("Connection failed: " . $e->getMessage() . "\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getRedisConnection() تُعيد المتغير العام $redis فقط، وbootstrap.php يتركه null
|
||||||
|
// عند فشل الاتصال — فهي لا ترمي استثناءً والـ try/catch أعلاه لا يلتقط شيئاً.
|
||||||
|
// بدون هذا الفحص كان السكربت ينهار فوراً بـ "call to a member function get() on null".
|
||||||
|
if (!$redis) {
|
||||||
|
error_log('[cron_kazan_adjuster] ABORT: Redis unavailable — Kazan discounts left untouched.');
|
||||||
|
die("Redis unavailable — aborting without touching Kazan discounts.\n");
|
||||||
|
}
|
||||||
|
|
||||||
$countries = ['SY', 'JO', 'EG', 'IQ'];
|
$countries = ['SY', 'JO', 'EG', 'IQ'];
|
||||||
|
|
||||||
foreach ($countries as $country) {
|
foreach ($countries as $country) {
|
||||||
|
|||||||
@@ -0,0 +1,194 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* cron_leak_detection.php
|
||||||
|
* ─────────────────────────────────────────────────────────────
|
||||||
|
* كشف التسرب خارج المنصة — الرحلة تحصل فعلاً والعمولة لا تصل.
|
||||||
|
*
|
||||||
|
* ── لماذا خادمياً ──
|
||||||
|
* جدول driver_ride_scam يملؤه تطبيق السائق عن نفسه، فنسخة معدّلة لا
|
||||||
|
* ترسل شيئاً. هذا الكرون يستنتج النمط من بيانات لا يملك السائق تزويرها:
|
||||||
|
* سجل القبول في driver_orders، وحالة الرحلة في ride.
|
||||||
|
*
|
||||||
|
* ── النمط ──
|
||||||
|
* قَبِل السائق → أُلغيت الرحلة → ولم تبدأ قط
|
||||||
|
* مرة واحدة قد تكون صدفة. تكرار نفس زوج (سائق، راكب) ليس صدفة.
|
||||||
|
*
|
||||||
|
* ── العقوبة ──
|
||||||
|
* لا حظر. تُكتب درجة الاشتباه في driver:score:$id (حقل leak_penalty)
|
||||||
|
* فتخفض ترتيب السائق في محرك الإسناد — يخسر السبق والرحلات الأقرب
|
||||||
|
* تدريجياً. موجع بلا حرمان، وقابل للتراجع فوراً إن تبيّن الخطأ.
|
||||||
|
* الحالات عالية الثقة تُترك في driver_leak_events لمراجعة بشرية.
|
||||||
|
*
|
||||||
|
* جدولة مقترحة (crontab): كل ساعة.
|
||||||
|
* docker compose exec -T php php /var/www/backend/bot/cron_leak_detection.php
|
||||||
|
*
|
||||||
|
* ⚠️ يجب أن يعمل داخل حاوية php — Redis لا ينشر منافذ.
|
||||||
|
*/
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../core/bootstrap.php';
|
||||||
|
|
||||||
|
// ── معاملات المعايرة ──
|
||||||
|
const LEAK_WINDOW_DAYS = 30; // نافذة احتساب التكرار
|
||||||
|
const LEAK_SCAN_HOURS = 48; // عمق الفحص في كل مرور (بهامش للتأخر)
|
||||||
|
const LEAK_PENALTY_MAX = 1.0; // سقف العقوبة
|
||||||
|
const LEAK_REVIEW_THRESHOLD = 0.70; // فوقها تستحق مراجعة بشرية
|
||||||
|
|
||||||
|
// الحالات التي تعني "أُلغيت بعد القبول"
|
||||||
|
const LEAK_CANCEL_STATUSES = ['CancelFromDriverAfterApply', 'cancelled_by_passenger'];
|
||||||
|
|
||||||
|
// الحالات التي تعني أن الرحلة بدأت أو اكتملت — وجودها ينفي الاشتباه.
|
||||||
|
// 'arrived' ليست منها عمداً: الوصول ثم الإلغاء هو النمط المشتبه نفسه،
|
||||||
|
// لا نفيه. (عملياً الإلغاء يكتب فوق الحالة، فالفلتر يعمل على النهائية.)
|
||||||
|
const LEAK_STARTED_STATUSES = ['started', 'Begin', 'Finished', 'finished'];
|
||||||
|
|
||||||
|
if (!isset($redisLocation) || !$redisLocation) {
|
||||||
|
fwrite(STDERR, "[leak] Redis غير متاح — هل يعمل الكرون داخل حاوية php؟\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$con = Database::get('main');
|
||||||
|
} catch (Exception $e) {
|
||||||
|
fwrite(STDERR, "[leak] DB unavailable: " . $e->getMessage() . "\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
// ١) الرحلات المشتبهة في النافذة الأخيرة
|
||||||
|
//
|
||||||
|
// ملاحظة: cancel_ride_by_driver.php يصفّر ride.driver_id عند الإلغاء،
|
||||||
|
// فالسائق لا يُعرف من جدول ride. driver_orders هو من يحتفظ بالربط.
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
$cancelPlaceholders = implode(',', array_fill(0, count(LEAK_CANCEL_STATUSES), '?'));
|
||||||
|
$startedPlaceholders = implode(',', array_fill(0, count(LEAK_STARTED_STATUSES), '?'));
|
||||||
|
|
||||||
|
$sql = "
|
||||||
|
SELECT dord.driver_id, dord.order_id AS ride_id, dord.status AS cancel_status,
|
||||||
|
r.passenger_id
|
||||||
|
FROM driver_orders dord
|
||||||
|
JOIN ride r ON r.id = dord.order_id
|
||||||
|
WHERE dord.status IN ($cancelPlaceholders)
|
||||||
|
AND dord.created_at >= NOW() - INTERVAL " . LEAK_SCAN_HOURS . " HOUR
|
||||||
|
AND r.status NOT IN ($startedPlaceholders)
|
||||||
|
AND dord.driver_id <> '0'
|
||||||
|
AND r.passenger_id <> ''
|
||||||
|
";
|
||||||
|
|
||||||
|
try {
|
||||||
|
$stmt = $con->prepare($sql);
|
||||||
|
$stmt->execute(array_merge(LEAK_CANCEL_STATUSES, LEAK_STARTED_STATUSES));
|
||||||
|
$suspects = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
fwrite(STDERR, "[leak] فشل الفحص: " . $e->getMessage() . "\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
// ٢) تقييم كل حالة وتسجيلها
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
$pairStmt = $con->prepare("
|
||||||
|
SELECT COUNT(*) FROM driver_leak_events
|
||||||
|
WHERE driver_id = ? AND passenger_id = ?
|
||||||
|
AND created_at >= NOW() - INTERVAL " . LEAK_WINDOW_DAYS . " DAY
|
||||||
|
");
|
||||||
|
|
||||||
|
$appStmt = $con->prepare("
|
||||||
|
SELECT COUNT(*) FROM driver_ride_scam
|
||||||
|
WHERE driverID = ? AND rideID = ?
|
||||||
|
");
|
||||||
|
|
||||||
|
$insertStmt = $con->prepare("
|
||||||
|
INSERT IGNORE INTO driver_leak_events
|
||||||
|
(driver_id, passenger_id, ride_id, cancel_status, pair_repeat, app_reported, confidence)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
|
");
|
||||||
|
|
||||||
|
$inserted = 0;
|
||||||
|
$flagged = 0;
|
||||||
|
|
||||||
|
foreach ($suspects as $s) {
|
||||||
|
try {
|
||||||
|
$pairStmt->execute([$s['driver_id'], $s['passenger_id']]);
|
||||||
|
$pairRepeat = ((int) $pairStmt->fetchColumn()) + 1;
|
||||||
|
|
||||||
|
$appStmt->execute([$s['driver_id'], $s['ride_id']]);
|
||||||
|
$appReported = ((int) $appStmt->fetchColumn()) > 0 ? 1 : 0;
|
||||||
|
|
||||||
|
// ── الثقة ──
|
||||||
|
// حالة منفردة ضعيفة عمداً: الإلغاء بعد القبول له أسباب مشروعة
|
||||||
|
// كثيرة (عطل، خطأ في العنوان، راكب غيّر رأيه). التكرار مع نفس
|
||||||
|
// الراكب هو ما يحوّلها من حادثة إلى نمط.
|
||||||
|
$confidence = 0.25;
|
||||||
|
if ($pairRepeat >= 2) $confidence = 0.60;
|
||||||
|
if ($pairRepeat >= 3) $confidence = 0.85;
|
||||||
|
|
||||||
|
// بلاغ التطبيق (اتصل ثم أُلغيت) يرفع الثقة ولا يصنعها وحده.
|
||||||
|
if ($appReported) $confidence = min(1.0, $confidence + 0.15);
|
||||||
|
|
||||||
|
$insertStmt->execute([
|
||||||
|
$s['driver_id'], $s['passenger_id'], $s['ride_id'],
|
||||||
|
$s['cancel_status'], $pairRepeat, $appReported, round($confidence, 3),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($insertStmt->rowCount() > 0) {
|
||||||
|
$inserted++;
|
||||||
|
if ($confidence >= LEAK_REVIEW_THRESHOLD) $flagged++;
|
||||||
|
}
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
fwrite(STDERR, "[leak] خطأ على الرحلة {$s['ride_id']}: " . $e->getMessage() . "\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
// ٣) تحويل السجل إلى عقوبة في محرك الإسناد
|
||||||
|
//
|
||||||
|
// العقوبة تُحسب من مجموع ثقة أحداث السائق في النافذة، لا من عددها —
|
||||||
|
// فحالتان ضعيفتان لا تساويان حالة واحدة مؤكدة.
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
$penalized = 0;
|
||||||
|
try {
|
||||||
|
$scoreStmt = $con->prepare("
|
||||||
|
SELECT driver_id, SUM(confidence) AS total
|
||||||
|
FROM driver_leak_events
|
||||||
|
WHERE created_at >= NOW() - INTERVAL " . LEAK_WINDOW_DAYS . " DAY
|
||||||
|
GROUP BY driver_id
|
||||||
|
");
|
||||||
|
$scoreStmt->execute();
|
||||||
|
|
||||||
|
foreach ($scoreStmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
|
||||||
|
// يُشبَع عند مجموع 3 — أي ثلاث حالات مؤكدة تقريباً = العقوبة كاملة.
|
||||||
|
$penalty = min(LEAK_PENALTY_MAX, ((float) $row['total']) / 3.0);
|
||||||
|
$redisLocation->hSet("driver:score:{$row['driver_id']}", 'leak_penalty', round($penalty, 3));
|
||||||
|
$penalized++;
|
||||||
|
}
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
fwrite(STDERR, "[leak] تعذّر تطبيق العقوبات: " . $e->getMessage() . "\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// تصفير عقوبة من خرج من النافذة: بلا هذا تبقى العقوبة أبدية في Redis
|
||||||
|
// حتى لو نظُف سجل السائق تماماً — أي عقوبة بلا انتهاء.
|
||||||
|
try {
|
||||||
|
$iterator = null;
|
||||||
|
$redisLocation->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
|
||||||
|
$activeStmt = $con->prepare("
|
||||||
|
SELECT DISTINCT driver_id FROM driver_leak_events
|
||||||
|
WHERE created_at >= NOW() - INTERVAL " . LEAK_WINDOW_DAYS . " DAY
|
||||||
|
");
|
||||||
|
$activeStmt->execute();
|
||||||
|
$active = array_flip($activeStmt->fetchAll(PDO::FETCH_COLUMN));
|
||||||
|
|
||||||
|
while (($keys = $redisLocation->scan($iterator, 'driver:score:*', 200)) !== false) {
|
||||||
|
foreach ($keys as $key) {
|
||||||
|
$driverId = substr($key, strlen('driver:score:'));
|
||||||
|
if ($driverId === '' || isset($active[$driverId])) continue;
|
||||||
|
if ($redisLocation->hExists($key, 'leak_penalty')) {
|
||||||
|
$redisLocation->hDel($key, 'leak_penalty');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
fwrite(STDERR, "[leak] تعذّر تنظيف العقوبات المنتهية: " . $e->getMessage() . "\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "[leak] فُحص " . count($suspects) . " حالة، سُجّل $inserted جديدة،"
|
||||||
|
. " منها $flagged تستحق مراجعة بشرية. عوقب $penalized سائق.\n";
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* cron_obligation_settlement.php — محرك تسوية الالتزامات
|
||||||
|
* ─────────────────────────────────────────────────────────────
|
||||||
|
* الجهة **الوحيدة** التي تحوّل قيداً في `obligation_ledger` إلى خصم فعلي
|
||||||
|
* من محفظة السائق. مُصدِرو الاستحقاق (التأمين، الوقود، الصيانة) يقيّدون
|
||||||
|
* فقط ولا يلمسون مالاً — وهذا ما يجعل إضافة منتج جديد لا تمسّ أخطر
|
||||||
|
* منطق في المنصة.
|
||||||
|
*
|
||||||
|
* هذا الملف يغلق ثغرة إنتاج قائمة: `cron_insurance_premiums.php` يقيّد
|
||||||
|
* الأقساط منذ إطلاقه وتعليقه يقول «تقرأه التسوية» — ولم تكن التسوية
|
||||||
|
* موجودة. كل قسط قُيّد حتى اليوم بقي `pending` بلا تحصيل.
|
||||||
|
*
|
||||||
|
* لماذا كرون منفصل لا خصم عند إنهاء الرحلة؟
|
||||||
|
* لأن `finish_ride_updates.php` مسار حرج والسائق ينتظر رده. نداء شبكي
|
||||||
|
* إلى سيرفر المحفظة داخله يعني تعليق شاشة السائق على بطء طرف ثالث،
|
||||||
|
* وفشلاً في التسوية يظهر للسائق كفشل في إنهاء رحلته.
|
||||||
|
*
|
||||||
|
* ضمانات عدم التكرار طبقتان:
|
||||||
|
* ١. `last_attempt_on` في القيد — محاولة واحدة لكل قيد في اليوم
|
||||||
|
* ٢. `settlement_ref` فريد في سيرفر المحفظة — يحسم السباق ويجعل
|
||||||
|
* إعادة النداء بعد انقطاع شبكي آمنة بالتعريف
|
||||||
|
*
|
||||||
|
* الأولى وحدها لا تكفي: نداء قد ينجح في المحفظة ثم ينقطع قبل أن يصل
|
||||||
|
* الرد، فيبقى القيد بلا تحديث. الطبقة الثانية تجعل إعادة المحاولة تُرجع
|
||||||
|
* نتيجة الخصم الأول بدل خصم ثانٍ.
|
||||||
|
*
|
||||||
|
* جدولة: مرة يومياً في آخر اليوم لا بعد قيد الاستحقاقات مباشرة —
|
||||||
|
* السقف نسبة من أرباح اليوم، وقراءتها بعد منتصف الليل تعني سقفاً صفرياً
|
||||||
|
* كل ليلة وتحصيلاً لا يقع أبداً.
|
||||||
|
* 30 23 * * * docker compose exec -T php php /var/www/backend/bot/cron_obligation_settlement.php
|
||||||
|
*/
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../core/bootstrap.php';
|
||||||
|
require_once __DIR__ . '/../obligations/functions.php';
|
||||||
|
|
||||||
|
try {
|
||||||
|
$con = Database::get('main');
|
||||||
|
} catch (Exception $e) {
|
||||||
|
fwrite(STDERR, '[obligation] DB unavailable: ' . $e->getMessage() . "\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
$sharedKey = getenv('S2S_SHARED_KEY') ?: '';
|
||||||
|
if ($sharedKey === '') {
|
||||||
|
// بلا مفتاح لن ينجح أي نداء. الخروج المبكر أوضح من مئة محاولة
|
||||||
|
// تعود 401 وتزيد `attempts` بلا سبب حقيقي.
|
||||||
|
fwrite(STDERR, "[obligation] S2S_SHARED_KEY غير معرّف — لا تسوية\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ينادي نقطة الخصم ويُرجع ما خُصم فعلاً، أو null عند فشل لا يمكن تفسيره.
|
||||||
|
*
|
||||||
|
* التمييز بين «خُصم صفر» و«فشل» جوهري: الأول حالة طبيعية (لا أرباح
|
||||||
|
* اليوم) تُسجَّل محاولةً، والثاني لا يجوز أن يُحسب محاولة — وإلا ضاع
|
||||||
|
* يوم تحصيل بسبب عطل شبكي عابر.
|
||||||
|
*/
|
||||||
|
function obligationDeduct(string $ref, string $driverId, string $productCode,
|
||||||
|
float $amount, float $capPercent): ?float
|
||||||
|
{
|
||||||
|
$payload = obligationWalletCall(
|
||||||
|
'/v2/main/ride/driverWallet/deduct_s2s_obligation.php',
|
||||||
|
[
|
||||||
|
'settlement_ref' => $ref,
|
||||||
|
'driverID' => $driverId,
|
||||||
|
'product_code' => $productCode,
|
||||||
|
'amount' => number_format($amount, 3, '.', ''),
|
||||||
|
'cap_percent' => number_format($capPercent, 2, '.', ''),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($payload === null || !isset($payload['deducted'])) {
|
||||||
|
error_log("[obligation] تعذّر الحصول على نتيجة خصم ($ref)");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return round((float) $payload['deducted'], 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
$today = date('Y-m-d');
|
||||||
|
|
||||||
|
$settled = 0;
|
||||||
|
$partial = 0;
|
||||||
|
$idle = 0;
|
||||||
|
$failed = 0;
|
||||||
|
$total = 0.0;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// الترتيب مقصود: السائق أولاً ليكون سقفه اليومي مُستهلَكاً بترتيب
|
||||||
|
// معلوم، ثم أولوية المنتج (التأمين قبل الوقود قبل الصيانة)، ثم
|
||||||
|
// الأقدم فالأحدث — الدَّين الأقدم أولى بالسداد.
|
||||||
|
$st = $con->query("
|
||||||
|
SELECT l.id, l.obligation_id, l.driver_id, l.product_code,
|
||||||
|
l.amount_remaining, l.amount_collected, l.amount, l.attempts,
|
||||||
|
p.daily_cap_percent, p.kind
|
||||||
|
FROM obligation_ledger l
|
||||||
|
JOIN driver_obligations o ON o.id = l.obligation_id
|
||||||
|
JOIN obligation_products p ON p.id = o.product_id
|
||||||
|
WHERE l.status IN ('pending', 'partial')
|
||||||
|
AND l.amount_remaining > 0
|
||||||
|
AND (l.last_attempt_on IS NULL OR l.last_attempt_on <> CURDATE())
|
||||||
|
ORDER BY l.driver_id ASC, p.priority ASC, l.charge_date ASC
|
||||||
|
");
|
||||||
|
|
||||||
|
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
|
||||||
|
$ledgerId = (int) $row['id'];
|
||||||
|
$remaining = round((float) $row['amount_remaining'], 3);
|
||||||
|
|
||||||
|
// المرجع مبنيّ على عدّاد المحاولات لا على تاريخ اليوم. الفرق ليس
|
||||||
|
// تجميلياً: `attempts` لا يزيد إلا بعد تحديث الدفتر بنجاح، فنداء
|
||||||
|
// نجح في المحفظة وضاع ردّه يُعاد لاحقاً — ولو بعد أيام — بالمرجع
|
||||||
|
// نفسه، فتُرجع المحفظة خصمه الأول بدل تنفيذ خصم ثانٍ. مرجعٌ
|
||||||
|
// مبنيّ على التاريخ كان سيخصم المبلغ مرتين في هذه الحالة بالضبط.
|
||||||
|
$ref = "obl_{$ledgerId}_{$row['attempts']}";
|
||||||
|
|
||||||
|
$deducted = obligationDeduct(
|
||||||
|
$ref, $row['driver_id'], $row['product_code'],
|
||||||
|
$remaining, (float) $row['daily_cap_percent']
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($deducted === null) {
|
||||||
|
// لا نلمس القيد إطلاقاً — ولا حتى `attempts`. قد يكون الخصم
|
||||||
|
// تمّ في المحفظة وضاع الرد، وإبقاء العدّاد كما هو يضمن أن
|
||||||
|
// المحاولة القادمة تحمل المرجع نفسه فتستردّ نتيجة الأولى.
|
||||||
|
$failed++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$collected = round((float) $row['amount_collected'] + $deducted, 3);
|
||||||
|
$newRemaining = round((float) $row['amount'] - $collected, 3);
|
||||||
|
if ($newRemaining < 0) {
|
||||||
|
$newRemaining = 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($newRemaining <= 0) {
|
||||||
|
$status = 'settled';
|
||||||
|
} elseif ($collected > 0) {
|
||||||
|
$status = 'partial';
|
||||||
|
} else {
|
||||||
|
$status = 'pending';
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$con->beginTransaction();
|
||||||
|
|
||||||
|
$con->prepare("
|
||||||
|
UPDATE obligation_ledger
|
||||||
|
SET amount_collected = ?, amount_remaining = ?, status = ?,
|
||||||
|
attempts = attempts + 1, last_attempt_on = ?,
|
||||||
|
settled_at = CASE WHEN ? = 'settled' THEN NOW() ELSE settled_at END
|
||||||
|
WHERE id = ?
|
||||||
|
")->execute([$collected, $newRemaining, $status, $today, $status, $ledgerId]);
|
||||||
|
|
||||||
|
// المقسّط وحده يراكم أصلاً مسدَّداً. الدوري بلا نهاية فلا
|
||||||
|
// معنى لأصلٍ ينفد عنده.
|
||||||
|
if ($deducted > 0 && $row['kind'] === 'installment') {
|
||||||
|
$con->prepare("
|
||||||
|
UPDATE driver_obligations
|
||||||
|
SET principal_paid = principal_paid + ?
|
||||||
|
WHERE id = ?
|
||||||
|
")->execute([$deducted, (int) $row['obligation_id']]);
|
||||||
|
|
||||||
|
// سداد الأصل كاملاً يُنهي الالتزام. بدون هذا يبقى قرض
|
||||||
|
// مسدَّد «نشطاً» فيظهر للسائق ويزاحم غيره على السقف.
|
||||||
|
$con->prepare("
|
||||||
|
UPDATE driver_obligations
|
||||||
|
SET status = 'completed', ended_at = CURDATE()
|
||||||
|
WHERE id = ? AND status = 'active'
|
||||||
|
AND principal_amount > 0
|
||||||
|
AND principal_paid >= principal_amount
|
||||||
|
")->execute([(int) $row['obligation_id']]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$con->commit();
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
if ($con->inTransaction()) $con->rollBack();
|
||||||
|
// الخصم تمّ فعلاً والقيد لم يُحدَّث — أخطر حالة هنا. لا إعادة
|
||||||
|
// محاولة تلقائية: المرجع نفسه سيُرجع الخصم الأول لا خصماً
|
||||||
|
// جديداً، لكن التباين بين الدفترين يحتاج عيناً بشرية.
|
||||||
|
error_log("[obligation] خُصم {$deducted} للقيد #{$ledgerId} ولم يُحدَّث الدفتر: " . $e->getMessage());
|
||||||
|
$failed++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$total += $deducted;
|
||||||
|
if ($status === 'settled') $settled++;
|
||||||
|
elseif ($deducted > 0) $partial++;
|
||||||
|
else $idle++;
|
||||||
|
}
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
fwrite(STDERR, '[obligation] فشل المرور: ' . $e->getMessage() . "\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
printf(
|
||||||
|
"[obligation] سُوِّي %d، جزئي %d، بلا خصم %d، فشل %d — إجمالي %.3f\n",
|
||||||
|
$settled, $partial, $idle, $failed, $total
|
||||||
|
);
|
||||||
@@ -28,6 +28,14 @@ try {
|
|||||||
die("[ReEngagement] Connection failed: " . $e->getMessage() . "\n");
|
die("[ReEngagement] Connection failed: " . $e->getMessage() . "\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getRedisConnection() لا ترمي استثناءً — تُعيد null عند تعذّر الاتصال.
|
||||||
|
// مفتاح مكافحة التكرار يعيش في Redis؛ بدونه يفشل الفحص "مفتوحاً"
|
||||||
|
// فيتلقّى كل راكب نفس رسالة الاستعادة في كل تشغيل.
|
||||||
|
if (!$redis) {
|
||||||
|
error_log('[ReEngagement] ABORT: Redis unavailable — anti-spam guard would fail open.');
|
||||||
|
die("[ReEngagement] Redis unavailable — aborting to avoid duplicate pushes.\n");
|
||||||
|
}
|
||||||
|
|
||||||
echo "[ReEngagement] Starting Passenger Re-engagement Engine...\n";
|
echo "[ReEngagement] Starting Passenger Re-engagement Engine...\n";
|
||||||
|
|
||||||
$REDIS_TTL = 72 * 3600; // anti-spam: 72 ساعة
|
$REDIS_TTL = 72 * 3600; // anti-spam: 72 ساعة
|
||||||
|
|||||||
@@ -34,6 +34,14 @@ try {
|
|||||||
die("[PredictiveDemand] Connection failed: " . $e->getMessage() . "\n");
|
die("[PredictiveDemand] Connection failed: " . $e->getMessage() . "\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getRedisConnection() لا ترمي استثناءً — تُعيد null عند تعذّر الاتصال.
|
||||||
|
// الإيقاف هنا مقصود: مفتاح مكافحة التكرار يعيش في Redis، وبدونه سيُعاد
|
||||||
|
// إرسال نفس الإشعارات للركاب في كل تشغيل.
|
||||||
|
if (!$redis) {
|
||||||
|
error_log('[PredictiveDemand] ABORT: Redis unavailable — anti-spam guard would fail open.');
|
||||||
|
die("[PredictiveDemand] Redis unavailable — aborting to avoid duplicate pushes.\n");
|
||||||
|
}
|
||||||
|
|
||||||
echo "[PredictiveDemand] Starting...\n";
|
echo "[PredictiveDemand] Starting...\n";
|
||||||
|
|
||||||
$GRID_SIZE = 0.01; // حجم الخلية (~1.1km)
|
$GRID_SIZE = 0.01; // حجم الخلية (~1.1km)
|
||||||
|
|||||||
@@ -0,0 +1,324 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* cron_scheduled_rides.php
|
||||||
|
* ─────────────────────────────────────────────────────────────
|
||||||
|
* يحوّل الحجوزات المستحقة إلى رحلات فعلية، ويغذّي توقّع الطلب.
|
||||||
|
*
|
||||||
|
* ── لماذا لا تُنشأ الرحلة وقت الحجز ──
|
||||||
|
* رحلة تُنشأ الآن لموعد بعد ست ساعات ستدور في السوق ست ساعات: تُربك
|
||||||
|
* الإسناد، وتشوّه الخريطة الحرارية، وتُحتسب في كثافة الطلب اللحظية.
|
||||||
|
* الحجز يبقى نيّة حتى يقترب موعده.
|
||||||
|
*
|
||||||
|
* ── وظيفتان ──
|
||||||
|
* ١. تذكير الراكب قبل موعده (ساعة، ثم ربع ساعة)
|
||||||
|
* ٢. إطلاق المستحق: الحجوزات التي بلغ موعدها ناقص هامش البحث
|
||||||
|
* ٣. نشر التوقّع: عدد الحجوزات القادمة لكل خلية جغرافية في Redis،
|
||||||
|
* ليقرأها cron_predictive_demand والخريطة الحرارية
|
||||||
|
*
|
||||||
|
* الثانية هي القيمة الحقيقية: حجز مؤكد لبعد ست ساعات معلومة يقينية،
|
||||||
|
* أدق من أي تنبؤ إحصائي، وتسمح بتوجيه السائقين **قبل** الذروة.
|
||||||
|
*
|
||||||
|
* جدولة مقترحة (crontab): **كل دقيقتين**، لا كل دقيقة.
|
||||||
|
*
|
||||||
|
* الاستعلامات كلها مفهرسة على (status, scheduled_at) وتكلفتها مهملة،
|
||||||
|
* لكن كل تشغيل يعني إنشاء عملية PHP جديدة داخل الحاوية — وهذا هو الحمل
|
||||||
|
* الحقيقي لا الاستعلام. وهوامش الإطلاق ١٥-٤٠ دقيقة، فدقيقة تأخير في
|
||||||
|
* الاستحقاق لا أثر لها إطلاقاً.
|
||||||
|
*
|
||||||
|
* *\/2 * * * * (كل دقيقتين)
|
||||||
|
* docker compose exec -T php php /var/www/backend/bot/cron_scheduled_rides.php
|
||||||
|
*
|
||||||
|
* ⚠️ يجب أن يعمل داخل حاوية php — Redis لا ينشر منافذ.
|
||||||
|
*/
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../core/bootstrap.php';
|
||||||
|
|
||||||
|
// حجز فات موعده بهذا القدر بلا إطلاق يُعتبر منتهياً: الراكب لم يعد
|
||||||
|
// ينتظره، وإطلاقه الآن يرسل له سائقاً لموعد مضى.
|
||||||
|
const SCHEDULE_EXPIRE_GRACE_MINUTES = 30;
|
||||||
|
|
||||||
|
// دقة خلية التوقّع — نفس شبكة cron_predictive_demand (0.01° ≈ 1.1 كم).
|
||||||
|
const SCHEDULE_GRID = 0.01;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$con = Database::get('main');
|
||||||
|
} catch (Exception $e) {
|
||||||
|
fwrite(STDERR, '[scheduled] DB unavailable: ' . $e->getMessage() . "\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
// ١) انتهاء صلاحية الحجوزات المهملة
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
$expired = 0;
|
||||||
|
try {
|
||||||
|
$st = $con->prepare("
|
||||||
|
UPDATE scheduled_rides
|
||||||
|
SET status = 'expired'
|
||||||
|
WHERE status = 'scheduled'
|
||||||
|
AND scheduled_at < NOW() - INTERVAL " . SCHEDULE_EXPIRE_GRACE_MINUTES . " MINUTE
|
||||||
|
");
|
||||||
|
$st->execute();
|
||||||
|
$expired = $st->rowCount();
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
fwrite(STDERR, '[scheduled] تعذّر تعليم المنتهية: ' . $e->getMessage() . "\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
// ١.٥) تذكير الراكب
|
||||||
|
//
|
||||||
|
// تذكيران: قبل ساعة ليرتّب أمره، وقبل ربع ساعة ليستعد للنزول.
|
||||||
|
// الختم في العمود يمنع التكرار — بدونه يصل التذكير على كل مرور للكرون.
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
$reminded = 0;
|
||||||
|
foreach ([[60, 'reminded_60_at', 'رحلتك المحجوزة بعد ساعة'],
|
||||||
|
[15, 'reminded_15_at', 'رحلتك المحجوزة بعد ربع ساعة']] as [$mins, $col, $title]) {
|
||||||
|
try {
|
||||||
|
$st = $con->prepare("
|
||||||
|
SELECT id, passenger_id, scheduled_at, start_name, end_name
|
||||||
|
FROM scheduled_rides
|
||||||
|
WHERE status = 'scheduled'
|
||||||
|
AND `$col` IS NULL
|
||||||
|
AND scheduled_at BETWEEN NOW() AND NOW() + INTERVAL $mins MINUTE
|
||||||
|
LIMIT 100
|
||||||
|
");
|
||||||
|
$st->execute();
|
||||||
|
|
||||||
|
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
|
||||||
|
// الختم أولاً ثم الإرسال: لو انقطع التنفيذ بينهما، أسوأ نتيجة
|
||||||
|
// تذكير لم يصل — لا تذكير يصل مئة مرة.
|
||||||
|
$con->prepare("UPDATE scheduled_rides SET `$col` = NOW() WHERE id = ?")
|
||||||
|
->execute([$row['id']]);
|
||||||
|
|
||||||
|
scheduleNotifyPassenger(
|
||||||
|
$con,
|
||||||
|
$row['passenger_id'],
|
||||||
|
$title,
|
||||||
|
'من ' . ($row['start_name'] ?: 'موقعك') . ' في '
|
||||||
|
. date('H:i', strtotime($row['scheduled_at'])),
|
||||||
|
['category' => 'scheduled_reminder', 'scheduled_id' => (string) $row['id']]
|
||||||
|
);
|
||||||
|
$reminded++;
|
||||||
|
}
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
fwrite(STDERR, "[scheduled] تعذّر تذكير $mins د: " . $e->getMessage() . "\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
// ٢) الحجوزات المستحقة للإطلاق
|
||||||
|
//
|
||||||
|
// المستحق: بلغ الوقت موعدَه ناقص هامشه. الهامش مشتقّ من المسافة وقت
|
||||||
|
// الحجز (رحلة مطار تحتاج وقتاً أطول لإيجاد سائق وللوصول).
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
$dispatched = 0;
|
||||||
|
$failed = 0;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$due = $con->prepare("
|
||||||
|
SELECT * FROM scheduled_rides
|
||||||
|
WHERE status = 'scheduled'
|
||||||
|
AND NOW() >= scheduled_at - INTERVAL lead_minutes MINUTE
|
||||||
|
AND scheduled_at >= NOW() - INTERVAL " . SCHEDULE_EXPIRE_GRACE_MINUTES . " MINUTE
|
||||||
|
ORDER BY scheduled_at ASC
|
||||||
|
LIMIT 100
|
||||||
|
");
|
||||||
|
$due->execute();
|
||||||
|
$bookings = $due->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
|
foreach ($bookings as $b) {
|
||||||
|
// قفل تفاؤلي: مرور ثانٍ للكرون (أو نسخة ثانية منه) لا يطلق نفس
|
||||||
|
// الحجز مرتين. الرحلة المزدوجة تعني سائقين وراكباً واحداً.
|
||||||
|
$lock = $con->prepare("
|
||||||
|
UPDATE scheduled_rides SET status = 'dispatching'
|
||||||
|
WHERE id = ? AND status = 'scheduled'
|
||||||
|
");
|
||||||
|
$lock->execute([$b['id']]);
|
||||||
|
if ($lock->rowCount() === 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$rideId = scheduleCreateRide($b);
|
||||||
|
|
||||||
|
if ($rideId) {
|
||||||
|
$con->prepare("
|
||||||
|
UPDATE scheduled_rides SET status = 'dispatched', ride_id = ?
|
||||||
|
WHERE id = ?
|
||||||
|
")->execute([$rideId, $b['id']]);
|
||||||
|
$dispatched++;
|
||||||
|
error_log("[scheduled] حجز #{$b['id']} → رحلة #$rideId");
|
||||||
|
} else {
|
||||||
|
// نعيده 'scheduled' لا 'failed': المرور القادم يحاول ثانيةً،
|
||||||
|
// وفشل شبكي عابر لا يجوز أن يحرم الراكب رحلته المحجوزة.
|
||||||
|
$con->prepare("
|
||||||
|
UPDATE scheduled_rides SET status = 'scheduled' WHERE id = ?
|
||||||
|
")->execute([$b['id']]);
|
||||||
|
$failed++;
|
||||||
|
error_log("[scheduled] تعذّر إنشاء رحلة للحجز #{$b['id']} — ستُعاد المحاولة");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
fwrite(STDERR, '[scheduled] فشل الإطلاق: ' . $e->getMessage() . "\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
// ٣) نشر التوقّع المؤكد
|
||||||
|
//
|
||||||
|
// هذه هي القيمة التي تتجاوز راحة الراكب: طلب معروف مسبقاً بمكانه
|
||||||
|
// ووقته. يُنشر في Redis ليقرأه التنبؤ والخريطة الحرارية.
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
$cells = 0;
|
||||||
|
try {
|
||||||
|
if (isset($redisLocation) && $redisLocation) {
|
||||||
|
// نافذة ٦ ساعات: أبعد من ذلك لا يفيد توجيه السائقين اليوم.
|
||||||
|
$st = $con->query("
|
||||||
|
SELECT start_location, scheduled_at
|
||||||
|
FROM scheduled_rides
|
||||||
|
WHERE status = 'scheduled'
|
||||||
|
AND scheduled_at BETWEEN NOW() AND NOW() + INTERVAL 6 HOUR
|
||||||
|
");
|
||||||
|
|
||||||
|
$buckets = [];
|
||||||
|
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
|
||||||
|
[$lat, $lng] = array_pad(
|
||||||
|
array_map('trim', explode(',', (string) $row['start_location'], 2)), 2, null
|
||||||
|
);
|
||||||
|
if (!is_numeric($lat) || !is_numeric($lng)) continue;
|
||||||
|
|
||||||
|
// المفتاح: خلية جغرافية + الساعة المتوقعة. التجميع بالساعة
|
||||||
|
// يكفي لقرار "أين يجب أن يكون السائقون الساعة السابعة".
|
||||||
|
$cell = round((float) $lat / SCHEDULE_GRID) * SCHEDULE_GRID
|
||||||
|
. ',' . round((float) $lng / SCHEDULE_GRID) * SCHEDULE_GRID;
|
||||||
|
$hour = date('Y-m-d H:00', strtotime($row['scheduled_at']));
|
||||||
|
|
||||||
|
$buckets["$cell|$hour"] = ($buckets["$cell|$hour"] ?? 0) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
$key = 'demand:scheduled';
|
||||||
|
$redisLocation->del($key);
|
||||||
|
if (!empty($buckets)) {
|
||||||
|
$redisLocation->hMSet($key, $buckets);
|
||||||
|
// عمر ساعتين: الكرون يعيد بناءه كل دقيقة، والانتهاء يمنع
|
||||||
|
// بقاء توقّع قديم لو توقّف الكرون.
|
||||||
|
$redisLocation->expire($key, 7200);
|
||||||
|
}
|
||||||
|
$cells = count($buckets);
|
||||||
|
}
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
fwrite(STDERR, '[scheduled] تعذّر نشر التوقّع: ' . $e->getMessage() . "\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// الأقواس ضرورية: الفاصلة العربية `،` بايتاتها ≥ 0x80، وPHP يعدّها جزءاً
|
||||||
|
// صالحاً من اسم المتغيّر — فبدونها يُقرأ "$dispatched،" متغيّراً آخر فارغاً.
|
||||||
|
echo "[scheduled] أُطلق {$dispatched}، تعذّر {$failed}، انتهى {$expired}،"
|
||||||
|
. " ذُكِّر {$reminded}، وخلايا التوقّع {$cells}\n";
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ينشئ الرحلة الفعلية من الحجز عبر add_ride.php.
|
||||||
|
*
|
||||||
|
* نستدعي النقطة ذاتها لا نكرّر منطقها: add_ride يسعّر، ويبني الحمولة،
|
||||||
|
* ويشغّل الإسناد (بالدفعات أو البثّ الحر)، ويكتب للقاعدتين. تكرار ذلك
|
||||||
|
* هنا كان سينتج نسخة تتباعد عن الأصل مع أول تعديل.
|
||||||
|
*
|
||||||
|
* السعر يُحسب لحظة الإنشاء لا وقت الحجز: سعر ما قبل ست ساعات لا يعرف
|
||||||
|
* الذروة ولا الطقس ولا كثافة السائقين.
|
||||||
|
*
|
||||||
|
* @return string|null رقم الرحلة، أو null عند الفشل.
|
||||||
|
*/
|
||||||
|
function scheduleCreateRide(array $b): ?string
|
||||||
|
{
|
||||||
|
$url = getenv('INTERNAL_API_BASE') ?: 'http://nginx';
|
||||||
|
$url .= '/ride/rides/add_ride.php';
|
||||||
|
|
||||||
|
[$startLat, $startLng] = array_pad(
|
||||||
|
array_map('trim', explode(',', (string) $b['start_location'], 2)), 2, ''
|
||||||
|
);
|
||||||
|
[$endLat, $endLng] = array_pad(
|
||||||
|
array_map('trim', explode(',', (string) $b['end_location'], 2)), 2, ''
|
||||||
|
);
|
||||||
|
|
||||||
|
$fields = [
|
||||||
|
'passenger_id' => $b['passenger_id'],
|
||||||
|
'start_location' => $b['start_location'],
|
||||||
|
'end_location' => $b['end_location'],
|
||||||
|
'start_lat' => $startLat,
|
||||||
|
'start_lng' => $startLng,
|
||||||
|
'end_lat' => $endLat,
|
||||||
|
'end_lng' => $endLng,
|
||||||
|
'start_name' => $b['start_name'] ?? '',
|
||||||
|
'end_name' => $b['end_name'] ?? '',
|
||||||
|
'car_type' => $b['car_type'],
|
||||||
|
'distance' => $b['distance'],
|
||||||
|
'duration' => $b['duration'],
|
||||||
|
// السعر يُتجاهَل: add_ride يسعّر داخلياً لحظة الإنشاء. نمرّره
|
||||||
|
// للتوثيق فقط — تقدير وقت الحجز لا يعرف الذروة ولا الطقس.
|
||||||
|
'price' => $b['estimated_price'],
|
||||||
|
'scheduled_at' => $b['scheduled_at'],
|
||||||
|
// وسم المصدر: add_ride قد يعامل الرحلة المحجوزة بأولوية أو
|
||||||
|
// هامش مختلف لاحقاً، والوسم يجعل ذلك ممكناً بلا تخمين.
|
||||||
|
'source' => 'scheduled',
|
||||||
|
'scheduled_id' => $b['id'],
|
||||||
|
];
|
||||||
|
|
||||||
|
$ch = curl_init($url);
|
||||||
|
curl_setopt_array($ch, [
|
||||||
|
CURLOPT_POST => true,
|
||||||
|
CURLOPT_POSTFIELDS => http_build_query($fields),
|
||||||
|
CURLOPT_RETURNTRANSFER => true,
|
||||||
|
CURLOPT_TIMEOUT => 15,
|
||||||
|
CURLOPT_HTTPHEADER => [
|
||||||
|
'Content-Type: application/x-www-form-urlencoded',
|
||||||
|
'X-S2S-Api-Key: ' . getenv('S2S_SHARED_KEY'),
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
$body = curl_exec($ch);
|
||||||
|
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||||
|
curl_close($ch);
|
||||||
|
|
||||||
|
if ($code !== 200 || !$body) {
|
||||||
|
error_log("[scheduled] add_ride رمز=$code رد=" . substr((string) $body, 0, 200));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$json = json_decode($body, true);
|
||||||
|
|
||||||
|
// add_ride يرد بـ printSuccess($insertedId) — الرقم في message.
|
||||||
|
$rideId = $json['message'] ?? $json['data'] ?? null;
|
||||||
|
|
||||||
|
return ($rideId && is_scalar($rideId)) ? (string) $rideId : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* يرسل إشعاراً للراكب. توكنه مشفَّر في جدول tokens — نفكّه كما يفعل
|
||||||
|
* cancel_ride_by_driver.php بالضبط.
|
||||||
|
*
|
||||||
|
* لا يرمي: فشل التذكير لا يُسقط الكرون ولا يمنع إطلاق الحجوزات.
|
||||||
|
*/
|
||||||
|
function scheduleNotifyPassenger(PDO $con, string $passengerId,
|
||||||
|
string $title, string $body, array $data): void
|
||||||
|
{
|
||||||
|
global $encryptionHelper;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$st = $con->prepare("SELECT token FROM tokens WHERE passengerID = ? ORDER BY id DESC LIMIT 1");
|
||||||
|
$st->execute([$passengerId]);
|
||||||
|
$raw = $st->fetchColumn();
|
||||||
|
if (!$raw) return;
|
||||||
|
|
||||||
|
$token = $raw;
|
||||||
|
if (!empty($encryptionHelper)) {
|
||||||
|
try {
|
||||||
|
$dec = $encryptionHelper->decryptData($raw);
|
||||||
|
if ($dec !== false && $dec !== '') $token = trim($dec);
|
||||||
|
} catch (Throwable $e) { /* نستخدم الخام */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (function_exists('sendFCM_Internal')) {
|
||||||
|
sendFCM_Internal($token, $title, $body, $data, 'scheduled_reminder', false);
|
||||||
|
}
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
error_log('[scheduled] تعذّر إرسال التذكير: ' . $e->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,6 +15,13 @@ try {
|
|||||||
die("Connection failed: " . $e->getMessage() . "\n");
|
die("Connection failed: " . $e->getMessage() . "\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getRedisConnection() لا ترمي استثناءً — تُعيد null عند تعذّر الاتصال.
|
||||||
|
// المُعاملات الموسمية تُنشر عبر Redis وحده ليقرأها محرّك التسعير.
|
||||||
|
if (!$redis) {
|
||||||
|
error_log('[SeasonalPricing] ABORT: Redis unavailable — seasonal multipliers not published.');
|
||||||
|
die("Redis unavailable — aborting seasonal pricing run.\n");
|
||||||
|
}
|
||||||
|
|
||||||
$countries = ['SY' => 'Asia/Damascus', 'JO' => 'Asia/Amman', 'EG' => 'Africa/Cairo', 'IQ' => 'Asia/Baghdad'];
|
$countries = ['SY' => 'Asia/Damascus', 'JO' => 'Asia/Amman', 'EG' => 'Africa/Cairo', 'IQ' => 'Asia/Baghdad'];
|
||||||
|
|
||||||
// Simulated Calendar of Events
|
// Simulated Calendar of Events
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* cron_sms_requests.php — شبكة الأمان لمسار الطلب بالرسائل
|
||||||
|
* ─────────────────────────────────────────────────────────────
|
||||||
|
* المعالجة الأصلية تتم فورياً داخل webhook_sms/webhook.php، لأن الراكب
|
||||||
|
* واقف ينتظر رداً ودقيقة تأخير تعني أنه ظنّ الرقم معطّلاً. هذا الكرون
|
||||||
|
* لا يعالج المسار السعيد إذن — وظيفته ما يسقط منه:
|
||||||
|
*
|
||||||
|
* ١. طلبات بقيت 'pending' (فشل شبكي عابر وقت الإنشاء)
|
||||||
|
* ٢. طلبات عَلِقت في 'dispatching' (مات التنفيذ بين القفل والنتيجة)
|
||||||
|
* ٣. رحلات لم يقبلها أحد — نخبر الراكب بدل تركه ينتظر بلا خبر
|
||||||
|
*
|
||||||
|
* الثالثة هي الأهم: راكب التطبيق يرى الخريطة فيعرف أن البحث جارٍ.
|
||||||
|
* راكب الرسائل لا يرى شيئاً — صمتنا عنده يساوي عطلاً.
|
||||||
|
*
|
||||||
|
* جدولة: كل دقيقة.
|
||||||
|
* *\/1 * * * * docker compose exec -T php php /var/www/backend/bot/cron_sms_requests.php
|
||||||
|
*/
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../core/bootstrap.php';
|
||||||
|
require_once __DIR__ . '/../sms/ride_request.php';
|
||||||
|
|
||||||
|
// طلب عَلِق في 'dispatching' أطول من هذا يُعتبر ميتاً ويُعاد للطابور.
|
||||||
|
const SMS_STUCK_MINUTES = 3;
|
||||||
|
|
||||||
|
// بعد هذه المدة بلا سائق نخبر الراكب. أقصر من مهلة التطبيق عمداً:
|
||||||
|
// من ينتظر بلا شاشة يفقد صبره أسرع.
|
||||||
|
const SMS_NO_DRIVER_MINUTES = 6;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$con = Database::get('main');
|
||||||
|
} catch (Exception $e) {
|
||||||
|
fwrite(STDERR, '[sms-cron] DB unavailable: ' . $e->getMessage() . "\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
// ١) تحرير العالق
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
$freed = 0;
|
||||||
|
try {
|
||||||
|
$st = $con->prepare("
|
||||||
|
UPDATE sms_ride_requests
|
||||||
|
SET status = 'pending'
|
||||||
|
WHERE status = 'dispatching'
|
||||||
|
AND updated_at < NOW() - INTERVAL " . SMS_STUCK_MINUTES . " MINUTE
|
||||||
|
");
|
||||||
|
$st->execute();
|
||||||
|
$freed = $st->rowCount();
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
fwrite(STDERR, '[sms-cron] تعذّر تحرير العالق: ' . $e->getMessage() . "\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
// ٢) إعادة محاولة المعلّق
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
$retried = 0;
|
||||||
|
$created = 0;
|
||||||
|
try {
|
||||||
|
$st = $con->query("
|
||||||
|
SELECT id, sender_norm, passenger_id, start_location, end_location,
|
||||||
|
start_name, end_name, distance, duration, attempts
|
||||||
|
FROM sms_ride_requests
|
||||||
|
WHERE status = 'pending' AND passenger_id IS NOT NULL
|
||||||
|
ORDER BY id ASC
|
||||||
|
LIMIT 50
|
||||||
|
");
|
||||||
|
|
||||||
|
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $req) {
|
||||||
|
$retried++;
|
||||||
|
if (smsProcessRequest($con, $req)) $created++;
|
||||||
|
}
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
fwrite(STDERR, '[sms-cron] فشل إعادة المحاولة: ' . $e->getMessage() . "\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
// ٣) إبلاغ من لم يجد سائقاً
|
||||||
|
//
|
||||||
|
// نعتمد على حالة الرحلة نفسها لا على مؤقّت منفصل: ما دامت 'waiting'
|
||||||
|
// فلا سائق قَبِل. والوسم في fail_reason يمنع تكرار الإبلاغ كل دقيقة.
|
||||||
|
// ═══════════════════════════════════════════════════════════════
|
||||||
|
$notified = 0;
|
||||||
|
try {
|
||||||
|
$st = $con->prepare("
|
||||||
|
SELECT s.id, s.sender_norm, s.ride_id
|
||||||
|
FROM sms_ride_requests s
|
||||||
|
JOIN ride r ON r.id = s.ride_id
|
||||||
|
WHERE s.status = 'dispatched'
|
||||||
|
AND (s.fail_reason IS NULL OR s.fail_reason <> 'no_driver_notified')
|
||||||
|
AND r.status IN ('waiting', 'wait')
|
||||||
|
AND s.updated_at < NOW() - INTERVAL " . SMS_NO_DRIVER_MINUTES . " MINUTE
|
||||||
|
LIMIT 50
|
||||||
|
");
|
||||||
|
$st->execute();
|
||||||
|
|
||||||
|
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
|
||||||
|
// الوسم أولاً ثم الإرسال: لو انقطع التنفيذ بينهما، أسوأ نتيجة
|
||||||
|
// رسالة لم تصل — لا رسالة تصل كل دقيقة.
|
||||||
|
$con->prepare("UPDATE sms_ride_requests SET fail_reason='no_driver_notified' WHERE id=?")
|
||||||
|
->execute([$row['id']]);
|
||||||
|
|
||||||
|
smsEnqueue($con, $row['sender_norm'],
|
||||||
|
'سيرو: ما زلنا نبحث عن سائق قريب منك. سنرسل لك رسالة فور قبول أحدهم،'
|
||||||
|
. ' أو أعد إرسال طلبك بعد قليل.',
|
||||||
|
'no_driver_yet', (string) $row['ride_id']);
|
||||||
|
$notified++;
|
||||||
|
}
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
fwrite(STDERR, '[sms-cron] تعذّر إبلاغ من بلا سائق: ' . $e->getMessage() . "\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "[sms-cron] حُرِّر {$freed}، أُعيدت محاولة {$retried}، أُنشئ {$created}،"
|
||||||
|
. " أُبلغ {$notified}\n";
|
||||||
+42
-13
@@ -23,7 +23,15 @@ if (!$SECRET_KEY) {
|
|||||||
echo json_encode(['status' => 'failure', 'message' => 'Server configuration error: BOT_SECRET_KEY not set in environment']);
|
echo json_encode(['status' => 'failure', 'message' => 'Server configuration error: BOT_SECRET_KEY not set in environment']);
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
$ALLOWED_DEVICES = ['SHAM_CASH_BOT_01', 'PRICE_SCRAPER_BOT_01', '77a9528112ef7c2a'];
|
// أجهزة البوت المسموح بها — تُضبط عبر BOT_ALLOWED_DEVICES (مفصولة بفواصل)
|
||||||
|
// حتى لا يتطلب ضم جهاز جديد تعديل الكود ونشره.
|
||||||
|
$ALLOWED_DEVICES = array_values(array_filter(array_map(
|
||||||
|
'trim',
|
||||||
|
explode(',', (string)(getenv('BOT_ALLOWED_DEVICES') ?: ''))
|
||||||
|
)));
|
||||||
|
if (!$ALLOWED_DEVICES) {
|
||||||
|
$ALLOWED_DEVICES = ['SHAM_CASH_BOT_01', 'PRICE_SCRAPER_BOT_01', '77a9528112ef7c2a'];
|
||||||
|
}
|
||||||
|
|
||||||
$method = $_SERVER['REQUEST_METHOD'];
|
$method = $_SERVER['REQUEST_METHOD'];
|
||||||
|
|
||||||
@@ -43,9 +51,12 @@ if ($method === 'GET') {
|
|||||||
// ---------------------------------------------------------
|
// ---------------------------------------------------------
|
||||||
// GET: Fetch Pending Task for the Bot
|
// GET: Fetch Pending Task for the Bot
|
||||||
// ---------------------------------------------------------
|
// ---------------------------------------------------------
|
||||||
$device_id = filterRequest('device_id');
|
// ملاحظة: filterRequest() تقرأ من POST أو JSON body فقط ولا تلمس $_GET
|
||||||
$ts = filterRequest('ts');
|
// (backend/core/helpers.php) — والبوت يرسل بارامترات التوقيع في الـ query
|
||||||
$sig = filterRequest('sig');
|
// string، لذا تُقرأ هنا من $_GET مباشرة.
|
||||||
|
$device_id = isset($_GET['device_id']) ? trim((string)$_GET['device_id']) : null;
|
||||||
|
$ts = isset($_GET['ts']) ? (int)$_GET['ts'] : null;
|
||||||
|
$sig = isset($_GET['sig']) ? trim((string)$_GET['sig']) : null;
|
||||||
|
|
||||||
if (!$device_id || !$ts || !$sig) {
|
if (!$device_id || !$ts || !$sig) {
|
||||||
jsonError("Missing security parameters");
|
jsonError("Missing security parameters");
|
||||||
@@ -64,6 +75,14 @@ if ($method === 'GET') {
|
|||||||
|
|
||||||
// Check Redis Queue for tasks
|
// Check Redis Queue for tasks
|
||||||
// Queue Name: queue:bot:tasks (Using Main Redis)
|
// Queue Name: queue:bot:tasks (Using Main Redis)
|
||||||
|
// bootstrap.php يترك $redis = null إذا فشل الاتصال — بدون هذا الفحص
|
||||||
|
// كان الطلب ينهار بخطأ 500 غامض بدل رسالة واضحة.
|
||||||
|
if (!$redis) {
|
||||||
|
http_response_code(503);
|
||||||
|
echo json_encode(['status' => 'failure', 'message' => 'Task queue unavailable']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
$taskJson = $redis->rpop('queue:bot:tasks');
|
$taskJson = $redis->rpop('queue:bot:tasks');
|
||||||
|
|
||||||
if ($taskJson) {
|
if ($taskJson) {
|
||||||
@@ -144,18 +163,28 @@ if ($method === 'GET') {
|
|||||||
}
|
}
|
||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
|
|
||||||
|
// العملة تتبع الدولة بدل تثبيتها على JOD — البوت يعمل على أكثر من سوق
|
||||||
|
$currencyByCountry = ['JO' => 'JOD', 'SY' => 'SYP', 'EG' => 'EGP'];
|
||||||
|
$currency = $currencyByCountry[strtoupper($country_code)] ?? 'JOD';
|
||||||
|
|
||||||
// 1. Save to MySQL
|
// 1. Save to MySQL
|
||||||
$stmt = $con->prepare("
|
try {
|
||||||
INSERT INTO scraped_competitor_prices
|
$stmt = $con->prepare("
|
||||||
(task_id, app_name, competitor_name, start_location, end_location, start_lat, start_lng, end_lat, end_lng, price_amount, price_per_km, distance_km, duration_min, currency, country_code)
|
INSERT INTO scraped_competitor_prices
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
(task_id, app_name, competitor_name, start_location, end_location, start_lat, start_lng, end_lat, end_lng, price_amount, price_per_km, distance_km, duration_min, currency, country_code)
|
||||||
");
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
$start_loc = "Lat: $start_lat, Lng: $start_lng";
|
");
|
||||||
$end_loc = "Lat: $end_lat, Lng: $end_lng";
|
$start_loc = "Lat: $start_lat, Lng: $start_lng";
|
||||||
$stmt->execute([$task_id, $app_name, $app_name, $start_loc, $end_loc, (string)$start_lat, (string)$start_lng, (string)$end_lat, (string)$end_lng, $price, $pricePerKm, $distance_km, $duration_min, 'JOD', $country_code]);
|
$end_loc = "Lat: $end_lat, Lng: $end_lng";
|
||||||
|
$stmt->execute([$task_id, $app_name, $app_name, $start_loc, $end_loc, (string)$start_lat, (string)$start_lng, (string)$end_lat, (string)$end_lng, $price, $pricePerKm, $distance_km, $duration_min, $currency, $country_code]);
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
// لا نُسقط الطلب: نسجّل الخطأ ونكمل إلى Redis حتى لا تضيع العيّنة
|
||||||
|
// من محرّك التسعير بسبب عطل في الكتابة إلى MySQL.
|
||||||
|
error_log("[Bot Worker] MySQL insert failed for task $task_id: " . $e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
// 2. Save to Redis (Calculate Price Per KM)
|
// 2. Save to Redis (Calculate Price Per KM)
|
||||||
if ($distance_km > 0 && $price > 0) {
|
if ($redis && $distance_km > 0 && $price > 0) {
|
||||||
// Store in Redis (Main) to be used by Pricing Engine
|
// Store in Redis (Main) to be used by Pricing Engine
|
||||||
// Store recent 50 prices for the app
|
// Store recent 50 prices for the app
|
||||||
$redis->lpush("competitor:price_history:$app_name", $pricePerKm);
|
$redis->lpush("competitor:price_history:$app_name", $pricePerKm);
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"require": {
|
"require": {
|
||||||
"vlucas/phpdotenv": "^5.6",
|
"vlucas/phpdotenv": "^5.6",
|
||||||
"firebase/php-jwt": "^6.0"
|
"firebase/php-jwt": "^7.0"
|
||||||
},
|
},
|
||||||
"prefer-stable": true,
|
"prefer-stable": true,
|
||||||
"config": {
|
"config": {
|
||||||
"audit": {
|
"platform": {
|
||||||
"ignore": ["PKSA-y2cr-5h3j-g3ys"]
|
"php": "8.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+21
-15
@@ -4,20 +4,20 @@
|
|||||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||||
"This file is @generated automatically"
|
"This file is @generated automatically"
|
||||||
],
|
],
|
||||||
"content-hash": "e192df06759c90826eeb518a1ea5f0c8",
|
"content-hash": "e5589fd14ce83adda13b8b9cebed44fa",
|
||||||
"packages": [
|
"packages": [
|
||||||
{
|
{
|
||||||
"name": "firebase/php-jwt",
|
"name": "firebase/php-jwt",
|
||||||
"version": "v6.11.1",
|
"version": "v7.1.0",
|
||||||
"source": {
|
"source": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/googleapis/php-jwt.git",
|
"url": "https://github.com/googleapis/php-jwt.git",
|
||||||
"reference": "d1e91ecf8c598d073d0995afa8cd5c75c6e19e66"
|
"reference": "b374a5d1a4f1f67fadc2165cdb284645945e2fc0"
|
||||||
},
|
},
|
||||||
"dist": {
|
"dist": {
|
||||||
"type": "zip",
|
"type": "zip",
|
||||||
"url": "https://api.github.com/repos/googleapis/php-jwt/zipball/d1e91ecf8c598d073d0995afa8cd5c75c6e19e66",
|
"url": "https://api.github.com/repos/googleapis/php-jwt/zipball/b374a5d1a4f1f67fadc2165cdb284645945e2fc0",
|
||||||
"reference": "d1e91ecf8c598d073d0995afa8cd5c75c6e19e66",
|
"reference": "b374a5d1a4f1f67fadc2165cdb284645945e2fc0",
|
||||||
"shasum": ""
|
"shasum": ""
|
||||||
},
|
},
|
||||||
"require": {
|
"require": {
|
||||||
@@ -25,6 +25,8 @@
|
|||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"guzzlehttp/guzzle": "^7.4",
|
"guzzlehttp/guzzle": "^7.4",
|
||||||
|
"phpfastcache/phpfastcache": "^9.2",
|
||||||
|
"phpseclib/phpseclib": "~3.0",
|
||||||
"phpspec/prophecy-phpunit": "^2.0",
|
"phpspec/prophecy-phpunit": "^2.0",
|
||||||
"phpunit/phpunit": "^9.5",
|
"phpunit/phpunit": "^9.5",
|
||||||
"psr/cache": "^2.0||^3.0",
|
"psr/cache": "^2.0||^3.0",
|
||||||
@@ -33,7 +35,8 @@
|
|||||||
},
|
},
|
||||||
"suggest": {
|
"suggest": {
|
||||||
"ext-sodium": "Support EdDSA (Ed25519) signatures",
|
"ext-sodium": "Support EdDSA (Ed25519) signatures",
|
||||||
"paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present"
|
"paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present",
|
||||||
|
"phpseclib/phpseclib": "Support PS256 (RSASSA-PSS) signatures"
|
||||||
},
|
},
|
||||||
"type": "library",
|
"type": "library",
|
||||||
"autoload": {
|
"autoload": {
|
||||||
@@ -58,16 +61,16 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
|
"description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
|
||||||
"homepage": "https://github.com/firebase/php-jwt",
|
"homepage": "https://github.com/googleapis/php-jwt",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"jwt",
|
"jwt",
|
||||||
"php"
|
"php"
|
||||||
],
|
],
|
||||||
"support": {
|
"support": {
|
||||||
"issues": "https://github.com/googleapis/php-jwt/issues",
|
"issues": "https://github.com/googleapis/php-jwt/issues",
|
||||||
"source": "https://github.com/googleapis/php-jwt/tree/v6.11.1"
|
"source": "https://github.com/googleapis/php-jwt/tree/v7.1.0"
|
||||||
},
|
},
|
||||||
"time": "2025-04-09T20:32:01+00:00"
|
"time": "2026-06-11T17:54:14+00:00"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "graham-campbell/result-type",
|
"name": "graham-campbell/result-type",
|
||||||
@@ -460,16 +463,16 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "vlucas/phpdotenv",
|
"name": "vlucas/phpdotenv",
|
||||||
"version": "v5.6.3",
|
"version": "v5.6.4",
|
||||||
"source": {
|
"source": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/vlucas/phpdotenv.git",
|
"url": "https://github.com/vlucas/phpdotenv.git",
|
||||||
"reference": "955e7815d677a3eaa7075231212f2110983adecc"
|
"reference": "416df702837983f8d5ff48c9c3fee4f5f57b980b"
|
||||||
},
|
},
|
||||||
"dist": {
|
"dist": {
|
||||||
"type": "zip",
|
"type": "zip",
|
||||||
"url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/955e7815d677a3eaa7075231212f2110983adecc",
|
"url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/416df702837983f8d5ff48c9c3fee4f5f57b980b",
|
||||||
"reference": "955e7815d677a3eaa7075231212f2110983adecc",
|
"reference": "416df702837983f8d5ff48c9c3fee4f5f57b980b",
|
||||||
"shasum": ""
|
"shasum": ""
|
||||||
},
|
},
|
||||||
"require": {
|
"require": {
|
||||||
@@ -528,7 +531,7 @@
|
|||||||
],
|
],
|
||||||
"support": {
|
"support": {
|
||||||
"issues": "https://github.com/vlucas/phpdotenv/issues",
|
"issues": "https://github.com/vlucas/phpdotenv/issues",
|
||||||
"source": "https://github.com/vlucas/phpdotenv/tree/v5.6.3"
|
"source": "https://github.com/vlucas/phpdotenv/tree/v5.6.4"
|
||||||
},
|
},
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
@@ -540,7 +543,7 @@
|
|||||||
"type": "tidelift"
|
"type": "tidelift"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"time": "2025-12-27T19:49:13+00:00"
|
"time": "2026-07-06T19:11:50+00:00"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"packages-dev": [],
|
"packages-dev": [],
|
||||||
@@ -551,5 +554,8 @@
|
|||||||
"prefer-lowest": false,
|
"prefer-lowest": false,
|
||||||
"platform": {},
|
"platform": {},
|
||||||
"platform-dev": {},
|
"platform-dev": {},
|
||||||
|
"platform-overrides": {
|
||||||
|
"php": "8.2"
|
||||||
|
},
|
||||||
"plugin-api-version": "2.9.0"
|
"plugin-api-version": "2.9.0"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,6 +33,75 @@ $decoded = $jwtService->authenticate();
|
|||||||
$user_id = $decoded->user_id ?? null;
|
$user_id = $decoded->user_id ?? null;
|
||||||
$role = $decoded->role ?? 'passenger';
|
$role = $decoded->role ?? 'passenger';
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 2. بوّابة صلاحيات افتراضية لمسار /Admin
|
||||||
|
// ============================================================
|
||||||
|
// النموذج السابق كان «آمن إن تذكّرت»: كل نقطة تحت Admin/ تفحص الدور بنفسها،
|
||||||
|
// ومن يُغفل الفحص يصبح مكشوفاً. وقد وُجد فعلاً أن getPassengerDetails.php
|
||||||
|
// و getPassengerDetailsByPassengerID.php و getPassengerbyEmail.php كانت بلا
|
||||||
|
// أي فحص، فكان أي حامل JWT صالح — بما فيه راكب عادي — يقرأ بيانات ركّاب
|
||||||
|
// مفكوكة التشفير.
|
||||||
|
//
|
||||||
|
// هنا نقلب النموذج إلى «آمن افتراضاً»: كل ملف تحت Admin/ يمرّ عبر connect.php
|
||||||
|
// يتطلب دور admin أو super_admin، ما لم يكن في قائمة استثناء صريحة.
|
||||||
|
//
|
||||||
|
// نقاط تسجيل الدخول (Admin/auth/*, jwtService.php) لا تستدعي connect.php
|
||||||
|
// أصلاً، فلا تتأثر بهذه البوّابة ولا يمكن أن تُقفل على نفسها.
|
||||||
|
//
|
||||||
|
// 2026-08-07: وُسِّعت البوّابة لتشمل serviceapp/ أيضاً. كان 34 من 39 ملفاً
|
||||||
|
// هناك بلا أي فحص دور — بينها getDriverByPhone و getPassengersByPhone و
|
||||||
|
// update_complaint — أي أن أي حامل JWT صالح (راكب عادي) يقرأ بيانات
|
||||||
|
// السائقين والركّاب ويغلق الشكاوى. تحققنا أن siro_rider و siro_driver لا
|
||||||
|
// يستدعيان أي نقطة تحت serviceapp/، فالإغلاق لا يكسر تطبيقات الجوال.
|
||||||
|
//
|
||||||
|
// ⚠️ لكل مجلد أدواره: تسجيل دخول تطبيق الخدمة (Admin/jwtService.php:51)
|
||||||
|
// يصدر الدور 'service' لا 'admin'. فرضُ admin على serviceapp/ كان
|
||||||
|
// سيمنع كل موظفي خدمة العملاء من كل نقاطهم.
|
||||||
|
$gatedDirs = array_filter([
|
||||||
|
realpath(__DIR__ . '/Admin') => ['admin', 'super_admin'],
|
||||||
|
realpath(__DIR__ . '/serviceapp') => ['service', 'admin', 'super_admin'],
|
||||||
|
], fn($k) => $k !== false, ARRAY_FILTER_USE_KEY);
|
||||||
|
|
||||||
|
$script = realpath($_SERVER['SCRIPT_FILENAME'] ?? '');
|
||||||
|
|
||||||
|
$gateRoles = null;
|
||||||
|
if ($script) {
|
||||||
|
foreach ($gatedDirs as $dir => $roles) {
|
||||||
|
if (str_starts_with($script, $dir . DIRECTORY_SEPARATOR)) {
|
||||||
|
$gateRoles = $roles;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($gateRoles !== null) {
|
||||||
|
// نقاط تحت Admin/ تستدعيها تطبيقات الجوال بأدوار غير إدارية.
|
||||||
|
// تم التحقق من مواضع الاستدعاء الفعلية في siro_rider و siro_driver:
|
||||||
|
// errorApp.php → التطبيقان يبلّغان عن الأخطاء
|
||||||
|
// sendEmailToDrivertransaction.php → تطبيق السائق
|
||||||
|
// بقية روابط Admin/ المعرّفة في التطبيقين غير مستدعاة إطلاقاً.
|
||||||
|
$adminGateExempt = [
|
||||||
|
'errorApp.php',
|
||||||
|
'sendEmailToDrivertransaction.php',
|
||||||
|
];
|
||||||
|
|
||||||
|
if (!in_array(basename($script), $adminGateExempt, true)
|
||||||
|
&& !in_array($role, $gateRoles, true)
|
||||||
|
) {
|
||||||
|
securityLog('Admin gate blocked non-admin request', [
|
||||||
|
'script' => basename($script),
|
||||||
|
'role' => $role,
|
||||||
|
'user_id' => $user_id ?? 'unknown',
|
||||||
|
'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
|
||||||
|
]);
|
||||||
|
http_response_code(403);
|
||||||
|
exit(json_encode([
|
||||||
|
'status' => 'failure',
|
||||||
|
'message' => 'Forbidden. Admin access required.',
|
||||||
|
], JSON_UNESCAPED_UNICODE));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// 3. Database Connection
|
// 3. Database Connection
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -156,7 +156,9 @@ class JwtService
|
|||||||
|
|
||||||
// 3. Issuer (Only check if configured)
|
// 3. Issuer (Only check if configured)
|
||||||
if (!empty($this->issuer) && ($decoded->iss ?? '') !== $this->issuer) {
|
if (!empty($this->issuer) && ($decoded->iss ?? '') !== $this->issuer) {
|
||||||
self::abort(401, 'Invalid token issuer: expected ' . $this->issuer . ' but got ' . ($decoded->iss ?? 'none'));
|
// التفاصيل في اللوج فقط — لا تُكشف في الرد.
|
||||||
|
error_log('[SECURITY] Issuer mismatch | expected: ' . $this->issuer . ' | got: ' . ($decoded->iss ?? 'none'));
|
||||||
|
self::abort(401, 'Invalid token issuer');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3.1 App Signature Verification (Service Only)
|
// 3.1 App Signature Verification (Service Only)
|
||||||
@@ -228,8 +230,15 @@ class JwtService
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ($fpInToken === null || $fpHeader === null) {
|
if ($fpInToken === null || $fpHeader === null) {
|
||||||
$allHeaders = json_encode(getallheaders());
|
// ملاحظة: ممنوع تسجيل الهيدرز كاملة — كانت تُسرّب الـ
|
||||||
error_log("[SECURITY] Fingerprint missing | user: $userId | fpInToken: " . ($fpInToken ?? 'NULL') . " | fpHeader: " . ($fpHeader ?? 'NULL') . " | Headers: $allHeaders");
|
// Authorization: Bearer <token> بالنص الصريح إلى error_log.
|
||||||
|
// نسجّل فقط أيّ الطرفين ناقص، دون أي قيمة.
|
||||||
|
error_log(sprintf(
|
||||||
|
"[SECURITY] Fingerprint missing | user: %s | inToken: %s | inHeader: %s",
|
||||||
|
$userId,
|
||||||
|
$fpInToken === null ? 'no' : 'yes',
|
||||||
|
$fpHeader === null ? 'no' : 'yes'
|
||||||
|
));
|
||||||
self::abort(403, 'Device verification required');
|
self::abort(403, 'Device verification required');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ class RateLimiter
|
|||||||
// حدود مختلفة لكل نوع endpoint
|
// حدود مختلفة لكل نوع endpoint
|
||||||
private const LIMITS = [
|
private const LIMITS = [
|
||||||
'login' => ['requests' => 5, 'window' => 60], // 5 محاولات / دقيقة
|
'login' => ['requests' => 5, 'window' => 60], // 5 محاولات / دقيقة
|
||||||
'tester_login' => ['requests' => 3, 'window' => 60], // 3 محاولات / دقيقة
|
'tester_login' => ['requests' => 30, 'window' => 60], // 30 محاولة / دقيقة (مراجعو المتاجر يكرّرون الدخول بسرعة)
|
||||||
'otp' => ['requests' => 3, 'window' => 300], // 3 محاولات / 5 دقائق
|
'otp' => ['requests' => 3, 'window' => 300], // 3 محاولات / 5 دقائق
|
||||||
'register' => ['requests' => 3, 'window' => 3600], // 3 محاولات / ساعة
|
'register' => ['requests' => 3, 'window' => 3600], // 3 محاولات / ساعة
|
||||||
'api' => ['requests' => 180, 'window' => 60], // 180 طلب / دقيقة (الإنتاج الرسمى)
|
'api' => ['requests' => 180, 'window' => 60], // 180 طلب / دقيقة (الإنتاج الرسمى)
|
||||||
@@ -79,7 +79,15 @@ class RateLimiter
|
|||||||
// ── بناء معرّف المستخدم ────────────────────────────────────
|
// ── بناء معرّف المستخدم ────────────────────────────────────
|
||||||
public static function identifier(?string $userId = null): string
|
public static function identifier(?string $userId = null): string
|
||||||
{
|
{
|
||||||
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
|
// كان REMOTE_ADDR وحده، وهو خلف دوكر دائماً عنوان الوسيط نفسه
|
||||||
|
// (172.24.0.1) — فيتشارك كل المستخدمين دلواً واحداً، ومحاولات دخول
|
||||||
|
// فاشلة من عميل واحد تحجب الجميع بـ 429 (ظهر ذلك في سجل الإنتاج).
|
||||||
|
// clientIp() تستخرج العميل الحقيقي من X-Forwarded-For ولا تثق به
|
||||||
|
// إلا إذا كان REMOTE_ADDR وسيطاً موثوقاً.
|
||||||
|
$ip = function_exists('clientIp')
|
||||||
|
? clientIp()
|
||||||
|
: ($_SERVER['REMOTE_ADDR'] ?? 'unknown');
|
||||||
|
|
||||||
return $userId ? "{$ip}:{$userId}" : $ip;
|
return $userId ? "{$ip}:{$userId}" : $ip;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -34,6 +34,12 @@ class Database
|
|||||||
'user' => 'DB_TRANSIT_USER',
|
'user' => 'DB_TRANSIT_USER',
|
||||||
'pass' => 'DB_TRANSIT_PASS',
|
'pass' => 'DB_TRANSIT_PASS',
|
||||||
],
|
],
|
||||||
|
'food' => [
|
||||||
|
'name' => 'DB_FOOD_NAME',
|
||||||
|
'host' => 'DB_FOOD_HOST',
|
||||||
|
'user' => 'DB_FOOD_USER',
|
||||||
|
'pass' => 'DB_FOOD_PASS',
|
||||||
|
],
|
||||||
];
|
];
|
||||||
|
|
||||||
public static function get(string $name = 'main'): PDO
|
public static function get(string $name = 'main'): PDO
|
||||||
@@ -67,7 +73,15 @@ class Database
|
|||||||
PDO::ATTR_EMULATE_PREPARES => false,
|
PDO::ATTR_EMULATE_PREPARES => false,
|
||||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||||
PDO::ATTR_PERSISTENT => true,
|
// الاتصالات الدائمة أُوقفت: كانت تُنتج "Packets out of order.
|
||||||
|
// Expected 1 received 0" بتكرار في الإنتاج — وهو عرض معروف لإعادة
|
||||||
|
// استخدام اتصال دائم تُرك في حالة غير نظيفة، أو أغلقه MySQL عند
|
||||||
|
// wait_timeout بينما ما زال PHP يعدّه حياً. والأسوأ أن التحذير
|
||||||
|
// يُطبع قبل الرؤوس فيُفسد الاستجابة بـ "headers already sent".
|
||||||
|
//
|
||||||
|
// الكلفة اتصال جديد لكل طلب، وهي مقبولة هنا: MySQL على شبكة دوكر
|
||||||
|
// نفسها و max-connections=300. الاستقرار أولى من هذا التوفير.
|
||||||
|
PDO::ATTR_PERSISTENT => false,
|
||||||
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
|
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
|
||||||
PDO::ATTR_TIMEOUT => 10,
|
PDO::ATTR_TIMEOUT => 10,
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* core/Security/BlindIndex.php
|
||||||
|
*
|
||||||
|
* فهرس أعمى للبحث فوق حقول مشفّرة.
|
||||||
|
*
|
||||||
|
* المشكلة: التشفير الآمن (AES-GCM) عشوائي — نفس النص ينتج تشفيراً مختلفاً في
|
||||||
|
* كل مرة، فلا يمكن البحث بمقارنة النص المشفّر. والحل القديم (CBC بـ IV ثابت)
|
||||||
|
* يجعل التشفير حتمياً فينجح البحث، لكنه يسرّب المساواة والبادئات المشتركة.
|
||||||
|
*
|
||||||
|
* الحل: نفصل التخزين عن البحث.
|
||||||
|
* - التخزين: AES-GCM عشوائي (لا يسرّب شيئاً).
|
||||||
|
* - البحث: عمود إضافي يحمل HMAC-SHA256 حتمياً للقيمة بعد تطبيعها.
|
||||||
|
*
|
||||||
|
* لماذا HMAC وليس sha256 عارياً؟ لأن مساحة أرقام الهواتف صغيرة (ملايين
|
||||||
|
* قليلة) — جدول عكسي لكل الأرقام يُبنى في ثوانٍ. المفتاح السرّي (pepper)
|
||||||
|
* المخزَّن في البيئة وحده يمنع ذلك، فمن يسرق قاعدة البيانات لا يملكه.
|
||||||
|
*/
|
||||||
|
|
||||||
|
final class BlindIndex
|
||||||
|
{
|
||||||
|
private string $pepper;
|
||||||
|
|
||||||
|
public function __construct(?string $pepper = null)
|
||||||
|
{
|
||||||
|
$pepper = $pepper ?: (getenv('BLIND_INDEX_PEPPER') ?: '');
|
||||||
|
if ($pepper === '') {
|
||||||
|
throw new RuntimeException(
|
||||||
|
'BLIND_INDEX_PEPPER is not set. Generate one with: openssl rand -hex 32'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
$this->pepper = $pepper;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* يحسب الفهرس لقيمة داخل حقل محدد.
|
||||||
|
*
|
||||||
|
* $scope يشمل الجدول والحقل (مثل "driver.phone") عمداً: بدونه يكون فهرس
|
||||||
|
* نفس الرقم متطابقاً في جدول السائقين والركاب، فيستطيع من يقرأ القاعدة
|
||||||
|
* ربط الحسابات ببعضها دون فك أي تشفير.
|
||||||
|
*/
|
||||||
|
public function index(string $scope, ?string $value): ?string
|
||||||
|
{
|
||||||
|
$normalized = self::normalize($scope, $value);
|
||||||
|
if ($normalized === null || $normalized === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return hash_hmac('sha256', $scope . ':' . $normalized, $this->pepper);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* فهرس مبتور للبحث الجزئي (مثل الأسماء).
|
||||||
|
*
|
||||||
|
* البتر مقصود: يُنتج تطابقات كاذبة تُصفّى بعد فك التشفير، وهذه الضبابية
|
||||||
|
* هي ما يمنع استخدام الفهرس نفسه في تحليل التكرارات.
|
||||||
|
*/
|
||||||
|
public function bucket(string $scope, ?string $value, int $length = 8): ?string
|
||||||
|
{
|
||||||
|
$full = $this->index($scope, $value);
|
||||||
|
return $full === null ? null : substr($full, 0, $length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* التطبيع قبل الحساب — بدونه يُنتج 0791234567 و+962791234567 فهرسين
|
||||||
|
* مختلفين ويفشل البحث.
|
||||||
|
*/
|
||||||
|
public static function normalize(string $scope, ?string $value): ?string
|
||||||
|
{
|
||||||
|
if ($value === null) return null;
|
||||||
|
$value = trim($value);
|
||||||
|
if ($value === '') return null;
|
||||||
|
|
||||||
|
if (str_contains($scope, 'phone')) {
|
||||||
|
$digits = preg_replace('/\D+/', '', $value);
|
||||||
|
// توحيد الصيغة المحلية والدولية على شكل واحد
|
||||||
|
$digits = preg_replace('/^00/', '', $digits);
|
||||||
|
if (str_starts_with($digits, '0')) {
|
||||||
|
$cc = getenv('DEFAULT_COUNTRY_CODE') ?: '962';
|
||||||
|
$digits = $cc . substr($digits, 1);
|
||||||
|
}
|
||||||
|
return $digits;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (str_contains($scope, 'email')) {
|
||||||
|
return mb_strtolower($value, 'UTF-8');
|
||||||
|
}
|
||||||
|
|
||||||
|
// الأسماء: توحيد حالة الأحرف والمسافات، وتوحيد أشكال الألف والياء
|
||||||
|
// والتاء المربوطة العربية حتى لا يتوقف البحث على شكل الكتابة.
|
||||||
|
$value = mb_strtolower($value, 'UTF-8');
|
||||||
|
$value = preg_replace('/\s+/u', ' ', $value);
|
||||||
|
$value = str_replace(
|
||||||
|
['أ', 'إ', 'آ', 'ٱ', 'ى', 'ة', 'ؤ', 'ئ'],
|
||||||
|
['ا', 'ا', 'ا', 'ا', 'ي', 'ه', 'و', 'ي'],
|
||||||
|
$value
|
||||||
|
);
|
||||||
|
// إزالة التشكيل
|
||||||
|
$value = preg_replace('/[\x{064B}-\x{0652}\x{0640}]/u', '', $value);
|
||||||
|
return trim($value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,16 @@ class EncryptionHelper
|
|||||||
private const TAG_LEN = 16;
|
private const TAG_LEN = 16;
|
||||||
private const PREFIX_GCM = 'GCM:'; // للتمييز بين الجديد والقديم
|
private const PREFIX_GCM = 'GCM:'; // للتمييز بين الجديد والقديم
|
||||||
|
|
||||||
public function __construct(string $key, ?string $cbcIv = null)
|
/**
|
||||||
|
* وضع الكتابة: 'cbc' (افتراضي) أو 'gcm'.
|
||||||
|
*
|
||||||
|
* القراءة غير متأثرة بهذا الوضع إطلاقاً — decryptData تتعرّف على الصيغتين
|
||||||
|
* عبر البادئة، فالسجلات القديمة تبقى مقروءة بلا ترحيل، والرجوع عن التحويل
|
||||||
|
* لا يُفقد أي سجل كُتب بـ GCM.
|
||||||
|
*/
|
||||||
|
private string $writeMode;
|
||||||
|
|
||||||
|
public function __construct(string $key, ?string $cbcIv = null, ?string $writeMode = null)
|
||||||
{
|
{
|
||||||
if (strlen($key) !== 32) {
|
if (strlen($key) !== 32) {
|
||||||
throw new InvalidArgumentException('Encryption key must be exactly 32 bytes.');
|
throw new InvalidArgumentException('Encryption key must be exactly 32 bytes.');
|
||||||
@@ -22,10 +31,34 @@ class EncryptionHelper
|
|||||||
$this->key = $key;
|
$this->key = $key;
|
||||||
// IV القديم للتوافقية أثناء مرحلة المايغريشن
|
// IV القديم للتوافقية أثناء مرحلة المايغريشن
|
||||||
$this->cbcIv = $cbcIv ?: getenv('initializationVector') ?: str_repeat('0', 16);
|
$this->cbcIv = $cbcIv ?: getenv('initializationVector') ?: str_repeat('0', 16);
|
||||||
|
|
||||||
|
$mode = strtolower($writeMode ?: (getenv('ENCRYPTION_MODE') ?: 'cbc'));
|
||||||
|
$this->writeMode = $mode === 'gcm' ? 'gcm' : 'cbc';
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── تشفير نص باستخدام AES-256-CBC الحتمي ──
|
public function writeMode(): string
|
||||||
|
{
|
||||||
|
return $this->writeMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* نقطة التشفير الموحّدة لكل التطبيق.
|
||||||
|
*
|
||||||
|
* حتى الآن كانت CBC بـ IV ثابت، أي حتمية: نفس النص ينتج نفس التشفير، وهو
|
||||||
|
* ما كان يسمح بالبحث عبر مقارنة النص المشفّر، لكنه يسرّب المساواة
|
||||||
|
* والبادئات المشتركة. مع ENCRYPTION_MODE=gcm يصبح التشفير عشوائياً
|
||||||
|
* وموثَّقاً، ويتكفّل الفهرس الأعمى (BlindIndex) بالبحث.
|
||||||
|
*/
|
||||||
public function encryptData(string $plainText): string
|
public function encryptData(string $plainText): string
|
||||||
|
{
|
||||||
|
if ($this->writeMode === 'gcm') {
|
||||||
|
return $this->encryptDataGCM($plainText);
|
||||||
|
}
|
||||||
|
return $this->encryptDataCBC($plainText);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── تشفير نص باستخدام AES-256-CBC الحتمي (للتوافقية والرجوع) ──
|
||||||
|
public function encryptDataCBC(string $plainText): string
|
||||||
{
|
{
|
||||||
$plainText = mb_convert_encoding($plainText, 'UTF-8');
|
$plainText = mb_convert_encoding($plainText, 'UTF-8');
|
||||||
$padded = $this->addPadding($plainText);
|
$padded = $this->addPadding($plainText);
|
||||||
|
|||||||
@@ -371,9 +371,48 @@ class SiroGeminiService {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
$data = json_decode($response, true);
|
|
||||||
$text = $data['candidates'][0]['content']['parts'][0]['text'] ?? '';
|
$text = $data['candidates'][0]['content']['parts'][0]['text'] ?? '';
|
||||||
return trim(preg_replace('/```html|```/', '', $text));
|
return trim(preg_replace('/```html|```/', '', $text));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Answers a driver support inquiry acting as Siro's smart assistant.
|
||||||
|
*/
|
||||||
|
public function answerSupportInquiry(
|
||||||
|
string $question,
|
||||||
|
array $driverContext,
|
||||||
|
string $model = 'gemini-flash-lite-latest'
|
||||||
|
): ?string {
|
||||||
|
if (!$this->apiKey) return null;
|
||||||
|
|
||||||
|
$contextJson = json_encode($driverContext, JSON_UNESCAPED_UNICODE);
|
||||||
|
|
||||||
|
$prompt = "
|
||||||
|
أنت مساعد الدعم الفني الذكي لتطبيق 'سيرو' (Siro) لنقل الركاب.
|
||||||
|
وظيفتك مساعدة السائقين (الكباتن) والإجابة على استفساراتهم باحترافية، ودقة، وبلهجة ودية ومهذبة جداً.
|
||||||
|
|
||||||
|
بيانات السائق الحالية (سياق مهم للإجابة على سؤاله):
|
||||||
|
$contextJson
|
||||||
|
|
||||||
|
سؤال السائق:
|
||||||
|
\"$question\"
|
||||||
|
|
||||||
|
المطلوب منك:
|
||||||
|
1. الإجابة مباشرة على سؤال السائق بناءً على السياق المعطى إذا كان يخص رحلاته أو رصيده المذكور في السياق.
|
||||||
|
2. إذا سأل عن إجراءات عامة، أجب كخبير في سيرو.
|
||||||
|
3. اجعل الإجابة ودية وواضحة جداً وقصيرة.
|
||||||
|
4. الرد يكون باللغة العربية حصراً.
|
||||||
|
5. لا تذكر تفاصيل تقنية (مثل json أو database)، بل تحدث كإنسان يقدم الدعم.
|
||||||
|
";
|
||||||
|
|
||||||
|
$prompt .= "\n\nالرجاء إرجاع الإجابة بصيغة JSON فقط كالتالي:\n{\n \"reply\": \"نص الإجابة هنا\"\n}";
|
||||||
|
|
||||||
|
$response = $this->callGemini($prompt, $model);
|
||||||
|
if ($response && isset($response['reply'])) {
|
||||||
|
return $response['reply'];
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,7 +42,9 @@ header("X-XSS-Protection: 1; mode=block");
|
|||||||
|
|
||||||
|
|
||||||
// CORS مع التحقق من المصدر المسموح
|
// CORS مع التحقق من المصدر المسموح
|
||||||
$allowedOrigins = array_map('trim', explode(',', getenv('CORS_ALLOWED_ORIGINS') ?: 'https://siromove.com,https://admin.siromove.com'));
|
$envOrigins = array_map('trim', explode(',', getenv('CORS_ALLOWED_ORIGINS') ?: ''));
|
||||||
|
$defaultOrigins = ['https://siromove.com', 'https://admin.siromove.com', 'https://jordan-siro.intaleqapp.com', 'http://localhost', 'http://127.0.0.1'];
|
||||||
|
$allowedOrigins = array_unique(array_merge($envOrigins, $defaultOrigins));
|
||||||
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
|
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
|
||||||
if (in_array($origin, $allowedOrigins)) {
|
if (in_array($origin, $allowedOrigins)) {
|
||||||
header("Access-Control-Allow-Origin: $origin");
|
header("Access-Control-Allow-Origin: $origin");
|
||||||
@@ -51,7 +53,8 @@ if (in_array($origin, $allowedOrigins)) {
|
|||||||
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
|
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
|
||||||
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Device-FP, X-HMAC-Auth, X-Internal-Key');
|
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Device-FP, X-HMAC-Auth, X-Internal-Key');
|
||||||
|
|
||||||
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
// REQUEST_METHOD غير معرّف عند التشغيل من سطر الأوامر (سكربتات الترحيل)
|
||||||
|
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
|
||||||
http_response_code(200);
|
http_response_code(200);
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
@@ -157,6 +160,17 @@ try {
|
|||||||
|
|
||||||
// 5. تحميل الـ Services الأساسية
|
// 5. تحميل الـ Services الأساسية
|
||||||
require_once __DIR__ . '/Security/EncryptionHelper.php';
|
require_once __DIR__ . '/Security/EncryptionHelper.php';
|
||||||
|
require_once __DIR__ . '/Security/BlindIndex.php';
|
||||||
|
|
||||||
|
// فهرس البحث الأعمى — اختياري: إن لم يُضبط BLIND_INDEX_PEPPER تبقى نقاط
|
||||||
|
// البحث تعمل بأسلوبها القديم بدل أن تفشل.
|
||||||
|
$blindIndex = null;
|
||||||
|
try {
|
||||||
|
$blindIndex = new BlindIndex();
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
error_log('[BlindIndex] disabled: ' . $e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
require_once __DIR__ . '/Database/Database.php';
|
require_once __DIR__ . '/Database/Database.php';
|
||||||
require_once __DIR__ . '/Auth/RateLimiter.php';
|
require_once __DIR__ . '/Auth/RateLimiter.php';
|
||||||
require_once __DIR__ . '/Auth/JwtService.php';
|
require_once __DIR__ . '/Auth/JwtService.php';
|
||||||
|
|||||||
@@ -38,6 +38,31 @@ function filterRequest(string $name, string $type = 'string'): mixed
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* مفتاح بحث ثابت لجداول التحقق (token_verification*, phone_verification*).
|
||||||
|
*
|
||||||
|
* هذه الجداول تستخدم رقم الهاتف كمفتاح بحث لا كبيان يُعرض: يُكتب عند الإرسال
|
||||||
|
* ويُقرأ عند التحقق. تخزينه مشفّراً كان يعمل فقط لأن التشفير حتمي — ومع
|
||||||
|
* AES-GCM العشوائي يُنتج الإرسال والتحقق قيمتين مختلفتين فلا ينجح أي رمز.
|
||||||
|
*
|
||||||
|
* البديل: بصمة HMAC حتمية للرقم بعد تطبيعه. لا تحتاج تعديل المخطط (العمود
|
||||||
|
* نصي أصلاً)، وتوحّد صيغ الرقم المحلية والدولية، ولا يمكن عكسها بلا المفتاح.
|
||||||
|
*/
|
||||||
|
function otpPhoneKey(?string $phone): string
|
||||||
|
{
|
||||||
|
if ($phone === null || trim($phone) === '') return '';
|
||||||
|
|
||||||
|
global $blindIndex, $encryptionHelper;
|
||||||
|
|
||||||
|
if ($blindIndex) {
|
||||||
|
return 'K:' . $blindIndex->index('otp.phone', $phone);
|
||||||
|
}
|
||||||
|
|
||||||
|
// بلا BLIND_INDEX_PEPPER نعود للسلوك القديم حتى لا يتعطل التحقق
|
||||||
|
return $encryptionHelper ? $encryptionHelper->encryptData($phone) : $phone;
|
||||||
|
}
|
||||||
|
|
||||||
// ── ردود JSON موحدة ─────────────────────────────────────────
|
// ── ردود JSON موحدة ─────────────────────────────────────────
|
||||||
function jsonSuccess(mixed $data = null, string $message = 'success', int $code = 200): never
|
function jsonSuccess(mixed $data = null, string $message = 'success', int $code = 200): never
|
||||||
{
|
{
|
||||||
@@ -263,3 +288,74 @@ function normalizePhone(string $phone): string
|
|||||||
return $d; // رقم خارج النطاق — يُعاد كما هو
|
return $d; // رقم خارج النطاق — يُعاد كما هو
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* إخفاء جزء من رقم الهاتف قبل عرضه لدور لا يملك صلاحية رؤيته كاملاً.
|
||||||
|
*
|
||||||
|
* نموذج الصلاحيات في اللوحة: `admin` يراقب بأرقام مُخفاة جزئياً،
|
||||||
|
* و`super_admin` وحده يرى الرقم كاملاً.
|
||||||
|
*
|
||||||
|
* يُبقي مقدّمة الدولة وآخر رقمين حتى يبقى الرقم مميّزاً للمتابعة التشغيلية
|
||||||
|
* دون كشف هوية صاحبه.
|
||||||
|
*/
|
||||||
|
function maskPhone(?string $phone): ?string
|
||||||
|
{
|
||||||
|
if ($phone === null || $phone === '') return $phone;
|
||||||
|
|
||||||
|
$d = preg_replace('/\D+/', '', $phone);
|
||||||
|
$len = strlen($d);
|
||||||
|
if ($len < 5) return str_repeat('*', max(0, $len));
|
||||||
|
|
||||||
|
$head = substr($d, 0, 3);
|
||||||
|
$tail = substr($d, -2);
|
||||||
|
return $head . str_repeat('*', $len - 5) . $tail;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* عنوان العميل الحقيقي خلف الوسطاء.
|
||||||
|
*
|
||||||
|
* سلسلة الطلب: العميل ← nginx المضيف ← nginx الحاوية ← php-fpm، فيصل
|
||||||
|
* REMOTE_ADDR دائماً كعنوان الوسيط. الاعتماد عليه وحده جعل RateLimiter يضع
|
||||||
|
* كل المستخدمين في دلو واحد، فمحاولات دخول فاشلة من عميل واحد تحجب الجميع.
|
||||||
|
*
|
||||||
|
* X-Forwarded-For قابل للتزوير من العميل، لذا لا نثق به إلا إذا كان
|
||||||
|
* REMOTE_ADDR نفسه وسيطاً موثوقاً (شبكات خاصة/لوكال). خلاف ذلك نعيد
|
||||||
|
* REMOTE_ADDR كما هو.
|
||||||
|
*/
|
||||||
|
function clientIp(): string
|
||||||
|
{
|
||||||
|
$remote = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
|
||||||
|
|
||||||
|
$isTrustedProxy = $remote !== 'unknown' && (
|
||||||
|
filter_var(
|
||||||
|
$remote,
|
||||||
|
FILTER_VALIDATE_IP,
|
||||||
|
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
|
||||||
|
) === false
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!$isTrustedProxy) {
|
||||||
|
return $remote;
|
||||||
|
}
|
||||||
|
|
||||||
|
$forwarded = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
|
||||||
|
if ($forwarded === '') {
|
||||||
|
return $remote;
|
||||||
|
}
|
||||||
|
|
||||||
|
// أول عنوان عام في السلسلة هو العميل؛ نتخطّى العناوين الخاصة التي
|
||||||
|
// أضافها الوسطاء.
|
||||||
|
foreach (explode(',', $forwarded) as $candidate) {
|
||||||
|
$candidate = trim($candidate);
|
||||||
|
if ($candidate === '') continue;
|
||||||
|
if (filter_var(
|
||||||
|
$candidate,
|
||||||
|
FILTER_VALIDATE_IP,
|
||||||
|
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
|
||||||
|
) !== false) {
|
||||||
|
return $candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $remote;
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,16 +2,22 @@
|
|||||||
|
|
||||||
require_once __DIR__ . '/../connect.php';
|
require_once __DIR__ . '/../connect.php';
|
||||||
|
|
||||||
// Get the values from the request
|
// المسار القديم للتأمين الصحي. المسار الجديد (خطط، أهلية، أقساط) في
|
||||||
$driver_id = filterRequest("driver_id");
|
// plans.php و subscribe.php و get.php — هذا يبقى لمن سُجّل هنا سابقاً.
|
||||||
$assured = filterRequest("assured"); // إذا كانت قيمة حساسة يجب تشفيرها
|
|
||||||
$health_insurance_provider = filterRequest("health_insurance_provider"); // إذا كانت حساسة، شفرها
|
|
||||||
|
|
||||||
// إذا تحتاج تشفير، فعّل التالي:
|
// الهوية من الـJWT لا من الطلب. كان الملف يقرأ driver_id من المدخلات
|
||||||
// $assured = $encryptionHelper->encryptData($assured);
|
// بلا أي فحص، فأي حامل رمز صالح يكتب سجل تأمين باسم أي سائق.
|
||||||
// $health_insurance_provider = $encryptionHelper->encryptData($health_insurance_provider);
|
$driver_id = $user_id ?? '';
|
||||||
|
if (empty($driver_id) || ($role ?? '') !== 'driver') {
|
||||||
|
jsonError('Unauthorized', 401);
|
||||||
|
}
|
||||||
|
|
||||||
// SQL using bind parameters
|
$assured = filterRequest("assured");
|
||||||
|
$health_insurance_provider = filterRequest("health_insurance_provider");
|
||||||
|
|
||||||
|
// upsert لا insert: العمود driver_id عليه مفتاح فريد، فأي حفظ ثانٍ
|
||||||
|
// لنفس السائق كان يفشل بخرق المفتاح — والحفظ الثاني هو الحالة
|
||||||
|
// الطبيعية (تعديل مزوّد التأمين) لا الاستثناء.
|
||||||
$sql = "INSERT INTO `driver_health_assurance` (
|
$sql = "INSERT INTO `driver_health_assurance` (
|
||||||
`driver_id`,
|
`driver_id`,
|
||||||
`assured`,
|
`assured`,
|
||||||
@@ -20,7 +26,10 @@ $sql = "INSERT INTO `driver_health_assurance` (
|
|||||||
:driver_id,
|
:driver_id,
|
||||||
:assured,
|
:assured,
|
||||||
:health_insurance_provider
|
:health_insurance_provider
|
||||||
)";
|
)
|
||||||
|
ON DUPLICATE KEY UPDATE
|
||||||
|
`assured` = VALUES(`assured`),
|
||||||
|
`health_insurance_provider` = VALUES(`health_insurance_provider`)";
|
||||||
|
|
||||||
$stmt = $con->prepare($sql);
|
$stmt = $con->prepare($sql);
|
||||||
$stmt->bindParam(':driver_id', $driver_id);
|
$stmt->bindParam(':driver_id', $driver_id);
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* driver_assurance/cancel.php — إلغاء وثيقة التأمين
|
||||||
|
*
|
||||||
|
* الإلغاء يوقف الأقساط القادمة ولا يمسّ الماضي: القيود المستحقّة تبقى
|
||||||
|
* مستحقّة. تصفيرها عند الإلغاء كانت ستجعل الإلغاء وسيلة للتهرّب من
|
||||||
|
* أيام تغطية استفاد منها السائق فعلاً.
|
||||||
|
*/
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../connect.php';
|
||||||
|
require_once __DIR__ . '/eligibility.php';
|
||||||
|
require_once __DIR__ . '/../obligations/functions.php';
|
||||||
|
|
||||||
|
$driverId = $user_id ?? '';
|
||||||
|
if (empty($driverId) || ($role ?? '') !== 'driver') {
|
||||||
|
jsonError('Unauthorized', 401);
|
||||||
|
}
|
||||||
|
|
||||||
|
$policy = assuranceActivePolicy($con, $driverId);
|
||||||
|
if (!$policy) {
|
||||||
|
jsonError('لا توجد وثيقة نشطة');
|
||||||
|
}
|
||||||
|
|
||||||
|
$reason = filterRequest('reason') ?: 'بطلب السائق';
|
||||||
|
|
||||||
|
// الوثيقة والالتزام يُغلقان معاً. التزام يبقى نشطاً بعد إلغاء وثيقته
|
||||||
|
// يعني قسطاً يُقيَّد كل ليلة على سائقٍ بلا تغطية — عكس الثغرة السابقة
|
||||||
|
// تماماً، وأسوأ منها: هناك مال يضيع على الشركة، وهنا مال يُؤخذ ظلماً.
|
||||||
|
try {
|
||||||
|
$con->beginTransaction();
|
||||||
|
|
||||||
|
// الشرط على driver_id إلى جانب المعرّف: الوثيقة أتت من استعلام
|
||||||
|
// مقيَّد بالسائق أصلاً، لكن الشرط هنا يجعل الاستعلام آمناً بذاته
|
||||||
|
// لو أعيد استعماله يوماً في سياق آخر.
|
||||||
|
$st = $con->prepare("
|
||||||
|
UPDATE driver_insurance_policies
|
||||||
|
SET status = 'cancelled', ended_at = CURDATE(), cancel_reason = ?
|
||||||
|
WHERE id = ? AND driver_id = ? AND status = 'active'
|
||||||
|
");
|
||||||
|
$st->execute([mb_substr($reason, 0, 255), $policy['id'], $driverId]);
|
||||||
|
|
||||||
|
if ($st->rowCount() === 0) {
|
||||||
|
$con->rollBack();
|
||||||
|
jsonError('تعذّر إلغاء الوثيقة');
|
||||||
|
}
|
||||||
|
|
||||||
|
obligationClose($con, $driverId, $policy['code'], $reason);
|
||||||
|
|
||||||
|
$con->commit();
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
if ($con->inTransaction()) $con->rollBack();
|
||||||
|
error_log('[assurance/cancel] ' . $e->getMessage());
|
||||||
|
jsonError('Server error');
|
||||||
|
}
|
||||||
|
|
||||||
|
// المستحق يُقرأ من الدفتر الموحّد لا من دفتر التأمين القديم: القديم
|
||||||
|
// مجمَّد بعد الترحيل، وقراءته تعني رقماً لا يتغيّر مهما سدّد السائق.
|
||||||
|
$pending = obligationPendingTotal($con, $driverId, $policy['code']);
|
||||||
|
|
||||||
|
error_log("[assurance] أُلغيت وثيقة #{$policy['id']} للسائق $driverId");
|
||||||
|
|
||||||
|
jsonSuccess([
|
||||||
|
'cancelled' => true,
|
||||||
|
'pending_balance' => $pending,
|
||||||
|
'currency' => $policy['currency'],
|
||||||
|
], $pending > 0
|
||||||
|
? 'أُلغيت الوثيقة. يبقى عليك مستحق أقساط سابقة قدره ' . $pending . ' ' . $policy['currency']
|
||||||
|
: 'أُلغيت الوثيقة');
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* driver_assurance/eligibility.php — حساب أهلية السائق للتأمين
|
||||||
|
* ─────────────────────────────────────────────────────────────
|
||||||
|
* قرار المالك: التأمين ليس خدمة تُمنح لكل من سجّل، بل مكافأة استمرار.
|
||||||
|
* لا يستحقّه السائق إلا بعد عدد رحلات مكتملة وتقييم جيد.
|
||||||
|
*
|
||||||
|
* المنطق التجاري خلفه: القسط كلفة متكررة تتحمّلها الشركة عن السائق أو
|
||||||
|
* تخصمها من أرباحه. منحه لمن قد يختفي بعد أسبوع يحوّل الأداة من
|
||||||
|
* ولاء إلى نزيف — والسائق الذي أتمّ مئتي رحلة بتقييم جيد أثبت أنه
|
||||||
|
* باقٍ، وهو بالضبط من نريد قفله معنا.
|
||||||
|
*
|
||||||
|
* الأرقام في جدول الخطط لا في هذا الملف: الشريك سيغيّرها، ومصر تختلف
|
||||||
|
* عن الأردن، وتعديل صف أرخص من نشر إصدار.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* يقيس السائق مقابل شروط خطة.
|
||||||
|
*
|
||||||
|
* @return array{
|
||||||
|
* eligible: bool,
|
||||||
|
* rides: int, rating: float, account_days: int,
|
||||||
|
* reasons: string[]
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
function assuranceCheckEligibility(PDO $con, string $driverId, array $plan): array
|
||||||
|
{
|
||||||
|
$rides = 0;
|
||||||
|
$rating = 0.0;
|
||||||
|
$days = 0;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// الرحلات المكتملة فقط. الحالة مكتوبة بحرفين مختلفين في
|
||||||
|
// الجدول تاريخياً ('Finished' و'finished')، وإغفال أحدهما
|
||||||
|
// يُنقص عدّاد السائق إلى النصف تقريباً.
|
||||||
|
$st = $con->prepare("
|
||||||
|
SELECT COUNT(*) FROM ride
|
||||||
|
WHERE driver_id = ? AND status IN ('Finished', 'finished')
|
||||||
|
");
|
||||||
|
$st->execute([$driverId]);
|
||||||
|
$rides = (int) $st->fetchColumn();
|
||||||
|
|
||||||
|
$st = $con->prepare("SELECT AVG(rating) FROM ratingDriver WHERE driver_id = ?");
|
||||||
|
$st->execute([$driverId]);
|
||||||
|
$avg = $st->fetchColumn();
|
||||||
|
// سائق بلا تقييمات ليس سيئاً — لكنه أيضاً غير مثبَت. عدد
|
||||||
|
// الرحلات المطلوب يضمن أن تقييماته وصلت على أي حال.
|
||||||
|
$rating = $avg === null || $avg === false ? 0.0 : round((float) $avg, 2);
|
||||||
|
|
||||||
|
$st = $con->prepare("SELECT DATEDIFF(NOW(), created_at) FROM driver WHERE id = ? LIMIT 1");
|
||||||
|
$st->execute([$driverId]);
|
||||||
|
$d = $st->fetchColumn();
|
||||||
|
$days = ($d === false || $d === null) ? 0 : (int) $d;
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log('[assurance] تعذّر حساب الأهلية: ' . $e->getMessage());
|
||||||
|
return [
|
||||||
|
'eligible' => false, 'rides' => 0, 'rating' => 0.0, 'account_days' => 0,
|
||||||
|
'reasons' => ['تعذّر التحقق حالياً'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$minRides = (int) ($plan['min_completed_rides'] ?? 200);
|
||||||
|
$minRating = (float) ($plan['min_rating'] ?? 4.50);
|
||||||
|
$minDays = (int) ($plan['min_account_days'] ?? 30);
|
||||||
|
|
||||||
|
// نجمع كل الأسباب لا أوّلها: السائق يستحق أن يعرف كل ما ينقصه
|
||||||
|
// دفعةً واحدة، لا أن يعالج شرطاً فيُفاجأ بالتالي.
|
||||||
|
$reasons = [];
|
||||||
|
if ($rides < $minRides) {
|
||||||
|
$reasons[] = "أكمل $minRides رحلة (لديك $rides)";
|
||||||
|
}
|
||||||
|
if ($rating < $minRating) {
|
||||||
|
$reasons[] = "تقييمك يجب ألّا يقل عن $minRating (تقييمك " . ($rating ?: '—') . ')';
|
||||||
|
}
|
||||||
|
if ($days < $minDays) {
|
||||||
|
$reasons[] = "مضيّ $minDays يوماً على حسابك (مضى $days)";
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'eligible' => empty($reasons),
|
||||||
|
'rides' => $rides,
|
||||||
|
'rating' => $rating,
|
||||||
|
'account_days' => $days,
|
||||||
|
'reasons' => $reasons,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* الوثيقة النشطة للسائق مع بيانات خطتها، أو null.
|
||||||
|
*/
|
||||||
|
function assuranceActivePolicy(PDO $con, string $driverId): ?array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$st = $con->prepare("
|
||||||
|
SELECT p.*, pl.code, pl.name_ar AS plan_name, pl.premium, pl.currency,
|
||||||
|
pl.billing_cycle, pl.coverage_summary,
|
||||||
|
pr.name AS provider_name, pr.name_ar AS provider_name_ar
|
||||||
|
FROM driver_insurance_policies p
|
||||||
|
JOIN insurance_plans pl ON pl.id = p.plan_id
|
||||||
|
JOIN insurance_providers pr ON pr.id = pl.provider_id
|
||||||
|
WHERE p.driver_id = ? AND p.status = 'active'
|
||||||
|
ORDER BY p.id DESC LIMIT 1
|
||||||
|
");
|
||||||
|
$st->execute([$driverId]);
|
||||||
|
return $st->fetch(PDO::FETCH_ASSOC) ?: null;
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log('[assurance] تعذّر جلب الوثيقة: ' . $e->getMessage());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* driver_assurance/get.php — حالة تأمين السائق
|
||||||
|
*
|
||||||
|
* كان هذا الملف فارغاً (صفر بايت) — يُستدعى فيرد بلا شيء.
|
||||||
|
*
|
||||||
|
* يرد بالوثيقة النشطة، وملخّص دفتر أقساطها، وآخر القيود. الدفتر جزء
|
||||||
|
* من الرد لا نقطة منفصلة: السائق الذي يُخصم من أرباحه يجب أن يرى
|
||||||
|
* مقابل ماذا في الشاشة نفسها، وإلا صار الخصم مفاجأة تُفقد الثقة.
|
||||||
|
*/
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../connect.php';
|
||||||
|
require_once __DIR__ . '/eligibility.php';
|
||||||
|
|
||||||
|
$driverId = $user_id ?? '';
|
||||||
|
if (empty($driverId) || ($role ?? '') !== 'driver') {
|
||||||
|
jsonError('Unauthorized', 401);
|
||||||
|
}
|
||||||
|
|
||||||
|
$policy = assuranceActivePolicy($con, $driverId);
|
||||||
|
|
||||||
|
if (!$policy) {
|
||||||
|
jsonSuccess([
|
||||||
|
'has_policy' => false,
|
||||||
|
'policy' => null,
|
||||||
|
'ledger' => ['pending_total' => 0, 'settled_total' => 0, 'currency' => null],
|
||||||
|
'entries' => [],
|
||||||
|
], 'لا توجد وثيقة نشطة');
|
||||||
|
}
|
||||||
|
|
||||||
|
$summary = ['pending_total' => 0.0, 'settled_total' => 0.0,
|
||||||
|
'currency' => $policy['currency']];
|
||||||
|
$entries = [];
|
||||||
|
|
||||||
|
// المصدر هو الدفتر الموحّد لا دفتر التأمين القديم (المجمَّد بعد ترحيل
|
||||||
|
// 2026_08_08). المفتاح صار (السائق + رمز المنتج) بدل رقم الوثيقة:
|
||||||
|
// الدفتر الموحّد لا يعرف الوثائق، يعرف التزامات.
|
||||||
|
try {
|
||||||
|
// المستحق من `amount_remaining` والمحصَّل من `amount_collected`:
|
||||||
|
// قيدٌ حُصِّل نصفه يظهر في الرقمين معاً بحصّته الصحيحة، بينما جمع
|
||||||
|
// `amount` حسب الحالة كان سيعدّه كاملاً في أحدهما ويكذب في كليهما.
|
||||||
|
$st = $con->prepare("
|
||||||
|
SELECT COALESCE(SUM(amount_remaining), 0) AS pending_total,
|
||||||
|
COALESCE(SUM(amount_collected), 0) AS settled_total
|
||||||
|
FROM obligation_ledger
|
||||||
|
WHERE driver_id = ? AND product_code = ?
|
||||||
|
");
|
||||||
|
$st->execute([$driverId, $policy['code']]);
|
||||||
|
if ($row = $st->fetch(PDO::FETCH_ASSOC)) {
|
||||||
|
$summary['pending_total'] = (float) $row['pending_total'];
|
||||||
|
$summary['settled_total'] = (float) $row['settled_total'];
|
||||||
|
}
|
||||||
|
|
||||||
|
// آخر ثلاثين قيداً: كافية لشهر يومي، وتمنع رداً ينمو بلا حد.
|
||||||
|
$st = $con->prepare("
|
||||||
|
SELECT charge_date, amount, amount_collected, amount_remaining,
|
||||||
|
currency, status, note
|
||||||
|
FROM obligation_ledger
|
||||||
|
WHERE driver_id = ? AND product_code = ?
|
||||||
|
ORDER BY charge_date DESC
|
||||||
|
LIMIT 30
|
||||||
|
");
|
||||||
|
$st->execute([$driverId, $policy['code']]);
|
||||||
|
$entries = $st->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log('[assurance/get] تعذّرت قراءة الدفتر: ' . $e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
jsonSuccess([
|
||||||
|
'has_policy' => true,
|
||||||
|
'policy' => [
|
||||||
|
'id' => (int) $policy['id'],
|
||||||
|
'plan' => $policy['plan_name'],
|
||||||
|
'provider' => $policy['provider_name_ar'] ?: $policy['provider_name'],
|
||||||
|
'policy_number' => $policy['policy_number'],
|
||||||
|
'coverage' => $policy['coverage_summary'],
|
||||||
|
'billing_cycle' => $policy['billing_cycle'],
|
||||||
|
'premium' => (float) $policy['premium'],
|
||||||
|
'currency' => $policy['currency'],
|
||||||
|
'started_at' => $policy['started_at'],
|
||||||
|
'last_charged_on' => $policy['last_charged_on'],
|
||||||
|
],
|
||||||
|
'ledger' => $summary,
|
||||||
|
'entries' => $entries,
|
||||||
|
], 'success');
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* driver_assurance/plans.php — الخطط المتاحة وأهلية السائق لكلٍّ منها
|
||||||
|
*
|
||||||
|
* نرد بكل الخطط لا المؤهَّل لها فقط، ومع كل واحدة سبب عدم الأهلية إن
|
||||||
|
* وُجد. إخفاء ما لا يستحقه السائق يجعل التأمين مجهولاً عنده؛ إظهاره
|
||||||
|
* مع «ينقصك ٤٠ رحلة» يحوّله إلى هدف يسعى إليه — وهذا هو مقصد الشرط
|
||||||
|
* أصلاً: ربط السائق بالمنصّة.
|
||||||
|
*/
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../connect.php';
|
||||||
|
require_once __DIR__ . '/eligibility.php';
|
||||||
|
require_once __DIR__ . '/../obligations/functions.php';
|
||||||
|
|
||||||
|
// الهوية من الـJWT لا من الطلب — الأهلية معلومة عن السائق نفسه،
|
||||||
|
// وقراءتها بمعرّف مُرسَل تكشف أرقام غيره.
|
||||||
|
$driverId = $user_id ?? '';
|
||||||
|
if (empty($driverId) || ($role ?? '') !== 'driver') {
|
||||||
|
jsonError('Unauthorized', 401);
|
||||||
|
}
|
||||||
|
|
||||||
|
$country = getenv('APP_COUNTRY') ?: 'Jordan';
|
||||||
|
|
||||||
|
try {
|
||||||
|
$st = $con->prepare("
|
||||||
|
SELECT pl.*, pr.name AS provider_name, pr.name_ar AS provider_name_ar
|
||||||
|
FROM insurance_plans pl
|
||||||
|
JOIN insurance_providers pr ON pr.id = pl.provider_id
|
||||||
|
WHERE pl.is_active = 1 AND pr.is_active = 1 AND pr.country = ?
|
||||||
|
ORDER BY pl.premium ASC
|
||||||
|
");
|
||||||
|
$st->execute([$country]);
|
||||||
|
$plans = $st->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log('[assurance/plans] ' . $e->getMessage());
|
||||||
|
jsonError('Server error');
|
||||||
|
}
|
||||||
|
|
||||||
|
$current = assuranceActivePolicy($con, $driverId);
|
||||||
|
|
||||||
|
// نداء واحد للمحفظة لكل الشاشة: الملخّص عن السائق لا عن الخطة.
|
||||||
|
// بدونه كانت الشاشة تعرض «مؤهَّل» ثم يُرفض الطلب عند الضغط — وهو أسوأ
|
||||||
|
// من الرفض المبكر: يعد السائق بشيء ثم يسحبه.
|
||||||
|
$incomeSummary = obligationWalletIncomeSummary($driverId);
|
||||||
|
|
||||||
|
$out = [];
|
||||||
|
foreach ($plans as $plan) {
|
||||||
|
$check = assuranceCheckEligibility($con, $driverId, $plan);
|
||||||
|
|
||||||
|
// بوابة الائتمان تُقاس على منتج الالتزام المقابل للخطة. غيابه يعني
|
||||||
|
// خطة لم تُرحَّل بعد — لا نحجبها ولا ندّعي أهليةً لها، بل نتركها
|
||||||
|
// لحكم شروط الخطة وحدها ونسجّل الحالة.
|
||||||
|
$product = obligationProduct($con, $plan['code']);
|
||||||
|
if ($product) {
|
||||||
|
$gate = obligationCheckWalletIncome($product, $driverId, $incomeSummary);
|
||||||
|
if (!$gate['eligible']) {
|
||||||
|
$check['eligible'] = false;
|
||||||
|
$check['reasons'] = array_merge($check['reasons'], $gate['reasons']);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
error_log("[assurance/plans] لا منتج التزام للخطة {$plan['code']}");
|
||||||
|
}
|
||||||
|
|
||||||
|
$out[] = [
|
||||||
|
'id' => (int) $plan['id'],
|
||||||
|
'code' => $plan['code'],
|
||||||
|
'name' => $plan['name_ar'],
|
||||||
|
'description' => $plan['description_ar'],
|
||||||
|
'provider' => $plan['provider_name_ar'] ?: $plan['provider_name'],
|
||||||
|
'billing_cycle' => $plan['billing_cycle'],
|
||||||
|
'premium' => (float) $plan['premium'],
|
||||||
|
'currency' => $plan['currency'],
|
||||||
|
'coverage' => $plan['coverage_summary'],
|
||||||
|
'eligible' => $check['eligible'],
|
||||||
|
'missing' => $check['reasons'],
|
||||||
|
'is_current' => $current && (int) $current['plan_id'] === (int) $plan['id'],
|
||||||
|
// تقدّم السائق نحو الشرط — رقم يفهمه بلا شرح.
|
||||||
|
'progress_rides' => $check['rides'],
|
||||||
|
'required_rides' => (int) $plan['min_completed_rides'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
jsonSuccess([
|
||||||
|
'plans' => $out,
|
||||||
|
'has_policy' => (bool) $current,
|
||||||
|
'driver_rating' => $current ? (float) $current['rating_at_signup'] : null,
|
||||||
|
], 'success');
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* driver_assurance/subscribe.php — اشتراك السائق في خطة تأمين
|
||||||
|
*
|
||||||
|
* الأهلية تُحسب هنا من جديد لا يُوثق بما أرسله التطبيق: الشاشة قد تكون
|
||||||
|
* مفتوحة منذ ساعة، وقد يُعدَّل الطلب يدوياً. النقطة التي تمنح تغطية
|
||||||
|
* مالية لا تصدّق عميلها.
|
||||||
|
*/
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../connect.php';
|
||||||
|
require_once __DIR__ . '/eligibility.php';
|
||||||
|
require_once __DIR__ . '/../obligations/functions.php';
|
||||||
|
|
||||||
|
$driverId = $user_id ?? '';
|
||||||
|
if (empty($driverId) || ($role ?? '') !== 'driver') {
|
||||||
|
jsonError('Unauthorized', 401);
|
||||||
|
}
|
||||||
|
|
||||||
|
$planId = (int) (filterRequest('plan_id', 'int') ?: 0);
|
||||||
|
if ($planId <= 0) {
|
||||||
|
jsonError('plan_id is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$st = $con->prepare("
|
||||||
|
SELECT pl.*, pr.is_active AS provider_active
|
||||||
|
FROM insurance_plans pl
|
||||||
|
JOIN insurance_providers pr ON pr.id = pl.provider_id
|
||||||
|
WHERE pl.id = ? AND pl.is_active = 1 LIMIT 1
|
||||||
|
");
|
||||||
|
$st->execute([$planId]);
|
||||||
|
$plan = $st->fetch(PDO::FETCH_ASSOC);
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
error_log('[assurance/subscribe] ' . $e->getMessage());
|
||||||
|
jsonError('Server error');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$plan || (int) $plan['provider_active'] !== 1) {
|
||||||
|
jsonError('Plan not available');
|
||||||
|
}
|
||||||
|
|
||||||
|
// وثيقة نشطة قائمة: لا نشترك مرتين ولا نستبدل بصمت. تبديل الخطة
|
||||||
|
// قرار مالي — يمرّ بإلغاء صريح ثم اشتراك جديد، ليبقى في السجل أثر.
|
||||||
|
if (assuranceActivePolicy($con, $driverId)) {
|
||||||
|
jsonError('لديك وثيقة تأمين نشطة بالفعل. ألغِها أولاً لتغيير الخطة.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$check = assuranceCheckEligibility($con, $driverId, $plan);
|
||||||
|
if (!$check['eligible']) {
|
||||||
|
jsonError('لم تستوفِ شروط هذه الخطة بعد: ' . implode('، ', $check['reasons']));
|
||||||
|
}
|
||||||
|
|
||||||
|
// بوابة الائتمان تُفحص هنا صراحةً رغم أن `obligationOpen` تفحصها أيضاً:
|
||||||
|
// الفحص هناك حارسٌ أخير يرمي استثناءً، ورسالته تصل للسائق كخطأ عام.
|
||||||
|
// السائق الذي يُرفض طلبه يستحق أن يعرف السبب وما يفعله ليستوفيه.
|
||||||
|
$product = obligationProduct($con, $plan['code']);
|
||||||
|
if (!$product) {
|
||||||
|
error_log("[assurance/subscribe] منتج الالتزام مفقود للخطة {$plan['code']}");
|
||||||
|
jsonError('تعذّر تفعيل الوثيقة حالياً');
|
||||||
|
}
|
||||||
|
|
||||||
|
$walletGate = obligationCheckWalletIncome($product, $driverId);
|
||||||
|
if (!$walletGate['eligible']) {
|
||||||
|
jsonError(
|
||||||
|
'التأمين يُخصم قسطه من أرباحك في المحفظة، ولذلك يشترط أن تمرّ أرباحك بها: '
|
||||||
|
. implode('، ', $walletGate['reasons'])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// كتابتان في معاملة واحدة: الوثيقة (السجل التأميني الذي يقرأه التطبيق)
|
||||||
|
// والالتزام (ما يراه محرك القيد والتسوية). وثيقة بلا التزام تعني تغطية
|
||||||
|
// تُمنح ولا يُحصَّل قسطها أبداً — وهي بالضبط الثغرة التي جاء هذا المحرك
|
||||||
|
// ليغلقها، فلا يجوز أن نعيد فتحها من باب الاشتراكات الجديدة.
|
||||||
|
try {
|
||||||
|
$con->beginTransaction();
|
||||||
|
|
||||||
|
$con->prepare("
|
||||||
|
INSERT INTO driver_insurance_policies
|
||||||
|
(driver_id, plan_id, status, started_at, rides_at_signup, rating_at_signup)
|
||||||
|
VALUES (?, ?, 'active', CURDATE(), ?, ?)
|
||||||
|
")->execute([$driverId, $planId, $check['rides'], $check['rating']]);
|
||||||
|
|
||||||
|
$policyId = (int) $con->lastInsertId();
|
||||||
|
|
||||||
|
obligationOpen($con, $driverId, $plan['code'], [
|
||||||
|
'cycle_amount' => (float) $plan['premium'],
|
||||||
|
'rides' => $check['rides'],
|
||||||
|
'rating' => $check['rating'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$con->commit();
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
if ($con->inTransaction()) $con->rollBack();
|
||||||
|
error_log('[assurance/subscribe] تعذّر إنشاء الوثيقة: ' . $e->getMessage());
|
||||||
|
jsonError('تعذّر تفعيل الوثيقة حالياً');
|
||||||
|
}
|
||||||
|
|
||||||
|
error_log("[assurance] السائق $driverId اشترك في الخطة {$plan['code']} — وثيقة #$policyId");
|
||||||
|
|
||||||
|
jsonSuccess([
|
||||||
|
'policy_id' => $policyId,
|
||||||
|
'plan' => $plan['name_ar'],
|
||||||
|
'premium' => (float) $plan['premium'],
|
||||||
|
'currency' => $plan['currency'],
|
||||||
|
'billing_cycle' => $plan['billing_cycle'],
|
||||||
|
// أول قسط يُقيَّد في تشغيل الكرون القادم لا الآن: الاشتراك ليس
|
||||||
|
// دفعاً، والقيد يجب أن يكون له تاريخ واضح يوافق دورة الفوترة.
|
||||||
|
'starts_on' => date('Y-m-d'),
|
||||||
|
], 'تم تفعيل وثيقة التأمين');
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
use PHPMailer\PHPMailer\PHPMailer;
|
use PHPMailer\PHPMailer\PHPMailer;
|
||||||
use PHPMailer\PHPMailer\Exception;
|
use PHPMailer\PHPMailer\Exception;
|
||||||
|
|
||||||
require_once __DIR__ . '/../../vendor/autoload.php';
|
require_once __DIR__ . '/../vendor/autoload.php';
|
||||||
require_once __DIR__ . '/../core/bootstrap.php';
|
require_once __DIR__ . '/../core/bootstrap.php';
|
||||||
|
|
||||||
// 1. فرض المصادقة (Auth Required)
|
// 1. فرض المصادقة (Auth Required)
|
||||||
|
|||||||
@@ -1,7 +1,17 @@
|
|||||||
<?php
|
<?php
|
||||||
//encrypt_decrypt.php
|
//encrypt_decrypt.php
|
||||||
// ⚠️ هذا الملف للتوافقية فقط. استخدم core/Security/EncryptionHelper.php للتشفير الجديد
|
// ⚠️ هذا الملف للتوافقية فقط. استخدم core/Security/EncryptionHelper.php للتشفير الجديد
|
||||||
require_once realpath(__DIR__ . '/../vendor/autoload.php');
|
// vendor يقع داخل backend/ لا فوقه. المسار السابق '/../vendor/autoload.php'
|
||||||
|
// يشير إلى /var/www/vendor غير الموجود، و realpath() تُعيد false عندئذٍ،
|
||||||
|
// فيصبح الاستدعاء require_once('') ويسقط بخطأ قاتل يُحلّ من مجلد العمل
|
||||||
|
// الحالي — وهو ما ظهر في السجل كـ "Failed opening required ''".
|
||||||
|
$autoloadPath = __DIR__ . '/vendor/autoload.php';
|
||||||
|
if (!file_exists($autoloadPath)) {
|
||||||
|
$autoloadPath = __DIR__ . '/../vendor/autoload.php';
|
||||||
|
}
|
||||||
|
if (file_exists($autoloadPath)) {
|
||||||
|
require_once $autoloadPath;
|
||||||
|
}
|
||||||
|
|
||||||
require_once 'load_env.php';
|
require_once 'load_env.php';
|
||||||
$siteUser = get_current_user();
|
$siteUser = get_current_user();
|
||||||
@@ -34,6 +44,12 @@ if (!$key) {
|
|||||||
$iv = getenv('initializationVector'); // 16 bytes
|
$iv = getenv('initializationVector'); // 16 bytes
|
||||||
|
|
||||||
|
|
||||||
|
// الصنف نفسه معرَّف أيضاً في core/Security/EncryptionHelper.php، وأي ملف
|
||||||
|
// يحمّل bootstrap.php ثم يصل إلى هنا كان ينهار بـ "Cannot declare class
|
||||||
|
// EncryptionHelper, because the name is already in use" — وهو ما أسقط
|
||||||
|
// blacklist_manager.php. نُبقي أول تعريف محمَّل (النسخة الحديثة في core)
|
||||||
|
// ونتخطّى هذه النسخة القديمة المتروكة للتوافقية.
|
||||||
|
if (!class_exists('EncryptionHelper', false)) {
|
||||||
class EncryptionHelper {
|
class EncryptionHelper {
|
||||||
private $key;
|
private $key;
|
||||||
private $iv;
|
private $iv;
|
||||||
@@ -150,6 +166,7 @@ class EncryptionHelper {
|
|||||||
return $decrypted;
|
return $decrypted;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} // نهاية حارس class_exists
|
||||||
// ✅ Load the key and IV from .env or use default values
|
// ✅ Load the key and IV from .env or use default values
|
||||||
|
|
||||||
// ✅ Ensure the lengths are correct
|
// ✅ Ensure the lengths are correct
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user