323 Commits
Author SHA1 Message Date
Hamza-Ayed bb9517826e feat: add service area restriction overlay and bump version to 1.0.3+8 2026-08-11 00:14:03 +03:00
Hamza-Ayed e52afa1863 Update: 2026-08-08 17:42:04 2026-08-08 17:42:04 +03:00
Hamza-Ayed e63f990aea Update: 2026-08-08 17:35:50 2026-08-08 17:35:50 +03:00
Hamza-Ayed 8c9f729ecd Update: 2026-08-08 16:55:39 2026-08-08 16:55:39 +03:00
Hamza-AyedandClaude Opus 5 dd44b84e81 docs: دليل التشغيل والأعطال المعروفة (المنافذ، nginx، القواعد، التوكن، سجل الملفات)
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-08 15:07:59 +03:00
Hamza-Ayed 875ce763bd Update: 2026-08-08 14:57:58 2026-08-08 14:57:59 +03:00
Hamza-Ayed c659af67dc Update: 2026-08-08 14:29:55 2026-08-08 14:29:55 +03:00
Hamza-Ayed ef37752ceb Update: 2026-08-08 14:26:43 2026-08-08 14:26:44 +03:00
Hamza-Ayed b97a1fd587 Update: 2026-08-08 14:12:15 2026-08-08 14:12:15 +03:00
Hamza-Ayed 8395436f23 Update: 2026-08-08 14:09:20 2026-08-08 14:09:20 +03:00
Hamza-Ayed c8e8e481a6 Update: 2026-08-08 13:33:53 2026-08-08 13:33:54 +03:00
Hamza-Ayed fae0e4a38a Update: 2026-08-08 12:58:16 2026-08-08 12:58:17 +03:00
Hamza-Ayed 611b5e616d Update: 2026-08-07 19:10:47 2026-08-07 19:10:47 +03:00
Hamza-Ayed 0db59647eb Update: 2026-08-07 19:01:00 2026-08-07 19:01:00 +03:00
Hamza-Ayed cdd36d4777 Update: 2026-08-07 16:25:34 2026-08-07 16:25:34 +03:00
Hamza-Ayed 9338e76894 Update: 2026-08-07 15:50:04 2026-08-07 15:50:04 +03:00
Hamza-Ayed b2a95c53aa Update: 2026-08-07 14:20:27 2026-08-07 14:20:27 +03:00
Hamza-Ayed 9e186f9ff3 Update: 2026-08-07 13:46:40 2026-08-07 13:46:40 +03:00
Hamza-Ayed d691e51ba4 Update: 2026-08-07 06:04:46 2026-08-07 06:04:46 +03:00
Hamza-Ayed 92a6aa5c0f Update: 2026-08-07 06:00:56 2026-08-07 06:00:56 +03:00
Hamza-Ayed 67465df000 Update: 2026-08-07 05:56:50 2026-08-07 05:56:50 +03:00
Hamza-Ayed 7a932580a3 Update: 2026-08-07 05:35:52 2026-08-07 05:35:52 +03:00
Hamza-Ayed 0b8b687ce1 Update: 2026-08-07 05:29:18 2026-08-07 05:29:18 +03:00
Hamza-Ayed b938e287c6 Update: 2026-08-07 05:05:45 2026-08-07 05:05:46 +03:00
Hamza-Ayed 977d238c84 Update: 2026-08-07 05:03:39 2026-08-07 05:03:39 +03:00
Hamza-Ayed 8e7c4a7104 Update: 2026-08-07 04:35:28 2026-08-07 04:35:28 +03:00
Hamza-Ayed f0ea698ab2 Update: 2026-08-07 02:58:47 2026-08-07 02:58:47 +03:00
Hamza-Ayed e070c2d9a8 Update: 2026-08-07 02:37:30 2026-08-07 02:37:30 +03:00
Hamza-Ayed 70772cf0d2 Update: 2026-08-07 02:32:14 2026-08-07 02:32:15 +03:00
Hamza-Ayed 3081aea802 Update: 2026-08-07 02:19:07 2026-08-07 02:19:07 +03:00
Hamza-Ayed b492034bad Update: 2026-08-07 02:10:33 2026-08-07 02:10:33 +03:00
Hamza-Ayed 9830e5f649 Update: 2026-08-07 01:53:09 2026-08-07 01:53:09 +03:00
Hamza-Ayed 5b864e30df Update: 2026-08-07 01:35:27 2026-08-07 01:35:27 +03:00
Hamza-Ayed 0cb1ab0ea3 Update: 2026-08-07 01:06:09 2026-08-07 01:06:09 +03:00
Hamza-Ayed a1104a4695 Update: 2026-08-07 00:57:03 2026-08-07 00:57:03 +03:00
Hamza-Ayed 6e451e8b71 Update: 2026-08-07 00:36:27 2026-08-07 00:36:27 +03:00
Hamza-Ayed 4d64a205fa Update: 2026-08-06 23:42:11 2026-08-06 23:42:11 +03:00
Hamza-Ayed 97471fd2bd refactor: migrate JWT storage to secure storage, update assets, and enhance login verification logic. 2026-08-06 22:54:52 +03:00
Hamza-Ayed 52101e650c Update: 2026-08-06 14:24:16 2026-08-06 14:24:16 +03:00
Hamza-Ayed e4553dabc1 chore: downgrade dependency versions and update Dart SDK constraint in pubspec.lock 2026-08-04 21:21:30 +03:00
Hamza-Ayed ca55aaebe8 Food: background location + native delivery overlay 2026-08-04 03:02:04 +03:00
Hamza-Ayed d695834d19 Food: single-source tracking, mode exclusivity, in-app navigation 2026-08-04 02:41:54 +03:00
Hamza-Ayed 788d3dcbe5 Food delivery driver module + masked calls + TURN 2026-08-04 02:08:20 +03:00
Hamza-Ayed f01e408ba6 Food delivery driver module + masked calls + TURN 2026-08-04 01:50:50 +03:00
Hamza-Ayed 04c214bdf6 Update: 2026-08-03 15:22:47 2026-08-03 15:22:47 +03:00
Hamza-Ayed 5f5e78691d Update: 2026-08-03 15:02:19 2026-08-03 15:02:19 +03:00
Hamza-Ayed dbf1e7870f Update: 2026-08-03 13:37:04 2026-08-03 13:37:04 +03:00
Hamza-Ayed 79333a4bee Update: 2026-08-03 13:22:27 2026-08-03 13:22:27 +03:00
Hamza-Ayed b60129d246 Update: 2026-08-03 13:10:56 2026-08-03 13:10:57 +03:00
Hamza-Ayed f36b30f0b8 Update: 2026-08-03 12:30:24 2026-08-03 12:30:25 +03:00
Hamza-Ayed ec467b01c6 Update: 2026-08-03 11:52:03 2026-08-03 11:52:03 +03:00
Hamza-Ayed 4abfd30ddd Update: 2026-08-03 11:34:06 2026-08-03 11:34:06 +03:00
Hamza-Ayed 0334f9881f Update: 2026-08-03 11:32:12 2026-08-03 11:32:12 +03:00
Hamza-Ayed 2b9f696372 Update: 2026-08-03 00:20:40 2026-08-03 00:20:40 +03:00
Hamza-Ayed c23c3c0721 Update: 2026-08-02 23:10:23 2026-08-02 23:10:23 +03:00
Hamza-Ayed 5691d84fa0 Update: 2026-08-02 23:03:25 2026-08-02 23:03:25 +03:00
Hamza-Ayed 2c962bf80a Update: 2026-08-02 22:51:18 2026-08-02 22:51:18 +03:00
Hamza-Ayed c9af364cbc Update: 2026-08-02 19:06:24 2026-08-02 19:06:24 +03:00
Hamza-Ayed 02e652a786 Update: 2026-08-02 18:28:40 2026-08-02 18:28:40 +03:00
Hamza-AyedandClaude Opus 5 03a21aa95d Bump transitive dev dependencies in lockfiles
matcher, test_api and related transitive packages, from pub get.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 18:19:55 +03:00
Hamza-AyedandClaude Opus 5 3b4b4639a6 Guard debug logs in release and remove device-check bypass
Log.print used developer.log with no kDebugMode guard, so release
builds emitted wallet JWTs, the HMAC secret, phone numbers and full
API responses to os_log/logcat on the user's device. Both the rider
and driver apps were affected.

Also removes a hardcoded test-account condition in the rider login
flow that skipped the entire FCM-token/fingerprint comparison — and
therefore the device-change OTP — for one email address.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 18:19:50 +03:00
Hamza-Ayed 4620e84d34 Update: 2026-08-02 17:52:28 2026-08-02 17:52:28 +03:00
Hamza-Ayed b78a6797d5 Fix table name click to cliq in all files 2026-08-01 04:31:53 +03:00
Hamza-Ayed 811b23ca9e Fix JSON payload parsing in payment server 2026-08-01 04:23:30 +03:00
Hamza-Ayed 915d517ba7 Port all fixes from IntaleqApp (Wallet, CLIQ, OTP, Docker) 2026-08-01 03:58:37 +03:00
Hamza-Ayed 12fc64dc9a Update: 2026-08-01 02:06:59 2026-08-01 02:06:59 +03:00
Hamza-Ayed 46e74330a1 Update: 2026-08-01 01:46:21 2026-08-01 01:46:21 +03:00
Hamza-Ayed 410fb14d77 Update: 2026-07-31 19:21:38 2026-07-31 19:21:38 +03:00
Hamza-Ayed cf3fea3834 Update: 2026-07-31 19:18:42 2026-07-31 19:18:43 +03:00
Hamza-Ayed 0452c36379 Update: 2026-07-31 19:14:05 2026-07-31 19:14:05 +03:00
Hamza-Ayed 7362f1ce96 Update: 2026-07-31 03:58:40 2026-07-31 03:58:40 +03:00
Hamza-Ayed 8d67530b44 Update: 2026-07-31 03:06:59 2026-07-31 03:06:59 +03:00
Hamza-Ayed f94a9478ac Update: 2026-07-31 03:00:06 2026-07-31 03:00:06 +03:00
Hamza-Ayed 7a576b7327 Update: 2026-07-30 12:31:26 2026-07-30 12:31:27 +03:00
Hamza-AyedandClaude Opus 5 ecfe756849 fix(bots): توجيه السوشال بوت لنقطة النهاية الصحيحة — التعليق العضوي كان ميتاً
السبب الجذري: BASE_URL واحد يشير إلى marketing_engine/index.php، بينما
`process_organic_post` و`log` موجودان في social_worker.php وحده. فكانا
يقعان على `default` فيعود {"status":"error"} بكود HTTP 200 — بلا استثناء
ولا سجل. أثره: processOrganicPost يعود null فيفشل شرط generated_comment في
FacebookBotService:137 → لا تعليق عضوي يُنشر أبداً، وكل logMessage يُبتلع
صامتاً فلم يظهر العطل في أي سجل. (تعليق العميل سطر 10 كان يذكر
social_worker.php أصلاً — الرابط هو ما خالف النية.)

- توجيه لكل أمر حسب موضعه: index.php لـ get_task/complete_task/fail_task/
  evaluate_posts · social_worker.php لـ process_organic_post/log
- evaluate_posts: index.php يرد بلا حقل `data`، والعميل كان يشترطه فيعود
  null في كل نجاح. النجاح صار يُقاس بـ status
- ترميز URL لكل المعاملات: رسالة خطأ فيها & أو # كانت تشقّ جسم
  x-www-form-urlencoded وتفسد صفّ المهمة
- كل رد غير 200 أو status != success يُسجَّل في Logcat بدل الصمت
- المضيف إلى BuildConfig.BACKEND_HOST في البوتين (gradle) — لا نطاق مشفّر
  في الكود، فتبديله لأي علامة أخرى سطر واحد
- val لا const val لقيم BuildConfig (ليست ثوابت وقت ترجمة في كوتلن)

لم يُبنَ بعد. لم يُمسّ أي PHP: الباك إند حيّ.
ما زال مفتوحاً بقرار المالك: (1) فحص X-Bot-Token معطَّل بتعليق في
social_worker.php:14 و index.php:17 والتوكن placeholder → النقطتان
مفتوحتان؛ (2) طابور social_tasks الذي يغذّيه schedule_manager بلا مستهلك.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 05:06:08 +03:00
Hamza-Ayed 4d2beaae5e chore: update Flutter SDK paths and project dependencies across packages 2026-07-27 04:56:25 +03:00
Hamza-AyedandClaude Opus 5 b84e26fe9a تسجيل نتيجة send_fcm.php — مسار الرسائل كان صندوقاً أسود بالكامل
send_fcm.php هي نقطة كل الرسائل والمكالمات بين الراكب والسائق (التطبيقان
يستدعيانها مباشرة)، ولم تكن تحتوي أي error_log إطلاقاً — بخلاف FcmService
التي تطبع [FCM_DEBUG] وتخدم دورة حياة الرحلة فقط.

النتيجة أن فشل الرسائل كان غير قابل للتشخيص: لا سبب، ولا رد Google، ولا
حتى معرفة إن كان الطلب وصل. وقد وعدت المستخدم بقراءة [FCM_DEBUG] لهذا
المسار وهو وعد خاطئ — لا وجود له هنا.

أُضيفت ثلاث نقاط:
- نتيجة الإرسال: category + طرف من التوكن + http + طول التوكن + رد Google
  عند الفشل. طول التوكن مقصود: توكن FCM الحقيقي ~163 محرفاً، والمشفّر في
  جدول tokens 216 — فيُكشف أي blob مشفّر من سطر واحد.
- رفض 403: التطبيقان لا يرسلان x-api-key، فلحظة ضبط FCM_INTERNAL_API_KEY
  تموت كل الرسائل بينهما بصمت. الآن يُسجَّل السبب صريحاً.
- رفض 400 على target فارغ: يعني أن المُرسِل لا يملك توكن الطرف الآخر
  (tokenPassenger أو driverToken لم يصله في حمولة القبول).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 01:35:01 +03:00
Hamza-AyedandClaude Opus 5 77c0b48ec2 إعادة تفعيل access_log في nginx — كان مطفأً فأفسد كل تشخيص
docker/nginx/default.conf:13 كان فيه:
    access_log off;   # أثناء اختبار الضغط؛ فعّله عند الحاجة
مُطفأً من اختبار ضغط قديم ونُسي.

أثره أن أي بحث في سجلّ الوصول يرجع صفراً دائماً:
    docker compose logs nginx | grep -c "send_fcm"   →  0
فيبدو الاستنتاج أن التطبيق لا يستدعي المسار إطلاقاً، والحقيقة أن السجلّ
فارغ لا أن الطلبات غائبة. استنتاج خاطئ تماماً بُني على قياس معطّل.

مع توجيه error_log في www-pool.conf (الالتزام e106d2df) تكتمل الرؤية:
nginx يقول هل وصل الطلب، وPHP يقول ماذا ردّ Google.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 01:31:56 +03:00
Hamza-AyedandClaude Opus 5 e106d2df4e توجيه error_log لمخرج الحاوية — كنا نشخّص الأعطال عمياناً
www-pool.conf كان يوجّه slowlog إلى /proc/self/fd/2 لكن لا شيء لـ error_log،
فكل رسائل error_log() في الباك إند تُبتلع ولا يظهر أي سطر في:
    docker compose logs php

والباك إند مليء بها ويعتمد عليها في التشخيص: [accept_ride] و [FCM_DEBUG]
(يطبع حمولة FCM ورد Google كاملاً) و 📲 [FCM_RESULT] و [SOCKET_DEBUG] و
[SSRF_BLOCKED] و [SOCKET_BLOCKED].

النتيجة العملية أن سبب فشل الإشعارات كان يمكن قراءته في سطر واحد من رد
Google (UNREGISTERED / INVALID_ARGUMENT / 403) بدل الاستنتاج من الكود.

catch_workers_output=yes ينقل stdout/stderr للعمّال، و decorate_workers_output=no
يمنع بادئات الضجيج، وphp_admin_value[error_log] يثبّت المسار على fd/2.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 01:30:03 +03:00
Hamza-AyedandClaude Opus 5 899a18b52d حرس السوكيتات المكرّرة للسائق — سبب «notified 0/0» وتحذيرات null
في لوج الإنتاج ثلاثة اتصالات متزامنة للسائق نفسه (التطبيق يفتح سوكيتاً من
location_controller وآخر من background_service ومحاولات لم تُنظَّف):
    ✅ Driver Connected: #243ea… (×3)

ومعالج disconnect كان ينفّذ unset($connectedDrivers[$driverId]) بلا تحقّق من
أيّ سوكيت أُغلق. فإغلاق نسخة واحدة كان يُطفئ السائق فعلياً وهو متصل:

1) dispatch_order يراه offline فيضع الطلب في طابور الانتظار بدل إرساله،
   ويظهر في اللوج:  🚫 Ride #2569 cancelled — notified 0/0 driver(s).
2) update_location من سوكيت ما زال حياً يجد $driverState[$driverId] محذوفاً،
   و &$driverState[...] يُنشئ مدخلاً null فتُقرأ منه كل الحسابات:
     Warning: Trying to access array offset on value of type null (860-872)
     Warning: Undefined array key "status" (907)

الإصلاحان:
- نحفظ sid (معرّف السوكيت) مع السجلّ، ولا ننظّف في disconnect إلا إذا كان
  المُغلَق هو المسجَّل حالياً؛ وإلا نتركه ونسجّل «stale duplicate».
- حرس على $driverState في update_location: يُعاد بناؤه إن غاب لأي سبب
  (إغلاق نسخة أخرى، إعادة تشغيل) بدل القراءة من null.

سيرفر فقط — لا يحتاج بناء التطبيقات. يبقى فتح التطبيق لعدة سوكيتات هدراً
في الحركة يستحق إصلاحاً في الطرف الآخر لاحقاً.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 01:26:20 +03:00
Hamza-AyedandClaude Opus 5 e6504acdea إرسال platform في مصافحة سوكيت السائق — كباتن iOS كانوا يفوتهم الطلب
driver_socket.php عند توزيع الطلب (dispatch_order) يرسل إشعار FCM احتياطياً
**فقط** إذا كانت المنصّة ios، لأن iOS يخنق أحداث السوكيت في الخلفية:

    $platform = $connectedDrivers[$driverId]['platform'] ?? 'android';
    if ($platform === 'ios' && !empty($token)) { sendFCM_Async(...) }

وتطبيق السائق لم يكن يرسل platform في الـ query إطلاقاً، فالافتراضي
'android' — أي أن كابتن الآيفون لا يستلم الإشعار الاحتياطي ويفوته الطلب وهو
في الخلفية، ويعتمد على السوكيت وحده وهو مخنوق أصلاً.

ظهر بالعين في لوج الإنتاج على جهاز آيفون:
    ✅ Driver Connected: #243ea897954387c9 (android)

أُضيف الحقل في موضعي الاتصال: location_controller و background_service.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 01:20:52 +03:00
Hamza-AyedandClaude Opus 5 ef1240b130 تصحيح مفتاح Redis لموقع السائق: driver:location ← driver:public
الموضعان كانا يقرآن مفتاحاً لا يُكتب في أي مكان في المشروع:
  $redisLocation->hGetAll("driver:location:$driverId")

الكاتب الفعلي هو معالج الدفعات في loction_server/driver_socket.php، وهو
يكتب hmset على driver:profile:{id} و driver:public:{id} معاً بنفس الحقول
(lat/lng/heading/speed/status/updated_at). و driver:public له TTL 86400
بينما driver:profile له 900 فقط، فالعام هو الأنسب للقراءة.

الأثر: كانت حمولة القبول تصل الراكب بلا إحداثيات أولية للسائق، فلا يظهر
الماركر إلا بعد أول تحديث موقع من السوكيت أو الـ polling.

أحد الموضعين ملف getRideOrderID.php الذي أضفته في f66db7db — نسخت النمط
من acceptRide.php فنقلت الخطأ معه.

مثبَّت على الإنتاج: redis-cli --scan --pattern 'driver:*' أرجع
driver:public:<id> فقط، ولا شيء باسم driver:location.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 01:14:26 +03:00
Hamza-AyedandClaude Opus 5 0e6dd68385 حذف http2 من إعداد سوكيتات TLS — nginx المضيف أقدم من 1.25.1
nginx على السيرفر يرفض التحميل:
  nginx: [emerg] unknown directive "http2" in siro-sockets-tls.conf:30

التوجيه http2 on; لم يُضَف إلا في nginx 1.25.1. والحذف هو الصحيح لا مجرد
حلٍّ سريع: ترقية WebSocket تعتمد على ترويسة Upgrade في HTTP/1.1 ولا معنى
لها في HTTP/2 أصلاً (وproxy_http_version 1.1 مضبوط في الـ location).

تحذير تشغيلي: بعد up --force-recreate انتقلت الحاويتان إلى 127.0.0.1:12020
و13030، فإن فشل nginx -t يبقى المنفذان 2020/3030 بلا أي مستمع (Connection
refused) حتى ينجح reload. رتّب النشر: صحّح الإعداد ⇒ nginx -t ⇒ reload.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 01:04:32 +03:00
Hamza-AyedandClaude Opus 5 afb5189515 إنهاء TLS أمام سوكيتات Workerman — إصلاح Socket Connect Error: timeout
السبب (مثبَّت على الإنتاج): التزام c35b350b بتاريخ 2026-07-23 — وهو التزام
تلقائي برسالة "Update: <time>" — أضاف المنفذ للروابط:
  -  'https://jordan-siro.intaleqapp.com'
  +  'https://jordan-siro.intaleqapp.com:2020'
وكانت القيمة العاملة قبل ذلك بلا منفذ (443) فيُنهي البروكسي TLS ويمرّر.

بإضافة :2020 صار التطبيق يضرب حاوية Workerman مباشرة، وهي تفتح المنفذ نصاً
صريحاً (new SocketIO(2020) بلا سياق SSL)، فمصافحة TLS تتجمّد حتى المهلة:
  ❌ Socket Connect Error: timeout
  ❌ Socket Connect Timeout: 20000
ونتيجته أن السائق لا يبعث update_location إطلاقاً ⇒ لا GPS في Redis ⇒ لا
موقع للراكب لا عبر السوكيت ولا عبر الـ polling (كلاهما يقرأ من نفس المصدر).

مثبَّت بالأدلة على السيرفر:
- ss: المنفذان 2020/3030 يملكهما docker-proxy (نص صريح)، و443 nginx.
- curl على 127.0.0.1:2020 يرد {"sid":...,"upgrades":["websocket"]} — أي أن
  الحاوية سليمة تماماً والناقص هو طبقة TLS وحدها.

الحل بلا أي بناء للتطبيقات (وبلا تنزيل مستوى الأمان — الـ JWT يُرسَل في
query string فلا يجوز إطلاقاً تحويله إلى http):
- الحاويتان تُنشران على 127.0.0.1:12020 و 127.0.0.1:13030 فقط.
- nginx على المضيف يستمع على 2020/3030 بشهادة الدومين ويمرّر إليهما مع
  ترقية WebSocket (nginx/siro-sockets-tls.conf).
- proxy_read/send_timeout 3600s: اتصال السائق يعيش ساعات، وبلا ذلك يقطعه
  nginx كل 60ث فتدخل الحاوية حلقة إعادة اتصال دائمة.
- proxy_buffering off و access_log off (نبضات GPS تُغرق القرص).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 01:01:42 +03:00
Hamza-AyedandClaude Opus 5 6fec88251c إصلاح أخطاء شاشة الكباتن من تحديث الذكاء الاصطناعي
استرجاع شبكة أمان موقع السائق (انحدارة من الالتزام ab3be7e2):
- كان شرط "Smart Mode" يتخطّى _startDriverLocationPollingWithTimer كلياً إذا
  جاء القبول من السوكيت. قبل إصلاح ترتيب الاتصال كان السوكيت يخسر دائماً
  فالـ polling يعمل ويحمل الموقع؛ وبعد أن صار يفوز تعطّلت شبكة الأمان.
- وصول حدث القبول لا يعني أن تدفّق المواقع يعمل: التدفّق له شرط مستقل —
  تطبيق السائق يحقن passenger_id في update_location فقط إذا كان rideStatus
  نشطاً و BoxName.passengerID مكتوباً، وهو لا يُكتب إلا بعد فتح صفحة خريطة
  السائق (map_driver_controller.dart:2444).
- الآن الـ polling يعمل دائماً، و handleDriverLocationUpdate يوقفه تلقائياً
  بعد 3 تحديثات ناجحة من السوكيت — وهذا المنطق كان موجوداً أصلاً وهو التصميم
  المقصود. السوكيت يبقى المسار السريع بلا فقدان شبكة الأمان.

عدم تعطيل إنشاء الرحلة بانتظار سوكيت غير قابل للوصول:
- ensureConnectedBeforeRide كانت تنتظر 4 ثوانٍ قبل كل طلب. سوكيتات
  Workerman تستمع نصّاً صريحاً على 2020/3030 بينما التطبيقان يستخدمان
  https:// عليها (nginx لا يمرّرها — انظر docker/nginx/default.conf)، فمصافحة
  TLS ضد منفذ غير TLS تتجمّد حتى المهلة ⇒ 4 ثوانٍ مهدورة في كل رحلة.
- المهلة صارت 2ث، وأُضيف cooldown دقيقتين: بعد فشل قريب لا ننتظر إطلاقاً بل
  نحاول الاتصال في الخلفية ونكمل الطلب فوراً.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 00:51:18 +03:00
Hamza-Ayed b76eccb763 إصلاح أخطاء شاشة الكباتن من تحديث الذكاء الاصطناعي 2026-07-27 00:25:02 +03:00
Hamza-AyedandClaude Opus 5 a26472ed9f إصلاح مسار الإشعار→الطلب عند الكابتن + توحيد إعادة اتصال سوكيت الراكب
سوكيت الراكب:
- setReconnectionAttempts: من 20 إلى لا نهائي، توحيداً مع تطبيق السائق. بعد
  20 محاولة كان يستسلم **نهائياً** فيصمت للأبد بعد دقائق من شبكة سيئة ويبقى
  الراكب على الـ polling بلا أن يدري — وخطره أكبر الآن لأن الاتصال صار يعيش
  من فتح الخريطة لا من إنشاء الرحلة.
- الـ heartbeat من 15ث إلى 30ث: Socket.IO يعمل ping/pong على مستوى
  البروتوكول ومستمع 'heartbeat' في passenger_socket.php فارغ أصلاً.

البدء البارد على iOS (سبب "التطبيق يغلق ونرجع من أول"):
- didChangeAppLifecycleState لا يُنفَّذ عند إطلاق التطبيق (يبدأ في resumed
  بلا انتقال حالة)، وهو المُنادي الوحيد لـ _checkPendingTrip ⇒ الضغط على
  الإشعار والتطبيق مقتول لا يوجّه لصفحة الطلب إطلاقاً.
- وحتى لو نُفِّذ، كان يستسلم على '/' ويحوّل المسؤولية لـ
  HomeCaptainController الذي لا يملك أي منطق كهذا ⇒ الطلب يبقى في التخزين
  للأبد. صار addPostFrameCallback + مُجدوِل يعيد المحاولة حتى خروج التطبيق
  من شاشة البداية (سقف ~30ث)، ولا يحذف الطلب قبل التوجيه.
- حرس إضافي: لا اقتحام لرحلة نشطة بطلب قديم، لا توجيه مكرر إذا كنا على
  OrderRequestPage، وتنظيف الحمولة التالفة.

TripOverlayPlugin أندرويد فقط بلا أي حرس منصّة:
- كل دالة كانت تنادي invokeMethod مباشرة ⇒ MissingPluginException على iOS
  (لا يوجد ios/ ولا مدخل في pubspec.plugin.platforms).
- الأخطر: backgroundMessageHandler كان ينادي showOverlay **قبل** حفظ
  pending_driver_list، فيسقط الاستثناء ويُلغي الحفظ كلياً على iOS. عُكس
  الترتيب — الحفظ أولاً دائماً، وهو الحدّ الأدنى الذي لا يتوقف على منصّة أو
  صلاحية.
- أُضيف isSupported وحُصِّنت كل الدوال (ترجع false/no-op ولا ترمي أبداً)،
  فلا يُقطع أيضاً _initApp قبل _listenToOverlayEvents.

أخطاء index في حمولة add_ride.php (أربع نقاط قبول):
- 'Duration' كان index 4 وهو end_lng لا المدة ⇒ صار 15 (duration_text).
  أحد المواضع كان فيه تعليق "انتبه: تأكد من الإندكس الصحيح للوقت".
- 'passengerWalletBurc' كان 26 وهو price_for_driver (أرباح السائق) لا رصيد
  الراكب ⇒ صار 27 (passenger_wallet).
- الموضعان مكرران في main.dart و local_notification.dart و order_over_lay.dart
  و order_request_controller.dart — وُحِّدت كلها.
- حرس الطول في backgroundMessageHandler: كان length > 29 مع قراءة index 30
  ⇒ RangeError على قائمة طولها 30 بالضبط.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 00:07:27 +03:00
Hamza-AyedandClaude Opus 5 ab3be7e2e3 وصل سوكيت الراكب قبل إنشاء الرحلة — ليسبق FCM والـ polling
كان السوكيت مضموناً أن يخسر السباق الأول بنيوياً. ترتيب
startSearchingForDriver كان:
  ① await postRideDetailsToServer()  → add_ride.php يوزّع الطلب على الكباتن فوراً
  ② _addRideToWaitingTable()          (بلا await)
  ③ initConnectionWithSocket()        ← السوكيت يبدأ الاتصال الآن فقط

بين ① و③ نافذة = ذهاب/عودة HTTP + مصافحة WebSocket + قراءة الـ JWT، ثانية
إلى ثلاث (أسوأ على 3G). وغرف Socket.IO لا تخزّن الأحداث: لو قبل كابتن داخل
تلك النافذة فإن $io->to('passenger_X')->emit() يُرمى نهائياً لأن الغرفة
فارغة — لا طابور ولا إعادة إرسال. وكابتن ينظر لقائمة السوق يقبل في أقل من
ثانية، فالنافذة مُرجَّحة لا نادرة.

هذا يفسّر لماذا كان الـ 404 على getRideOrderID.php قاتلاً: السوكيت يخسر،
والـ FCM يصل بعد أن ضبط الـ polling _isAcceptanceProcessed=true فيُرفض،
والشبكة الاحتياطية الوحيدة مكسورة.

ترتيب السيرفر كان صحيحاً أصلاً (acceptRide.php ينادي
notifyPassengerOnRideServer قبل sendFCM_Internal) — المشكلة أن المستقبِل
لم يكن موجوداً بعد.

التغييرات:
- ensureConnectedBeforeRide(): يوصل وينتظر الانضمام للغرفة بسقف 4 ثوانٍ،
  ولا يُفشل إنشاء الرحلة عند انتهاء المهلة (نكمل ونتّكل على FCM/polling).
- startSearchingForDriver ينتظرها قبل postRideDetailsToServer.
- وصل السوكيت في initializeDataAfterLogin (عند فتح الخريطة) فيصير الانتظار
  صفراً عملياً في الحالة الطبيعية.
- _isConnecting يغطّي نافذة الـ await على الـ JWT حتى لا يفتح النداءان
  المتزامنان سوكيتين، وحرس على passengerID الفارغ.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 16:26:23 +03:00
Hamza-AyedandClaude Opus 5 f66db7db42 إضافة getRideOrderID.php المفقود — المسار الاحتياطي لبيانات السائق
تطبيق الراكب يطلب /ride/rides/getRideOrderID.php منذ البداية، والموجود على
السيرفر getRideOrderIDNew.php فقط ⇒ 404 صامت في getUpdatedRideForDriverApply.

هذا يفسّر عرضين ظنّاهما منفصلين:
- الـ polling يسبق الـ FCM فيضبط _isAcceptanceProcessed=true ثم يأخذ 404،
  فيُرفض بعدها payload الـ FCM الذي يحمل driver_info كاملاً
  ("Already processed") ⇒ الرحلة مقبولة بلا معلومات سائق.
- ولأن driverToken يبقى فارغاً، ترد send_fcm.php بـ 400 Missing: target
  ⇒ رسائل الراكب للسائق لا تُرسَل إطلاقاً. (الاتجاه المعاكس كان يعمل بعد
  إصلاح getRideWaiting.php — نفس خطأ التشفير معكوساً.)

getRideOrderIDNew.php لا يصلح بديلاً: داخلي عبر get_connect.php →
validateInternalKey فلا يستطيع التطبيق مناداته، ولا يرجع
ratingCount/completedRides/driverTier.

النقطة الجديدة:
- connect.php (JWT)، والراكب من الـ JWT فقط لا من الطلب (حماية IDOR).
- نفس استعلام acceptRide.php وشكل رده حرفياً حتى يقرأه
  _fillDriverDataLocally بنفس المفاتيح.
- فك تشفير driverToken.token — بلا ذلك يصل التطبيق blob يستخدمه كـ FCM
  target فيرفضه FCM بـ 400.
- تفادي تصادم المفاتيح: getUpdatedRideForDriverApply يقرأ
  passengerName + last_name كاسم الراكب، فلقب السائق نُقل إلى
  driver_last_name واسم الراكب الحقيقي يُرجَّع في مكانه.
- ride DB هو المرجع مع fallback على primary، ورحلة بلا سائق ترد success
  لا failure.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 16:18:02 +03:00
Hamza-AyedandClaude Opus 5 143146c1b4 إصلاح سوكيت الراكب وتوحيد مسارات الإشعارات
سوكيت الراكب (سبب عدم ظهور معلومات السائق عند القبول):
- تطبيق الراكب كان يرسل id فقط بلا jwt، و passenger_socket.php يرفض أي
  اتصال بلا jwt ⇒ الراكب لا ينضم لغرفته أبداً ولا يستلم ride_status_change
  ولا driver_location_update. تظهر حالة القبول عبر الـ polling فقط بينما
  driver_info يصل بالسوكيت وحده. (سوكيت السائق يعتبر الـ jwt اختيارياً،
  ومن هنا جاء التباين بين التطبيقين.)
- cancelled_by_driver كان يسقط من switch حالات الراكب فيبقى معلّقاً بعد
  إلغاء السائق.
- حماية socket (late) من القراءة قبل التهيئة عند الانسحاب بلا jwt.

الإشعارات والرسائل (سبب "مرات توصل ومرات لا"):
- جدول tokens يخزّن توكن الراكب مشفّراً، و getRideWaiting.php كان يرجعه
  بلا فك تشفير ⇒ من يقبل من قائمة السوق يحمل blob مشفّراً يستخدمه كـ FCM
  target فيرفضه FCM بـ 400: لا إشعار قبول ولا رسائل. ومن يقبل من الـ
  dispatch/FCM يحمل نصاً صريحاً فتعمل. الفرق كان في طريقة القبول.
- acceptRide.php يحلّ التوكن من القاعدة دائماً ولا يثق بالعميل (أصحّ أمنياً).
- market_new_ride كان لا يحمل passengerId ولا الإحداثيات فتصل "null"؛
  أُضيفت بلا أي PII لأن الحمولة تُبَثّ لكل سائق قريب لا للفائز فقط.
- send_fcm.php: مهلة على OAuth (كان يعلّق حتى مهلة PHP فتُسقط الرسالة
  بصمت)، توحيد ding→default لأندرويد، وحقن title/body/tone في data
  مطابقةً لـ FcmService.
- تطبيق السائق يقرأ title/body من data أولاً مثل الراكب، ولا يعرض فقاعة
  فارغة للرسائل الصامتة.

السوكيت والإعدادات:
- forwardLocationToPassengerSocket كان يقرأ lat/lng والحمولة فيها
  latitude/longitude ⇒ المسافة تخرج ضخمة والـ throttle معطّل تماماً
  فيُعاد التوجيه مع كل نبضة GPS.
- notifyPassengerOnRideServer كان يرجع null بصمت مطلق عند حجب العنوان.
- العنوان الافتراضي لسيرفر الموقع كان nginx/loction_server/driver_socket.php
  وهو ديمون Workerman لا يُخدَم عبر nginx ⇒ صار socket_driver:2021.
  (LOCATION_API_URL بقي على nginx لأن api_get_nearby.php سكربت عادي.)
- ride_server/passenger_socket.php (النسخة التي يشغّلها Docker) كانت ناقصة
  كل كود مواصلاتي الموجود في passenger_server/ ⇒ نُقل مع REDIS_HOST.
- .env.example: ALLOWED_SOCKET_URLS يغطّي أسماء حاويات Docker، وإضافة
  PASSENGER_SOCKET_INTERNAL_URL.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 15:47:23 +03:00
Hamza-Ayed e269cb9b70 إصلاح أخطاء شاشة الكباتن من تحديث الذكاء الاصطناعي 2026-07-26 13:44:07 +03:00
Hamza-Ayed 330dfc6dba إصلاح أخطاء شاشة الكباتن من تحديث الذكاء الاصطناعي 2026-07-26 13:15:45 +03:00
Hamza-Ayed 4b5235c35c إصلاح أخطاء شاشة الكباتن من تحديث الذكاء الاصطناعي 2026-07-26 12:18:23 +03:00
Hamza-Ayed 16feb51a75 إصلاح توافق فلاتر مع Theme الجديد 2026-07-26 11:36:26 +03:00
Hamza-Ayed 3af99cc18a إصلاح توافق فلاتر مع Theme الجديد 2026-07-26 11:33:20 +03:00
Hamza-Ayed 7830efead7 إصلاح توافق فلاتر مع Theme الجديد 2026-07-26 04:28:09 +03:00
Hamza-Ayed ca6cb7a3fe تصميم عالمي جديد، وإصلاح الخرائط ومراقب السيرفرات 2026-07-26 04:21:42 +03:00
Hamza-Ayed f325ffce42 تصميم عالمي جديد، وإصلاح الخرائط ومراقب السيرفرات 2026-07-26 04:02:10 +03:00
Hamza-Ayed c43f801542 إصلاح الشاشة البيضاء ومسار base-href 2026-07-26 03:26:15 +03:00
Hamza-Ayed 2bacb1b9e1 تحديث شامل للوحة التحكم وإضافة كافة الميزات للـ WebSidebar 2026-07-26 03:22:47 +03:00
Hamza-Ayed 5ec54c03f5 تحديث شامل للوحة التحكم وإضافة كافة الميزات للـ WebSidebar 2026-07-26 02:58:59 +03:00
Hamza-Ayed a954f49307 Update: 2026-07-26 02:51:53 2026-07-26 02:51:54 +03:00
Hamza-Ayed 91fe0f78f7 Update: 2026-07-26 01:29:57 2026-07-26 01:29:57 +03:00
Hamza-Ayed 5f5b68a8cd Update: 2026-07-26 01:27:56 2026-07-26 01:27:56 +03:00
Hamza-Ayed 1664743ef9 Update: 2026-07-26 01:11:28 2026-07-26 01:11:28 +03:00
Hamza-Ayed 1dfc302a4f Update: 2026-07-26 01:03:40 2026-07-26 01:03:41 +03:00
Hamza-Ayed 76c8652bf0 Update: 2026-07-25 20:18:18 2026-07-25 20:18:18 +03:00
Hamza-AyedandClaude Opus 5 a095472f39 تتبّع composer.lock ومنع تكرار انهيار خادم الدفع
vendor/ و composer.lock كانا مستثنيين في .gitignore، فلم يصل أيٌّ منهما
إلى السيرفر. النتيجة أن realpath() في payment_server/v2/main/connect.php:3
ترجع false وينهار كل مسار /v2/main/ بـ Fatal error.

- إزالة قاعدتَي composer.lock من .gitignore (vendor/ يبقى مستثنى)
- الالتزام بملفات القفل لـ payment_server/v2 و ride_server و loction_server
- ترقية firebase/php-jwt في payment_server/v2 من ^6.11 إلى ^7.0 (v7.1.0)
  لأن 6.11.x محجوب بتحذير أمني PKSA-y2cr-5h3j-g3ys — لا تغيير في الشيفرة،
  الاستخدام محصور في JWT::encode/decode و Key وأصناف الاستثناءات
- تثبيت platform.php=8.2 ليطابق القفل صورة الحاوية لا PHP المحلي

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 20:11:59 +03:00
Hamza-Ayed c8a9e98ff5 Update: 2026-07-25 20:09:31 2026-07-25 20:09:31 +03:00
Hamza-Ayed e03b9c30d5 Update: 2026-07-25 18:43:44 2026-07-25 18:43:44 +03:00
Hamza-Ayed 20ea9aa12c Update: 2026-07-25 18:42:18 2026-07-25 18:42:18 +03:00
Hamza-Ayed 8d3e63d1c7 Update: 2026-07-25 18:40:38 2026-07-25 18:40:38 +03:00
Hamza-Ayed 4bbc687c15 Update: 2026-07-25 18:28:30 2026-07-25 18:28:31 +03:00
Hamza-Ayed 5e103f60f2 Update: 2026-07-25 18:19:51 2026-07-25 18:19:52 +03:00
Hamza-Ayed 27369b8ac1 Update: 2026-07-25 18:05:37 2026-07-25 18:05:37 +03:00
Hamza-AyedandClaude Opus 5 61d6380861 Fix SQL injection and stale status matching in the wallet endpoints
The three endpoints the driver app calls for its wallet built their queries by
interpolating the driver id straight into SQL. Anything the app sent went into
the statement, and these run against the payments database.

They also matched only status = 'Finished'. The current ride pipeline writes
'completed', so a driver's completed rides, pending payouts and weekly
earnings all read as zero regardless of how much they had driven — which is
what the wallet errors in the admin error log are sitting next to.

getAllPayment.php, driverStatistic.php and getCountRide.php now bind the id
and match either spelling. Verified no interpolated identifier remains and
every rewritten condition is balanced.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 17:57:52 +03:00
Hamza-AyedandClaude Opus 5 3fb7bc5190 Show the build id, tame long table cells, and add purposeful motion
The build identifier now sits in the sidebar footer. "Is my deploy actually
live?" was only answerable by opening Session & Security, which is the wrong
place for the first question asked after every deploy.

Error-log rows carry stack traces and full URLs. They stretched their row far
past the viewport and pushed the other columns out of view, which is exactly
where the console is least usable. Values over 70 characters truncate and
expand on click.

Motion is limited to two things that mean something: content arriving
(staggered, so a grid resolves instead of snapping), and a fetch being in
flight — the refresh control spins and the status pill pulses, so a section
that legitimately returns nothing still shows that it tried. All of it is
disabled under prefers-reduced-motion.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 17:49:48 +03:00
Hamza-Ayed f9110a7d92 Update: 2026-07-25 17:40:28 2026-07-25 17:40:29 +03:00
Hamza-AyedandClaude Opus 5 a0812dbd10 Fix broadcast delivery; make transit organisations manageable
Broadcasts never reached anyone. The internal FCM call defaulted to
127.0.0.1, which inside the php container is the php container itself — the
web server runs in a separate nginx container, reachable by service name on
the Compose network. Every send failed the curl and returned a generic 502.
The default now points at nginx, the URL is overridable via FCM_INTERNAL_URL,
and the error carries the actual reason and target instead of a bare status.

Transit organisations were a read-only count table with nothing to act on.
The module now supports the operations an admin actually needs:
- open an organisation for its counts, routes, recent trips and admins
- create one, including the founding administrator create.php requires
- edit city, contact details, contract status and trial end, with a
  confirmation when the contract changes since suspending cuts off service
- add an administrator, and enable or disable an existing one

Verified end to end against the endpoints' real payload shapes, including
that an incomplete create form is rejected before any request is sent.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 17:10:51 +03:00
Hamza-AyedandClaude Opus 5 bc1b0129e8 Fix v2 analytics status matching; give Growth and Analytics real charts
Eight queries across the v2 modules counted only status = 'Finished' and so
reported zero on live data, where the current ride pipeline writes
'completed': realtime revenue for today and yesterday, financial stats,
settlements, driver scorecard, driver ranking, and both revenue queries. All
now match either spelling.

Growth and Advanced Analytics rendered through the generic shape-detecting
renderer, which produced raw tables that said little. Both now have purpose-
built views:

- Growth: totals, 30-day joins, and a two-series daily chart. growth.php only
  returns days that had signups, so the series is expanded to a continuous
  30-day axis with explicit zeros — plotting the returned rows directly would
  hide the gaps and make a quiet month look like steady growth. A caption
  states how many days actually had a signup.
- Analytics: revenue summary tiles, a daily revenue trend, and the captain
  ranking, with a note explaining that platform share is what remains after
  the captain's cut.

Null aggregates render as "—" rather than 0.00, and markers are drawn only on
days with a value so a flat zero line stays readable.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 16:55:58 +03:00
Hamza-AyedandClaude Opus 5 2135edcf43 Close the remaining ciphertext joins and a SQL injection in email verification
- Customer-service notes joined to the account by comparing encrypted phone
  columns. Both notes tables now carry phone_key, written when a note is
  saved, and the three joins match on it.
- The email_verifications join was comparing a plaintext column against an
  encrypted one, so it never matched and `verified` was always NULL in both
  passenger and driver sign-in. It is now resolved in PHP against the
  decrypted address, which fixes a pre-existing bug rather than only
  preparing for GCM.
- auth/sendVerifyEmail.php built all three of its statements by interpolating
  the request values into SQL. Any caller could inject through the email or
  token field. Now parameterised.
- serviceapp/register.php duplicate detection consults the users indexes and
  writes them with the row.

Sweep confirms no join or lookup compares two encrypted columns any more.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 16:48:10 +03:00
Hamza-AyedandClaude Opus 5 35a66935aa Repair verification joins broken by the OTP key change; extend backfill
Storing the verification phone as a keyed HMAC fixed OTP lookups but broke
every query that joined those tables back to the account, because
phone_verification*.phone_number no longer holds the same value as
driver.phone / passengers.phone. Six joins were affected, and four of them
feed the `verified` flag that the rider and driver apps check at sign-in — so
this was already failing under the current CBC mode, not only after a switch
to GCM.

Accounts now carry phone_key, computed exactly as otpPhoneKey() does, and the
joins match on it. It is written at registration for both apps and populated
for existing rows by the backfill.

The backfill also covers the columns added for the remaining lookups:
users.email_bidx/phone_bidx and driver.national_bidx, which were migrated but
never populated, and honours a per-field prefix so phone_key reproduces
otpPhoneKey's exact output.

Insert column/value counts verified with a paren-aware parser after editing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 16:40:53 +03:00
Hamza-AyedandClaude Opus 5 8d7e3118b5 Migrate remaining encrypted-column lookups to the blind index
Completes the set of queries that matched a freshly encrypted value against a
stored one, which only works while encryption is deterministic. Each keeps its
original comparison and adds an index comparison in the same WHERE, so nothing
changes today.

- passenger sign-in by email, service-staff sign-in, Firebase token lookup
- driver lookup by phone and by national number
- admin ride lookup and ride monitor (both tables)
- nabeh: driver status, user resolution, ride history, complaint submission

transit_org_admins lives in the transit database and has no index column, so
login there falls back to decrypting the small set of active admins and
comparing normalised numbers.

Schema: adds users.email_bidx/phone_bidx and driver.national_bidx with their
indexes.

Verified that every :*_bidx placeholder introduced is actually bound — an
unbound one is a fatal error at request time, not a silent miss.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 16:36:32 +03:00
Hamza-AyedandClaude Opus 5 39b5a7fc7f Keep OTP phone numbers recoverable for customer-service follow-up
Storing the verification phone as a keyed HMAC made OTP lookups independent
of the encryption mode, but the hash is one-way — and customer service reads
those same rows to chase people who requested a code and never finished
registering. That workflow would have lost the number entirely.

The verification tables now carry both forms: phone_number holds the lookup
key, and a new phone_enc column holds the encrypted number, which is
decryptable when a human needs to call.

The two follow-up queries also compared the verification row against the
driver/passengers tables and the notes tables by matching ciphertext, which
only ever worked because encryption was deterministic. Under GCM every number
would have looked unregistered and every note would have disappeared. Both now
read the number from phone_enc and match on normalised plaintext, so they are
correct under either mode.

Rows written before phone_enc existed are skipped rather than shown without a
number.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 16:27:29 +03:00
Hamza-AyedandClaude Opus 5 a1c19b052d Make OTP verification independent of the encryption mode
The verification tables (token_verification*, phone_verification*) use the
phone number as a lookup key: written when the code is sent, read when it is
checked. Storing it encrypted worked only because encryptData() is
deterministic — under AES-GCM the two sides would produce different
ciphertexts and no code would ever verify, locking every user out of
registration and OTP sign-in.

otpPhoneKey() stores a keyed HMAC of the normalised number instead. No schema
change is needed since the column is textual, local and international formats
now resolve to the same key, and the value cannot be reversed without the
pepper. It falls back to the previous behaviour when no pepper is configured.

Applied to both sides of every affected flow — request/verify, and the driver
and passenger send/verify pairs — including the OTP value itself where it is
compared by equality rather than decrypted. auth/otp/verify.php already
decrypts the token before comparing, so it needed no change there.

Also adds ENCRYPTION_MODE to EncryptionHelper: encryptData() writes GCM when
set to 'gcm', CBC otherwise. Verified in both directions — rows written under
CBC stay readable after switching, and rows written under GCM stay readable
after rolling back — so the switch is reversible by an environment variable.

The admin console's own OTP is unaffected: it keys the table by the stored
ciphertext read from adminUser, identical on both sides.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 16:18:16 +03:00
Hamza-AyedandClaude Opus 5 c9b4d14da6 Route account lookups through the blind index and keep it fresh on write
These are the paths that must stop depending on deterministic encryption
before storage can move to AES-GCM. Each keeps its original ciphertext
comparison in the same statement, so behaviour is unchanged today and no
account becomes unreachable during the transition.

Lookups:
- auth/login.php — passenger sign-in matched the raw value against the
  encrypted column, which only works because encryptData() is CBC with a
  fixed IV.
- auth/passenger/register.php and auth/driver/register.php — duplicate
  detection. Without the index these would stop detecting existing accounts
  under GCM and allow the same phone to register twice.

Writes now populate the index in the same statement as the value:
- both registration paths write phone/email/name indexes with the row;
  driver indexes are computed before the encryption pass, since the raw
  values are unavailable afterwards.
- passenger profile update and admin driver update refresh the index when
  the underlying field changes. For the composite name index the untouched
  half is read back from the row.

Adds --audit to the backfill script: recomputes every index from its
encrypted value and reports missing or stale entries. Drift here is silent
by nature — it surfaces only when a real search fails.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 16:04:40 +03:00
Hamza-AyedandClaude Opus 5 15f55ff3e4 Add --verify to the backfill script
Confirms a value is findable through the blind index after backfilling,
without opening the console or the database. Prints matched row ids only.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 15:59:50 +03:00
Hamza-AyedandClaude Opus 5 761b957c96 Silence REQUEST_METHOD warning when bootstrap runs from the CLI
The migration and backfill scripts load bootstrap.php outside a request, where
$_SERVER['REQUEST_METHOD'] does not exist, so every CLI run printed a warning
before its output.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 15:55:18 +03:00
Hamza-AyedandClaude Opus 5 57e22477fb Add an idempotent CLI migration runner
phpMyAdmin is unreachable on this deployment, so schema changes need a path
that does not depend on it. migrate.php reuses core/Database, meaning no
credentials are passed on the command line, and checks information_schema
before each ALTER so re-running is safe and never fails on a duplicate
column. Supports --status and --dry-run.

Covers the blind-index columns and the missing adminUser status/approved_by/
approved_at columns. Every change is additive and nullable, so applying it to
a running database changes no behaviour on its own.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 15:35:34 +03:00
Hamza-AyedandClaude Opus 5 6802026dbd Add blind-index search layer; fix captain detail 200-with-empty-body
Searching encrypted columns currently works only because encryptData() is
AES-CBC with a fixed IV, i.e. deterministic. That determinism is what leaks
equality and shared prefixes, and it is why moving storage to AES-GCM would
break every lookup. This separates the two concerns.

- core/Security/BlindIndex.php: HMAC-SHA256 over a normalised value, keyed by
  a secret pepper. Phone numbers have a small keyspace, so a bare SHA-256
  would be reversible by enumeration; the pepper lives in the environment, not
  the database. The scope string includes table and field so the same number
  does not produce a matching index across tables.
  Normalisation unifies local/international phone forms, lowercases emails and
  folds Arabic alef/ya/ta-marbuta and diacritics for names.
- migrations/: nullable *_bidx columns plus indexes, and the missing
  adminUser.status/approved_by/approved_at columns that admin approvals need.
- scripts/backfill_blind_index.php: restartable, batched, --dry-run capable,
  touches only index columns.
- Admin lookups by phone/email now match the index, keeping the old ciphertext
  comparison in the same query so search keeps working until the backfill runs.
  bootstrap exposes $blindIndex as null when no pepper is configured.

Also: AdminCaptain/getCaptainDetailsById.php selected driver.education, a
column absent from this schema. The PDOException was uncaught, so the client
received an empty body with HTTP 200 — the "non-JSON response" seen when
opening a captain. It now omits the column, catches the error, reports it as
JSON, and requires an admin role.

Console: opening any sidebar section refetches its data instead of showing
what was loaded when the console started.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 15:16:09 +03:00
Hamza-AyedandClaude Opus 5 81ee2acefd Add removal/blacklist tools, Arabic UI, and a persistent sign-in error
Authorisation: driver/deleteCaptain.php permanently deletes a captain and had
no role check at all — any valid token, including a driver's or passenger's,
could delete captains. It now requires super_admin. The two unblacklist
endpoints had no role check either and now require an admin role.

Console:
- Blacklist & removal screen (super admin only): current blocks, permanent
  removal, and lifting a block. Deletion additionally requires the phone
  number to be retyped, because the row is deleted outright.
- Arabic interface with full RTL layout and a language toggle. Sidebar,
  content offset, input affordances, toasts and directional icons all mirror;
  numbers, identifiers and the diagnostics output stay LTR.
- Sign-in failures now render in the form and stay there. They were only
  shown as a toast, which disappears before it can be read — a locked
  account or a rejected device looked like the page simply returning to
  the login screen with no explanation.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 14:53:26 +03:00
Hamza-Ayed 42f6d33efd Update: 2026-07-25 14:44:30 2026-07-25 14:44:30 +03:00
Hamza-AyedandClaude Opus 5 4009af8dd3 Add campaign launcher and app version manager; fix SQL injection in updatePackages
serviceapp/updatePackages.php built its UPDATE by interpolating the request
values straight into the SQL string, so any caller with a valid token could
execute arbitrary SQL through the version field. It now uses bound
parameters, requires an admin role, validates the version format, and writes
an audit entry.

trigger_campaign.php gains dry_run=1: it performs the same Gemini analysis
and target selection but returns before creating the promo code and before
dispatching any notification. Launching without previewing was the only
option before, and a launch writes a seven-day discount and pushes to every
passenger in the country.

Console:
- Campaign launcher with a mandatory preview. Launching stays disabled until
  the current parameters have been previewed, and re-locks if any parameter
  changes afterwards or once a launch completes.
- App version manager with the same version-format check as the server and a
  confirmation naming the old and new values.

Cache busting: assets are served straight off a bind mount with no version,
so browsers kept running the previously cached build after a deploy. Both
asset links now carry ?v=, and the build id is shown in Session & Security
and printed in the diagnostics report.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 14:41:27 +03:00
Hamza-AyedandClaude Opus 5 67f55e5192 Add driver document review and staff onboarding
Driver documents: paged list from auth/driver/drivers_pending_list.php, a
detail panel showing each uploaded document as a thumbnail linking to the
full image, and activation via Admin/driver/updateDriverFromAdmin.php. The
confirmation states how many documents were reviewed and warns explicitly
when a captain has none on file, since approving then activates an
unverified account.

Details are requested as a POST body. The mobile app calls this endpoint as
GET "?id=", which filterRequest() never reads, so its detail lookup cannot
be receiving an id at all.

Staff: pending admin/service accounts with per-account activation via
Staff/activate.php, the employee list, and a creation form posting to
Staff/add.php. Administrator accounts are offered only to super admins,
matching add.php's own check; passwords are rejected below 8 characters and
cleared from the form after submission.

Both screens mask phone numbers for plain admins and never render
token/password/fingerprint fields.

Also stop .btn-primary stretching to full width when used inline in a card
header — it is styled for the login form.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 14:30:49 +03:00
Hamza-AyedandClaude Opus 5 a0ab6c5155 Add broadcast notifications and transit route approvals
Broadcast: ride/firebase/send_fcm.php is an internal service guarded by a
shared secret, so the browser cannot call it — holding that key client-side
would expose it, and the endpoint cannot tell who the sender is. A new
Admin/notifications/broadcast.php sits in front of it: it runs behind
connect.php, requires super_admin, restricts the target to the two topics the
apps actually subscribe to ('drivers'/'passengers') so it cannot be used to
push to an arbitrary topic or a single device token, bounds the title and
body, writes an audit entry before dispatching, and only then forwards the
call internally with the shared secret.

The composer shows a live push preview and an explicit confirmation naming
the audience, since a broadcast cannot be recalled.

Route approvals: draft routes render with their stops, distance and stop
count, and approve/reject posts to transit/route/approve.php behind a
confirmation stating the consequence. Available to admins and super admins,
matching the endpoint's own role check.

Also render user-supplied text with unicode-bidi: plaintext — Arabic names,
addresses and messages were being laid out left-to-right inside the
English UI.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 02:15:02 +03:00
Hamza-AyedandClaude Opus 5 41a06bba0c Add fleet, invoice, promo and lookup-driven admin modules
Brings the console to 18 modules across 26 navigation entries.

- Fleet performance (best captains, per-captain card charges), invoice
  totals and promo codes as read-only panels.
- Ride monitor: monitorRide.php and getDriverGiftPayment.php answer only for
  a given phone number, so they get an input rather than a panel that would
  render an error on load.
- Status-like values in generated tiles use the same label mapping as the
  tables, so raw values such as cancelled_by_passenger no longer leak into
  the UI.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 02:02:08 +03:00
Hamza-AyedandClaude Opus 5 db4ca7dd7a Fix dashbord.php parse error; require super_admin on pricing and crypto tools
Hotfix: a comment added to the dashboard SQL contained double quotes inside
the double-quoted PHP string, terminating it and making dashbord.php fail to
parse. Production was returning a parse error for every dashboard request.

Authorisation gaps closed — connect.php only proves a token is valid, it does
not check what the caller is allowed to do:

- Admin/ggg.php decrypts any database field and was authorised solely by an
  admin phone number sent in the request body. Anyone who knew a listed
  number could decrypt platform data without signing in. It now runs behind
  connect.php, requires super_admin, keeps the phone list as a second factor,
  and records every use.
- ride/kazan/update.php, kazan/add.php and ride/promo/{add,update,delete}.php
  changed live pricing and discount codes with no role check at all, so any
  valid token — including a driver's or passenger's — could rewrite the fare
  table. All now require super_admin.

Staff/pending.php: adminUser has no `status` column in this deployment, so
the query failed with an opaque "unavailable". It now checks for the column
and reports the actual reason.

Console: Kazan tariff editor for super admins — sends only changed fields,
shows an old → new confirmation before saving, and stays read-only with an
explanatory notice for plain admins.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 02:00:14 +03:00
Hamza-AyedandClaude Opus 5 852c6ece5c Fix admin status handling for the current ride pipeline; extend console
The ride table holds two generations of status values: the legacy CamelCase
set ('Finished', 'CancelFromPassenger') and the lowercase set written by
backend/ride/rides/* today ('completed', 'cancelled_by_passenger'). Admin
queries only matched the legacy set, so on live data:

- get_rides_by_status.php returned nothing meaningful for every filter, and
  the "in progress" default masked it.
- dashbord.php reported total_driver_earnings as NULL, completed_rides as a
  fraction of the real count, and cancelled_rides as 0.
- driver_avg_duration averaged in negative durations, yielding "-00h 22m".

All three now match on LOWER(status) across both families.

Staff/pending.php ran with no authentication at all, exposing pending
admins' names and phone numbers to any caller; it now goes through
connect.php with a role check. It also returned HTTP 400 for everything when
the `users` table was absent — each source is queried independently and
reports its own availability.

Console:
- Render rides from either schema generation (price/date/time and
  start_location coordinates, or the older address/created_at columns).
- Null aggregates render as "—" rather than a measured 0.00.
- Add tariff/promo, WhatsApp send and encryption modules, all super-admin
  gated; pricing remains read-only.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 01:47:55 +03:00
Hamza-Ayed 915a148ebf Update: 2026-07-25 01:38:11 2026-07-25 01:38:11 +03:00
Hamza-Ayed 0d9095fd3f Update: 2026-07-25 01:16:32 2026-07-25 01:16:33 +03:00
Hamza-Ayed eda7018434 Update: 2026-07-25 01:02:01 2026-07-25 01:02:02 +03:00
Hamza-Ayed 822cb5963a Ensure Live Backend mode is enforced and clear old Demo localStorage session 2026-07-25 00:44:11 +03:00
Hamza-Ayed 8ec7b9aae6 Bind live MySQL database tables (Rides, Passengers, Pending Approvals) into Siro Admin Portal 2026-07-25 00:41:18 +03:00
Hamza-Ayed c9168c1c80 Enhance Siro Admin Dashboard with live backend API database bindings 2026-07-25 00:33:32 +03:00
Hamza-Ayed 10f1154cc7 Update adminUser fingerprint and fingerprint_hash in database upon successful OTP verification 2026-07-25 00:30:14 +03:00
Hamza-Ayed 9d2a665d64 Restore WhatsApp OTP (Nabeh API) flow for Admin authentication 2026-07-25 00:25:53 +03:00
Hamza-Ayed 4c738e8f43 Remove legacy encrypt_decrypt.php - bootstrap.php already provides encryptionHelper 2026-07-25 00:23:27 +03:00
Hamza-Ayed 032e1edda5 Remove broken providers.php require_once - issue JWT directly on valid password 2026-07-24 23:59:27 +03:00
Hamza-Ayed 1ca2c5a5dd Fix require_once path in login.php using realpath 2026-07-24 23:51:28 +03:00
Hamza-Ayed f115292dd2 Refactor login.php with decryption lookup for encrypted fields and restore Nabeh OTP integration 2026-07-24 23:48:57 +03:00
Hamza-Ayed 60e344598b Fix Admin login path issue and issue direct JWT on valid credentials 2026-07-24 23:45:28 +03:00
Hamza-Ayed 8bc9290916 Safely initialize encryptionHelper and handle Throwable in Admin login.php 2026-07-24 23:42:39 +03:00
Hamza-Ayed 9e2964d307 Allow email and ID login in Admin auth login.php and bind web device fingerprint 2026-07-24 23:38:17 +03:00
Hamza-Ayed b3126013f5 Update: 2026-07-24 23:31:37 2026-07-24 23:31:37 +03:00
Hamza-Ayed 5ebff42841 Update: 2026-07-24 23:23:54 2026-07-24 23:23:55 +03:00
Hamza-Ayed 2944f21f53 Add dashboard web applications (siro-admin & siro-service) with docker Nginx routing 2026-07-24 22:59:26 +03:00
Hamza-Ayed 917dfc025f Update: 2026-07-24 22:57:32 2026-07-24 22:57:32 +03:00
Hamza-Ayed 0b24bc21b6 Update: 2026-07-24 22:55:34 2026-07-24 22:55:34 +03:00
Hamza-Ayed 474c212bcb refactor: migrate amount fields to decimal and implement location service restriction for unsupported regions 2026-07-24 15:08:37 +03:00
Hamza-Ayed e7629a9eb9 Update: 2026-07-23 22:14:10 2026-07-23 22:14:10 +03:00
Hamza-Ayed 695d6d7cb2 Update: 2026-07-23 21:18:25 2026-07-23 21:18:25 +03:00
Hamza-Ayed e7aa28fe3d Update: 2026-07-23 21:05:22 2026-07-23 21:05:22 +03:00
Hamza-Ayed 7d646b579b Update: 2026-07-23 21:02:51 2026-07-23 21:02:51 +03:00
Hamza-Ayed b4451a0dde Update: 2026-07-23 20:50:10 2026-07-23 20:50:10 +03:00
Hamza-Ayed 92eb7fe25d Update: 2026-07-23 20:43:21 2026-07-23 20:43:21 +03:00
Hamza-Ayed 1e785061ec Fix decryptData null type error and live analytics overflow 2026-07-23 20:42:48 +03:00
Hamza-Ayed 12e70f3d7e Fix status warning in admin login 2026-07-23 20:34:27 +03:00
Hamza-Ayed 12a1cbc98c Update: 2026-07-23 20:15:22 2026-07-23 20:15:22 +03:00
Hamza-Ayed c35b350b31 Update: 2026-07-23 16:56:57 2026-07-23 16:56:58 +03:00
Hamza-Ayed 1cef598fc5 Update: 2026-07-23 02:19:01 2026-07-23 02:19:01 +03:00
Hamza-Ayed e5bf70fddb Update: 2026-07-23 02:14:58 2026-07-23 02:14:58 +03:00
Hamza-Ayed 9e065e5a83 Update: 2026-07-23 00:16:56 2026-07-23 00:16:56 +03:00
Hamza-Ayed ed8a93a6a3 Update: 2026-07-23 00:13:41 2026-07-23 00:13:41 +03:00
Hamza-Ayed a7fa40dc31 Update: 2026-07-23 00:11:36 2026-07-23 00:11:37 +03:00
Hamza-Ayed b86f95c90d Update: 2026-07-22 23:27:18 2026-07-22 23:27:18 +03:00
Hamza-Ayed b83ca1f664 Update: 2026-07-22 23:20:32 2026-07-22 23:20:33 +03:00
Hamza-Ayed fbb95c70fa Update: 2026-07-22 23:06:34 2026-07-22 23:06:34 +03:00
Hamza-Ayed b9efba3787 Update: 2026-07-22 18:32:11 2026-07-22 18:32:11 +03:00
Hamza-Ayed e798f84c03 Update: 2026-07-22 18:30:10 2026-07-22 18:30:11 +03:00
Hamza-Ayed 55fbe22f8e Update: 2026-07-22 18:23:10 2026-07-22 18:23:10 +03:00
Hamza-Ayed f76623a25e Update: 2026-07-22 18:20:33 2026-07-22 18:20:33 +03:00
Hamza-Ayed f62716b510 Update: 2026-07-22 18:11:54 2026-07-22 18:11:54 +03:00
Hamza-Ayed 771b436c69 Update: 2026-07-22 17:58:19 2026-07-22 17:58:19 +03:00
Hamza-Ayed 939c7a9c2c Update: 2026-07-22 17:49:27 2026-07-22 17:49:28 +03:00
Hamza-Ayed ccbe3ab88d Update: 2026-07-22 16:01:21 2026-07-22 16:01:21 +03:00
Hamza-Ayed 09a4bbc79f Fix driver visibility radius and silence tolerance in api_get_nearby 2026-07-22 15:45:54 +03:00
Hamza-Ayed 901f429b9c Update driver and rider socket URLs to jordan-siro.intaleqapp.com for Docker setup 2026-07-22 04:15:18 +03:00
Hamza-Ayed 6282be37d8 Fix get.php key loading fallback 2026-07-22 04:03:37 +03:00
Hamza-Ayed a2f0911d13 Fix api_get_nearby syntax error and Docker key paths 2026-07-22 03:59:40 +03:00
Hamza-Ayed dabf4c13ba Fix driver_socket JWT compatibility for Flutter app 2026-07-22 03:57:14 +03:00
Hamza-Ayed 1b45b505f8 Update: 2026-07-22 01:40:24 2026-07-22 01:40:24 +03:00
Hamza-Ayed 8ec0ac2942 Update: 2026-07-22 01:35:37 2026-07-22 01:35:37 +03:00
Hamza-Ayed 26d0ec2982 Update: 2026-07-22 01:07:41 2026-07-22 01:07:41 +03:00
Hamza-Ayed 11d7d86b2f Update: 2026-07-22 01:06:03 2026-07-22 01:06:03 +03:00
Hamza-Ayed a4b5a2545c Update: 2026-07-22 01:04:56 2026-07-22 01:04:57 +03:00
Hamza-Ayed be14b2716e Update: 2026-07-22 01:01:26 2026-07-22 01:01:26 +03:00
Hamza-Ayed 9a73f4303d Update: 2026-07-22 00:55:45 2026-07-22 00:55:45 +03:00
Hamza-Ayed bbcefd20cf Update: 2026-07-22 00:52:19 2026-07-22 00:52:20 +03:00
Hamza-Ayed 521d76c4cf Update: 2026-07-22 00:48:30 2026-07-22 00:48:30 +03:00
Hamza-Ayed b613022169 Update: 2026-07-22 00:46:37 2026-07-22 00:46:37 +03:00
Hamza-Ayed 540e77984b Update: 2026-07-22 00:44:11 2026-07-22 00:44:11 +03:00
Hamza-Ayed bec8089fd1 Update: 2026-07-22 00:42:09 2026-07-22 00:42:09 +03:00
Hamza-Ayed a5ae6fecbe Update: 2026-07-22 00:40:58 2026-07-22 00:40:58 +03:00
Hamza-Ayed 16101927e1 Update: 2026-07-22 00:39:28 2026-07-22 00:39:28 +03:00
Hamza-Ayed 58222fbf81 Update: 2026-07-22 00:37:03 2026-07-22 00:37:03 +03:00
Hamza-Ayed bcab0ea221 Update: 2026-07-22 00:36:04 2026-07-22 00:36:05 +03:00
Hamza-Ayed 87b4f12da0 Update: 2026-07-22 00:33:44 2026-07-22 00:33:44 +03:00
Hamza-Ayed 17abdada10 Update: 2026-07-22 00:32:07 2026-07-22 00:32:07 +03:00
Hamza-Ayed 2b302db1dd Update: 2026-07-22 00:29:56 2026-07-22 00:29:56 +03:00
Hamza-Ayed cf95455bcf Update: 2026-07-22 00:27:49 2026-07-22 00:27:50 +03:00
Hamza-Ayed 699b380f2b Update: 2026-07-21 20:58:30 2026-07-21 20:58:30 +03:00
Hamza-Ayed 3d0c266b7a Update: 2026-07-21 20:55:19 2026-07-21 20:55:20 +03:00
Hamza-Ayed 586deec4f4 Update: 2026-07-21 20:50:03 2026-07-21 20:50:04 +03:00
Hamza-Ayed bb3536aa90 Update: 2026-07-21 20:40:48 2026-07-21 20:40:48 +03:00
Hamza-Ayed 23f697b1c6 Update: 2026-07-21 19:43:50 2026-07-21 19:43:51 +03:00
Hamza-Ayed 1bec13634a Update: 2026-07-21 19:34:29 2026-07-21 19:34:29 +03:00
Hamza-Ayed 0ee3655c05 Update: 2026-07-21 19:31:02 2026-07-21 19:31:02 +03:00
Hamza-Ayed 4f47c0ad1d Update: 2026-07-21 19:28:08 2026-07-21 19:28:08 +03:00
Hamza-Ayed f3905bcb2c Update: 2026-07-21 19:24:57 2026-07-21 19:24:57 +03:00
Hamza-Ayed 1103f6ffcf Update: 2026-07-21 19:22:23 2026-07-21 19:22:23 +03:00
Hamza-Ayed 0351bffafc Update: 2026-07-21 19:19:15 2026-07-21 19:19:15 +03:00
Hamza-Ayed 096f6a13a0 Update: 2026-07-21 19:15:57 2026-07-21 19:15:57 +03:00
Hamza-Ayed ebd6f3734a Update: 2026-07-21 19:09:42 2026-07-21 19:09:42 +03:00
Hamza-Ayed 8d8c3a3817 Update: 2026-07-21 19:03:47 2026-07-21 19:03:47 +03:00
Hamza-Ayed 432245a688 Update: 2026-07-21 18:55:51 2026-07-21 18:55:51 +03:00
Hamza-Ayed 5d68ec5d0c Update: 2026-07-21 18:33:13 2026-07-21 18:33:13 +03:00
Hamza-Ayed c9bef58f47 Update: 2026-07-21 18:31:25 2026-07-21 18:31:25 +03:00
Hamza-Ayed 36ca266132 Update: 2026-07-21 18:25:21 2026-07-21 18:25:21 +03:00
Hamza-Ayed e88d45add4 Update: 2026-07-21 18:24:21 2026-07-21 18:24:21 +03:00
Hamza-Ayed 6d6c7cab7f Update: 2026-07-21 18:18:21 2026-07-21 18:18:21 +03:00
Hamza-Ayed 818220bba2 Update: 2026-07-21 17:47:43 2026-07-21 17:47:43 +03:00
Hamza-Ayed 0f59975144 Update: 2026-07-21 17:31:31 2026-07-21 17:31:31 +03:00
Hamza-Ayed 24e03ae46c Update: 2026-07-21 17:29:09 2026-07-21 17:29:09 +03:00
Hamza-Ayed 58ada98dd7 Update: 2026-07-21 17:27:39 2026-07-21 17:27:39 +03:00
Hamza-Ayed 1b4d831ca6 Update: 2026-07-21 17:23:24 2026-07-21 17:23:24 +03:00
Hamza-Ayed 69f043c297 Update: 2026-07-21 17:19:49 2026-07-21 17:19:50 +03:00
Hamza-Ayed e1154d7281 Update: 2026-07-21 17:16:36 2026-07-21 17:16:36 +03:00
Hamza-Ayed 630c6277ac Update: 2026-07-21 17:13:31 2026-07-21 17:13:31 +03:00
Hamza-Ayed 772398d961 Update: 2026-07-21 17:09:08 2026-07-21 17:09:08 +03:00
Hamza-Ayed b89191c018 Update: 2026-07-21 16:59:10 2026-07-21 16:59:10 +03:00
Hamza-Ayed 13d10d13c7 feat: implement gate selection bottom sheet for location routing and update intaleq_maps dependency 2026-07-21 16:12:08 +03:00
Hamza-Ayed 085b180bdb feat: implement secure OTP-based payout workflow with dynamic fee calculation and improved authentication checks 2026-07-19 01:51:39 +03:00
Hamza-Ayed 5e80c886a0 Update: 2026-07-17 00:32:33 2026-07-17 00:32:33 +03:00
Hamza-Ayed dda813ace1 Update: 2026-07-17 00:31:27 2026-07-17 00:31:27 +03:00
Hamza-Ayed 5ae5628f37 Update: 2026-07-17 00:23:48 2026-07-17 00:23:48 +03:00
Hamza-Ayed b385cace36 Update: 2026-07-17 00:20:03 2026-07-17 00:20:03 +03:00
Hamza-Ayed 64b17fbb26 Update: 2026-07-17 00:19:20 2026-07-17 00:19:20 +03:00
Hamza-Ayed c00bfa24ba Update: 2026-07-17 00:18:34 2026-07-17 00:18:34 +03:00
Hamza-Ayed 1f57b642c3 Update: 2026-07-17 00:17:59 2026-07-17 00:17:59 +03:00
Hamza-Ayed c5ed2099f9 Update: 2026-07-17 00:15:49 2026-07-17 00:15:49 +03:00
Hamza-Ayed 8cb83b31f2 Update: 2026-07-17 00:13:30 2026-07-17 00:13:30 +03:00
Hamza-Ayed 034d64b6f2 Update: 2026-07-16 23:19:11 2026-07-16 23:19:11 +03:00
Hamza-Ayed ab77ed529a Update: 2026-07-14 19:10:36 2026-07-14 19:10:36 +03:00
Hamza-Ayed 48382f5d4a docs: restructure documentation, add digital legacy report, and secure contracts 2026-07-14 18:45:29 +03:00
Hamza-Ayed 540ae4d4bc chore: reorganize transit documentation and remove obsolete project files and assets 2026-07-14 17:57:01 +03:00
Hamza-Ayed a81f805796 Update: 2026-07-14 00:54:50 2026-07-14 00:54:51 +03:00
Hamza-Ayed a547b81b60 Update: 2026-07-14 00:34:22 2026-07-14 00:34:22 +03:00
Hamza-Ayed c956f27230 Update: 2026-07-14 00:10:05 2026-07-14 00:10:05 +03:00
Hamza-Ayed c3fb42cae9 Update: 2026-07-13 23:44:27 2026-07-13 23:44:27 +03:00
Hamza-Ayed a2484d0bf5 Update: 2026-07-13 22:31:28 2026-07-13 22:31:29 +03:00
Hamza-Ayed c6f48a1f91 Update: 2026-07-13 22:23:21 2026-07-13 22:23:22 +03:00
Hamza-Ayed fd3f4a365a Update: 2026-07-13 18:23:52 2026-07-13 18:23:52 +03:00
Hamza-Ayed 7bf6dc1be7 Update: 2026-07-13 04:13:50 2026-07-13 04:13:50 +03:00
Hamza-Ayed 653d73422f Update: 2026-07-12 18:53:59 2026-07-12 18:53:59 +03:00
Hamza-Ayed 8cd4a4b57e Update: 2026-07-12 17:46:46 2026-07-12 17:46:46 +03:00
Hamza-Ayed 27200013ac Update: 2026-07-12 17:22:40 2026-07-12 17:22:40 +03:00
Hamza-Ayed 8fa2f153c1 refactor: disable Mawasalati feature, wrap controller initialization in post-frame callbacks, and add documentation plan 2026-07-12 06:27:36 +03:00
Hamza-Ayed 08340493c0 Update: 2026-07-12 06:04:42 2026-07-12 06:04:42 +03:00
Hamza-Ayed 1f68cb7333 Update: 2026-07-12 05:49:17 2026-07-12 05:49:17 +03:00
Hamza-Ayed 24fb56f08f Update: 2026-07-12 05:40:28 2026-07-12 05:40:28 +03:00
Hamza-Ayed 1fa517acc9 chore: remove service_unavailable_area translation keys and add mowasalaty strategy report 2026-07-12 02:53:36 +03:00
Hamza-Ayed 8f4bb1631c Update: 2026-07-12 00:24:19 2026-07-12 00:24:19 +03:00
Hamza-Ayed 83f5bf516b feat: add Nabeh payment verification proxy and update UI components 2026-07-11 22:14:37 +03:00
Hamza-Ayed de761c1d97 Update: 2026-07-11 19:38:43 2026-07-11 19:38:43 +03:00
Hamza-Ayed 9535d702d6 Update: 2026-07-11 19:32:42 2026-07-11 19:32:42 +03:00
Hamza-Ayed 8353c4cef4 Update: 2026-07-11 19:26:05 2026-07-11 19:26:05 +03:00
Hamza-Ayed ce2f3d5675 Update: 2026-07-11 19:11:50 2026-07-11 19:11:50 +03:00
Hamza-Ayed cb9aefc591 Update: 2026-07-11 19:04:58 2026-07-11 19:04:59 +03:00
Hamza-Ayed 06dc0aaffe Update: 2026-07-11 05:39:23 2026-07-11 05:39:23 +03:00
Hamza-Ayed 8b19adeb80 Update: 2026-07-11 00:49:03 2026-07-11 00:49:03 +03:00
Hamza-Ayed 04468dad08 Update: 2026-07-10 23:59:23 2026-07-10 23:59:23 +03:00
Hamza-Ayed 6294d6e725 Update: 2026-07-10 22:31:26 2026-07-10 22:31:27 +03:00
Hamza-Ayed 607c9bd9f4 Update: 2026-07-10 19:42:49 2026-07-10 19:42:50 +03:00
Hamza-Ayed 2bce11b940 Update: 2026-07-10 17:26:15 2026-07-10 17:26:16 +03:00
Hamza-Ayed 81d4715664 Update: 2026-07-10 16:09:37 2026-07-10 16:09:37 +03:00
Hamza-Ayed 5fb2c25504 Update: 2026-07-10 13:41:34 2026-07-10 13:41:34 +03:00
Hamza-Ayed be6e5bed92 Update: 2026-07-10 03:07:55 2026-07-10 03:07:55 +03:00
Hamza-Ayed b18fd027b6 Update: 2026-07-10 03:04:06 2026-07-10 03:04:06 +03:00
Hamza-Ayed 2ff7450d0b Update: 2026-07-09 17:18:06 2026-07-09 17:18:06 +03:00
Hamza-Ayed 461a1402ab Update: 2026-07-09 16:59:48 2026-07-09 16:59:48 +03:00
Hamza-Ayed 5e6aeb7908 refactor: unify device analysis and performance testing logic for improved module consistency 2026-07-09 15:09:02 +03:00
Hamza-Ayed d94808c380 Update: 2026-07-09 15:01:29 2026-07-09 15:01:29 +03:00
Hamza-Ayed 87dc925ea7 Refactor(Auth): Complete auth folder restructuring, security patches, and Flutter endpoint updates 2026-07-09 05:22:05 +03:00
Hamza-Ayed 45859883a5 Update: 2026-07-09 05:02:10 2026-07-09 05:02:10 +03:00
Hamza-Ayed 2152d34a8e fix: resolve stale price display in driver ratings and remove misleading discount UI in rider ratings 2026-07-09 04:48:19 +03:00
Hamza-Ayed 03e9d648a1 chore: update localization strings for driver and rider apps 2026-07-09 04:22:12 +03:00
Hamza-Ayed a526dae042 Update: 2026-07-09 04:13:14 2026-07-09 04:13:14 +03:00
Hamza-Ayed 70718946f5 Update: 2026-07-09 03:41:48 2026-07-09 03:41:48 +03:00
Hamza-Ayed 7dff7b6973 Update: 2026-07-09 01:55:25 2026-07-09 01:55:25 +03:00
Hamza-Ayed ac0c343f18 Update: 2026-07-09 01:01:15 2026-07-09 01:01:16 +03:00
Hamza-Ayed 6fe1d665e7 Update: 2026-07-08 23:37:26 2026-07-08 23:37:26 +03:00
Hamza-Ayed d452f9baa9 feat: integrate seasonal surge multipliers and grid-specific commission discounts into pricing logic 2026-07-08 23:23:44 +03:00
Hamza-Ayed 21877153eb feat: harden backend security with HMAC verification, SSL validation, and documentation updates while removing legacy scripts. 2026-07-08 22:10:01 +03:00
Hamza-Ayed 628e169552 Update: 2026-07-07 04:57:50 2026-07-07 04:57:51 +03:00
Hamza-Ayed 5725fb36f4 Update: 2026-07-06 19:27:17 2026-07-06 19:27:17 +03:00
Hamza-Ayed 3c9a3dbef8 Update: 2026-07-06 19:17:19 2026-07-06 19:17:20 +03:00
Hamza-Ayed d6ab09c19b Update: 2026-07-06 18:23:46 2026-07-06 18:23:46 +03:00
Hamza-Ayed 9d257c5d7d Update: 2026-07-06 17:51:16 2026-07-06 17:51:16 +03:00
Hamza-Ayed e21e1f4ec2 Update: 2026-07-06 17:15:10 2026-07-06 17:15:10 +03:00
Hamza-Ayed eb850a2afc Update: 2026-07-06 17:13:49 2026-07-06 17:13:49 +03:00
Hamza-Ayed 281bceb121 Add PM2 ecosystem config 2026-07-06 17:08:21 +03:00
Hamza-Ayed cdfd1b8e02 Update: 2026-07-06 17:05:27 2026-07-06 17:05:27 +03:00
Hamza-Ayed e42d700245 Update: 2026-07-06 17:00:43 2026-07-06 17:00:43 +03:00
Hamza-Ayed 61cb615ae7 Update: 2026-07-06 04:33:26 2026-07-06 04:33:26 +03:00
Hamza-Ayed 8e6dbf96e2 Update: 2026-07-06 04:25:14 2026-07-06 04:25:14 +03:00
Hamza-Ayed df1f487804 Update: 2026-07-06 04:23:43 2026-07-06 04:23:43 +03:00
Hamza-Ayed 32a6531613 Update: 2026-07-06 04:21:17 2026-07-06 04:21:17 +03:00
Hamza-Ayed e42754bb0e Update: 2026-07-06 04:16:38 2026-07-06 04:16:38 +03:00
Hamza-Ayed cadc26518b Update: 2026-07-06 03:51:32 2026-07-06 03:51:32 +03:00
Hamza-Ayed ff49586d6d Update: 2026-07-06 03:45:17 2026-07-06 03:45:17 +03:00
Hamza-Ayed 63440b07dc Update: 2026-07-06 03:30:52 2026-07-06 03:30:52 +03:00
Hamza-Ayed c7863dc98f Update: 2026-07-06 03:11:39 2026-07-06 03:11:39 +03:00
Hamza-Ayed 823805417c Update: 2026-07-06 03:06:32 2026-07-06 03:06:32 +03:00
1306 changed files with 363411 additions and 38077 deletions
Vendored
BIN
View File
Binary file not shown.
+18
View File
@@ -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
}
]
}
+22
View File
@@ -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
View File
@@ -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.
+3
View File
@@ -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"
+17
View File
@@ -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
# =============================================================================
+9 -9
View File
@@ -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']);
}
+60 -19
View File
@@ -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();
+94 -77
View File
@@ -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);
}
+61 -11
View File
@@ -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
View File
@@ -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
+12
View File
@@ -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"); // يمكن أن يأتي من البارامتر أو نخليه افتراضي
+26 -10
View File
@@ -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 !== '') {
+89
View File
@@ -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');
+90
View File
@@ -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');
+44
View File
@@ -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);
}
+88
View File
@@ -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);
}
+53
View File
@@ -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);
}
+28
View File
@@ -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
+25
View File
@@ -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
View File
@@ -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);
}
+4 -7
View File
@@ -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)
+60
View File
@@ -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);
+125
View File
@@ -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;
+5 -1
View File
@@ -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 {
+14 -6
View File
@@ -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;
}
+16 -22
View File
@@ -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);
+52
View File
@@ -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);
}
+88
View File
@@ -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);
}
+44
View File
@@ -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]);
+31
View File
@@ -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]);
+72
View File
@@ -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');
+88
View File
@@ -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,
]);
+72
View File
@@ -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],
]);
+75
View File
@@ -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']]);
+58
View File
@@ -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");
+48
View File
@@ -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
+2 -2
View File
@@ -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();
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+2 -2
View File
@@ -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();
+5 -11
View File
@@ -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);
}
?>
-40
View File
@@ -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}")
+70 -90
View 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";
}
?>
-29
View File
@@ -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");
}
?>
-23
View File
@@ -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");
}
?>
-66
View File
@@ -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");
}
?>
@@ -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";
@@ -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.");
@@ -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);
@@ -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 {
// الاستعلام عن السائق حسب رقم الهاتف وحالة التحقق
+123
View File
@@ -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();
?>
@@ -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 = 'تسجيل سائق جديد';
@@ -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');
@@ -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
View File
@@ -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']);
+65 -24
View File
@@ -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);
+20 -12
View File
@@ -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
View File
@@ -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