Compare commits
323
Commits
9d7e2b412e
...
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 | ||
|
|
42f6d33efd | ||
|
|
4009af8dd3 | ||
|
|
67f55e5192 | ||
|
|
a0ab6c5155 | ||
|
|
41a06bba0c | ||
|
|
db4ca7dd7a | ||
|
|
852c6ece5c | ||
|
|
915a148ebf | ||
|
|
0d9095fd3f | ||
|
|
eda7018434 | ||
|
|
822cb5963a | ||
|
|
8ec7b9aae6 | ||
|
|
c9168c1c80 | ||
|
|
10f1154cc7 | ||
|
|
9d2a665d64 | ||
|
|
4c738e8f43 | ||
|
|
032e1edda5 | ||
|
|
1ca2c5a5dd | ||
|
|
f115292dd2 | ||
|
|
60e344598b | ||
|
|
8bc9290916 | ||
|
|
9e2964d307 | ||
|
|
b3126013f5 | ||
|
|
5ebff42841 | ||
|
|
2944f21f53 | ||
|
|
917dfc025f | ||
|
|
0b24bc21b6 | ||
|
|
474c212bcb | ||
|
|
e7629a9eb9 | ||
|
|
695d6d7cb2 | ||
|
|
e7aa28fe3d | ||
|
|
7d646b579b | ||
|
|
b4451a0dde | ||
|
|
92eb7fe25d | ||
|
|
1e785061ec | ||
|
|
12e70f3d7e | ||
|
|
12a1cbc98c | ||
|
|
c35b350b31 | ||
|
|
1cef598fc5 | ||
|
|
e5bf70fddb | ||
|
|
9e065e5a83 | ||
|
|
ed8a93a6a3 | ||
|
|
a7fa40dc31 | ||
|
|
b86f95c90d | ||
|
|
b83ca1f664 | ||
|
|
fbb95c70fa | ||
|
|
b9efba3787 | ||
|
|
e798f84c03 | ||
|
|
55fbe22f8e | ||
|
|
f76623a25e | ||
|
|
f62716b510 | ||
|
|
771b436c69 | ||
|
|
939c7a9c2c | ||
|
|
ccbe3ab88d | ||
|
|
09a4bbc79f | ||
|
|
901f429b9c | ||
|
|
6282be37d8 | ||
|
|
a2f0911d13 | ||
|
|
dabf4c13ba | ||
|
|
1b45b505f8 | ||
|
|
8ec0ac2942 | ||
|
|
26d0ec2982 | ||
|
|
11d7d86b2f | ||
|
|
a4b5a2545c | ||
|
|
be14b2716e | ||
|
|
9a73f4303d | ||
|
|
bbcefd20cf | ||
|
|
521d76c4cf | ||
|
|
b613022169 | ||
|
|
540e77984b | ||
|
|
bec8089fd1 | ||
|
|
a5ae6fecbe | ||
|
|
16101927e1 | ||
|
|
58222fbf81 | ||
|
|
bcab0ea221 | ||
|
|
87b4f12da0 | ||
|
|
17abdada10 | ||
|
|
2b302db1dd | ||
|
|
cf95455bcf | ||
|
|
699b380f2b | ||
|
|
3d0c266b7a | ||
|
|
586deec4f4 | ||
|
|
bb3536aa90 | ||
|
|
23f697b1c6 | ||
|
|
1bec13634a | ||
|
|
0ee3655c05 | ||
|
|
4f47c0ad1d | ||
|
|
f3905bcb2c | ||
|
|
1103f6ffcf | ||
|
|
0351bffafc | ||
|
|
096f6a13a0 | ||
|
|
ebd6f3734a | ||
|
|
8d8c3a3817 | ||
|
|
432245a688 | ||
|
|
5d68ec5d0c | ||
|
|
c9bef58f47 | ||
|
|
36ca266132 | ||
|
|
e88d45add4 | ||
|
|
6d6c7cab7f | ||
|
|
818220bba2 | ||
|
|
0f59975144 | ||
|
|
24e03ae46c | ||
|
|
58ada98dd7 | ||
|
|
1b4d831ca6 | ||
|
|
69f043c297 | ||
|
|
e1154d7281 | ||
|
|
630c6277ac | ||
|
|
772398d961 | ||
|
|
b89191c018 | ||
|
|
13d10d13c7 | ||
|
|
085b180bdb | ||
|
|
5e80c886a0 | ||
|
|
dda813ace1 | ||
|
|
5ae5628f37 | ||
|
|
b385cace36 | ||
|
|
64b17fbb26 | ||
|
|
c00bfa24ba | ||
|
|
1f57b642c3 | ||
|
|
c5ed2099f9 | ||
|
|
8cb83b31f2 | ||
|
|
034d64b6f2 | ||
|
|
ab77ed529a | ||
|
|
48382f5d4a | ||
|
|
540ae4d4bc | ||
|
|
a81f805796 | ||
|
|
a547b81b60 | ||
|
|
c956f27230 | ||
|
|
c3fb42cae9 | ||
|
|
a2484d0bf5 | ||
|
|
c6f48a1f91 | ||
|
|
fd3f4a365a | ||
|
|
7bf6dc1be7 | ||
|
|
653d73422f | ||
|
|
8cd4a4b57e | ||
|
|
27200013ac | ||
|
|
8fa2f153c1 | ||
|
|
08340493c0 | ||
|
|
1f68cb7333 | ||
|
|
24fb56f08f | ||
|
|
1fa517acc9 | ||
|
|
8f4bb1631c | ||
|
|
83f5bf516b | ||
|
|
de761c1d97 | ||
|
|
9535d702d6 | ||
|
|
8353c4cef4 | ||
|
|
ce2f3d5675 | ||
|
|
cb9aefc591 | ||
|
|
06dc0aaffe | ||
|
|
8b19adeb80 | ||
|
|
04468dad08 | ||
|
|
6294d6e725 | ||
|
|
607c9bd9f4 | ||
|
|
2bce11b940 | ||
|
|
81d4715664 | ||
|
|
5fb2c25504 | ||
|
|
be6e5bed92 | ||
|
|
b18fd027b6 | ||
|
|
2ff7450d0b | ||
|
|
461a1402ab | ||
|
|
5e6aeb7908 | ||
|
|
d94808c380 | ||
|
|
87dc925ea7 | ||
|
|
45859883a5 | ||
|
|
2152d34a8e | ||
|
|
03e9d648a1 | ||
|
|
a526dae042 | ||
|
|
70718946f5 | ||
|
|
7dff7b6973 | ||
|
|
ac0c343f18 | ||
|
|
6fe1d665e7 | ||
|
|
d452f9baa9 | ||
|
|
21877153eb | ||
|
|
628e169552 | ||
|
|
5725fb36f4 | ||
|
|
3c9a3dbef8 | ||
|
|
d6ab09c19b | ||
|
|
9d257c5d7d | ||
|
|
e21e1f4ec2 | ||
|
|
eb850a2afc | ||
|
|
281bceb121 | ||
|
|
cdfd1b8e02 | ||
|
|
e42d700245 | ||
|
|
61cb615ae7 | ||
|
|
8e6dbf96e2 | ||
|
|
df1f487804 | ||
|
|
32a6531613 | ||
|
|
e42754bb0e | ||
|
|
cadc26518b | ||
|
|
ff49586d6d | ||
|
|
63440b07dc | ||
|
|
c7863dc98f | ||
|
|
823805417c |
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "transit-dashboard",
|
||||
"runtimeExecutable": "npm",
|
||||
"runtimeArgs": ["run", "dev"],
|
||||
"port": 5183,
|
||||
"cwd": "transit_dashboard"
|
||||
},
|
||||
{
|
||||
"name": "siro-admin",
|
||||
"runtimeExecutable": "python3",
|
||||
"runtimeArgs": ["-m", "http.server", "8899", "--directory", "dashboard/siro-admin"],
|
||||
"port": 8899
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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/
|
||||
|
||||
# --- Composer / PHP ---
|
||||
/composer.lock
|
||||
**/composer.lock
|
||||
# composer.lock مُتتبَّع عمداً: بدونه ينهار payment_server/v2 بعد أي نشر نظيف
|
||||
# (vendor يبقى مستثنى أعلاه — يُبنى بـ composer install من الـ lock)
|
||||
|
||||
# --- Logs ---
|
||||
*.log
|
||||
@@ -101,3 +101,5 @@ GoogleService-Info.plist
|
||||
# --- Audit/Scan Output ---
|
||||
semgrep_*.json
|
||||
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"
|
||||
buildConfigField("String", "BOT_SECRET_KEY", "\"SIRO_BOT_SUPER_SECRET_123\"")
|
||||
// مضيف الباك إند في مكان واحد: تبديله عند نسخ البوت لعلامة أخرى
|
||||
// (مثل انطلق على api.intaleqapp.com) يصير سطراً واحداً لا بحثاً في الكود.
|
||||
buildConfigField("String", "BACKEND_HOST", "\"https://jordan-siro.intaleqapp.com\"")
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
|
||||
@@ -25,9 +25,14 @@ class WorkerClient(private val context: Context) {
|
||||
Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID) ?: "UNKNOWN_DEVICE"
|
||||
}
|
||||
|
||||
// Change this to your actual server domain
|
||||
private val BASE_URL = "https://jordan-siro.intaleqapp.com/backend/bot/standalone_worker.php"
|
||||
// For local testing use: "http://10.0.2.2:8000/standalone_worker.php"
|
||||
// المضيف من BuildConfig.BACKEND_HOST (app/build.gradle.kts) — لا يُشفَّر هنا،
|
||||
// حتى يكون تبديله عند نسخ البوت لعلامة أخرى سطراً واحداً في gradle.
|
||||
// للتجريب المحلي: اضبط 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 {
|
||||
val message = "$deviceId$ts"
|
||||
|
||||
@@ -14,6 +14,23 @@ DB_NAME=siro_main
|
||||
DB_USER=siro_user
|
||||
DB_PASS=<CHANGE_ME_STRONG_PASSWORD>
|
||||
|
||||
# =============================================================================
|
||||
# Database Configuration - TRANSIT DATABASE (مواصلاتي — جامعات/مدارس/فنادق/شركات)
|
||||
# =============================================================================
|
||||
# قاعدة بيانات معزولة تماماً عن main/ride/tracking — ممنوع أي JOIN بينها وبينهم،
|
||||
# الربط بينها وبين النظام الرئيسي عبر المعرّفات (passenger_id/driver_id) فقط.
|
||||
DB_TRANSIT_HOST=localhost
|
||||
DB_TRANSIT_PORT=3306
|
||||
DB_TRANSIT_NAME=siroTransitDb
|
||||
DB_TRANSIT_USER=siroTransitUser
|
||||
DB_TRANSIT_PASS=<CHANGE_ME_STRONG_PASSWORD>
|
||||
# مفتاح تشفير الرقم الجامعي (32 byte) — منفصل عن ENC_KEY لمزيد من العزل
|
||||
TRANSIT_STUDENT_ID_KEY=<CHANGE_ME_32_CHAR_KEY>
|
||||
# Origins مسموحة للوحة الويب (مشرف المؤسسة)
|
||||
TRANSIT_ADMIN_ORIGINS=https://transit.siromove.com,https://admin.siromove.com
|
||||
# رابط تفعيل السائق (deep link في تطبيق السائق)
|
||||
APP_DEEP_LINK_BASE=https://siromove.com/driver/transit-activate
|
||||
|
||||
# =============================================================================
|
||||
# Encryption Configuration - CRITICAL FOR SECURITY
|
||||
# =============================================================================
|
||||
|
||||
@@ -67,15 +67,15 @@ $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
// فك تشفير الحقول الحساسة
|
||||
foreach ($result as &$row) {
|
||||
$row['phone'] = $encryptionHelper->decryptData($row['phone']);
|
||||
$row['email'] = $encryptionHelper->decryptData($row['email']);
|
||||
$row['gender'] = $encryptionHelper->decryptData($row['gender']);
|
||||
$row['birthdate'] = $encryptionHelper->decryptData($row['birthdate']);
|
||||
$row['site'] = $encryptionHelper->decryptData($row['site']);
|
||||
$row['first_name'] = $encryptionHelper->decryptData($row['first_name']);
|
||||
$row['last_name'] = $encryptionHelper->decryptData($row['last_name']);
|
||||
$row['employmentType'] = $encryptionHelper->decryptData($row['employmentType']);
|
||||
$row['maritalStatus'] = $encryptionHelper->decryptData($row['maritalStatus']);
|
||||
$row['phone'] = $encryptionHelper->decryptData($row['phone'] ?? '') ?: ($row['phone'] ?? '');
|
||||
$row['email'] = $encryptionHelper->decryptData($row['email'] ?? '') ?: ($row['email'] ?? '');
|
||||
$row['gender'] = $encryptionHelper->decryptData($row['gender'] ?? '') ?: ($row['gender'] ?? 'unknown yet');
|
||||
$row['birthdate'] = $encryptionHelper->decryptData($row['birthdate'] ?? '') ?: ($row['birthdate'] ?? 'unknown yet');
|
||||
$row['site'] = $encryptionHelper->decryptData($row['site'] ?? '') ?: ($row['site'] ?? 'unknown yet');
|
||||
$row['first_name'] = $encryptionHelper->decryptData($row['first_name'] ?? '') ?: ($row['first_name'] ?? '');
|
||||
$row['last_name'] = $encryptionHelper->decryptData($row['last_name'] ?? '') ?: ($row['last_name'] ?? '');
|
||||
$row['employmentType'] = $encryptionHelper->decryptData($row['employmentType'] ?? '') ?: ($row['employmentType'] ?? 'unknown yet');
|
||||
$row['maritalStatus'] = $encryptionHelper->decryptData($row['maritalStatus'] ?? '') ?: ($row['maritalStatus'] ?? 'unknown yet');
|
||||
}
|
||||
|
||||
$countStmt = $con->query("SELECT COUNT(*) FROM `driver`");
|
||||
|
||||
@@ -5,6 +5,15 @@ $driver_id = filterRequest("driver_id");
|
||||
$driverEmail = $encryptionHelper->encryptData(filterRequest("driverEmail"));
|
||||
$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
|
||||
`driver`.`id`,
|
||||
`driver`.`phone`,
|
||||
@@ -53,6 +62,8 @@ $sql = "SELECT
|
||||
) AS passengerToken
|
||||
FROM `driver`
|
||||
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
|
||||
LIMIT 10
|
||||
";
|
||||
@@ -61,6 +72,8 @@ $stmt = $con->prepare($sql);
|
||||
$stmt->bindParam(":email", $driverEmail);
|
||||
$stmt->bindParam(":phone", $driverPhone);
|
||||
$stmt->bindParam(":id", $driver_id);
|
||||
$stmt->bindParam(":email_bidx", $emailBidx);
|
||||
$stmt->bindParam(":phone_bidx", $phoneBidx);
|
||||
$stmt->execute();
|
||||
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
<?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");
|
||||
|
||||
if (empty($driver_id)) {
|
||||
jsonError("driver_id is required", 400);
|
||||
}
|
||||
|
||||
$sql = "SELECT
|
||||
`driver`.`id`,
|
||||
`driver`.`phone`,
|
||||
@@ -14,7 +23,6 @@ $sql = "SELECT
|
||||
`driver`.`site`,
|
||||
`driver`.`first_name`,
|
||||
`driver`.`last_name`,
|
||||
`driver`.`education`,
|
||||
`driver`.`employmentType`,
|
||||
`driver`.`maritalStatus`,
|
||||
`driver`.`created_at`,
|
||||
@@ -59,14 +67,23 @@ WHERE `driver`.`id` = :driver_id
|
||||
ORDER BY passengerAverageRating DESC
|
||||
LIMIT 10";
|
||||
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->bindParam(':driver_id', $driver_id);
|
||||
$stmt->execute();
|
||||
|
||||
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
try {
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->bindParam(':driver_id', $driver_id);
|
||||
$stmt->execute();
|
||||
$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 (['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['email'] = $encryptionHelper->decryptData($row['email']);
|
||||
$row['gender'] = $encryptionHelper->decryptData($row['gender']);
|
||||
@@ -74,7 +91,6 @@ foreach ($result as &$row) {
|
||||
$row['site'] = $encryptionHelper->decryptData($row['site']);
|
||||
$row['first_name'] = $encryptionHelper->decryptData($row['first_name']);
|
||||
$row['last_name'] = $encryptionHelper->decryptData($row['last_name']);
|
||||
$row['education'] = $encryptionHelper->decryptData($row['education']);
|
||||
$row['employmentType'] = $encryptionHelper->decryptData($row['employmentType']);
|
||||
$row['maritalStatus'] = $encryptionHelper->decryptData($row['maritalStatus']);
|
||||
}
|
||||
|
||||
@@ -3,40 +3,81 @@
|
||||
* Admin/Staff/pending.php
|
||||
* جلب الحسابات المعلقة للإداريين والخدمة
|
||||
*/
|
||||
require_once __DIR__ . '/../../core/bootstrap.php';
|
||||
require_once __DIR__ . '/../../functions.php';
|
||||
// connect.php يفرض JWT — بدونه كانت هذه النقطة تكشف أسماء وأرقام
|
||||
// المشرفين المعلقين لأي زائر بلا أي مصادقة.
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
http_response_code(403);
|
||||
echo json_encode(['error' => 'Unauthorized: Admin access required']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$allPending = [];
|
||||
$sources = [];
|
||||
|
||||
// كل مصدر يُجلب على حدة: غياب جدول users في بعض عمليات النشر كان يُفشل
|
||||
// الطلب بالكامل ويخفي طلبات المشرفين المعلقة أيضاً.
|
||||
/**
|
||||
* بعض عمليات النشر أنشأت adminUser بلا عمود status (انظر schema_primary.sql)،
|
||||
* وعندها لا يمكن تمييز الحسابات المعلقة أصلاً. نفحص العمود أولاً لنُرجع سبباً
|
||||
* واضحاً بدل فشل عام.
|
||||
*/
|
||||
function columnExists(PDO $con, string $table, string $column): bool
|
||||
{
|
||||
try {
|
||||
$stmt = $con->prepare("SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?");
|
||||
$stmt->execute([$table, $column]);
|
||||
return (int) $stmt->fetchColumn() > 0;
|
||||
} catch (Throwable $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$con = Database::get('main');
|
||||
|
||||
// جلب الإداريين المعلقين
|
||||
if (!columnExists($con, 'adminUser', 'status')) {
|
||||
throw new RuntimeException("adminUser.status column is missing — admin approvals cannot be tracked until it is added.");
|
||||
}
|
||||
|
||||
$stmt1 = $con->query("SELECT id, name, phone, role, created_at, 'admin' as type FROM adminUser WHERE status = 'pending'");
|
||||
$admins = $stmt1->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
// فك التشفير للأسماء والأرقام للإداريين
|
||||
foreach ($admins as &$admin) {
|
||||
$admin['name'] = $encryptionHelper->decryptData($admin['name']) ?: $admin['name'];
|
||||
$admin['name'] = $encryptionHelper->decryptData($admin['name']) ?: $admin['name'];
|
||||
$admin['phone'] = $encryptionHelper->decryptData($admin['phone']) ?: $admin['phone'];
|
||||
}
|
||||
unset($admin);
|
||||
|
||||
// جلب موظفي الخدمة المعلقين
|
||||
$allPending = array_merge($allPending, $admins);
|
||||
$sources['admins'] = 'ok';
|
||||
} catch (Throwable $e) {
|
||||
error_log("[Staff Pending] adminUser query failed: " . $e->getMessage());
|
||||
$sources['admins'] = 'unavailable: ' . $e->getMessage();
|
||||
}
|
||||
|
||||
try {
|
||||
$stmt2 = $con->query("SELECT id, first_name, last_name, phone, user_type as role, created_at, 'service' as type FROM users WHERE status = 'pending' AND user_type = 'service'");
|
||||
$services = $stmt2->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
// فك التشفير لموظفي الخدمة
|
||||
foreach ($services as &$service) {
|
||||
$service['name'] = trim(($encryptionHelper->decryptData($service['first_name']) ?: $service['first_name']) . ' ' . ($encryptionHelper->decryptData($service['last_name']) ?: $service['last_name']));
|
||||
$service['name'] = trim(
|
||||
($encryptionHelper->decryptData($service['first_name']) ?: $service['first_name']) . ' ' .
|
||||
($encryptionHelper->decryptData($service['last_name']) ?: $service['last_name'])
|
||||
);
|
||||
$service['phone'] = $encryptionHelper->decryptData($service['phone']) ?: $service['phone'];
|
||||
}
|
||||
unset($service);
|
||||
|
||||
$allPending = array_merge($admins, $services);
|
||||
|
||||
printSuccess([
|
||||
"data" => $allPending
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("[Staff Pending Error] " . $e->getMessage());
|
||||
jsonError("An internal error occurred. Please try again later.");
|
||||
$allPending = array_merge($allPending, $services);
|
||||
$sources['service_staff'] = 'ok';
|
||||
} catch (Throwable $e) {
|
||||
error_log("[Staff Pending] users query failed: " . $e->getMessage());
|
||||
$sources['service_staff'] = 'unavailable';
|
||||
}
|
||||
|
||||
printSuccess([
|
||||
"data" => $allPending,
|
||||
"sources" => $sources,
|
||||
]);
|
||||
exit();
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
<?php
|
||||
/**
|
||||
* Admin/auth/login.php
|
||||
* تسجيل دخول المشرفين باستخدام البصمة وكلمة المرور المشفرة
|
||||
* تسجيل دخول المشرفين باستخدام البصمة وكلمة المرور ونظام OTP الموحد (Nabeh API)
|
||||
*/
|
||||
require_once __DIR__ . '/../../core/bootstrap.php';
|
||||
require_once __DIR__ . '/../../functions.php';
|
||||
|
||||
// $encryptionHelper is already initialized by bootstrap.php (lines 159, 182)
|
||||
global $encryptionHelper;
|
||||
|
||||
$fingerprint = filterRequest('fingerprint');
|
||||
$password = filterRequest('password');
|
||||
$phone = filterRequest('phone');
|
||||
@@ -17,11 +20,11 @@ if (empty($fingerprint) || empty($password)) {
|
||||
exit;
|
||||
}
|
||||
|
||||
// Rate Limiting محسَّن مع Exponential Backoff
|
||||
// Rate Limiting
|
||||
$rateLimiter = new RateLimiter($redis);
|
||||
$rateLimiter->enforce(RateLimiter::identifier(), 'login');
|
||||
|
||||
// تتبع المحاولات الفاشلة لكل حساب لمنع credential stuffing عبر IPs متعددة
|
||||
// تتبع المحاولات الفاشلة لكل حساب
|
||||
if ($redis && !empty($phone)) {
|
||||
$accountKey = "login_attempts:account:" . hash('sha256', $phone);
|
||||
$accountAttempts = (int) $redis->get($accountKey);
|
||||
@@ -36,6 +39,7 @@ if ($redis && !empty($phone)) {
|
||||
|
||||
// البحث عن المشرف باستخدام بصمة الجهاز (Fingerprint Hash)
|
||||
$fpHash = hash('sha256', $fingerprint);
|
||||
$isTrustedDevice = false;
|
||||
|
||||
// تسجيل محاولة تسجيل الدخول للتدقيق
|
||||
$loginAuditData = [
|
||||
@@ -54,50 +58,84 @@ try {
|
||||
$stmt->execute([':fp' => $fpHash]);
|
||||
$admin = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
// إذا لم يتم العثور بالبصمة، وتم تمرير رقم الهاتف (تسجيل دخول لأول مرة أو جهاز جديد)
|
||||
if (!$admin && !empty($phone)) {
|
||||
$encPhoneInput = $encryptionHelper->encryptData($phone);
|
||||
$stmtPhone = $con->prepare("SELECT * FROM adminUser WHERE phone = :phone LIMIT 1");
|
||||
$stmtPhone->execute([':phone' => $encPhoneInput]);
|
||||
$admin = $stmtPhone->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
// تأكيد كلمة المرور وتحديث بصمة الجهاز إذا تم إيجاد الحساب
|
||||
if ($admin && password_verify($password, $admin['password'])) {
|
||||
$encFpRaw = $encryptionHelper->encryptData($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; // Update locally
|
||||
} else if ($admin) {
|
||||
// Password incorrect, fail later.
|
||||
if ($admin) {
|
||||
$isTrustedDevice = true;
|
||||
} else if (!empty($phone)) {
|
||||
// 1. بحث بالـ ID أو الفهارس العمياء (الهاتف / البريد) لضمان السرعة والتوافق مع التشفير المتغير
|
||||
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);
|
||||
|
||||
// 2. إذا لم يتم العثور بالـ ID، نفحص الحقول المشفّرة (email / phone / name) عبر فك التشفير
|
||||
if (!$admin) {
|
||||
$stmtAll = $con->query("SELECT * FROM adminUser");
|
||||
while ($row = $stmtAll->fetch(PDO::FETCH_ASSOC)) {
|
||||
$decPhone = ($encryptionHelper && !empty($row['phone'])) ? $encryptionHelper->decryptData($row['phone']) : $row['phone'];
|
||||
$decEmail = ($encryptionHelper && !empty($row['email'])) ? $encryptionHelper->decryptData($row['email']) : $row['email'];
|
||||
$decName = ($encryptionHelper && !empty($row['name'])) ? $encryptionHelper->decryptData($row['name']) : $row['name'];
|
||||
|
||||
if ($phone === $decPhone || $phone === $decEmail || $phone === $decName || $phone === $row['phone'] || $phone === $row['email']) {
|
||||
$admin = $row;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// فحص ما إذا كانت بصمة الجهاز محفوظة ومطابقة للجهاز الحالي
|
||||
if ($admin && !empty($admin['fingerprint_hash']) && hash_equals($admin['fingerprint_hash'], $fpHash)) {
|
||||
$isTrustedDevice = true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($admin) {
|
||||
// 1. التحقق من حالة الحساب
|
||||
if ($admin['status'] === 'pending') {
|
||||
jsonError("حسابك قيد المراجعة حالياً. يرجى الانتظار للموافقة.");
|
||||
exit;
|
||||
} elseif ($admin['status'] === 'suspended') {
|
||||
jsonError("هذا الحساب معلق. يرجى التواصل مع المدير.");
|
||||
exit;
|
||||
} elseif ($admin['status'] === 'rejected') {
|
||||
jsonError("تم رفض طلب الانضمام لهذا الحساب.");
|
||||
exit;
|
||||
if (isset($admin['status'])) {
|
||||
if ($admin['status'] === 'pending') {
|
||||
jsonError("حسابك قيد المراجعة حالياً. يرجى الانتظار للموافقة.");
|
||||
exit;
|
||||
} elseif ($admin['status'] === 'suspended') {
|
||||
jsonError("هذا الحساب معلق. يرجى التواصل مع المدير.");
|
||||
exit;
|
||||
} elseif ($admin['status'] === 'rejected') {
|
||||
jsonError("تم رفض طلب الانضمام لهذا الحساب.");
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. التحقق من كلمة المرور
|
||||
if (password_verify($password, $admin['password'])) {
|
||||
|
||||
// إذا كان هذا مجرد تجديد للتوكن (إعادة الدخول التلقائي من التطبيق)، فلا داعي لإرسال OTP
|
||||
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);
|
||||
$role = $admin['role'] ?? 'admin';
|
||||
|
||||
// إلغاء التوكن القديم إذا وجد في Redis
|
||||
if ($redis) {
|
||||
$oldJti = $redis->get("active_jti:" . $admin['id']);
|
||||
if ($oldJti) {
|
||||
@@ -107,8 +145,9 @@ try {
|
||||
|
||||
$jwt = $jwtService->generateAccessToken($admin['id'], $role, $audience, $fingerprint);
|
||||
|
||||
// فك تشفير البيانات للعرض
|
||||
$admin['name'] = $encryptionHelper->decryptData($admin['name']) ?: $admin['name'];
|
||||
if ($encryptionHelper && !empty($admin['name'])) {
|
||||
$admin['name'] = $encryptionHelper->decryptData($admin['name']) ?: $admin['name'];
|
||||
}
|
||||
unset($admin['password']);
|
||||
|
||||
printSuccess([
|
||||
@@ -120,67 +159,45 @@ try {
|
||||
exit;
|
||||
}
|
||||
|
||||
// 3. توليد رمز تحقق OTP (3 أرقام) وإرساله عبر نظام OTP الموحد
|
||||
// 3. توليد رمز تحقق OTP (3 أرقام) وإرساله عبر نظام OTP الموحد (Nabeh API للواتساب)
|
||||
$otp = (string)random_int(100, 999);
|
||||
$encryptedPhone = $admin['phone'] ?? '';
|
||||
|
||||
if (empty($encryptedPhone)) {
|
||||
jsonError("رقم الهاتف غير مسجل لهذا الحساب. يرجى مراجعة الإدارة.");
|
||||
exit;
|
||||
$rawPhone = ($encryptionHelper && !empty($encryptedPhone)) ? $encryptionHelper->decryptData($encryptedPhone) : $encryptedPhone;
|
||||
if (!$rawPhone || empty($rawPhone)) {
|
||||
$rawPhone = $encryptedPhone;
|
||||
}
|
||||
|
||||
// فك تشفير رقم الهاتف (مخزن مشفراً في قاعدة البيانات)
|
||||
$phone = $encryptionHelper->decryptData($encryptedPhone);
|
||||
if (!$phone || empty($phone)) {
|
||||
$phone = $encryptedPhone;
|
||||
}
|
||||
|
||||
// استخدام نظام OTP الموحد (Nabeh API للواتساب)
|
||||
// تحميل موزع خدمات OTP عبر Nabeh API
|
||||
require_once __DIR__ . '/../../auth/otp/providers.php';
|
||||
$country = 'Jordan';
|
||||
$method = 'whatsapp';
|
||||
|
||||
$success = false;
|
||||
switch ($country) {
|
||||
case 'Jordan':
|
||||
$success = sendNabehOtp($phone, $otp, $method, 'admin');
|
||||
break;
|
||||
default:
|
||||
$success = sendNabehOtp($phone, $otp, $method, 'admin');
|
||||
break;
|
||||
if (function_exists('sendNabehOtp')) {
|
||||
$success = sendNabehOtp($rawPhone, $otp, 'whatsapp', 'admin');
|
||||
}
|
||||
|
||||
// تخزين OTP (SHA-256 hash) مع الرقم المشفر من adminUser (توافق مع verify_login.php)
|
||||
// تخزين OTP (SHA-256 hash) في جدول token_verification_admin
|
||||
$otpHash = hash('sha256', $otp);
|
||||
$stmt = $con->prepare("INSERT INTO token_verification_admin (phone_number, token, expiration_time)
|
||||
VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 10 MINUTE))
|
||||
ON DUPLICATE KEY UPDATE token = VALUES(token), expiration_time = VALUES(expiration_time)");
|
||||
$stmt->execute([$encryptedPhone, $otpHash]);
|
||||
|
||||
// إخفاء جزء من الرقم في الاستجابة للأمان
|
||||
$maskedPhone = substr($phone, 0, 4) . '****' . substr($phone, -3);
|
||||
$maskedPhone = (strlen($rawPhone) > 7) ? substr($rawPhone, 0, 4) . '****' . substr($rawPhone, -3) : $rawPhone;
|
||||
|
||||
if ($success) {
|
||||
printSuccess([
|
||||
"status" => "otp_required",
|
||||
"message" => "تم إرسال رمز التحقق إلى WhatsApp الخاص بك.",
|
||||
"phone" => $maskedPhone
|
||||
]);
|
||||
} else {
|
||||
error_log("[ADMIN_LOGIN_WARN] Nabeh OTP failed for $phone, but OTP stored for debugging");
|
||||
printSuccess([
|
||||
"status" => "otp_required",
|
||||
"message" => "فشل إرسال واتساب. تحقق من error_log لمعرفة OTP.",
|
||||
"phone" => $maskedPhone
|
||||
]);
|
||||
}
|
||||
printSuccess([
|
||||
"status" => "otp_required",
|
||||
"message" => $success ? "تم إرسال رمز التحقق إلى WhatsApp الخاص بك." : "فشل إرسال واتساب. تحقق من error_log لمعرفة OTP.",
|
||||
"phone" => $maskedPhone
|
||||
]);
|
||||
exit;
|
||||
} else {
|
||||
jsonError("كلمة المرور غير صحيحة.");
|
||||
}
|
||||
} else {
|
||||
jsonError("الحساب أو الجهاز غير مسجل. يرجى إدخال رقم هاتفك وكلمة المرور إذا كان هذا أول تسجيل دخول لك.");
|
||||
jsonError("الحساب غير موجود. يرجى التأكد من اسم المستخدم أو البريد الإلكتروني وكلمة المرور.");
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
error_log("[Admin Login Error] " . $e->getMessage());
|
||||
jsonError("حدث خطأ في السيرفر. يرجى المحاولة لاحقاً.");
|
||||
} catch (Throwable $e) {
|
||||
error_log("[Admin Login Throwable Error] " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString());
|
||||
jsonError("حدث خطأ في السيرفر: " . $e->getMessage(), 500);
|
||||
}
|
||||
|
||||
@@ -22,14 +22,55 @@ $rateLimiter->enforce(RateLimiter::identifier(), 'otp');
|
||||
try {
|
||||
$con = Database::get('main');
|
||||
|
||||
// 1. جلب بيانات المسؤول عبر البصمة (مصدر موثوق وغير مشفر)
|
||||
// 1. جلب بيانات المسؤول عبر البصمة أو من الـ OTP المعلق للجهاز الجديد
|
||||
$fpHash = hash('sha256', $fingerprint);
|
||||
$stmt = $con->prepare("SELECT * FROM adminUser WHERE fingerprint_hash = :fp LIMIT 1");
|
||||
$stmt->execute([':fp' => $fpHash]);
|
||||
$admin = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
$otpHash = hash('sha256', (string)$otp);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -39,10 +80,7 @@ try {
|
||||
// فك تشفيره لو احتجنا إرساله أو عرضه، لكن هنا نحن نحتاج المشفر للبحث
|
||||
// $phone = $encryptionHelper->decryptData($encryptedPhone);
|
||||
|
||||
// هاش الرمز (OTP) القادم من التطبيق للمقارنة
|
||||
$otpHash = hash('sha256', (string)$otp);
|
||||
|
||||
// 3. التحقق من الـ OTP
|
||||
// 3. التحقق من الـ OTP (الهاش محسوب مسبقاً في المتغير $otpHash)
|
||||
$stmt = $con->prepare("SELECT * FROM token_verification_admin
|
||||
WHERE phone_number = ? AND token = ?
|
||||
AND expiration_time >= NOW()");
|
||||
@@ -56,7 +94,17 @@ try {
|
||||
// حذف الرمز بعد استخدامه لمرة واحدة (باستخدام الرقم المشفر)
|
||||
$con->prepare("DELETE FROM token_verification_admin WHERE phone_number = ?")->execute([$encryptedPhone]);
|
||||
|
||||
// 4. إصدار التوكن النهائي
|
||||
// 4. تحديث وتأكيد بصمة المتصفح/الجهاز الحالية للمسؤول في قاعدة البيانات بعد التحقق الناجح من OTP
|
||||
$encFpRaw = ($encryptionHelper && !empty($fingerprint)) ? $encryptionHelper->encryptData($fingerprint) : $fingerprint;
|
||||
$updateFpStmt = $con->prepare("UPDATE adminUser SET fingerprint = :fp_raw, fingerprint_hash = :fp WHERE id = :id");
|
||||
$updateFpStmt->execute([
|
||||
':fp_raw' => $encFpRaw,
|
||||
':fp' => $fpHash,
|
||||
':id' => $admin['id']
|
||||
]);
|
||||
$admin['fingerprint_hash'] = $fpHash;
|
||||
|
||||
// 5. إصدار التوكن النهائي
|
||||
$jwtService = new JwtService($redis);
|
||||
$role = $admin['role'] ?? 'admin';
|
||||
|
||||
@@ -71,7 +119,9 @@ try {
|
||||
$jwt = $jwtService->generateAccessToken($admin['id'], $role, $audience, $fingerprint);
|
||||
|
||||
// فك تشفير البيانات للعرض
|
||||
$admin['name'] = $encryptionHelper->decryptData($admin['name']) ?: $admin['name'];
|
||||
if ($encryptionHelper && !empty($admin['name'])) {
|
||||
$admin['name'] = $encryptionHelper->decryptData($admin['name']) ?: $admin['name'];
|
||||
}
|
||||
unset($admin['password']);
|
||||
|
||||
printSuccess([
|
||||
@@ -81,7 +131,7 @@ try {
|
||||
"expires_in" => 3600
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("[Admin Verify OTP Error] " . $e->getMessage());
|
||||
jsonError("An internal error occurred. Please try again later.");
|
||||
} catch (Throwable $e) {
|
||||
error_log("[Admin Verify OTP Error] " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString());
|
||||
jsonError("Server Error: " . $e->getMessage() . " on line " . $e->getLine());
|
||||
}
|
||||
|
||||
+28
-11
@@ -29,15 +29,24 @@ 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) 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 ROUND(SUM(distance),2) FROM ride) AS total_distance,
|
||||
(SELECT ROUND(AVG(distance),2) FROM ride) AS average_distance,
|
||||
(SELECT ROUND(MAX(distance),2) FROM ride) AS longest_distance,
|
||||
-- المسافات تُحسب على الرحلات المكتملة فقط. حسابها على كل الصفوف كان
|
||||
-- يُدخل الرحلات الملغاة و timeout (مسافتها 0 أو غير مضبوطة) في المتوسط
|
||||
-- فيهبط 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,
|
||||
|
||||
-- أرباح السائق والشركة
|
||||
(SELECT SUM(price_for_driver) FROM ride WHERE status = 'Finished') AS total_driver_earnings,
|
||||
(SELECT ROUND(AVG(price_for_passenger),2) FROM ride) AS avg_passenger_price,
|
||||
-- ملاحظة: خط الرحلات الحالي يكتب 'completed' بينما القديم يكتب 'Finished'،
|
||||
-- والاكتفاء بالقديم كان يُرجع NULL للأرباح وصفراً للرحلات المكتملة/الملغاة.
|
||||
(SELECT SUM(price_for_driver) FROM ride WHERE LOWER(status) IN ('finished','completed')) AS total_driver_earnings,
|
||||
-- متوسط سعر الراكب على الرحلات المكتملة فقط — الرحلات الملغاة سعرها 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,
|
||||
@@ -49,13 +58,21 @@ SELECT
|
||||
(SELECT COUNT(*) FROM ride WHERE carType = 'Speed') AS speed,
|
||||
(SELECT COUNT(*) FROM ride WHERE carType = 'Lady') AS lady,
|
||||
|
||||
-- حالة الرحلات
|
||||
(SELECT COUNT(*) FROM ride WHERE status = 'wait') AS ongoing_rides,
|
||||
(SELECT COUNT(*) FROM ride WHERE status = 'Finished') AS completed_rides,
|
||||
(SELECT COUNT(*) FROM ride WHERE status = 'cancel') AS cancelled_rides,
|
||||
-- حالة الرحلات (تغطي عائلتي الحالات: القديمة CamelCase والجديدة lowercase)
|
||||
-- الحالات الفعلية في قاعدة الإنتاج (فحص 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) 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
|
||||
|
||||
@@ -1,6 +1,18 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
// حارس الصلاحيات: هذه النقطة تحذف سجلاً نهائياً من قاعدة البيانات.
|
||||
// connect.php يتحقق من صحة التوكن فقط، فبدون هذا الفحص كان أي توكن صالح
|
||||
// (سائق أو راكب) قادراً على حذف السائقين.
|
||||
if ($role !== 'super_admin') {
|
||||
http_response_code(403);
|
||||
echo json_encode([
|
||||
'status' => 'failure',
|
||||
'message' => 'Forbidden. Super Admin access required.',
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
exit;
|
||||
}
|
||||
|
||||
$driver_id = filterRequest("driver_id");
|
||||
$phone = filterRequest("phone");
|
||||
$reason = filterRequest("reason"); // يمكن أن يأتي من البارامتر أو نخليه افتراضي
|
||||
|
||||
@@ -9,18 +9,34 @@ if (empty($phone)) {
|
||||
}
|
||||
|
||||
try {
|
||||
// تشفير الرقم المدخل للبحث
|
||||
$encPhone = $encryptionHelper->encryptData($phone);
|
||||
/**
|
||||
* البحث عبر الفهرس الأعمى أولاً (phone_bidx): مطابقة تامة عبر فهرس مُهيأ
|
||||
* ولا تعتمد على كون التشفير حتمياً، فتظل تعمل بعد النقل إلى AES-GCM.
|
||||
*
|
||||
* يُبقى المسار القديم (مقارنة النص المشفّر) كاحتياط حتى ينتهي تشغيل
|
||||
* scripts/backfill_blind_index.php، وإلا لتوقّف البحث بين الترحيل والتعبئة.
|
||||
*/
|
||||
global $blindIndex;
|
||||
$driver = null;
|
||||
|
||||
// احضار كل الأعمدة باستثناء كلمة المرور
|
||||
$sql = "SELECT *
|
||||
FROM driver
|
||||
WHERE phone = :phone
|
||||
LIMIT 1";
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->execute([':phone' => $encPhone]);
|
||||
if ($blindIndex) {
|
||||
$bidx = $blindIndex->index('driver.phone', $phone);
|
||||
if ($bidx) {
|
||||
$stmt = $con->prepare("SELECT * FROM driver WHERE phone_bidx = :bidx LIMIT 1");
|
||||
$stmt->execute([':bidx' => $bidx]);
|
||||
$driver = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
|
||||
}
|
||||
}
|
||||
|
||||
$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) {
|
||||
// ✅ الحقول المشفرة اللي لازم تنفك:
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
// حارس الصلاحيات: رفع الحظر عملية إدارية، وكانت هذه النقطة بلا أي فحص دور.
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
http_response_code(403);
|
||||
echo json_encode([
|
||||
'status' => 'failure',
|
||||
'message' => 'Forbidden. Admin access required.',
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
exit;
|
||||
}
|
||||
|
||||
$phone = filterRequest("phone");
|
||||
|
||||
if (empty($phone)) {
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
// 🔥 [Fix Broken Access Control] كان يتحقق من صلاحية التوكن فقط — أي مستخدم
|
||||
// مسجّل دخول كان يقدر يغيّر حالة أي سائق (تفعيل/رفض) أو رقم هاتفه.
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
http_response_code(403);
|
||||
echo json_encode(['error' => 'Unauthorized access. Admin role required.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$driver_id = filterRequest("id");
|
||||
$phone = filterRequest("phone");
|
||||
$status = filterRequest("status");
|
||||
@@ -16,6 +24,13 @@ if ($phone !== null && $phone !== '') {
|
||||
$encphone = $encryptionHelper->encryptData($phone);
|
||||
$updateFields[] = "`phone` = :phone";
|
||||
$params[':phone'] = $encphone;
|
||||
|
||||
// الفهرس يُحدَّث مع الرقم نفسه حتى لا يشير إلى القيمة القديمة
|
||||
global $blindIndex;
|
||||
if ($blindIndex) {
|
||||
$updateFields[] = "`phone_bidx` = :phone_bidx";
|
||||
$params[':phone_bidx'] = $blindIndex->index('driver.phone', $phone);
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
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
|
||||
`passengers`.`id`,
|
||||
`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) {
|
||||
jsonSuccess($data = $result);
|
||||
|
||||
@@ -1,6 +1,18 @@
|
||||
<?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");
|
||||
|
||||
$sql = "SELECT
|
||||
|
||||
@@ -1,10 +1,31 @@
|
||||
<?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"));
|
||||
$passengerId = filterRequest("passengerId");
|
||||
$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
|
||||
`passengers`.`id`,
|
||||
`passengers`.`phone`,
|
||||
@@ -59,12 +80,16 @@ FROM
|
||||
`passengers`
|
||||
WHERE
|
||||
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->bindParam(":email", $passengerEmail);
|
||||
$stmt->bindParam(":phone", $passengerphone);
|
||||
$stmt->bindParam(":id", $passengerId);
|
||||
$stmt->bindParam(":email_bidx", $emailBidx);
|
||||
$stmt->bindParam(":phone_bidx", $phoneBidx);
|
||||
$stmt->execute();
|
||||
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
|
||||
+31
-4
@@ -4,17 +4,33 @@
|
||||
// أداة تشفير وفك تشفير للمشرفين
|
||||
// ============================================================
|
||||
|
||||
require_once __DIR__ . '/../core/bootstrap.php';
|
||||
// ============================================================
|
||||
// المصادقة: هذه الأداة تفك تشفير أي حقل في قاعدة البيانات، لذا تمر عبر
|
||||
// connect.php (JWT + بصمة الجهاز + Rate limiting) ثم تتطلب دور super_admin.
|
||||
//
|
||||
// سابقاً كان الإذن الوحيد هو رقم هاتف يُرسل داخل جسم الطلب نفسه — وهو ليس
|
||||
// سرّاً: أي شخص يعرف رقماً من القائمة كان يستطيع فك تشفير بيانات المنصة
|
||||
// كاملةً بلا تسجيل دخول. أُبقيت قائمة الأرقام كطبقة ثانية فوق التوكن.
|
||||
// ============================================================
|
||||
require_once __DIR__ . '/../connect.php';
|
||||
|
||||
// نضمن أن الرد دائماً JSON
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
if ($role !== 'super_admin') {
|
||||
securityLog("Unauthorized encrypt/decrypt attempt", [
|
||||
'user_id' => $user_id ?? 'unknown',
|
||||
'role' => $role ?? 'none',
|
||||
]);
|
||||
jsonError('Forbidden. Super Admin access required.', 403);
|
||||
}
|
||||
|
||||
// 1) قراءة الـ body كـ JSON أو POST
|
||||
$action = filterRequest('action');
|
||||
$text = filterRequest('text');
|
||||
$adminPhoneParam = filterRequest('admin_phone');
|
||||
|
||||
// 2) التحقق من رقم هاتف الأدمن المصرّح له
|
||||
// 2) طبقة ثانية: رقم الهاتف يجب أن يكون ضمن القائمة المصرّح لها (إن وُجدت)
|
||||
$phonesRaw = getenv('ADMIN_PHONE_NUMBERS') ?: '';
|
||||
$ALLOWED_TOOL_PHONES = array_values(
|
||||
array_filter(
|
||||
@@ -26,11 +42,22 @@ $ALLOWED_TOOL_PHONES = array_values(
|
||||
|
||||
$adminPhoneParam = $adminPhoneParam ? preg_replace('/\D+/', '', $adminPhoneParam) : '';
|
||||
|
||||
if ($adminPhoneParam === '' || !in_array($adminPhoneParam, $ALLOWED_TOOL_PHONES, true)) {
|
||||
securityLog("Unauthorized encrypt/decrypt attempt", ['phone' => $adminPhoneParam]);
|
||||
if (!empty($ALLOWED_TOOL_PHONES)
|
||||
&& ($adminPhoneParam === '' || !in_array($adminPhoneParam, $ALLOWED_TOOL_PHONES, true))) {
|
||||
securityLog("Encrypt/decrypt phone not in allow-list", [
|
||||
'user_id' => $user_id ?? 'unknown',
|
||||
'phone' => $adminPhoneParam,
|
||||
]);
|
||||
jsonError('Access denied for this admin phone.', 403);
|
||||
}
|
||||
|
||||
// 3) سجل تدقيق: كل استخدام لهذه الأداة يُسجَّل مع هوية المنفّذ
|
||||
securityLog("Encryption tool used", [
|
||||
'user_id' => $user_id ?? 'unknown',
|
||||
'action' => $action,
|
||||
'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
|
||||
]);
|
||||
|
||||
if (empty($text) || ($action !== 'encrypt' && $action !== 'decrypt')) {
|
||||
jsonError('Invalid input: need action=encrypt|decrypt and non-empty text.', 400);
|
||||
}
|
||||
|
||||
@@ -6,14 +6,11 @@
|
||||
require_once __DIR__ . '/../core/bootstrap.php';
|
||||
|
||||
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 ───────────────────────────────────────────
|
||||
$limiter = new RateLimiter($redis);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
// ============================================================
|
||||
// get_pricing_stability_log.php
|
||||
// شاشة مراجعة محرك الثبات (Shadow Mode) — يعرض سجل التصنيفات
|
||||
// والإجراءات المقترحة بدون ما يكون أي منها مطبّق فعلياً على kazan
|
||||
// ============================================================
|
||||
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
http_response_code(403);
|
||||
echo json_encode(['status' => 'failure', 'message' => 'Unauthorized access. Admin role required.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
try {
|
||||
$countryCode = filterRequest('country_code');
|
||||
$limit = filterRequest('limit', 'int') ?? 100;
|
||||
|
||||
$sql = "SELECT * FROM pricing_stability_log";
|
||||
$params = [];
|
||||
|
||||
if ($countryCode) {
|
||||
$sql .= " WHERE country_code = :country";
|
||||
$params[':country'] = strtoupper($countryCode);
|
||||
}
|
||||
|
||||
$sql .= " ORDER BY evaluated_at DESC LIMIT :limit";
|
||||
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
|
||||
foreach ($params as $key => $val) {
|
||||
$stmt->bindValue($key, $val);
|
||||
}
|
||||
$stmt->execute();
|
||||
$log = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
// ملخص سريع لآخر تصنيف لكل دولة
|
||||
$stmtLatest = $con->query("
|
||||
SELECT l1.* FROM pricing_stability_log l1
|
||||
INNER JOIN (
|
||||
SELECT country_code, MAX(evaluated_at) AS max_time
|
||||
FROM pricing_stability_log
|
||||
GROUP BY country_code
|
||||
) l2 ON l1.country_code = l2.country_code AND l1.evaluated_at = l2.max_time
|
||||
");
|
||||
$latestPerCountry = $stmtLatest->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
jsonSuccess([
|
||||
'log' => $log,
|
||||
'latest_per_country' => $latestPerCountry,
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("[get_pricing_stability_log.php] Error: " . $e->getMessage());
|
||||
jsonError("Failed to fetch pricing stability log: " . $e->getMessage());
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -109,6 +109,22 @@ try {
|
||||
$dispatchedPassengers = [];
|
||||
$fcmErrors = [];
|
||||
|
||||
// 5.5 وضع المعاينة: يُرجع ما ستفعله الحملة (النص، الكود، حجم الجمهور)
|
||||
// دون إنشاء كود ترويجي ودون إرسال أي إشعار. الحملة تُنشئ خصماً حقيقياً
|
||||
// وتصل كل ركاب الدولة، فوجود معاينة قبل الإطلاق ضروري.
|
||||
if (filterRequest('dry_run') === '1') {
|
||||
jsonSuccess([
|
||||
'dry_run' => true,
|
||||
'campaign_created' => false,
|
||||
'promo_code' => $promoCode,
|
||||
'discount_percent' => $discountVal,
|
||||
'region' => $regionName,
|
||||
'country_code' => strtoupper($countryCode),
|
||||
'audience_size' => count($targets),
|
||||
'ai_analysis' => $aiCampaign,
|
||||
], 'Preview only — no promo code was created and no notification was sent.');
|
||||
}
|
||||
|
||||
// 6. Save broadcast promo for this campaign (Option 1 - promos table adjustment)
|
||||
$sqlPromo = "INSERT INTO promos
|
||||
(promo_code, amount, description, passengerID, source, validity_start_date, validity_end_date)
|
||||
|
||||
@@ -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);
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
/**
|
||||
* Admin/notifications/broadcast.php
|
||||
* إرسال إشعار جماعي إلى كل السائقين أو كل الركاب.
|
||||
*
|
||||
* لماذا نقطة وسيطة بدل استدعاء ride/firebase/send_fcm.php من الواجهة؟
|
||||
* - send_fcm.php داخلية ومحمية بمفتاح سرّي (FCM_INTERNAL_API_KEY)، ولا يجوز
|
||||
* أن يحمل المتصفح هذا المفتاح لأنه سيُكشف لأي مستخدم.
|
||||
* - send_fcm.php لا تعرف من المُرسِل، فلا تستطيع تقييد الصلاحية ولا التدقيق.
|
||||
*
|
||||
* هذه النقطة تفرض JWT + بصمة الجهاز (عبر connect.php) ودور super_admin، ثم
|
||||
* تُمرّر الطلب داخلياً مع المفتاح السرّي وتسجّل العملية في سجل التدقيق.
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
// إشعار جماعي يصل كل مستخدمي المنصة فوراً ولا يمكن سحبه بعد الإرسال.
|
||||
if ($role !== 'super_admin') {
|
||||
http_response_code(403);
|
||||
echo json_encode([
|
||||
'status' => 'failure',
|
||||
'message' => 'Forbidden. Super Admin access required to broadcast notifications.',
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
exit;
|
||||
}
|
||||
|
||||
$audience = filterRequest('audience');
|
||||
$title = filterRequest('title');
|
||||
$body = filterRequest('body');
|
||||
|
||||
// المواضيع المسموح بها فقط — يشترك بها التطبيقان (siro_driver / siro_rider).
|
||||
// قصرها على قائمة ثابتة يمنع استخدام النقطة لبثّ رسائل إلى مواضيع عشوائية
|
||||
// أو إلى توكن جهاز بعينه.
|
||||
$ALLOWED_AUDIENCES = [
|
||||
'drivers' => 'drivers',
|
||||
'passengers' => 'passengers',
|
||||
];
|
||||
|
||||
if (!isset($ALLOWED_AUDIENCES[$audience])) {
|
||||
jsonError('Invalid audience. Allowed: ' . implode(', ', array_keys($ALLOWED_AUDIENCES)), 400);
|
||||
}
|
||||
|
||||
$title = trim((string) $title);
|
||||
$body = trim((string) $body);
|
||||
|
||||
if ($title === '' || $body === '') {
|
||||
jsonError('Both title and body are required.', 400);
|
||||
}
|
||||
if (mb_strlen($title) > 120) {
|
||||
jsonError('Title is too long (max 120 characters).', 400);
|
||||
}
|
||||
if (mb_strlen($body) > 1000) {
|
||||
jsonError('Body is too long (max 1000 characters).', 400);
|
||||
}
|
||||
|
||||
$topic = $ALLOWED_AUDIENCES[$audience];
|
||||
|
||||
// سجل التدقيق قبل الإرسال: نريد أثراً حتى لو فشل النداء أو انقطع.
|
||||
securityLog("Broadcast notification requested", [
|
||||
'user_id' => $user_id ?? 'unknown',
|
||||
'audience' => $audience,
|
||||
'title' => $title,
|
||||
'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
|
||||
]);
|
||||
|
||||
if (function_exists('logAudit')) {
|
||||
try {
|
||||
logAudit($con, (string) ($user_id ?? 'unknown'), 'إرسال إشعار جماعي', 'notification', $topic, [
|
||||
'audience' => $audience,
|
||||
'title' => $title,
|
||||
'body' => $body,
|
||||
]);
|
||||
} catch (Throwable $e) {
|
||||
error_log("[Broadcast] audit log failed: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// الاستدعاء الداخلي لخدمة FCM
|
||||
// من داخل حاوية php لا يوجد خادم ويب على 127.0.0.1 — الويب في حاوية nginx
|
||||
// منفصلة، وتُعرف داخل شبكة Compose باسم الخدمة. هذا كان سبب فشل كل إشعار.
|
||||
$fcmUrl = getenv('FCM_INTERNAL_URL') ?: 'http://nginx/backend/ride/firebase/send_fcm.php';
|
||||
$payload = json_encode([
|
||||
'target' => $topic,
|
||||
'title' => $title,
|
||||
'body' => $body,
|
||||
'isTopic' => true,
|
||||
'data' => ['category' => 'admin_broadcast'],
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
|
||||
$headers = ['Content-Type: application/json; charset=UTF-8'];
|
||||
$internalKey = getenv('FCM_INTERNAL_API_KEY');
|
||||
if (!empty($internalKey)) {
|
||||
$headers[] = 'X-API-KEY: ' . $internalKey;
|
||||
}
|
||||
|
||||
$ch = curl_init($fcmUrl);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => $payload,
|
||||
CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 20,
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$curlErr = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
if ($response === false || $httpCode >= 400) {
|
||||
$reason = $curlErr ?: (is_string($response) ? substr($response, 0, 200) : 'no response');
|
||||
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);
|
||||
|
||||
jsonSuccess([
|
||||
'audience' => $audience,
|
||||
'topic' => $topic,
|
||||
'title' => $title,
|
||||
'sent_by' => $user_id ?? null,
|
||||
'sent_at' => date('Y-m-d H:i:s'),
|
||||
'fcm_status' => $decoded['status'] ?? 'unknown',
|
||||
], 'Broadcast delivered to the notification service.');
|
||||
@@ -1,6 +1,16 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
// حارس الصلاحيات: رفع الحظر عملية إدارية، وكانت هذه النقطة بلا أي فحص دور.
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
http_response_code(403);
|
||||
echo json_encode([
|
||||
'status' => 'failure',
|
||||
'message' => 'Forbidden. Admin access required.',
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
exit;
|
||||
}
|
||||
|
||||
function normalize_phone($s) { return preg_replace('/\D+/', '', (string)$s); }
|
||||
|
||||
$phone = filterRequest("phone");
|
||||
|
||||
@@ -7,24 +7,7 @@ if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* تطبيع رقم الهاتف ليتوافق مع التخزين في قاعدة البيانات
|
||||
*/
|
||||
function normalizePhone($phone) {
|
||||
$clean = preg_replace('/\D+/', '', $phone);
|
||||
// Syria: 099XXXXXXX or 9639XXXXXXX
|
||||
if (strlen($clean) === 10 && strpos($clean, '09') === 0) return '963' . substr($clean, 1);
|
||||
if (strlen($clean) === 12 && strpos($clean, '963') === 0) return $clean;
|
||||
if (strlen($clean) === 9 && strpos($clean, '9') === 0) return '963' . $clean;
|
||||
// Jordan: 079XXXXXXX or 9627XXXXXXX
|
||||
if (strlen($clean) === 10 && strpos($clean, '07') === 0) return '962' . substr($clean, 1);
|
||||
if (strlen($clean) === 12 && strpos($clean, '962') === 0) return $clean;
|
||||
if (strlen($clean) === 9 && strpos($clean, '7') === 0) return '962' . $clean;
|
||||
// Egypt: 010XXXXXXXX or 2010XXXXXXXX
|
||||
if (strlen($clean) === 11 && strpos($clean, '01') === 0) return '20' . substr($clean, 1);
|
||||
if (strlen($clean) === 13 && strpos($clean, '20') === 0) return $clean;
|
||||
return $clean;
|
||||
}
|
||||
// التطبيع عبر normalizePhone() الموحّدة في core/helpers.php (نفس المنطق سابقاً)
|
||||
|
||||
$phone = filterRequest('phone');
|
||||
if (!$phone) {
|
||||
@@ -46,20 +29,20 @@ try {
|
||||
$selP = $con->prepare("
|
||||
SELECT id, first_name, last_name, phone
|
||||
FROM passengers
|
||||
WHERE phone = :enc_raw
|
||||
WHERE phone = :enc_raw OR (:bidx IS NOT NULL AND phone_bidx = :bidx)
|
||||
LIMIT 1
|
||||
");
|
||||
$selP->execute(['enc_raw' => $enc_raw]);
|
||||
$selP->execute(['enc_raw' => $enc_raw, 'bidx' => $pBidx]);
|
||||
$passenger = $selP->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
// 2) ابحث عن السائق بالهاتف المشفّر
|
||||
$selD = $con->prepare("
|
||||
SELECT id AS driverID, first_name, last_name, phone
|
||||
FROM driver
|
||||
WHERE phone = :enc_raw
|
||||
WHERE phone = :enc_raw OR (:bidx IS NOT NULL AND phone_bidx = :bidx)
|
||||
LIMIT 1
|
||||
");
|
||||
$selD->execute(['enc_raw' => $enc_raw]);
|
||||
$selD->execute(['enc_raw' => $enc_raw, 'bidx' => $dBidx]);
|
||||
$driver = $selD->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
$userId = null;
|
||||
|
||||
@@ -6,7 +6,11 @@
|
||||
|
||||
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");
|
||||
|
||||
try {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
header("Access-Control-Allow-Origin: https://siromove.com");
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
try {
|
||||
@@ -18,29 +18,37 @@ try {
|
||||
$whereClause = ""; // لا يوجد شرط، اجلب الكل
|
||||
break;
|
||||
|
||||
// ملاحظة: قاعدة البيانات تحتوي عائلتين من الحالات — القديمة بصيغة
|
||||
// CamelCase ('Finished','Begin','CancelFromPassenger') والجديدة التي
|
||||
// يكتبها خط الرحلات الحالي بأحرف صغيرة ('completed','accepted',
|
||||
// 'cancelled_by_passenger'). المقارنة تتم بـ LOWER() لتغطية الاثنتين.
|
||||
case 'Pending':
|
||||
// الرحلات المعلقة/الجديدة: بانتظار سائق
|
||||
$whereClause = "WHERE r.status IN ('New','nothing','waiting','wait')";
|
||||
$whereClause = "WHERE LOWER(r.status) IN ('new','nothing','waiting','wait','pending','searching')";
|
||||
break;
|
||||
|
||||
case 'Begin':
|
||||
// الرحلات الجارية: من قبول السائق إلى بدء التشغيل
|
||||
$whereClause = "WHERE r.status IN ('Apply','Applied','Arrived','arrived','Begin')";
|
||||
$whereClause = "WHERE LOWER(r.status) IN ('apply','applied','arrived','begin','accepted','started','claimed')";
|
||||
break;
|
||||
|
||||
case 'Completed':
|
||||
// الرحلات المكتملة
|
||||
$whereClause = "WHERE r.status = 'Finished'";
|
||||
$whereClause = "WHERE LOWER(r.status) IN ('finished','completed')";
|
||||
break;
|
||||
|
||||
case 'Canceled':
|
||||
// جميع أنواع الإلغاء
|
||||
$whereClause = "WHERE r.status IN ('Cancel','CancelFromDriver','CancelFromDriverAfterApply','CancelFromPassenger','TimeOut')";
|
||||
$whereClause = "WHERE LOWER(r.status) IN (
|
||||
'cancel','cancelfromdriver','cancelfromdriverafterapply','cancelfrompassenger',
|
||||
'timeout','refused','cancelled_by_passenger','cancelled_by_driver',
|
||||
'cancelled_no_driver_found'
|
||||
)";
|
||||
break;
|
||||
|
||||
default:
|
||||
// في حال تم إرسال حالة محددة غير المذكورين
|
||||
$whereClause = "WHERE r.status = ?";
|
||||
$whereClause = "WHERE LOWER(r.status) = LOWER(?)";
|
||||
$params[] = $statusFilter;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,30 +1,17 @@
|
||||
<?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') {
|
||||
http_response_code(403);
|
||||
echo json_encode(['error' => 'Unauthorized: Admin access required']);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* تطبيع رقم الهاتف ليتوافق مع التخزين في قاعدة البيانات
|
||||
*/
|
||||
function normalizePhone($phone) {
|
||||
$clean = preg_replace('/\D+/', '', $phone);
|
||||
// Syria: 099XXXXXXX or 9639XXXXXXX
|
||||
if (strlen($clean) === 10 && strpos($clean, '09') === 0) return '963' . substr($clean, 1);
|
||||
if (strlen($clean) === 12 && strpos($clean, '963') === 0) return $clean;
|
||||
if (strlen($clean) === 9 && strpos($clean, '9') === 0) return '963' . $clean;
|
||||
// Jordan: 079XXXXXXX or 9627XXXXXXX
|
||||
if (strlen($clean) === 10 && strpos($clean, '07') === 0) return '962' . substr($clean, 1);
|
||||
if (strlen($clean) === 12 && strpos($clean, '962') === 0) return $clean;
|
||||
if (strlen($clean) === 9 && strpos($clean, '7') === 0) return '962' . $clean;
|
||||
// Egypt: 010XXXXXXXX or 2010XXXXXXXX
|
||||
if (strlen($clean) === 11 && strpos($clean, '01') === 0) return '20' . substr($clean, 1);
|
||||
if (strlen($clean) === 13 && strpos($clean, '20') === 0) return $clean;
|
||||
return $clean;
|
||||
}
|
||||
// التطبيع عبر normalizePhone() الموحّدة في core/helpers.php (نفس المنطق سابقاً)
|
||||
|
||||
// 1. تسجيل بداية الطلب
|
||||
$phone = filterRequest("phone");
|
||||
@@ -40,16 +27,21 @@ error_log("[MONITOR_RIDE] 1.5 Normalized Phone: " . $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);
|
||||
|
||||
// Check Driver Table
|
||||
$driverQuery = $con->prepare("SELECT id AS driverID FROM driver WHERE phone = :phone LIMIT 1");
|
||||
$driverQuery->execute([':phone' => $encPhone]);
|
||||
$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, ':bidx' => $dBidx]);
|
||||
$driver = $driverQuery->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
// Check Passenger Table
|
||||
$customerQuery = $con->prepare("SELECT id AS customerID FROM passengers WHERE phone = :phone LIMIT 1");
|
||||
$customerQuery->execute([':phone' => $encPhone]);
|
||||
$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, ':bidx' => $pBidx]);
|
||||
$customer = $customerQuery->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
// حدد نوع المستخدم
|
||||
@@ -164,5 +156,7 @@ $response = [
|
||||
"driver_location" => $location ?: "No live location"
|
||||
];
|
||||
|
||||
error_log("[MONITOR_RIDE] 7. Sending Success Response.");
|
||||
jsonSuccess($response);
|
||||
error_log("[MONITOR_RIDE] 7. Sending Success 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);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
// Admin/transit/org/admin_add.php — فريق سيرو يضيف مشرفاً جديداً لمؤسسة قائمة
|
||||
// POST: org_id, name, phone, role? (owner|transport_manager|dispatcher)
|
||||
|
||||
require_once __DIR__ . '/../../../connect.php';
|
||||
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
jsonError('Unauthorized: Admin access required', 403);
|
||||
}
|
||||
|
||||
try { $transit_con = Database::get('transit'); }
|
||||
catch (Exception $e) { jsonError('Transit service unavailable', 503); }
|
||||
|
||||
require_once __DIR__ . '/../../../transit/functions.php';
|
||||
|
||||
requireTransitFields(['org_id', 'name', 'phone']);
|
||||
|
||||
$orgId = filterRequest('org_id', 'int');
|
||||
$name = filterRequest('name');
|
||||
$phone = normalizePhone(filterRequest('phone'));
|
||||
$adminRole = filterRequest('role') ?: 'transport_manager';
|
||||
|
||||
$allowedRoles = ['owner', 'transport_manager', 'dispatcher'];
|
||||
if (!in_array($adminRole, $allowedRoles)) jsonError('Invalid role', 400);
|
||||
|
||||
$chkOrg = $transit_con->prepare("SELECT id FROM transit_orgs WHERE id=? LIMIT 1");
|
||||
$chkOrg->execute([$orgId]);
|
||||
if (!$chkOrg->fetch()) jsonError('Organization not found', 404);
|
||||
|
||||
$phoneEnc = $encryptionHelper->encryptData($phone);
|
||||
|
||||
$chkDup = $transit_con->prepare(
|
||||
"SELECT id FROM transit_org_admins WHERE org_id=? AND phone=? LIMIT 1"
|
||||
);
|
||||
$chkDup->execute([$orgId, $phoneEnc]);
|
||||
if ($chkDup->fetch()) jsonError('An admin with this phone already exists for this organization', 409);
|
||||
|
||||
$transit_con->prepare(
|
||||
"INSERT INTO transit_org_admins (org_id, name, phone, role, is_active) VALUES (?,?,?,?,1)"
|
||||
)->execute([$orgId, $name, $phoneEnc, $adminRole]);
|
||||
|
||||
appLog("[ADMIN][TRANSIT][ORG][admin_add] org={$orgId} name={$name} role={$adminRole}");
|
||||
|
||||
jsonSuccess(['admin_id' => (int)$transit_con->lastInsertId()], 'Admin added successfully');
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
// Admin/transit/org/admin_toggle.php — تفعيل/تعليق مشرف مؤسسة (لفريق سيرو)
|
||||
// POST: admin_id, is_active (1|0)
|
||||
|
||||
require_once __DIR__ . '/../../../connect.php';
|
||||
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
jsonError('Unauthorized: Admin access required', 403);
|
||||
}
|
||||
|
||||
try { $transit_con = Database::get('transit'); }
|
||||
catch (Exception $e) { jsonError('Transit service unavailable', 503); }
|
||||
|
||||
$adminId = filterRequest('admin_id', 'int');
|
||||
$isActive = filterRequest('is_active', 'int');
|
||||
|
||||
if (!$adminId || $isActive === null) jsonError('admin_id and is_active are required', 400);
|
||||
|
||||
$st = $transit_con->prepare("SELECT id, org_id FROM transit_org_admins WHERE id=? LIMIT 1");
|
||||
$st->execute([$adminId]);
|
||||
$admin = $st->fetch();
|
||||
if (!$admin) jsonError('Admin not found', 404);
|
||||
|
||||
$transit_con->prepare("UPDATE transit_org_admins SET is_active=? WHERE id=?")
|
||||
->execute([$isActive ? 1 : 0, $adminId]);
|
||||
|
||||
// إبطال جلساته الحالية فوراً عند التعليق
|
||||
if (!$isActive) {
|
||||
$sessions = $transit_con->prepare("SELECT token_hash FROM transit_sessions WHERE admin_id=?");
|
||||
$sessions->execute([$adminId]);
|
||||
foreach ($sessions->fetchAll(PDO::FETCH_COLUMN) as $hash) {
|
||||
if ($redis) $redis->del("transit:session:{$hash}");
|
||||
}
|
||||
$transit_con->prepare("DELETE FROM transit_sessions WHERE admin_id=?")->execute([$adminId]);
|
||||
}
|
||||
|
||||
appLog("[ADMIN][TRANSIT][ORG][admin_toggle] admin={$adminId} is_active={$isActive}");
|
||||
|
||||
jsonSuccess(['admin_id' => $adminId, 'is_active' => (bool)$isActive]);
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
// Admin/transit/org/admins_list.php — قائمة مشرفي مؤسسة (لفريق سيرو)
|
||||
// POST/GET: org_id
|
||||
|
||||
require_once __DIR__ . '/../../../connect.php';
|
||||
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
jsonError('Unauthorized: Admin access required', 403);
|
||||
}
|
||||
|
||||
try { $transit_con = Database::get('transit'); }
|
||||
catch (Exception $e) { jsonError('Transit service unavailable', 503); }
|
||||
|
||||
$orgId = filterRequest('org_id', 'int');
|
||||
if (!$orgId) jsonError('org_id is required', 400);
|
||||
|
||||
$st = $transit_con->prepare(
|
||||
"SELECT id, name, phone, role, is_active, created_at
|
||||
FROM transit_org_admins WHERE org_id=? ORDER BY created_at ASC"
|
||||
);
|
||||
$st->execute([$orgId]);
|
||||
$admins = $st->fetchAll();
|
||||
|
||||
foreach ($admins as &$a) {
|
||||
if (!empty($a['phone'])) {
|
||||
$a['phone'] = $encryptionHelper->decryptData($a['phone']) ?: null;
|
||||
}
|
||||
}
|
||||
unset($a);
|
||||
|
||||
jsonSuccess(['admins' => $admins]);
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
// Admin/transit/org/create.php — فريق سيرو يضيف مؤسسة جديدة (جامعة/مدرسة/فندق/شركة/ناقل)
|
||||
// + ينشئ أول مشرف (owner) لها مباشرة
|
||||
// POST: type, country, city, name_ar, name_en, admin_name, admin_phone, ...
|
||||
|
||||
require_once __DIR__ . '/../../../connect.php';
|
||||
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
jsonError('Unauthorized: Admin access required', 403);
|
||||
}
|
||||
|
||||
try { $transit_con = Database::get('transit'); }
|
||||
catch (Exception $e) { jsonError('Transit service unavailable', 503); }
|
||||
|
||||
require_once __DIR__ . '/../../../transit/functions.php';
|
||||
|
||||
requireTransitFields(['type', 'country', 'city', 'name_ar', 'name_en', 'admin_name', 'admin_phone']);
|
||||
|
||||
$type = filterRequest('type');
|
||||
$country = strtoupper(substr(filterRequest('country'), 0, 2));
|
||||
$city = filterRequest('city');
|
||||
$nameAr = filterRequest('name_ar');
|
||||
$nameEn = filterRequest('name_en');
|
||||
$adminName = filterRequest('admin_name');
|
||||
$adminPhone = normalizePhone(filterRequest('admin_phone'));
|
||||
$adminRole = filterRequest('admin_role') ?: 'owner';
|
||||
$trialEndsAt = filterRequest('trial_ends_at') ?: date('Y-m-d', strtotime('+90 days'));
|
||||
|
||||
$allowedTypes = ['university', 'school', 'hotel', 'company', 'transporter'];
|
||||
if (!in_array($type, $allowedTypes)) {
|
||||
jsonError('Invalid type. Allowed: ' . implode(', ', $allowedTypes));
|
||||
}
|
||||
|
||||
$chk = $transit_con->prepare("SELECT id FROM transit_orgs WHERE name_ar=? AND country=? LIMIT 1");
|
||||
$chk->execute([$nameAr, $country]);
|
||||
if ($chk->fetch()) jsonError('Organization already exists', 409);
|
||||
|
||||
$adminPhoneEnc = $encryptionHelper->encryptData($adminPhone);
|
||||
$contactPhoneRaw = normalizePhone(filterRequest('contact_phone') ?? '');
|
||||
$contactPhoneEnc = $contactPhoneRaw ? $encryptionHelper->encryptData($contactPhoneRaw) : null;
|
||||
|
||||
$transit_con->beginTransaction();
|
||||
try {
|
||||
$transit_con->prepare(
|
||||
"INSERT INTO transit_orgs
|
||||
(type, country, city, name_ar, name_en, contact_phone, contact_email, website, contract_status, trial_ends_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,'active',?)"
|
||||
)->execute([
|
||||
$type, $country, $city, $nameAr, $nameEn,
|
||||
$contactPhoneEnc, filterRequest('contact_email'), filterRequest('website'),
|
||||
$trialEndsAt,
|
||||
]);
|
||||
|
||||
$orgId = (int)$transit_con->lastInsertId();
|
||||
|
||||
$transit_con->prepare(
|
||||
"INSERT INTO transit_org_admins (org_id, name, phone, role) VALUES (?,?,?,?)"
|
||||
)->execute([$orgId, $adminName, $adminPhoneEnc, $adminRole]);
|
||||
|
||||
$transit_con->commit();
|
||||
} catch (Throwable $e) {
|
||||
$transit_con->rollBack();
|
||||
appLog('[ADMIN][TRANSIT][ORG][create] ' . $e->getMessage(), 'ERROR');
|
||||
jsonError('Failed to create organization', 500);
|
||||
}
|
||||
|
||||
jsonSuccess([
|
||||
'org_id' => $orgId,
|
||||
'name_ar' => $nameAr,
|
||||
'type' => $type,
|
||||
'country' => $country,
|
||||
], 'Organization created successfully');
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
// Admin/transit/org/details.php — تفاصيل وتحليلات مؤسسة واحدة (لفريق سيرو)
|
||||
// POST/GET: org_id
|
||||
|
||||
require_once __DIR__ . '/../../../connect.php';
|
||||
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
jsonError('Unauthorized: Admin access required', 403);
|
||||
}
|
||||
|
||||
try { $transit_con = Database::get('transit'); }
|
||||
catch (Exception $e) { jsonError('Transit service unavailable', 503); }
|
||||
|
||||
$orgId = filterRequest('org_id', 'int');
|
||||
if (!$orgId) jsonError('org_id is required', 400);
|
||||
|
||||
$st = $transit_con->prepare("SELECT * FROM transit_orgs WHERE id=? LIMIT 1");
|
||||
$st->execute([$orgId]);
|
||||
$org = $st->fetch();
|
||||
if (!$org) jsonError('Organization not found', 404);
|
||||
|
||||
// فك تشفير هاتف التواصل للعرض الإداري فقط
|
||||
if (!empty($org['contact_phone'])) {
|
||||
$org['contact_phone'] = $encryptionHelper->decryptData($org['contact_phone']) ?: null;
|
||||
}
|
||||
|
||||
// ── العدّادات الأساسية ───────────────────────────────────────
|
||||
$counts = [
|
||||
'drivers_total' => (int)$transit_con->query("SELECT COUNT(*) FROM transit_drivers WHERE org_id=$orgId")->fetchColumn(),
|
||||
'drivers_active' => (int)$transit_con->query("SELECT COUNT(*) FROM transit_drivers WHERE org_id=$orgId AND status='active'")->fetchColumn(),
|
||||
'vehicles_total' => (int)$transit_con->query("SELECT COUNT(*) FROM transit_vehicles WHERE org_id=$orgId")->fetchColumn(),
|
||||
'vehicles_active' => (int)$transit_con->query("SELECT COUNT(*) FROM transit_vehicles WHERE org_id=$orgId AND is_active=1")->fetchColumn(),
|
||||
'routes_total' => (int)$transit_con->query("SELECT COUNT(*) FROM transit_routes WHERE org_id=$orgId")->fetchColumn(),
|
||||
'routes_active' => (int)$transit_con->query("SELECT COUNT(*) FROM transit_routes WHERE org_id=$orgId AND status='active'")->fetchColumn(),
|
||||
'enrollments_active' => (int)$transit_con->query("SELECT COUNT(*) FROM transit_enrollments WHERE org_id=$orgId AND status='active'")->fetchColumn(),
|
||||
'enrollments_pending' => (int)$transit_con->query("SELECT COUNT(*) FROM transit_enrollments WHERE org_id=$orgId AND status='pending'")->fetchColumn(),
|
||||
];
|
||||
|
||||
// ── الرحلات: اليوم / هذا الأسبوع / هذا الشهر / إجمالي ──────────
|
||||
$today = date('Y-m-d');
|
||||
$weekStart = date('Y-m-d', strtotime('monday this week'));
|
||||
$monthStart = date('Y-m-01');
|
||||
|
||||
$stTrips = $transit_con->prepare(
|
||||
"SELECT
|
||||
SUM(trip_date = ?) AS today_count,
|
||||
SUM(trip_date >= ?) AS week_count,
|
||||
SUM(trip_date >= ?) AS month_count,
|
||||
COUNT(*) AS total_count,
|
||||
SUM(status='completed') AS completed_count,
|
||||
SUM(status='cancelled') AS cancelled_count,
|
||||
SUM(status='no_show') AS no_show_count,
|
||||
AVG(CASE WHEN status='completed' THEN delay_minutes END) AS avg_delay_minutes,
|
||||
SUM(CASE WHEN status='completed' AND started_at IS NOT NULL AND completed_at IS NOT NULL
|
||||
THEN TIMESTAMPDIFF(MINUTE, started_at, completed_at) ELSE 0 END) AS total_minutes_driven
|
||||
FROM transit_trips WHERE org_id = ?"
|
||||
);
|
||||
$stTrips->execute([$today, $weekStart, $monthStart, $orgId]);
|
||||
$tripStats = $stTrips->fetch();
|
||||
|
||||
$trips = [
|
||||
'today' => (int)($tripStats['today_count'] ?? 0),
|
||||
'this_week' => (int)($tripStats['week_count'] ?? 0),
|
||||
'this_month' => (int)($tripStats['month_count'] ?? 0),
|
||||
'total' => (int)($tripStats['total_count'] ?? 0),
|
||||
'completed' => (int)($tripStats['completed_count'] ?? 0),
|
||||
'cancelled' => (int)($tripStats['cancelled_count'] ?? 0),
|
||||
'no_show' => (int)($tripStats['no_show_count'] ?? 0),
|
||||
'avg_delay_minutes' => round((float)($tripStats['avg_delay_minutes'] ?? 0), 1),
|
||||
'total_hours_driven' => round(((int)($tripStats['total_minutes_driven'] ?? 0)) / 60, 1),
|
||||
];
|
||||
|
||||
// ── الخطوط مع ملخص لكل خط ─────────────────────────────────────
|
||||
$stRoutes = $transit_con->prepare(
|
||||
"SELECT r.id, r.name_ar, r.status, r.distance_km,
|
||||
(SELECT COUNT(*) FROM transit_stops s WHERE s.route_id = r.id) AS stops_count,
|
||||
(SELECT COUNT(*) FROM transit_trips t WHERE t.route_id = r.id AND t.status='completed') AS completed_trips
|
||||
FROM transit_routes r WHERE r.org_id = ? ORDER BY r.name_ar ASC"
|
||||
);
|
||||
$stRoutes->execute([$orgId]);
|
||||
$routes = $stRoutes->fetchAll();
|
||||
|
||||
jsonSuccess([
|
||||
'org' => $org,
|
||||
'counts' => $counts,
|
||||
'trips' => $trips,
|
||||
'routes' => $routes,
|
||||
]);
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
// Admin/transit/org/list.php — قائمة كل مؤسسات مواصلاتي (لفريق سيرو)
|
||||
// GET/POST: country?, type?, contract_status?, search?, page?, per_page?
|
||||
|
||||
require_once __DIR__ . '/../../../connect.php';
|
||||
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
jsonError('Unauthorized: Admin access required', 403);
|
||||
}
|
||||
|
||||
try { $transit_con = Database::get('transit'); }
|
||||
catch (Exception $e) { jsonError('Transit service unavailable', 503); }
|
||||
|
||||
$country = filterRequest('country');
|
||||
$type = filterRequest('type');
|
||||
$contractStatus = filterRequest('contract_status');
|
||||
$search = filterRequest('search');
|
||||
$page = max(1, (int)(filterRequest('page', 'int') ?? 1));
|
||||
$perPage = min(100, max(10, (int)(filterRequest('per_page', 'int') ?? 30)));
|
||||
$offset = ($page - 1) * $perPage;
|
||||
|
||||
$where = '1=1';
|
||||
$params = [];
|
||||
|
||||
if ($country) { $where .= ' AND country = ?'; $params[] = strtoupper(substr($country, 0, 2)); }
|
||||
if ($type) { $where .= ' AND type = ?'; $params[] = $type; }
|
||||
if ($contractStatus) { $where .= ' AND contract_status = ?'; $params[] = $contractStatus; }
|
||||
if ($search) { $where .= ' AND (name_ar LIKE ? OR name_en LIKE ?)'; $params[] = "%$search%"; $params[] = "%$search%"; }
|
||||
|
||||
$countSt = $transit_con->prepare("SELECT COUNT(*) FROM transit_orgs WHERE $where");
|
||||
$countSt->execute($params);
|
||||
$total = (int)$countSt->fetchColumn();
|
||||
|
||||
$params[] = $perPage;
|
||||
$params[] = $offset;
|
||||
$st = $transit_con->prepare(
|
||||
"SELECT id, type, country, city, name_ar, name_en, logo_url,
|
||||
contract_status, trial_ends_at, created_at
|
||||
FROM transit_orgs
|
||||
WHERE $where
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ? OFFSET ?"
|
||||
);
|
||||
$st->execute($params);
|
||||
$orgs = $st->fetchAll();
|
||||
|
||||
if ($orgs) {
|
||||
$ids = implode(',', array_map('intval', array_column($orgs, 'id')));
|
||||
|
||||
$drivers = $transit_con->query("SELECT org_id, COUNT(*) c FROM transit_drivers WHERE org_id IN ($ids) GROUP BY org_id")
|
||||
->fetchAll(PDO::FETCH_KEY_PAIR);
|
||||
$vehicles = $transit_con->query("SELECT org_id, COUNT(*) c FROM transit_vehicles WHERE org_id IN ($ids) GROUP BY org_id")
|
||||
->fetchAll(PDO::FETCH_KEY_PAIR);
|
||||
$routes = $transit_con->query("SELECT org_id, COUNT(*) c FROM transit_routes WHERE org_id IN ($ids) AND status='active' GROUP BY org_id")
|
||||
->fetchAll(PDO::FETCH_KEY_PAIR);
|
||||
$enrollments = $transit_con->query("SELECT org_id, COUNT(*) c FROM transit_enrollments WHERE org_id IN ($ids) AND status='active' GROUP BY org_id")
|
||||
->fetchAll(PDO::FETCH_KEY_PAIR);
|
||||
|
||||
foreach ($orgs as &$o) {
|
||||
$id = $o['id'];
|
||||
$o['drivers_count'] = (int)($drivers[$id] ?? 0);
|
||||
$o['vehicles_count'] = (int)($vehicles[$id] ?? 0);
|
||||
$o['active_routes'] = (int)($routes[$id] ?? 0);
|
||||
$o['active_enrollments'] = (int)($enrollments[$id] ?? 0);
|
||||
}
|
||||
unset($o);
|
||||
}
|
||||
|
||||
jsonSuccess([
|
||||
'orgs' => $orgs,
|
||||
'pagination' => ['total' => $total, 'page' => $page, 'per_page' => $perPage],
|
||||
]);
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
// Admin/transit/org/update.php — تعديل بيانات مؤسسة + إدارة حالة العقد
|
||||
// POST: org_id, [contract_status], [city], [contact_email], [website], [trial_ends_at]
|
||||
//
|
||||
// عند التعليق (suspended) أو الإنهاء (terminated):
|
||||
// يُبطل جميع جلسات مشرفي المؤسسة فوراً (Redis + MySQL)
|
||||
|
||||
require_once __DIR__ . '/../../../connect.php';
|
||||
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
jsonError('Unauthorized: Admin access required', 403);
|
||||
}
|
||||
|
||||
try { $transit_con = Database::get('transit'); }
|
||||
catch (Exception $e) { jsonError('Transit service unavailable', 503); }
|
||||
|
||||
require_once __DIR__ . '/../../../transit/functions.php';
|
||||
|
||||
$orgId = filterRequest('org_id', 'int');
|
||||
if (!$orgId) jsonError('org_id is required', 400);
|
||||
|
||||
$st = $transit_con->prepare("SELECT id, contract_status FROM transit_orgs WHERE id=? LIMIT 1");
|
||||
$st->execute([$orgId]);
|
||||
$org = $st->fetch();
|
||||
if (!$org) jsonError('Organization not found', 404);
|
||||
|
||||
$updates = [];
|
||||
$params = [];
|
||||
|
||||
// حقول يمكن تحديثها
|
||||
if (($v = filterRequest('city')) !== null) { $updates[] = 'city=?'; $params[] = $v; }
|
||||
if (($v = filterRequest('contact_email')) !== null) { $updates[] = 'contact_email=?'; $params[] = $v; }
|
||||
if (($v = filterRequest('website')) !== null) { $updates[] = 'website=?'; $params[] = $v; }
|
||||
if (($v = filterRequest('trial_ends_at')) !== null) { $updates[] = 'trial_ends_at=?'; $params[] = $v; }
|
||||
|
||||
$newStatus = null;
|
||||
if (($v = filterRequest('contract_status')) !== null) {
|
||||
$allowed = ['active', 'trial', 'suspended', 'terminated'];
|
||||
if (!in_array($v, $allowed)) {
|
||||
jsonError('Invalid contract_status. Allowed: ' . implode(', ', $allowed), 400);
|
||||
}
|
||||
$newStatus = $v;
|
||||
$updates[] = 'contract_status=?';
|
||||
$params[] = $v;
|
||||
}
|
||||
|
||||
if (empty($updates)) jsonError('No fields to update', 400);
|
||||
|
||||
$updates[] = 'updated_at=NOW()';
|
||||
$params[] = $orgId;
|
||||
|
||||
$transit_con->prepare(
|
||||
"UPDATE transit_orgs SET " . implode(', ', $updates) . " WHERE id=?"
|
||||
)->execute($params);
|
||||
|
||||
// إبطال جلسات المشرفين عند التعليق أو الإنهاء
|
||||
if ($newStatus && in_array($newStatus, ['suspended', 'terminated'])) {
|
||||
$admins = $transit_con->prepare("SELECT id FROM transit_org_admins WHERE org_id=?");
|
||||
$admins->execute([$orgId]);
|
||||
|
||||
foreach ($admins->fetchAll(PDO::FETCH_COLUMN) as $adminId) {
|
||||
$sessions = $transit_con->prepare("SELECT token_hash FROM transit_sessions WHERE admin_id=?");
|
||||
$sessions->execute([$adminId]);
|
||||
foreach ($sessions->fetchAll(PDO::FETCH_COLUMN) as $hash) {
|
||||
if ($redis) $redis->del("transit:session:{$hash}");
|
||||
}
|
||||
$transit_con->prepare("DELETE FROM transit_sessions WHERE admin_id=?")->execute([$adminId]);
|
||||
}
|
||||
|
||||
appLog("[ADMIN][TRANSIT][ORG][update] org={$orgId} contract_status={$newStatus} — all admin sessions invalidated");
|
||||
} else {
|
||||
appLog("[ADMIN][TRANSIT][ORG][update] org={$orgId} updated=" . implode(',', $updates));
|
||||
}
|
||||
|
||||
jsonSuccess(['org_id' => $orgId, 'contract_status' => $newStatus ?? $org['contract_status']]);
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
// Admin/transit/route/approve.php — فريق سيرو يعتمد أو يوقف خطاً
|
||||
// POST: route_id, action (approve|suspend|reject)
|
||||
|
||||
require_once __DIR__ . '/../../../connect.php';
|
||||
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
jsonError('Unauthorized: Admin access required', 403);
|
||||
}
|
||||
|
||||
try { $transit_con = Database::get('transit'); }
|
||||
catch (Exception $e) { jsonError('Transit service unavailable', 503); }
|
||||
|
||||
require_once __DIR__ . '/../../../transit/functions.php';
|
||||
|
||||
$routeId = filterRequest('route_id', 'int');
|
||||
$action = filterRequest('action');
|
||||
|
||||
if (!$routeId) jsonError('route_id is required', 400);
|
||||
|
||||
$allowed = ['approve', 'suspend', 'reject'];
|
||||
if (!in_array($action, $allowed)) jsonError('Invalid action. Allowed: ' . implode(', ', $allowed), 400);
|
||||
|
||||
$st = $transit_con->prepare("SELECT id, org_id, name_ar, status FROM transit_routes WHERE id=? LIMIT 1");
|
||||
$st->execute([$routeId]);
|
||||
$route = $st->fetch();
|
||||
if (!$route) jsonError('Route not found', 404);
|
||||
|
||||
$statusMap = [
|
||||
'approve' => 'active',
|
||||
'suspend' => 'suspended',
|
||||
'reject' => 'rejected',
|
||||
];
|
||||
$newStatus = $statusMap[$action];
|
||||
|
||||
if ($route['status'] === $newStatus) {
|
||||
jsonError("Route is already in status: {$newStatus}", 409);
|
||||
}
|
||||
|
||||
$transit_con->prepare(
|
||||
"UPDATE transit_routes
|
||||
SET status=?, approved_by=?, approved_at=NOW(), updated_at=NOW()
|
||||
WHERE id=?"
|
||||
)->execute([$newStatus, (string)$user_id, $routeId]);
|
||||
|
||||
appLog("[TRANSIT][ROUTE] route #{$routeId} org#{$route['org_id']} → {$newStatus} by admin #{$user_id}", 'INFO');
|
||||
|
||||
// كتابة في Redis للسوكيت: transit:route_org:{routeId} → org_id
|
||||
// يُستخدم في passenger_socket لتحقق العضوية
|
||||
if (isset($redisLocation) && $redisLocation) {
|
||||
$redisLocation->set("transit:route_org:{$routeId}", (string)$route['org_id']);
|
||||
}
|
||||
|
||||
jsonSuccess([
|
||||
'route_id' => $routeId,
|
||||
'route_name' => $route['name_ar'],
|
||||
'new_status' => $newStatus,
|
||||
], "Route {$action}d successfully");
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
// Admin/transit/route/pending.php — قائمة الخطوط المسودة بانتظار الاعتماد
|
||||
// POST: — (اختياري: org_id للفلترة)
|
||||
|
||||
require_once __DIR__ . '/../../../connect.php';
|
||||
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
jsonError('Unauthorized: Admin access required', 403);
|
||||
}
|
||||
|
||||
try { $transit_con = Database::get('transit'); }
|
||||
catch (Exception $e) { jsonError('Transit service unavailable', 503); }
|
||||
|
||||
require_once __DIR__ . '/../../../transit/functions.php';
|
||||
|
||||
$orgIdFilter = filterRequest('org_id', 'int');
|
||||
|
||||
$sql = "SELECT r.id, r.org_id, r.name_ar, r.name_en, r.direction, r.distance_km,
|
||||
r.duration_min, r.status, r.created_at,
|
||||
o.name_ar AS org_name, o.type AS org_type, o.country,
|
||||
(SELECT COUNT(*) FROM transit_stops s WHERE s.route_id = r.id) AS stops_count
|
||||
FROM transit_routes r
|
||||
JOIN transit_orgs o ON o.id = r.org_id
|
||||
WHERE r.status = 'draft'";
|
||||
|
||||
$params = [];
|
||||
if ($orgIdFilter) {
|
||||
$sql .= " AND r.org_id = ?";
|
||||
$params[] = $orgIdFilter;
|
||||
}
|
||||
$sql .= " ORDER BY r.created_at DESC LIMIT 100";
|
||||
|
||||
$st = $transit_con->prepare($sql);
|
||||
$st->execute($params);
|
||||
$routes = $st->fetchAll();
|
||||
|
||||
// جلب محطات كل خط للمعاينة
|
||||
$stStops = $transit_con->prepare(
|
||||
"SELECT id, sequence, name_ar, latitude, longitude, is_major
|
||||
FROM transit_stops WHERE route_id=? ORDER BY sequence ASC"
|
||||
);
|
||||
foreach ($routes as &$r) {
|
||||
$stStops->execute([$r['id']]);
|
||||
$r['stops'] = $stStops->fetchAll();
|
||||
}
|
||||
unset($r);
|
||||
|
||||
jsonSuccess(['routes' => $routes, 'total' => count($routes)]);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
/**
|
||||
* dashboard_data.php
|
||||
* API موحّد للداشبورد التحليلي — يقرأ من ملفات JSON المؤرشفة + بيانات حيّة من Redis.
|
||||
*
|
||||
* Parameters:
|
||||
* date (optional) — YYYY-MM-DD, default: today
|
||||
* section (optional) — realtime|gap|heatmap|pricing|revenue|growth|market|complaints|funnel|hourly|weekly|zones|retention|all
|
||||
* default: all
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../../../connect.php';
|
||||
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
http_response_code(403);
|
||||
echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$requestedDate = filterRequest('date') ?: date('Y-m-d');
|
||||
$section = filterRequest('section') ?: 'all';
|
||||
|
||||
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $requestedDate)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['status' => 'error', 'message' => 'Invalid date format']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$cacheBase = __DIR__ . '/../../../cache/analytics';
|
||||
$dayDir = "$cacheBase/$requestedDate";
|
||||
|
||||
$response = [
|
||||
'status' => 'success',
|
||||
'date' => $requestedDate,
|
||||
'section' => $section,
|
||||
'data' => [],
|
||||
];
|
||||
|
||||
function loadSnapshot(string $dir, string $name): ?array {
|
||||
$path = "$dir/$name.json";
|
||||
if (!file_exists($path)) return null;
|
||||
$data = json_decode(file_get_contents($path), true);
|
||||
return is_array($data) ? $data : null;
|
||||
}
|
||||
|
||||
function loadLatestRealtime(string $dir): ?array {
|
||||
$files = glob("$dir/realtime_*.json");
|
||||
if (empty($files)) return null;
|
||||
sort($files);
|
||||
$latest = end($files);
|
||||
$data = json_decode(file_get_contents($latest), true);
|
||||
return is_array($data) ? $data : null;
|
||||
}
|
||||
|
||||
$sectionMap = [
|
||||
'realtime' => fn() => loadLatestRealtime($dayDir),
|
||||
'gap' => fn() => loadSnapshot($dayDir, 'supply_demand_gap'),
|
||||
'heatmap' => fn() => loadSnapshot($dayDir, 'heatmap'),
|
||||
'pricing' => fn() => loadSnapshot($dayDir, 'pricing_grids'),
|
||||
'demand' => fn() => loadSnapshot($dayDir, 'predictive_demand'),
|
||||
'revenue' => fn() => loadSnapshot($dayDir, 'revenue_30d'),
|
||||
'growth' => fn() => loadSnapshot($dayDir, 'growth_30d'),
|
||||
'market' => fn() => loadSnapshot($dayDir, 'market_health'),
|
||||
'complaints' => fn() => loadSnapshot($dayDir, 'complaints_open'),
|
||||
'funnel' => fn() => loadSnapshot($dayDir, 'ride_funnel'),
|
||||
'hourly' => fn() => loadSnapshot($dayDir, 'hourly_pattern'),
|
||||
'weekly' => fn() => loadSnapshot($dayDir, 'weekly_comparison'),
|
||||
'zones' => fn() => loadSnapshot($dayDir, 'top_zones'),
|
||||
'retention' => fn() => loadSnapshot($dayDir, 'retention_cohort'),
|
||||
'competitor' => fn() => loadSnapshot($dayDir, 'competitor_prices_24h'),
|
||||
];
|
||||
|
||||
try {
|
||||
if (!is_dir($dayDir)) {
|
||||
$response['data'] = null;
|
||||
$response['note'] = "No snapshot data for $requestedDate";
|
||||
|
||||
$indexPath = "$cacheBase/index.json";
|
||||
if (file_exists($indexPath)) {
|
||||
$idx = json_decode(file_get_contents($indexPath), true);
|
||||
$response['available_dates'] = $idx['available_dates'] ?? [];
|
||||
}
|
||||
|
||||
echo json_encode($response, JSON_UNESCAPED_UNICODE);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($section === 'all') {
|
||||
foreach ($sectionMap as $key => $loader) {
|
||||
$result = $loader();
|
||||
if ($result !== null) {
|
||||
$response['data'][$key] = $result;
|
||||
}
|
||||
}
|
||||
} elseif (isset($sectionMap[$section])) {
|
||||
$response['data'] = $sectionMap[$section]();
|
||||
} else {
|
||||
http_response_code(400);
|
||||
echo json_encode([
|
||||
'status' => 'error',
|
||||
'message' => "Unknown section: $section",
|
||||
'available' => array_keys($sectionMap),
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$indexPath = "$cacheBase/index.json";
|
||||
if (file_exists($indexPath)) {
|
||||
$idx = json_decode(file_get_contents($indexPath), true);
|
||||
$response['available_dates'] = $idx['available_dates'] ?? [];
|
||||
}
|
||||
|
||||
echo json_encode($response, JSON_UNESCAPED_UNICODE);
|
||||
|
||||
} catch (Exception $e) {
|
||||
http_response_code(500);
|
||||
error_log("[dashboard_data.php] " . $e->getMessage());
|
||||
echo json_encode(['status' => 'error', 'message' => 'Internal error']);
|
||||
}
|
||||
@@ -17,7 +17,7 @@ try {
|
||||
SUM(r.price) as total_revenue
|
||||
FROM driver d
|
||||
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
|
||||
ORDER BY completed_rides DESC
|
||||
LIMIT 10
|
||||
|
||||
@@ -17,7 +17,7 @@ try {
|
||||
SUM(price - price_for_driver) as company_profit,
|
||||
COUNT(*) as total_rides
|
||||
FROM ride
|
||||
WHERE status = 'Finished'
|
||||
WHERE LOWER(status) IN ('finished','completed')
|
||||
AND created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
|
||||
GROUP BY DATE(created_at)
|
||||
ORDER BY date ASC
|
||||
@@ -32,7 +32,7 @@ try {
|
||||
SUM(price - price_for_driver) as total_profit_all,
|
||||
AVG(price) as avg_ride_price
|
||||
FROM ride
|
||||
WHERE status = 'Finished'
|
||||
WHERE LOWER(status) IN ('finished','completed')
|
||||
AND created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
|
||||
");
|
||||
$stmt->execute();
|
||||
|
||||
@@ -17,7 +17,7 @@ try {
|
||||
SUM(r.price_for_driver) as total_earned,
|
||||
COUNT(r.id) as total_rides
|
||||
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
|
||||
HAVING total_earned > 0
|
||||
ORDER BY total_earned DESC
|
||||
|
||||
@@ -18,7 +18,7 @@ try {
|
||||
0 as cash_payments,
|
||||
0 as digital_payments
|
||||
FROM ride
|
||||
WHERE status = 'Finished'
|
||||
WHERE LOWER(status) IN ('finished','completed')
|
||||
");
|
||||
$stmt->execute();
|
||||
$stats = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
@@ -2,7 +2,14 @@
|
||||
// Admin/v2/quality/blacklist_manager.php
|
||||
require_once __DIR__ . '/../../../connect.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') {
|
||||
jsonError("Unauthorized", 403);
|
||||
|
||||
@@ -40,7 +40,7 @@ try {
|
||||
$stmt = $con->prepare("
|
||||
SELECT
|
||||
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 = 'passenger' THEN 1 ELSE 0 END) as passenger_cancellations
|
||||
FROM ride
|
||||
|
||||
@@ -26,12 +26,12 @@ try {
|
||||
$online_drivers = $stmt->fetchColumn();
|
||||
|
||||
// 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();
|
||||
$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();
|
||||
$revenue_yesterday = $stmt->fetchColumn();
|
||||
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
<?php
|
||||
// Admin/v2/security/audit_logs.php
|
||||
|
||||
// ── سجل تتبع ────────────────────────────────────────────
|
||||
$debugFile = __DIR__ . '/../../../logs/audit_debug.txt';
|
||||
$logDir = dirname($debugFile);
|
||||
if (!is_dir($logDir)) @mkdir($logDir, 0777, true);
|
||||
|
||||
@file_put_contents($debugFile, "[" . date('Y-m-d H:i:s') . "] === REQUEST START ===\n", FILE_APPEND);
|
||||
// كان هنا تتبّع تشخيصي يكتب ملفاً نصياً على القرص مع كل طلب، ويسجّل فيه
|
||||
// user_id والدور. أُزيل: يراكم ملفاً بلا حد في الإنتاج ويسرّب سياق الجلسة.
|
||||
// ما يستحق التسجيل يذهب إلى error_log مع الأخطاء وحدها.
|
||||
|
||||
try {
|
||||
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) {
|
||||
@file_put_contents($debugFile, " → Loading FAILED: " . $e->getMessage() . "\n", FILE_APPEND);
|
||||
error_log('[audit_logs] bootstrap failed: ' . $e->getMessage());
|
||||
http_response_code(500);
|
||||
printFailure('loading failed', 500);
|
||||
exit;
|
||||
@@ -21,7 +17,6 @@ try {
|
||||
|
||||
// ── فحص الصلاحيات ────────────────────────────────────────
|
||||
if ($role !== 'super_admin' && $role !== 'admin') {
|
||||
@file_put_contents($debugFile, " → BLOCKED: role=$role\n", FILE_APPEND);
|
||||
printFailure("Unauthorized. role=$role", 403);
|
||||
}
|
||||
|
||||
@@ -55,12 +50,11 @@ try {
|
||||
}
|
||||
|
||||
$count = count($logs);
|
||||
@file_put_contents($debugFile, " → SUCCESS: fetched $count logs\n", FILE_APPEND);
|
||||
|
||||
jsonSuccess($logs);
|
||||
|
||||
} 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);
|
||||
}
|
||||
?>
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
import os
|
||||
|
||||
# Configuration
|
||||
PROJECT_DIR = '.'
|
||||
OUTPUT_FILE = 'siro_v1_secure_latest.md'
|
||||
EXCLUDED_DIRS = {'.git', 'vendor', 'node_modules', '.gemini'}
|
||||
EXCLUDED_FILES = {OUTPUT_FILE, 'aggregate_files.py'}
|
||||
|
||||
def aggregate_files():
|
||||
with open(OUTPUT_FILE, 'w', encoding='utf-8') as outfile:
|
||||
outfile.write(f'# Siro V1 - Secure Latest Version\n\n')
|
||||
|
||||
for root, dirs, files in os.walk(PROJECT_DIR):
|
||||
# Prune excluded directories
|
||||
dirs[:] = [d for d in dirs if d not in EXCLUDED_DIRS]
|
||||
|
||||
for file in files:
|
||||
if file in EXCLUDED_FILES:
|
||||
continue
|
||||
|
||||
filepath = os.path.join(root, file)
|
||||
rel_path = os.path.relpath(filepath, PROJECT_DIR)
|
||||
|
||||
# We mainly want to include code files
|
||||
if any(file.endswith(ext) for ext in ['.php', '.sql', '.ini', '.json', '.md', '.txt', '.py', '.sh']):
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8', errors='ignore') as infile:
|
||||
content = infile.read()
|
||||
|
||||
outfile.write(f'## File: {rel_path}\n')
|
||||
outfile.write(f'```\n')
|
||||
outfile.write(content)
|
||||
outfile.write(f'\n```\n\n')
|
||||
print(f"Added: {rel_path}")
|
||||
except Exception as e:
|
||||
print(f"Could not read {rel_path}: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
aggregate_files()
|
||||
print(f"\nDone! File created: {OUTPUT_FILE}")
|
||||
@@ -1,120 +1,100 @@
|
||||
<?php
|
||||
/**
|
||||
* get_competitor_context.php
|
||||
* ──────────────────────────
|
||||
* واجهة فائقة السرعة (Ultra-Fast API)
|
||||
* تقرأ البيانات مباشرة من الـ Redis المولد عبر الـ Cron Job.
|
||||
* زمن الاستجابة: O(1).
|
||||
*/
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
require_once __DIR__ . '/../../connect.php'; // Web-safe
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
$lat = filterRequest('lat');
|
||||
$lng = filterRequest('lng');
|
||||
$countryCode = filterRequest('country_code');
|
||||
$lat = filterRequest('passenger_lat') ?: filterRequest('lat');
|
||||
$lng = filterRequest('passenger_lng') ?: filterRequest('lng');
|
||||
$country = filterRequest('country') ?: filterRequest('country_code');
|
||||
$distance = (float)(filterRequest('distance') ?: 0);
|
||||
$siroPrice = (float)(filterRequest('siro_price') ?: 0);
|
||||
|
||||
if (!$lat || !$lng || !$countryCode) {
|
||||
if (!$lat || !$lng || !$country) {
|
||||
echo json_encode(["status" => "error", "message" => "Missing parameters"]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$lat = (float)$lat;
|
||||
$lng = (float)$lng;
|
||||
$countryCode = strtoupper($countryCode);
|
||||
$countryCode = strtoupper($country);
|
||||
if ($countryCode == 'JORDAN') $countryCode = 'JO';
|
||||
if ($countryCode == 'SYRIA') $countryCode = 'SY';
|
||||
if ($countryCode == 'EGYPT') $countryCode = 'EG';
|
||||
|
||||
$avgPricePerKm = 0;
|
||||
$topComp = 'TaxiF'; // Default
|
||||
|
||||
try {
|
||||
$redis = getRedisConnection();
|
||||
$cacheJson = $redis->get('siro:cache:pricing:grids');
|
||||
if ($cacheJson) {
|
||||
$cacheData = json_decode($cacheJson, true);
|
||||
if ($cacheData && isset($cacheData['grids'])) {
|
||||
$gridSize = 0.025;
|
||||
$gLat = round($lat / $gridSize) * $gridSize;
|
||||
$gLng = round($lng / $gridSize) * $gridSize;
|
||||
$gridKey = "{$countryCode}_" . number_format($gLat, 3) . "_" . number_format($gLng, 3);
|
||||
|
||||
$grids = $cacheData['grids'];
|
||||
if (isset($grids[$gridKey])) {
|
||||
$avgPricePerKm = (float)$grids[$gridKey]['avg_price'];
|
||||
$topComp = $grids[$gridKey]['top_competitor'] ?? 'TaxiF';
|
||||
} else {
|
||||
$fallbackKey = "{$countryCode}_FALLBACK";
|
||||
if (isset($grids[$fallbackKey])) {
|
||||
$avgPricePerKm = (float)$grids[$fallbackKey]['avg_price'];
|
||||
$topComp = $grids[$fallbackKey]['top_competitor'] ?? 'TaxiF';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
echo json_encode(["status" => "error", "message" => "Redis connection failed"]);
|
||||
exit;
|
||||
// Continue with defaults if Redis fails
|
||||
}
|
||||
|
||||
if (!$cacheJson) {
|
||||
echo json_encode(["status" => "success", "data" => null, "message" => "Cache not generated yet"]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$cacheData = json_decode($cacheJson, true);
|
||||
|
||||
if (!$cacheData || !isset($cacheData['grids'])) {
|
||||
echo json_encode(["status" => "success", "data" => null, "message" => "Invalid cache data"]);
|
||||
exit;
|
||||
}
|
||||
|
||||
// محاولة إيجاد الشبكة (Grid) للراكب
|
||||
$gridSize = 0.025;
|
||||
$gLat = round($lat / $gridSize) * $gridSize;
|
||||
$gLng = round($lng / $gridSize) * $gridSize;
|
||||
$gridKey = "{$countryCode}_" . number_format($gLat, 3) . "_" . number_format($gLng, 3);
|
||||
|
||||
$grids = $cacheData['grids'];
|
||||
|
||||
if (isset($grids[$gridKey])) {
|
||||
$compData = $grids[$gridKey];
|
||||
} else {
|
||||
// إذا لم نجد، نستخدم الـ Fallback للدولة
|
||||
$fallbackKey = "{$countryCode}_FALLBACK";
|
||||
if (isset($grids[$fallbackKey])) {
|
||||
$compData = $grids[$fallbackKey];
|
||||
} else {
|
||||
echo json_encode(["status" => "success", "data" => null, "message" => "No data for this region"]);
|
||||
exit;
|
||||
// If we couldn't get a price from Redis, use a smart default based on country
|
||||
if ($avgPricePerKm <= 0) {
|
||||
if ($countryCode === 'JO') {
|
||||
$avgPricePerKm = 0.35;
|
||||
$topComp = 'TaxiF';
|
||||
} else if ($countryCode === 'SY') {
|
||||
$avgPricePerKm = 4000;
|
||||
$topComp = 'Yango';
|
||||
} else if ($countryCode === 'EG') {
|
||||
$avgPricePerKm = 15;
|
||||
$topComp = 'inDrive';
|
||||
}
|
||||
}
|
||||
|
||||
$avgPrice = $compData['avg_price'];
|
||||
$topComp = $compData['top_competitor'] ?? 'Other';
|
||||
// Calculate the competitor's total price based on distance and average market per-km rate
|
||||
// 🔥 لا يوجد أي تعديل صناعي على سعر المنافس هنا — الرقم المعروض للراكب
|
||||
// يجب أن يعكس بيانات السوق الحقيقية فقط، حتى لو لم نكن أرخص فعلياً في هذه الرحلة.
|
||||
$competitorTotalPrice = round($distance * $avgPricePerKm, 2);
|
||||
|
||||
// جلب سعر Siro للمقارنة السريعة
|
||||
$sqlKazan = "SELECT (price_km + start_price) AS siro_base
|
||||
FROM kazan
|
||||
WHERE country_code = :cc AND type = 'speed'
|
||||
LIMIT 1";
|
||||
$stmtKazan = $con->prepare($sqlKazan);
|
||||
$stmtKazan->execute([':cc' => $countryCode]);
|
||||
$kazanRow = $stmtKazan->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
$siroPrice = $kazanRow ? (float)$kazanRow['siro_base'] : $avgPrice * 0.9;
|
||||
// Format the labels
|
||||
$compNameAr = 'التطبيقات الأخرى';
|
||||
|
||||
// نعرض شارة "أوفر" فقط إذا كنا أرخص فعلياً حسب البيانات الحقيقية — لا تلاعب بالأرقام
|
||||
$savingsPct = 0;
|
||||
if ($avgPrice > 0 && $siroPrice < $avgPrice) {
|
||||
$savingsPct = (($avgPrice - $siroPrice) / $avgPrice) * 100;
|
||||
$savingsLabel = null;
|
||||
if ($competitorTotalPrice > 0 && $siroPrice > 0 && $siroPrice < $competitorTotalPrice) {
|
||||
$savingsPct = (($competitorTotalPrice - $siroPrice) / $competitorTotalPrice) * 100;
|
||||
$savingsLabel = "أوفر بـ " . number_format($savingsPct, 1) . "% من $compNameAr ⚡";
|
||||
}
|
||||
|
||||
$passengerMessage = null;
|
||||
$driverMessage = null;
|
||||
$extraEarnings = 0;
|
||||
|
||||
if ($savingsPct > 2) {
|
||||
$compNameAr = match(strtolower($topComp)) {
|
||||
'careem' => 'كريم',
|
||||
'uber' => 'أوبر',
|
||||
'yallago' => 'يلا غو',
|
||||
'jenny' => 'جيني',
|
||||
default => 'التطبيقات الأخرى'
|
||||
};
|
||||
|
||||
$passengerMessage = "أوفر بـ " . number_format($savingsPct, 1) . "% من $compNameAr ⚡";
|
||||
|
||||
// قراءة نسبة عمولة سيرو ديناميكياً من الإنفيرومنت، والنسبة الافتراضية 10% إذا لم تكن موجودة
|
||||
$siroCommissionRate = (float)(getenv('SIRO_COMMISSION_' . $countryCode) ?: 0.10);
|
||||
$extraEarnings = $siroPrice * $siroCommissionRate;
|
||||
|
||||
$driverMessage = "رحلة مربحة! تكسب أكثر مقارنة بـ $compNameAr 💰";
|
||||
}
|
||||
$siroCommissionRate = 0.14; // Default 14% commission
|
||||
if ($countryCode === 'JO') $siroCommissionRate = 0.14;
|
||||
$extraEarnings = $siroPrice * $siroCommissionRate;
|
||||
$driverExtraLabel = "رحلة مربحة! تكسب أكثر مقارنة بـ $compNameAr 💰";
|
||||
|
||||
// Return exactly what Dart expects in the root JSON
|
||||
echo json_encode([
|
||||
"status" => "success",
|
||||
"data" => [
|
||||
"competitor_avg_price" => $avgPrice,
|
||||
"top_competitor" => $topComp,
|
||||
"savings_percent" => $savingsPct,
|
||||
"passenger_badge_text" => $passengerMessage,
|
||||
"driver_badge_text" => $driverMessage,
|
||||
"driver_extra_earnings" => round($extraEarnings, 2),
|
||||
"source" => "redis_cache"
|
||||
]
|
||||
"has_competitor_data" => true,
|
||||
"competitor_avg_price" => $competitorTotalPrice,
|
||||
"top_competitor" => $topComp,
|
||||
"savings_percent" => $savingsPct,
|
||||
"savings_label" => $savingsLabel,
|
||||
"driver_extra_amount" => round($extraEarnings, 2),
|
||||
"driver_extra_label" => $driverExtraLabel
|
||||
]);
|
||||
?>
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
<?php
|
||||
// ============================================================
|
||||
// create_tester_driver.php
|
||||
// Script to seed/register a pre-verified tester driver.
|
||||
// ============================================================
|
||||
|
||||
require_once __DIR__ . '/../../core/bootstrap.php';
|
||||
|
||||
$email = 'driver_tester@siromove.com';
|
||||
$phone = '+962790000002';
|
||||
$password = 'SiroDriver2026!';
|
||||
$hashedPassword = password_hash($password, PASSWORD_BCRYPT);
|
||||
|
||||
$encryptedEmail = $encryptionHelper->encryptData($email);
|
||||
$encryptedPhone = $encryptionHelper->encryptData($phone);
|
||||
$encryptedFirstName = $encryptionHelper->encryptData('Driver');
|
||||
$encryptedLastName = $encryptionHelper->encryptData('Tester');
|
||||
$encryptedGender = $encryptionHelper->encryptData('Male');
|
||||
$encryptedBirthdate = $encryptionHelper->encryptData('1990-01-01');
|
||||
$encryptedSite = $encryptionHelper->encryptData('Jordan');
|
||||
|
||||
try {
|
||||
$con = Database::get('main');
|
||||
|
||||
// 1. Check if driver exists
|
||||
$stmt = $con->prepare("SELECT id FROM driver WHERE email = :email LIMIT 1");
|
||||
$stmt->bindParam(':email', $encryptedEmail);
|
||||
$stmt->execute();
|
||||
$driver = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if ($driver) {
|
||||
$driverId = $driver['id'];
|
||||
$update = $con->prepare("UPDATE driver SET password = :password, phone = :phone WHERE id = :id");
|
||||
$update->bindParam(':password', $hashedPassword);
|
||||
$update->bindParam(':phone', $encryptedPhone);
|
||||
$update->bindParam(':id', $driverId);
|
||||
$update->execute();
|
||||
echo "Driver tester updated successfully.\n";
|
||||
} else {
|
||||
$driverId = bin2hex(random_bytes(10)); // 20 chars unique id
|
||||
$insert = $con->prepare("INSERT INTO driver (id, phone, email, password, gender, birthdate, site, first_name, last_name)
|
||||
VALUES (:id, :phone, :email, :password, :gender, :birthdate, :site, :first_name, :last_name)");
|
||||
$insert->bindParam(':id', $driverId);
|
||||
$insert->bindParam(':phone', $encryptedPhone);
|
||||
$insert->bindParam(':email', $encryptedEmail);
|
||||
$insert->bindParam(':password', $hashedPassword);
|
||||
$insert->bindParam(':gender', $encryptedGender);
|
||||
$insert->bindParam(':birthdate', $encryptedBirthdate);
|
||||
$insert->bindParam(':site', $encryptedSite);
|
||||
$insert->bindParam(':first_name', $encryptedFirstName);
|
||||
$insert->bindParam(':last_name', $encryptedLastName);
|
||||
$insert->execute();
|
||||
echo "Driver tester created successfully with ID: $driverId\n";
|
||||
}
|
||||
|
||||
// 2. Ensure phone_verification row exists
|
||||
$stmtPhone = $con->prepare("SELECT * FROM phone_verification WHERE phone_number = :phone LIMIT 1");
|
||||
$stmtPhone->bindParam(':phone', $encryptedPhone);
|
||||
$stmtPhone->execute();
|
||||
if ($stmtPhone->fetch()) {
|
||||
$updatePhone = $con->prepare("UPDATE phone_verification SET is_verified = 1 WHERE phone_number = :phone");
|
||||
$updatePhone->bindParam(':phone', $encryptedPhone);
|
||||
$updatePhone->execute();
|
||||
} else {
|
||||
$insertPhone = $con->prepare("INSERT INTO phone_verification (phone_number, is_verified) VALUES (:phone, 1)");
|
||||
$insertPhone->bindParam(':phone', $encryptedPhone);
|
||||
$insertPhone->execute();
|
||||
}
|
||||
|
||||
// 3. Ensure CarRegistration row exists
|
||||
$stmtCar = $con->prepare("SELECT * FROM CarRegistration WHERE driverID = :driverID LIMIT 1");
|
||||
$stmtCar->bindParam(':driverID', $driverId);
|
||||
$stmtCar->execute();
|
||||
if ($stmtCar->fetch()) {
|
||||
$updateCar = $con->prepare("UPDATE CarRegistration SET make = 'Toyota', model = 'Prius', year = '2020' WHERE driverID = :driverID");
|
||||
$updateCar->bindParam(':driverID', $driverId);
|
||||
$updateCar->execute();
|
||||
} else {
|
||||
$insertCar = $con->prepare("INSERT INTO CarRegistration (driverID, make, model, year) VALUES (:driverID, 'Toyota', 'Prius', '2020')");
|
||||
$insertCar->bindParam(':driverID', $driverId);
|
||||
$insertCar->execute();
|
||||
}
|
||||
|
||||
echo "Verification and Car Registration configured.\n";
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "Error: " . $e->getMessage() . "\n";
|
||||
}
|
||||
?>
|
||||
@@ -1,29 +0,0 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
$appPlatform = filterRequest("appPlatform");
|
||||
|
||||
|
||||
$sql = "SELECT
|
||||
*
|
||||
FROM
|
||||
`testApp`
|
||||
WHERE
|
||||
appPlatform = '$appPlatform'-- AND isTest = 0;";
|
||||
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->execute();
|
||||
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
if ($stmt->rowCount() > 0) {
|
||||
// Print the retrieved data
|
||||
// echo json_encode($result);
|
||||
jsonSuccess($data = $result);
|
||||
} else {
|
||||
// Print a failure message
|
||||
|
||||
jsonError($message = "No driver order data found");
|
||||
}
|
||||
|
||||
?>
|
||||
@@ -1,23 +0,0 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
$appPlatform = filterRequest("appPlatform");
|
||||
|
||||
$sql = "UPDATE
|
||||
`testApp`
|
||||
SET
|
||||
`isTest` = '1'
|
||||
WHERE
|
||||
`testApp`.appPlatform = '$appPlatform';";
|
||||
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->execute();
|
||||
|
||||
if ($stmt->rowCount() > 0) {
|
||||
// Print a success message
|
||||
jsonSuccess($message = "Test data updated successfully");
|
||||
} else {
|
||||
// Print a failure message
|
||||
jsonError($message = "Failed to update driver order data");
|
||||
}
|
||||
?>
|
||||
@@ -1,66 +0,0 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
$email = filterRequest('email');
|
||||
$phone = filterRequest('phone');
|
||||
$password = filterRequest('password');
|
||||
|
||||
// تشفير الحقول المطلوبة قبل الاستعلام
|
||||
$email = $encryptionHelper->encryptData($email);
|
||||
$phone = $encryptionHelper->encryptData($phone);
|
||||
|
||||
$sql = "SELECT
|
||||
driver.id,
|
||||
driver.phone,
|
||||
driver.email,
|
||||
driver.password,
|
||||
driver.gender,
|
||||
driver.birthdate,
|
||||
driver.site,
|
||||
driver.first_name,
|
||||
driver.last_name,
|
||||
driver.education,
|
||||
driver.employmentType,
|
||||
driver.maritalStatus,
|
||||
driver.created_at,
|
||||
driver.updated_at,
|
||||
email_verifications.verified
|
||||
FROM
|
||||
driver
|
||||
LEFT JOIN email_verifications ON email_verifications.email = driver.email
|
||||
WHERE
|
||||
driver.phone = :phone AND driver.email = :email";
|
||||
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->bindParam(':email', $email);
|
||||
$stmt->bindParam(':phone', $phone);
|
||||
$stmt->execute();
|
||||
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
$count = $stmt->rowCount();
|
||||
|
||||
if ($count > 0) {
|
||||
$stored_password = $data[0]['password'];
|
||||
if (password_verify($password, $stored_password)) {
|
||||
|
||||
// فك التشفير للحقول الحساسة
|
||||
$data[0]['phone'] = $encryptionHelper->decryptData($data[0]['phone']);
|
||||
$data[0]['email'] = $encryptionHelper->decryptData($data[0]['email']);
|
||||
$data[0]['gender'] = $encryptionHelper->decryptData($data[0]['gender']);
|
||||
$data[0]['birthdate'] = $encryptionHelper->decryptData($data[0]['birthdate']);
|
||||
$data[0]['site'] = $encryptionHelper->decryptData($data[0]['site']);
|
||||
$data[0]['first_name'] = $encryptionHelper->decryptData($data[0]['first_name']);
|
||||
$data[0]['last_name'] = $encryptionHelper->decryptData($data[0]['last_name']);
|
||||
$data[0]['education'] = $encryptionHelper->decryptData($data[0]['education']);
|
||||
$data[0]['employmentType'] = $encryptionHelper->decryptData($data[0]['employmentType']);
|
||||
$data[0]['maritalStatus'] = $encryptionHelper->decryptData($data[0]['maritalStatus']);
|
||||
|
||||
unset($data[0]['password']); // لا نرجّع الباسورد
|
||||
jsonSuccess($data);
|
||||
} else {
|
||||
jsonError("Incorrect password.");
|
||||
}
|
||||
} else {
|
||||
jsonError("User does not exist.");
|
||||
}
|
||||
?>
|
||||
@@ -1,181 +0,0 @@
|
||||
<?php
|
||||
// ============================================================
|
||||
// loginUsingCredentialsWithoutGoogle.php
|
||||
// مخصص لدخول الفاحصين (Testers) بالإيميل والباسورد
|
||||
// ============================================================
|
||||
|
||||
require_once __DIR__ . '/../../core/bootstrap.php';
|
||||
|
||||
$email = filterRequest('email');
|
||||
$password = filterRequest('password');
|
||||
$audience = filterRequest('aud') ?? 'siro-driver-android'; // الافتراضي
|
||||
$fingerprint = filterRequest('fingerPrint') ?? filterRequest('fingerprint');
|
||||
|
||||
// 1. تطبيق حد معدل الطلبات (Rate Limiting) للفاحصين: 3 محاولات بالدقيقة لكل IP
|
||||
$rateLimiter = new RateLimiter($redis);
|
||||
$rateLimiter->enforce(RateLimiter::identifier(), 'tester_login');
|
||||
|
||||
if (!$email || !$password) {
|
||||
echo json_encode(["status" => "failure", "message" => "Email and password are required"]);
|
||||
exit();
|
||||
}
|
||||
|
||||
// 2. التحقق من أن الحساب مخصص للفحص فقط (isTest check)
|
||||
$allowedTesterEmailsEnv = getenv('ALLOWED_TESTER_EMAILS') ?: '';
|
||||
$allowedEmails = array_filter(array_map('trim', explode(',', $allowedTesterEmailsEnv)));
|
||||
if (empty($allowedEmails)) {
|
||||
$allowedEmails = [
|
||||
'driver_tester@siromove.com',
|
||||
'passenger_tester@siromove.com',
|
||||
];
|
||||
}
|
||||
|
||||
$cleanEmail = strtolower(trim($email));
|
||||
$isTester = in_array($cleanEmail, $allowedEmails) ||
|
||||
substr($cleanEmail, -13) === '@siromove.com' ||
|
||||
str_contains($cleanEmail, 'tester') ||
|
||||
str_contains($cleanEmail, 'reviewer');
|
||||
|
||||
// تشفير الإيميل لاستخدامه في الاستعلام
|
||||
$encryptedEmail = $encryptionHelper->encryptData($email);
|
||||
|
||||
try {
|
||||
$con = Database::get('main');
|
||||
|
||||
// Auto-seed/create tester driver if it doesn't exist
|
||||
if ($cleanEmail === 'driver_tester@siromove.com') {
|
||||
$stmtCheck = $con->prepare("SELECT id FROM driver WHERE email = :email LIMIT 1");
|
||||
$stmtCheck->bindParam(':email', $encryptedEmail);
|
||||
$stmtCheck->execute();
|
||||
if (!$stmtCheck->fetch()) {
|
||||
$driverId = 'tester_driver_id_2026';
|
||||
$phone = '+962790000002';
|
||||
$hashedPassword = password_hash('SiroDriver2026!', PASSWORD_DEFAULT);
|
||||
|
||||
$encryptedPhone = $encryptionHelper->encryptData($phone);
|
||||
$encryptedFirstName = $encryptionHelper->encryptData('Driver');
|
||||
$encryptedLastName = $encryptionHelper->encryptData('Tester');
|
||||
$encryptedGender = $encryptionHelper->encryptData('Male');
|
||||
$encryptedBirthdate = $encryptionHelper->encryptData('1990-01-01');
|
||||
$encryptedSite = $encryptionHelper->encryptData('Jordan');
|
||||
|
||||
// Insert driver
|
||||
$insert = $con->prepare("INSERT INTO driver (id, phone, email, password, gender, birthdate, site, first_name, last_name)
|
||||
VALUES (:id, :phone, :email, :password, :gender, :birthdate, :site, :first_name, :last_name)");
|
||||
$insert->execute([
|
||||
':id' => $driverId,
|
||||
':phone' => $encryptedPhone,
|
||||
':email' => $encryptedEmail,
|
||||
':password' => $hashedPassword,
|
||||
':gender' => $encryptedGender,
|
||||
':birthdate' => $encryptedBirthdate,
|
||||
':site' => $encryptedSite,
|
||||
':first_name' => $encryptedFirstName,
|
||||
':last_name' => $encryptedLastName
|
||||
]);
|
||||
|
||||
// Ensure phone_verification row exists
|
||||
$stmtPhone = $con->prepare("SELECT * FROM phone_verification WHERE phone_number = :phone LIMIT 1");
|
||||
$stmtPhone->bindParam(':phone', $encryptedPhone);
|
||||
$stmtPhone->execute();
|
||||
if (!$stmtPhone->fetch()) {
|
||||
$insertPhone = $con->prepare("INSERT INTO phone_verification (phone_number, is_verified) VALUES (:phone, 1)");
|
||||
$insertPhone->bindParam(':phone', $encryptedPhone);
|
||||
$insertPhone->execute();
|
||||
} else {
|
||||
$updatePhone = $con->prepare("UPDATE phone_verification SET is_verified = 1 WHERE phone_number = :phone");
|
||||
$updatePhone->bindParam(':phone', $encryptedPhone);
|
||||
$updatePhone->execute();
|
||||
}
|
||||
|
||||
// Ensure CarRegistration row exists
|
||||
$stmtCar = $con->prepare("SELECT * FROM CarRegistration WHERE driverID = :driverID LIMIT 1");
|
||||
$stmtCar->bindParam(':driverID', $driverId);
|
||||
$stmtCar->execute();
|
||||
if (!$stmtCar->fetch()) {
|
||||
$insertCar = $con->prepare("INSERT INTO CarRegistration (driverID, vin, car_plate, make, model, year, expiration_date, color, owner, color_hex, fuel)
|
||||
VALUES (:driverID, :vin, :car_plate, 'Toyota', 'Prius', 2020, '2030-01-01', 'White', :owner, '#FFFFFF', 'Petrol')");
|
||||
$encryptedVin = $encryptionHelper->encryptData('TESTVIN1234567890');
|
||||
$encryptedPlate = $encryptionHelper->encryptData('155186');
|
||||
$encryptedOwner = $encryptionHelper->encryptData('Driver Tester');
|
||||
$insertCar->execute([
|
||||
':driverID' => $driverId,
|
||||
':vin' => $encryptedVin,
|
||||
':car_plate' => $encryptedPlate,
|
||||
':owner' => $encryptedOwner
|
||||
]);
|
||||
} else {
|
||||
$updateCar = $con->prepare("UPDATE CarRegistration SET make = 'Toyota', model = 'Prius', year = 2020 WHERE driverID = :driverID");
|
||||
$updateCar->bindParam(':driverID', $driverId);
|
||||
$updateCar->execute();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SQL لاسترجاع المستخدم بناءً على البريد الإلكتروني المشفر
|
||||
$sql = "SELECT
|
||||
driver.*,
|
||||
phone_verification.is_verified,
|
||||
CarRegistration.make,
|
||||
CarRegistration.model,
|
||||
CarRegistration.year
|
||||
FROM driver
|
||||
LEFT JOIN phone_verification ON phone_verification.phone_number = driver.phone
|
||||
LEFT JOIN CarRegistration ON CarRegistration.driverID = driver.id
|
||||
WHERE
|
||||
driver.email = :email
|
||||
LIMIT 1";
|
||||
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->bindParam(':email', $encryptedEmail);
|
||||
$stmt->execute();
|
||||
|
||||
$data = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if ($data) {
|
||||
// التحقق من أن الحساب معلم كحساب فحص في قاعدة البيانات أو البيئة
|
||||
$isTestInDb = (isset($data['is_test']) && $data['is_test'] == 1) || (isset($data['isTest']) && $data['isTest'] == 1);
|
||||
if (!$isTestInDb && !$isTester) {
|
||||
jsonError("Access denied. Not a tester account.");
|
||||
exit();
|
||||
}
|
||||
// فحص الباسورد (في نظامنا، يمكن أن يكون الباسورد هو HMAC أو نص عادي للفاحصين)
|
||||
// لنفترض أن الفاحص له باسورد عادي أو مشفر بـ bcrypt
|
||||
if (password_verify($password, $data['password']) || $password === $data['password']) {
|
||||
unset($data['password']);
|
||||
|
||||
// فك تشفير الحقول الحساسة
|
||||
$data['phone'] = $encryptionHelper->decryptData($data['phone']);
|
||||
$data['email'] = $encryptionHelper->decryptData($data['email']);
|
||||
$data['gender'] = $encryptionHelper->decryptData($data['gender']);
|
||||
$data['birthdate'] = $encryptionHelper->decryptData($data['birthdate']);
|
||||
$data['site'] = $encryptionHelper->decryptData($data['site']);
|
||||
$data['first_name'] = $encryptionHelper->decryptData($data['first_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);
|
||||
$jwt = $jwtService->generateAccessToken($data['id'], 'tester', $audience, $fingerprint);
|
||||
|
||||
echo json_encode([
|
||||
"status" => "success",
|
||||
"jwt" => $jwt,
|
||||
"data" => [$data] // مطابق لنسق التطبيق الذي يتوقع مصفوفة
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
} else {
|
||||
jsonError("Incorrect password.");
|
||||
}
|
||||
} else {
|
||||
jsonError("User does not exist.");
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
error_log("[Tester Login Error] " . $e->getMessage());
|
||||
jsonError("Server error occurred.");
|
||||
} finally {
|
||||
$stmt = null;
|
||||
$con = null;
|
||||
}
|
||||
exit();
|
||||
?>
|
||||
@@ -1,39 +0,0 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/../connect.php';
|
||||
|
||||
// استقبال القيم
|
||||
$phoneNumber = filterRequest("phone_number");
|
||||
$email = filterRequest("email");
|
||||
|
||||
// تشفير القيم المطلوبة للمقارنة داخل SQL
|
||||
$phoneNumber = $encryptionHelper->encryptData($phoneNumber);
|
||||
$email = $encryptionHelper->encryptData($email);
|
||||
|
||||
// تنفيذ الاستعلام
|
||||
$sql = "
|
||||
SELECT
|
||||
pv.*,
|
||||
p.email
|
||||
FROM
|
||||
`phone_verification_passenger` pv
|
||||
INNER JOIN
|
||||
`passengers` p ON pv.phone_number = p.phone
|
||||
WHERE
|
||||
pv.phone_number = :phoneNumber AND p.email = :email
|
||||
";
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->bindParam(':phoneNumber', $phoneNumber, PDO::PARAM_STR);
|
||||
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
|
||||
$stmt->execute();
|
||||
|
||||
if ($stmt->rowCount() > 0) {
|
||||
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
// يمكنك هنا لاحقًا تفكيك تشفير أي حقل إذا كنت ترجع phone/email مثلاً للمستخدم، لكن في حالتنا ما في حاجة.
|
||||
|
||||
jsonSuccess($rows);
|
||||
} else {
|
||||
jsonError("No Phone verified or related email found");
|
||||
}
|
||||
?>
|
||||
+2
-2
@@ -1,10 +1,10 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/../connect.php';
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
// استقبال وتشفير رقم الهاتف
|
||||
$phoneNumber = filterRequest("phone_number");
|
||||
$phoneNumber = $encryptionHelper->encryptData($phoneNumber);
|
||||
$phoneNumber = otpPhoneKey($phoneNumber);
|
||||
|
||||
// تجهيز الاستعلام باستخدام bindParam للحماية
|
||||
$sql = "SELECT * FROM `phone_verification` WHERE `phone_number` = :phone_number";
|
||||
+19
-2
@@ -1,7 +1,24 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../../../connect.php';
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
$driverId = filterRequest("id");
|
||||
// 🔥 [Fix Broken Access Control] كان يتحقق من صلاحية التوكن فقط — أي مستخدم
|
||||
// مسجّل دخول (راكب/سائق آخر) كان يقدر يجلب بيانات أي سائق مفكوكة التشفير
|
||||
// (هوية وطنية، هاتف، عنوان...) بالإضافة لروابط وثائقه الشخصية.
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
http_response_code(403);
|
||||
echo json_encode(['error' => 'Unauthorized access. Admin role required.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// 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)) {
|
||||
jsonError("driver_id is required.");
|
||||
+13
-1
@@ -1,5 +1,17 @@
|
||||
<?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] كان يتحقق من صلاحية التوكن فقط بدون التحقق
|
||||
// من الدور — أي توكن صالح (حتى راكب) كان يقدر يسحب قائمة السائقين المعلّقين
|
||||
// وبياناتهم الشخصية المفكوكة التشفير.
|
||||
if ($role !== 'admin' && $role !== 'super_admin') {
|
||||
http_response_code(403);
|
||||
echo json_encode(['error' => 'Unauthorized access. Admin role required.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$limit = isset($_POST['limit']) ? (int)$_POST['limit'] : (isset($_GET['limit']) ? (int)$_GET['limit'] : 10);
|
||||
$offset = isset($_POST['offset']) ? (int)$_POST['offset'] : (isset($_GET['offset']) ? (int)$_GET['offset'] : 0);
|
||||
+2
-2
@@ -1,10 +1,10 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../../../connect.php';
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
$phoneNumber = filterRequest("phone_number");
|
||||
|
||||
// تشفير الرقم قبل البحث
|
||||
$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
|
||||
$phoneNumber_encrypted = otpPhoneKey($phoneNumber);
|
||||
|
||||
try {
|
||||
// الاستعلام عن السائق حسب رقم الهاتف وحالة التحقق
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
global $blindIndex;
|
||||
|
||||
$email = filterRequest('email');
|
||||
$phone = filterRequest('phone');
|
||||
$password = filterRequest('password');
|
||||
|
||||
if (empty($phone) && empty($email)) {
|
||||
jsonError("Phone or email is required.");
|
||||
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
|
||||
driver.id,
|
||||
driver.phone,
|
||||
driver.email,
|
||||
driver.password,
|
||||
driver.gender,
|
||||
driver.birthdate,
|
||||
driver.site,
|
||||
driver.first_name,
|
||||
driver.last_name,
|
||||
driver.education,
|
||||
driver.employmentType,
|
||||
driver.maritalStatus,
|
||||
driver.created_at,
|
||||
driver.updated_at,
|
||||
driver.email AS _email_enc
|
||||
FROM
|
||||
driver
|
||||
WHERE
|
||||
$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->execute($params);
|
||||
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
$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) {
|
||||
$stored_password = $data[0]['password'];
|
||||
if (password_verify($password, $stored_password)) {
|
||||
|
||||
// فك التشفير للحقول الحساسة
|
||||
$data[0]['phone'] = $encryptionHelper->decryptData($data[0]['phone']);
|
||||
$data[0]['email'] = $encryptionHelper->decryptData($data[0]['email']);
|
||||
$data[0]['gender'] = $encryptionHelper->decryptData($data[0]['gender']);
|
||||
$data[0]['birthdate'] = $encryptionHelper->decryptData($data[0]['birthdate']);
|
||||
$data[0]['site'] = $encryptionHelper->decryptData($data[0]['site']);
|
||||
$data[0]['first_name'] = $encryptionHelper->decryptData($data[0]['first_name']);
|
||||
$data[0]['last_name'] = $encryptionHelper->decryptData($data[0]['last_name']);
|
||||
$data[0]['education'] = $encryptionHelper->decryptData($data[0]['education']);
|
||||
$data[0]['employmentType'] = $encryptionHelper->decryptData($data[0]['employmentType']);
|
||||
$data[0]['maritalStatus'] = $encryptionHelper->decryptData($data[0]['maritalStatus']);
|
||||
|
||||
unset($data[0]['password']); // لا نرجّع الباسورد
|
||||
jsonSuccess($data);
|
||||
} else {
|
||||
jsonError("Incorrect password.");
|
||||
}
|
||||
} else {
|
||||
jsonError("User does not exist.");
|
||||
}
|
||||
?>
|
||||
@@ -23,7 +23,7 @@ try {
|
||||
CarRegistration.make, CarRegistration.model, CarRegistration.year,
|
||||
df.is_claimed, inv.isInstall, inv.isGiftToken
|
||||
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 CarRegistration ON CarRegistration.driverID = driver.id
|
||||
LEFT JOIN invites inv ON inv.driverId = driver.id
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
// ============================================================
|
||||
// loginUsingCredentialsWithoutGoogle.php
|
||||
// مخصص لدخول الفاحصين (Testers) بالإيميل والباسورد
|
||||
// ============================================================
|
||||
|
||||
require_once __DIR__ . '/../../core/bootstrap.php';
|
||||
|
||||
$email = filterRequest('email');
|
||||
$password = filterRequest('password');
|
||||
$audience = filterRequest('aud') ?? 'siro-driver-android'; // الافتراضي
|
||||
$fingerprint = filterRequest('fingerPrint') ?? filterRequest('fingerprint');
|
||||
|
||||
// 1. حد معدل الطلبات مطبّق على الجميع (الحد مرفوع إلى 30/دقيقة في RateLimiter)
|
||||
$rateLimiter = new RateLimiter($redis);
|
||||
$rateLimiter->enforce(RateLimiter::identifier(), 'tester_login');
|
||||
|
||||
// 2. قائمة بيضاء صريحة لحسابات الفحص — مطابقة تامة فقط، لا مطابقة جزئية ولا مطابقة نطاق
|
||||
$allowedTesterEmailsEnv = getenv('ALLOWED_TESTER_EMAILS') ?: ($_ENV['ALLOWED_TESTER_EMAILS'] ?? '');
|
||||
$allowedEmails = array_filter(array_map(
|
||||
fn($e) => strtolower(trim($e)),
|
||||
explode(',', $allowedTesterEmailsEnv)
|
||||
));
|
||||
if (empty($allowedEmails)) {
|
||||
$allowedEmails = [
|
||||
'driver_tester@siromove.com',
|
||||
'passenger_tester@siromove.com',
|
||||
];
|
||||
}
|
||||
|
||||
$cleanEmail = strtolower(trim((string) $email));
|
||||
$isTester = in_array($cleanEmail, $allowedEmails, true);
|
||||
|
||||
if (!$email || !$password) {
|
||||
echo json_encode(["status" => "failure", "message" => "Email and password are required"]);
|
||||
exit();
|
||||
}
|
||||
|
||||
try {
|
||||
$con = Database::get('main');
|
||||
|
||||
$encryptedEmail = $encryptionHelper->encryptData($email);
|
||||
global $blindIndex;
|
||||
$emailBidx = $blindIndex ? $blindIndex->index('driver.email', $email) : null;
|
||||
|
||||
$sql = "SELECT
|
||||
driver.*,
|
||||
phone_verification.is_verified,
|
||||
CarRegistration.make,
|
||||
CarRegistration.model,
|
||||
CarRegistration.year
|
||||
FROM driver
|
||||
LEFT JOIN phone_verification ON phone_verification.phone_number = driver.phone_key
|
||||
LEFT JOIN CarRegistration ON CarRegistration.driverID = driver.id
|
||||
WHERE driver.email = :email";
|
||||
|
||||
$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->execute($params);
|
||||
|
||||
$data = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if ($data) {
|
||||
$isTestInDb = (isset($data['is_test']) && $data['is_test'] == 1) || (isset($data['isTest']) && $data['isTest'] == 1);
|
||||
if (!$isTestInDb && !$isTester) {
|
||||
jsonError("Access denied. Not a tester account.");
|
||||
exit();
|
||||
}
|
||||
|
||||
if (password_verify($password, $data['password'] ?? '')) {
|
||||
unset($data['password']);
|
||||
|
||||
if(isset($data['phone'])) $data['phone'] = $encryptionHelper->decryptData($data['phone']);
|
||||
if(isset($data['email'])) $data['email'] = $encryptionHelper->decryptData($data['email']);
|
||||
if(isset($data['gender'])) $data['gender'] = $encryptionHelper->decryptData($data['gender']);
|
||||
if(isset($data['birthdate'])) $data['birthdate'] = $encryptionHelper->decryptData($data['birthdate']);
|
||||
if(isset($data['site'])) $data['site'] = $encryptionHelper->decryptData($data['site']);
|
||||
if(isset($data['first_name'])) $data['first_name'] = $encryptionHelper->decryptData($data['first_name']);
|
||||
if(isset($data['last_name'])) $data['last_name'] = $encryptionHelper->decryptData($data['last_name']);
|
||||
|
||||
$jwtService = new JwtService($redis);
|
||||
$jwt = $jwtService->generateAccessToken($data['id'], 'tester', $audience, $fingerprint);
|
||||
|
||||
echo json_encode([
|
||||
"status" => "success",
|
||||
"jwt" => $jwt,
|
||||
"data" => [$data]
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
} else {
|
||||
jsonError("Incorrect password.");
|
||||
}
|
||||
} else {
|
||||
jsonError("User does not exist.");
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
error_log("[Tester Login Error] " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine());
|
||||
jsonError("Server error occurred: " . $e->getMessage() . " in " . basename($e->getFile()) . ":" . $e->getLine());
|
||||
} finally {
|
||||
$stmt = null;
|
||||
$con = null;
|
||||
}
|
||||
exit();
|
||||
?>
|
||||
+58
-6
@@ -7,9 +7,14 @@
|
||||
*/
|
||||
//register_driver_and_car.php
|
||||
$allowRegistration = true;
|
||||
require_once __DIR__ . '/../../../connect.php';
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
// Rate Limiting: الحماية من التسجيل العشوائي وهجمات الـ Bots
|
||||
$rateLimiter = new RateLimiter($redis);
|
||||
$rateLimiter->enforce(RateLimiter::identifier(), 'register_driver');
|
||||
|
||||
|
||||
try {
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
jsonError("Invalid method.");
|
||||
@@ -120,6 +125,25 @@ try {
|
||||
}
|
||||
/* ================== 🔴 END PHONE FORMATTING LOGIC 🔴 ================== */
|
||||
|
||||
// ======================================================
|
||||
// Step 1.5: التحقق الفعلي من ملكية رقم الهاتف قبل إكمال المعالجة (سد الثغرة)
|
||||
// ======================================================
|
||||
require_once __DIR__ . '/../../core/Security/EncryptionHelper.php';
|
||||
$tempEncryptionHelper = new EncryptionHelper($redis);
|
||||
$phoneNumber_encrypted_check = $tempEncryptionHelper->encryptData($data['phone']);
|
||||
|
||||
$verifyCheckStmt = $con->prepare(
|
||||
"SELECT id FROM phone_verification_driver
|
||||
WHERE phone_number = ? AND verified = 1 AND created_at > DATE_SUB(NOW(), INTERVAL 30 MINUTE)
|
||||
LIMIT 1"
|
||||
);
|
||||
$verifyCheckStmt->execute([$phoneNumber_encrypted_check]);
|
||||
if ($verifyCheckStmt->rowCount() === 0) {
|
||||
error_log("[Register_Debug_driver] Error: Phone number not verified via OTP.");
|
||||
jsonError("Phone number must be verified before registration.");
|
||||
exit();
|
||||
}
|
||||
// ======================================================
|
||||
|
||||
// تجهيز تاريخ الميلاد قبل التشفير
|
||||
if (!empty($data['birthdate'])) {
|
||||
@@ -359,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);
|
||||
|
||||
/* ================== 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 = [
|
||||
"phone","email","first_name","last_name","name_arabic","gender",
|
||||
"national_number","address","site","fullNameMaritial","birthdate"
|
||||
@@ -378,8 +414,18 @@ Therefore, do NOT assume a specific field is on the front or the back of a card.
|
||||
$con->beginTransaction();
|
||||
|
||||
/* ================== 6) Check duplicate ================== */
|
||||
$dup = $con->prepare("SELECT id FROM driver WHERE phone = :p OR email = :e");
|
||||
$dup->execute([':p' => $data['phone'], ':e' => $data['email']]);
|
||||
$dup = $con->prepare(
|
||||
"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) {
|
||||
$con->rollBack();
|
||||
jsonError("Phone or email already registered.");
|
||||
@@ -394,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,
|
||||
first_name, last_name, accountBank, bankCode,
|
||||
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 (
|
||||
:id, :phone, :email, :pwd, :gender, :license_type, :national_number,
|
||||
:name_arabic, :issue_date, :expiry_date, :license_categories,
|
||||
:address, :licenseIssueDate, :status, :birthdate, :site,
|
||||
:first_name, :last_name, :accountBank, :bankCode,
|
||||
: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);
|
||||
@@ -432,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',
|
||||
':fullNameMaritial' => !empty($data['fullNameMaritial']) ? $data['fullNameMaritial'] : 'yet',
|
||||
':expirationDate' => !empty($data['expirationDate']) ? $data['expirationDate'] : 'yet',
|
||||
':phone_bidx' => $phoneBidx,
|
||||
':email_bidx' => $emailBidx,
|
||||
':name_bidx' => $nameBidx,
|
||||
':phone_key' => $phoneKey,
|
||||
]);
|
||||
if (!$okD) {
|
||||
$con->rollBack();
|
||||
@@ -528,7 +580,7 @@ Therefore, do NOT assume a specific field is on the front or the back of a card.
|
||||
|
||||
/* ================== 11) Notification ================== */
|
||||
try {
|
||||
$fcmSendUrl = 'https://api.intaleq.xyz/siro/ride/firebase/send_fcm.php';
|
||||
$fcmSendUrl = getenv('FCM_ENDPOINT_URL') ?: 'http://nginx/backend/ride/firebase/send_fcm.php';
|
||||
|
||||
$driverFullName = $raw_first_name . ' ' . $raw_last_name;
|
||||
$notificationTitle = 'تسجيل سائق جديد';
|
||||
+2
-2
@@ -51,8 +51,8 @@ $sentOK = ($httpCode === 200 && ($decoded['success'] ?? false));
|
||||
|
||||
if ($sentOK) {
|
||||
/* 3) تشفير البيانات وحفظها في DB ----------------------------------- */
|
||||
$receiver_enc = $encryptionHelper->encryptData($receiver);
|
||||
$otp_enc = $encryptionHelper->encryptData($otp);
|
||||
$receiver_enc = otpPhoneKey($receiver);
|
||||
$otp_enc = otpPhoneKey($otp); // يجب أن يطابق صيغة المقارنة في verify_otp
|
||||
|
||||
$exp = date('Y-m-d H:i:s', strtotime('+5 minutes'));
|
||||
$now = date('Y-m-d H:i:s');
|
||||
+3
-2
@@ -9,8 +9,9 @@ if (empty($phoneNumber) || empty($otp)) {
|
||||
exit();
|
||||
}
|
||||
|
||||
$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
|
||||
$otp_encrypted = $encryptionHelper->encryptData($otp);
|
||||
$phoneNumber_encrypted = otpPhoneKey($phoneNumber);
|
||||
// الرمز يُقارن بالتساوي أيضاً، فيحتاج نفس الصيغة الثابتة
|
||||
$otp_encrypted = otpPhoneKey($otp);
|
||||
|
||||
try {
|
||||
$stmt = $con->prepare("
|
||||
+51
-3
@@ -11,16 +11,39 @@ if (empty($phone) && empty($email)) {
|
||||
exit;
|
||||
}
|
||||
|
||||
// Build WHERE dynamically: support phone-only, email-only, or both
|
||||
/**
|
||||
* البحث عن الحساب.
|
||||
*
|
||||
* سابقاً كان يقارن القيمة الخام بالعمود المشفّر مباشرةً، وهو ما ينجح فقط لأن
|
||||
* التشفير الحالي حتمي (CBC بـ IV ثابت). الفهرس الأعمى يجعل هذا الاستعلام
|
||||
* مستقلاً عن أسلوب التشفير، فلا ينكسر تسجيل الدخول عند الانتقال إلى AES-GCM.
|
||||
*
|
||||
* تُبقى المقارنتان القديمتان في نفس الشرط كاحتياط للحسابات التي لم تُفهرس بعد.
|
||||
*/
|
||||
global $blindIndex;
|
||||
|
||||
$conditions = [];
|
||||
$params = [':password' => $password];
|
||||
|
||||
if (!empty($phone)) {
|
||||
$conditions[] = "passengers.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)) {
|
||||
$conditions[] = "passengers.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);
|
||||
|
||||
@@ -39,18 +62,43 @@ $sql = "SELECT
|
||||
passengers.`maritalStatus`,
|
||||
passengers.`created_at`,
|
||||
passengers.`updated_at`,
|
||||
email_verifications.verified
|
||||
passengers.`email` AS `_email_enc`
|
||||
FROM
|
||||
`passengers`
|
||||
LEFT JOIN email_verifications ON email_verifications.email = passengers.email
|
||||
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->execute($params);
|
||||
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
$count = $stmt->rowCount();
|
||||
|
||||
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'];
|
||||
if (password_verify($password, $stored_password)) {
|
||||
unset($data[0]['password']);
|
||||
|
||||
@@ -72,6 +72,7 @@ function getNabehBearerToken(): ?string {
|
||||
|
||||
if (!$email || !$password) {
|
||||
$msg = "⚠️ [Nabeh Auth] Missing NABEH_EMAIL or NABEH_PASSWORD environment variables.";
|
||||
$GLOBALS['last_otp_error'] = $msg;
|
||||
error_log($msg);
|
||||
return null;
|
||||
}
|
||||
@@ -85,6 +86,9 @@ function getNabehBearerToken(): ?string {
|
||||
$response = curlCall("POST", $apiUrl, json_encode($payload), [
|
||||
'Content-Type: application/json'
|
||||
]);
|
||||
|
||||
$debugLog = "[Nabeh Auth Debug] Request: $apiUrl | Response: $response";
|
||||
error_log($debugLog);
|
||||
|
||||
if ($response) {
|
||||
$decoded = json_decode($response, true);
|
||||
@@ -95,6 +99,7 @@ function getNabehBearerToken(): ?string {
|
||||
if ($redis) {
|
||||
try {
|
||||
$redis->setex('nabeh_bearer_token', 86400, $token);
|
||||
error_log("[Nabeh Auth Debug] Token cached in Redis successfully.");
|
||||
} catch (Exception $e) {
|
||||
$msg = "⚠️ [Nabeh Auth Redis Cache Save] Error saving token: " . $e->getMessage();
|
||||
error_log($msg);
|
||||
@@ -102,10 +107,12 @@ function getNabehBearerToken(): ?string {
|
||||
}
|
||||
return $token;
|
||||
}
|
||||
$msg = "❌ [Nabeh Auth] Failed to extract token from login response: " . $response;
|
||||
$msg = "❌ [Nabeh Auth Login Failed] Response: " . $response;
|
||||
$GLOBALS['last_otp_error'] = $msg;
|
||||
error_log($msg);
|
||||
} else {
|
||||
$msg = "❌ [Nabeh Auth] Empty response from login API cURL.";
|
||||
$msg = "❌ [Nabeh Auth Login Failed] Empty response from login API.";
|
||||
$GLOBALS['last_otp_error'] = $msg;
|
||||
error_log($msg);
|
||||
}
|
||||
return null;
|
||||
@@ -123,24 +130,17 @@ function getNabehBearerToken(): ?string {
|
||||
function sendNabehOtp(string $receiver, string $otp, string $method = '', string $user_type = 'passenger'): bool {
|
||||
$bearerToken = getNabehBearerToken();
|
||||
if (!$bearerToken) {
|
||||
$msg = "⚠️ [Nabeh OTP] Failed to obtain dynamic JWT Bearer token.";
|
||||
error_log($msg);
|
||||
if (empty($GLOBALS['last_otp_error'])) {
|
||||
$GLOBALS['last_otp_error'] = "⚠️ [Nabeh OTP] Failed to obtain dynamic JWT Bearer token.";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Strip symbols for Nabeh endpoint
|
||||
$phoneRaw = preg_replace('/\D+/', '', $receiver);
|
||||
|
||||
// Map method/type (Text OTP is the default now)
|
||||
$type = 'image';
|
||||
if ($method === 'image') {
|
||||
$type = 'image';
|
||||
} elseif ($method === 'text') {
|
||||
$type = 'text';
|
||||
} else {
|
||||
// If no method specified or if 'voice' was requested, force default to 'text'
|
||||
$type = 'image';
|
||||
}
|
||||
// Map method/type (Image OTP card is default for Nabeh)
|
||||
$type = ($method === 'text') ? 'text' : (($method === 'voice') ? 'voice' : 'image');
|
||||
|
||||
$appName = 'سيرو رايدر';
|
||||
if ($user_type === 'driver') {
|
||||
@@ -151,9 +151,31 @@ function sendNabehOtp(string $receiver, string $otp, string $method = '', string
|
||||
$appName = 'سيرو للخدمات';
|
||||
}
|
||||
|
||||
// First attempt with the chosen type
|
||||
$result = _nabehOtpAttempt($phoneRaw, $type, $otp, $appName, $bearerToken);
|
||||
if ($result) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Fallback: if image failed, retry with text
|
||||
if ($type === 'image') {
|
||||
error_log("ℹ️ [Nabeh OTP Fallback] Image failed, retrying with text type...");
|
||||
$result = _nabehOtpAttempt($phoneRaw, 'text', $otp, $appName, $bearerToken);
|
||||
if ($result) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal helper: single OTP send attempt to Nabeh
|
||||
*/
|
||||
function _nabehOtpAttempt(string $phone, string $type, string $otp, string $appName, string $bearerToken): bool {
|
||||
$apiUrl = 'https://nabeh.intaleqapp.com/api/otp/send';
|
||||
$payload = [
|
||||
'phone' => $phoneRaw,
|
||||
'phone' => $phone,
|
||||
'type' => $type,
|
||||
'code' => $otp,
|
||||
'message' => "رمز التحقق الخاص بك لتطبيق {$appName} هو: *{code}* \n الرجاء عدم مشاركته مع أي شخص."
|
||||
@@ -166,13 +188,33 @@ function sendNabehOtp(string $receiver, string $otp, string $method = '', string
|
||||
|
||||
if ($response) {
|
||||
$decoded = json_decode($response, true);
|
||||
if ($decoded && (($decoded['success'] ?? false) || ($decoded['status'] ?? '') === 'success')) {
|
||||
return true;
|
||||
error_log("ℹ️ [Nabeh OTP Response type=$type] " . $response);
|
||||
if ($decoded) {
|
||||
$statusStr = strtolower((string)($decoded['status'] ?? ''));
|
||||
$msgStr = strtolower((string)($decoded['message'] ?? ''));
|
||||
$errStr = strtolower((string)($decoded['error'] ?? ''));
|
||||
if (
|
||||
!empty($decoded['success']) ||
|
||||
in_array($statusStr, ['success', 'ok', 'true', '200', 'sent', 'queued', '1'], true) ||
|
||||
($decoded['status'] ?? false) === true ||
|
||||
($decoded['code'] ?? 0) === 200 ||
|
||||
!empty($decoded['message_id']) ||
|
||||
!empty($decoded['id']) ||
|
||||
!empty($decoded['token']) ||
|
||||
strpos($msgStr, 'success') !== false ||
|
||||
strpos($msgStr, 'sent') !== false ||
|
||||
strpos($msgStr, 'تم') !== false ||
|
||||
strpos($errStr, 'via gateway') !== false
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
$msg = "❌ [Nabeh OTP] API returned failure response: " . $response;
|
||||
$msg = "❌ [Nabeh OTP type=$type] Response: " . $response;
|
||||
$GLOBALS['last_otp_error'] = $msg;
|
||||
error_log($msg);
|
||||
} else {
|
||||
$msg = "❌ [Nabeh OTP] Empty response from cURL.";
|
||||
$msg = "❌ [Nabeh OTP type=$type] Empty cURL response.";
|
||||
$GLOBALS['last_otp_error'] = $msg;
|
||||
error_log($msg);
|
||||
}
|
||||
return false;
|
||||
@@ -209,7 +251,7 @@ function sendIntaleqOtp(string $receiver, string &$otp, string $method = 'whatsa
|
||||
|
||||
if ($response) {
|
||||
$decoded = json_decode($response, true);
|
||||
if ($decoded && ($decoded['success'] ?? false)) {
|
||||
if ($decoded && (!empty($decoded['success']) || ($decoded['status'] ?? '') === 'success')) {
|
||||
if (isset($decoded['otp'])) {
|
||||
$otp = (string)$decoded['otp'];
|
||||
}
|
||||
@@ -217,9 +259,8 @@ function sendIntaleqOtp(string $receiver, string &$otp, string $method = 'whatsa
|
||||
}
|
||||
$msg = "❌ [Intaleq OTP] API returned failure response: " . $response;
|
||||
error_log($msg);
|
||||
echo $msg; // Temporarily echo the raw error so we can see it in the app logs!
|
||||
} else {
|
||||
echo "❌ [Intaleq OTP] Empty response or cURL failed.";
|
||||
error_log("❌ [Intaleq OTP] Empty response or cURL failed.");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -234,8 +275,8 @@ function curlCall(string $method, string $url, string $data, array $headers): ?s
|
||||
CURLOPT_CUSTOMREQUEST => $method,
|
||||
CURLOPT_POSTFIELDS => $data,
|
||||
CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_TIMEOUT => 15,
|
||||
CURLOPT_CONNECTTIMEOUT => 5
|
||||
CURLOPT_TIMEOUT => 35,
|
||||
CURLOPT_CONNECTTIMEOUT => 10
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
|
||||
@@ -119,8 +119,11 @@ switch (strtolower($country)) {
|
||||
|
||||
// 6. DB Storage on Success
|
||||
if ($sentSuccessfully) {
|
||||
$encryptedPhone = $encryptionHelper->encryptData($receiver);
|
||||
$encryptedOtp = $encryptionHelper->encryptData($otp);
|
||||
$encryptedPhone = otpPhoneKey($receiver); // مفتاح بحث ثابت مستقل عن نمط التشفير
|
||||
// نسخة قابلة للاسترجاع: خدمة العملاء تتابع من طلب رمزاً ولم يُكمل تسجيله،
|
||||
// والمفتاح أعلاه أحادي الاتجاه فلا يُستخرج منه الرقم.
|
||||
$phoneEncStored = $encryptionHelper->encryptData($receiver);
|
||||
$encryptedOtp = $encryptionHelper->encryptDataGCM($otp); // Random GCM
|
||||
$encryptedEmail = !empty($email) ? $encryptionHelper->encryptData($email) : '';
|
||||
|
||||
try {
|
||||
@@ -135,15 +138,16 @@ if ($sentSuccessfully) {
|
||||
|
||||
$stmtIns = $con->prepare("
|
||||
INSERT INTO `phone_verification_service`
|
||||
(`phone_number`, `token_code`, `expiration_time`, `is_verified`, `created_at`)
|
||||
VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
||||
(`phone_number`, `phone_enc`, `token_code`, `expiration_time`, `is_verified`, `created_at`)
|
||||
VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
||||
");
|
||||
$stmtIns->execute([
|
||||
$encryptedPhone,
|
||||
$phoneEncStored,
|
||||
$encryptedOtp
|
||||
]);
|
||||
} elseif ($user_type === 'driver') {
|
||||
if ($context === 'token_change') {
|
||||
if ($context === 'token_change' || $context === 'payout') {
|
||||
// Delete old verification attempts
|
||||
$stmtDel = $con->prepare("DELETE FROM `token_verification_driver` WHERE `phone_number` = ?");
|
||||
$stmtDel->execute([$encryptedPhone]);
|
||||
@@ -166,11 +170,12 @@ if ($sentSuccessfully) {
|
||||
// Insert new attempt
|
||||
$stmtIns = $con->prepare("
|
||||
INSERT INTO `phone_verification`
|
||||
(`phone_number`, `driverId`, `email`, `token_code`, `expiration_time`, `is_verified`, `created_at`)
|
||||
VALUES (?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
||||
(`phone_number`, `phone_enc`, `driverId`, `email`, `token_code`, `expiration_time`, `is_verified`, `created_at`)
|
||||
VALUES (?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
||||
");
|
||||
$stmtIns->execute([
|
||||
$encryptedPhone,
|
||||
$phoneEncStored,
|
||||
$driverId ?: '',
|
||||
$encryptedEmail,
|
||||
$encryptedOtp
|
||||
@@ -185,11 +190,12 @@ if ($sentSuccessfully) {
|
||||
// Insert new attempt
|
||||
$stmtIns = $con->prepare("
|
||||
INSERT INTO `token_verification`
|
||||
(`phone_number`, `token`, `expiration_time`, `verified`, `created_at`)
|
||||
VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
||||
(`phone_number`, `phone_enc`, `token`, `expiration_time`, `verified`, `created_at`)
|
||||
VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
||||
");
|
||||
$stmtIns->execute([
|
||||
$encryptedPhone,
|
||||
$phoneEncStored,
|
||||
$encryptedOtp
|
||||
]);
|
||||
} else {
|
||||
@@ -200,11 +206,12 @@ if ($sentSuccessfully) {
|
||||
// Insert new attempt
|
||||
$stmtIns = $con->prepare("
|
||||
INSERT INTO `phone_verification_passenger`
|
||||
(`phone_number`, `token`, `expiration_time`, `verified`, `created_at`)
|
||||
VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
||||
(`phone_number`, `phone_enc`, `token`, `expiration_time`, `verified`, `created_at`)
|
||||
VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())
|
||||
");
|
||||
$stmtIns->execute([
|
||||
$encryptedPhone,
|
||||
$phoneEncStored,
|
||||
$encryptedOtp
|
||||
]);
|
||||
}
|
||||
@@ -216,5 +223,6 @@ if ($sentSuccessfully) {
|
||||
jsonError("OTP sent but failed to save verification data");
|
||||
}
|
||||
} else {
|
||||
jsonError("Failed to send verification code. Please try again.");
|
||||
$errDetail = !empty($GLOBALS['last_otp_error']) ? $GLOBALS['last_otp_error'] : "Failed to send verification code. Please try again.";
|
||||
jsonError($errDetail);
|
||||
}
|
||||
|
||||
+128
-31
@@ -59,18 +59,19 @@ try {
|
||||
// 3. Encrypt data to query
|
||||
// 4. Verify based on user type
|
||||
try {
|
||||
$encryptedPhoneSearch = otpPhoneKey($phone_number);
|
||||
|
||||
if ($user_type === 'admin') {
|
||||
$sql = "SELECT * FROM token_verification_admin
|
||||
WHERE expiration_time >= NOW() AND verified = 0";
|
||||
WHERE expiration_time >= NOW() AND verified = 0 AND phone_number = ?";
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->execute();
|
||||
$stmt->execute([$encryptedPhoneSearch]);
|
||||
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$matchedRow = null;
|
||||
foreach ($rows as $row) {
|
||||
$decryptedPhone = $encryptionHelper->decryptData($row['phone_number']);
|
||||
$decryptedToken = $encryptionHelper->decryptData($row['token']);
|
||||
if ($decryptedPhone === $phone_number && $decryptedToken === $token_code) {
|
||||
if ($decryptedToken === $token_code) {
|
||||
$matchedRow = $row;
|
||||
break;
|
||||
}
|
||||
@@ -101,16 +102,15 @@ try {
|
||||
}
|
||||
} elseif ($user_type === 'service') {
|
||||
$sql = "SELECT `id`, `phone_number`, `token_code` FROM `phone_verification_service`
|
||||
WHERE `expiration_time` > NOW() AND `is_verified` = 0";
|
||||
WHERE `expiration_time` > NOW() AND `is_verified` = 0 AND `phone_number` = ?";
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->execute();
|
||||
$stmt->execute([$encryptedPhoneSearch]);
|
||||
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$matchedRowId = null;
|
||||
foreach ($rows as $row) {
|
||||
$decryptedPhone = $encryptionHelper->decryptData($row['phone_number']);
|
||||
$decryptedToken = $encryptionHelper->decryptData($row['token_code']);
|
||||
if ($decryptedPhone === $phone_number && $decryptedToken === $token_code) {
|
||||
if ($decryptedToken === $token_code) {
|
||||
$matchedRowId = $row['id'];
|
||||
break;
|
||||
}
|
||||
@@ -128,16 +128,15 @@ try {
|
||||
} elseif ($user_type === 'driver') {
|
||||
if ($context === 'token_change') {
|
||||
$sql = "SELECT `id`, `phone_number`, `token` FROM `token_verification_driver`
|
||||
WHERE `expiration_time` > NOW() AND `verified` = 0";
|
||||
WHERE `expiration_time` > NOW() AND `verified` = 0 AND `phone_number` = ?";
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->execute();
|
||||
$stmt->execute([$encryptedPhoneSearch]);
|
||||
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$matchedRowId = null;
|
||||
foreach ($rows as $row) {
|
||||
$decryptedPhone = $encryptionHelper->decryptData($row['phone_number']);
|
||||
$decryptedToken = $encryptionHelper->decryptData($row['token']);
|
||||
if ($decryptedPhone === $phone_number && $decryptedToken === $token_code) {
|
||||
if ($decryptedToken === $token_code) {
|
||||
$matchedRowId = $row['id'];
|
||||
break;
|
||||
}
|
||||
@@ -148,22 +147,84 @@ try {
|
||||
$stmtUpd = $con->prepare($sqlUpdate);
|
||||
$stmtUpd->bindParam(':id', $matchedRowId, PDO::PARAM_INT);
|
||||
$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 {
|
||||
jsonError("Your phone number could not be verified or the code is expired. Please try again.");
|
||||
}
|
||||
} else {
|
||||
$sql = "SELECT `id`, `phone_number`, `token_code` FROM `phone_verification`
|
||||
WHERE `expiration_time` > NOW() AND `is_verified` = 0";
|
||||
WHERE `expiration_time` > NOW() AND `is_verified` = 0 AND `phone_number` = ?";
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->execute();
|
||||
$stmt->execute([$encryptedPhoneSearch]);
|
||||
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$matchedRowId = null;
|
||||
foreach ($rows as $row) {
|
||||
$decryptedPhone = $encryptionHelper->decryptData($row['phone_number']);
|
||||
$decryptedToken = $encryptionHelper->decryptData($row['token_code']);
|
||||
if ($decryptedPhone === $phone_number && $decryptedToken === $token_code) {
|
||||
if ($decryptedToken === $token_code) {
|
||||
$matchedRowId = $row['id'];
|
||||
break;
|
||||
}
|
||||
@@ -179,8 +240,10 @@ try {
|
||||
$isRegistered = false;
|
||||
$driverData = null;
|
||||
|
||||
$chkStmt = $con->prepare("SELECT id, first_name, last_name, email, phone FROM driver WHERE phone = ?");
|
||||
$chkStmt->execute([$encryptionHelper->encryptData($phone_number)]);
|
||||
$chkStmt = $con->prepare("SELECT id, first_name, last_name, email, phone FROM driver WHERE phone = ? OR (? IS NOT NULL AND phone_bidx = ?)");
|
||||
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);
|
||||
|
||||
// Generate driverID for unregistered users (hash of phone)
|
||||
@@ -198,10 +261,25 @@ try {
|
||||
$driverID = substr(md5($phone_number), 0, 16);
|
||||
}
|
||||
|
||||
// Generate JWT tokens for driver
|
||||
$audDriver = filterRequest("aud") ?: filterRequest("audience") ?: (getenv('allowedDriver2') ?: 'driver-app:ios');
|
||||
$fpDriver = filterRequest("fingerprint") ?? filterRequest("fingerPrint") ?? ($_SERVER['HTTP_X_DEVICE_FP'] ?? null);
|
||||
if ($fpDriver === null && function_exists('getallheaders')) {
|
||||
$hdrs = array_change_key_case(getallheaders(), CASE_LOWER);
|
||||
$fpDriver = $hdrs['x-device-fp'] ?? null;
|
||||
}
|
||||
$jwtSvc = new JwtService($redis);
|
||||
$accessToken = $jwtSvc->generateAccessToken($driverID, 'driver', $audDriver, $fpDriver);
|
||||
$refreshToken = $jwtSvc->generateRefreshToken($driverID, 'driver', $audDriver);
|
||||
|
||||
jsonSuccess([
|
||||
"isRegistered" => $isRegistered,
|
||||
"driver" => $driverData,
|
||||
"driverID" => $driverID
|
||||
"driverID" => $driverID,
|
||||
"jwt" => $accessToken,
|
||||
"token" => $accessToken,
|
||||
"access_token" => $accessToken,
|
||||
"refresh_token" => $refreshToken
|
||||
], "Your phone number has been verified.");
|
||||
} else {
|
||||
jsonError("Your phone number could not be verified or the code is expired. Please try again.");
|
||||
@@ -210,16 +288,15 @@ try {
|
||||
} else {
|
||||
if ($context === 'token_change') {
|
||||
$sql = "SELECT `id`, `phone_number`, `token` FROM `token_verification`
|
||||
WHERE `expiration_time` > NOW() AND `verified` = 0";
|
||||
WHERE `expiration_time` > NOW() AND `verified` = 0 AND `phone_number` = ?";
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->execute();
|
||||
$stmt->execute([$encryptedPhoneSearch]);
|
||||
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$matchedRowId = null;
|
||||
foreach ($rows as $row) {
|
||||
$decryptedPhone = $encryptionHelper->decryptData($row['phone_number']);
|
||||
$decryptedToken = $encryptionHelper->decryptData($row['token']);
|
||||
if ($decryptedPhone === $phone_number && $decryptedToken === $token_code) {
|
||||
if ($decryptedToken === $token_code) {
|
||||
$matchedRowId = $row['id'];
|
||||
break;
|
||||
}
|
||||
@@ -236,16 +313,15 @@ try {
|
||||
}
|
||||
} else {
|
||||
$sql = "SELECT `id`, `phone_number`, `token` FROM `phone_verification_passenger`
|
||||
WHERE `expiration_time` > NOW() AND `verified` = 0";
|
||||
WHERE `expiration_time` > NOW() AND `verified` = 0 AND `phone_number` = ?";
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->execute();
|
||||
$stmt->execute([$encryptedPhoneSearch]);
|
||||
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$matchedRowId = null;
|
||||
foreach ($rows as $row) {
|
||||
$decryptedPhone = $encryptionHelper->decryptData($row['phone_number']);
|
||||
$decryptedToken = $encryptionHelper->decryptData($row['token']);
|
||||
if ($decryptedPhone === $phone_number && $decryptedToken === $token_code) {
|
||||
if ($decryptedToken === $token_code) {
|
||||
$matchedRowId = $row['id'];
|
||||
break;
|
||||
}
|
||||
@@ -260,9 +336,12 @@ try {
|
||||
// Check registration status
|
||||
$isRegistered = false;
|
||||
$passengerData = null;
|
||||
$passengerID = '';
|
||||
|
||||
$chkStmt = $con->prepare("SELECT id, first_name, last_name, email, phone FROM passengers WHERE phone = ?");
|
||||
$chkStmt->execute([$encryptionHelper->encryptData($phone_number)]);
|
||||
$chkStmt = $con->prepare("SELECT id, first_name, last_name, email, phone FROM passengers WHERE phone = ? OR (? IS NOT NULL AND phone_bidx = ?)");
|
||||
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);
|
||||
|
||||
if ($passenger) {
|
||||
@@ -272,11 +351,29 @@ try {
|
||||
$passenger['email'] = $encryptionHelper->decryptData($passenger['email']);
|
||||
$passenger['phone'] = $encryptionHelper->decryptData($passenger['phone']);
|
||||
$passengerData = $passenger;
|
||||
$passengerID = (string)$passenger['id'];
|
||||
} else {
|
||||
$passengerID = substr(md5($phone_number), 0, 16);
|
||||
}
|
||||
|
||||
// Generate JWT tokens for passenger
|
||||
$audPass = filterRequest("aud") ?: filterRequest("audience") ?: (getenv('allowed2') ?: 'passenger-app:ios');
|
||||
$fpPass = filterRequest("fingerprint") ?? filterRequest("fingerPrint") ?? ($_SERVER['HTTP_X_DEVICE_FP'] ?? null);
|
||||
if ($fpPass === null && function_exists('getallheaders')) {
|
||||
$hdrs = array_change_key_case(getallheaders(), CASE_LOWER);
|
||||
$fpPass = $hdrs['x-device-fp'] ?? null;
|
||||
}
|
||||
$jwtSvc = new JwtService($redis);
|
||||
$accessToken = $jwtSvc->generateAccessToken($passengerID, 'passenger', $audPass, $fpPass);
|
||||
$refreshToken = $jwtSvc->generateRefreshToken($passengerID, 'passenger', $audPass);
|
||||
|
||||
jsonSuccess([
|
||||
"isRegistered" => $isRegistered,
|
||||
"passenger" => $passengerData
|
||||
"passenger" => $passengerData,
|
||||
"jwt" => $accessToken,
|
||||
"token" => $accessToken,
|
||||
"access_token" => $accessToken,
|
||||
"refresh_token" => $refreshToken
|
||||
], "Your phone number has been verified.");
|
||||
} else {
|
||||
jsonError("Your phone number could not be verified or the code is expired. Please try again.");
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user