131 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
661 changed files with 322583 additions and 15260 deletions
Vendored
BIN
View File
Binary file not shown.
+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"
@@ -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']);
}
+38 -17
View File
@@ -39,6 +39,7 @@ if ($redis && !empty($phone)) {
// البحث عن المشرف باستخدام بصمة الجهاز (Fingerprint Hash)
$fpHash = hash('sha256', $fingerprint);
$isTrustedDevice = false;
// تسجيل محاولة تسجيل الدخول للتدقيق
$loginAuditData = [
@@ -57,11 +58,29 @@ try {
$stmt->execute([':fp' => $fpHash]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);
// إذا لم يتم العثور بالبصمة، نبحث بالـ ID المباشر أو بفك تشفير البيانات (AES-GCM Decryption in PHP)
if (!$admin && !empty($phone)) {
// 1. بحث مباشر بالـ ID المعياري Unencrypted
$stmtId = $con->prepare("SELECT * FROM adminUser WHERE id = :id LIMIT 1");
$stmtId->execute([':id' => $phone]);
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) عبر فك التشفير
@@ -79,16 +98,9 @@ try {
}
}
// عند إيجاد الحساب وتأكيد كلمة المرور، نقوم بتحديث وبث بصمة الجهاز للجلسة
if ($admin && password_verify($password, $admin['password'])) {
$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;
// فحص ما إذا كانت بصمة الجهاز محفوظة ومطابقة للجهاز الحالي
if ($admin && !empty($admin['fingerprint_hash']) && hash_equals($admin['fingerprint_hash'], $fpHash)) {
$isTrustedDevice = true;
}
}
@@ -110,8 +122,17 @@ try {
// 2. التحقق من كلمة المرور
if (password_verify($password, $admin['password'])) {
// إذا كان تجديد توكن تلقائي من التطبيق/الجهاز الموثوق
if ($isRenewal) {
// إذا كان الجهاز موثوقاً (البصمة محفوظة ومطابقة) أو طلب تجديد توكن تلقائي
if ($isTrustedDevice || $isRenewal) {
$encFpRaw = $encryptionHelper ? $encryptionHelper->encryptData($fingerprint) : $fingerprint;
$updateStmt = $con->prepare("UPDATE adminUser SET fingerprint = :fp_raw, fingerprint_hash = :fp WHERE id = :id");
$updateStmt->execute([
':fp_raw' => $encFpRaw,
':fp' => $fpHash,
':id' => $admin['id']
]);
$admin['fingerprint_hash'] = $fpHash;
$jwtService = new JwtService($redis);
$role = $admin['role'] ?? 'admin';
+47 -9
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()");
@@ -93,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());
}
+19 -6
View File
@@ -33,15 +33,20 @@ SELECT
-- كانت تُنتج متوسط مدة سالباً.
(SELECT TIME_FORMAT(SEC_TO_TIME(AVG(TIMESTAMPDIFF(SECOND, rideTimeStart, rideTimeFinish))), '%Hh %im') FROM ride WHERE rideTimeStart IS NOT NULL AND rideTimeFinish IS NOT NULL AND TIMESTAMPDIFF(SECOND, rideTimeStart, rideTimeFinish) > 0) AS driver_avg_duration,
(SELECT 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,
-- أرباح السائق والشركة
-- ملاحظة: خط الرحلات الحالي يكتب 'completed' بينما القديم يكتب 'Finished'،
-- والاكتفاء بالقديم كان يُرجع NULL للأرباح وصفراً للرحلات المكتملة/الملغاة.
(SELECT SUM(price_for_driver) FROM ride WHERE LOWER(status) IN ('finished','completed')) AS total_driver_earnings,
(SELECT ROUND(AVG(price_for_passenger),2) FROM ride) AS avg_passenger_price,
-- متوسط سعر الراكب على الرحلات المكتملة فقط — الرحلات الملغاة سعرها 0
-- وكانت تسحب المتوسط إلى أسفل.
(SELECT ROUND(AVG(price_for_passenger),2) FROM ride WHERE LOWER(status) IN ('finished','completed') AND price_for_passenger > 0) AS avg_passenger_price,
-- توزيع الرحلات حسب الوقت
(SELECT COUNT(*) FROM ride WHERE HOUR(created_at) BETWEEN 6 AND 11) AS morning_ride_count,
@@ -54,12 +59,20 @@ SELECT
(SELECT COUNT(*) FROM ride WHERE carType = 'Lady') AS lady,
-- حالة الرحلات (تغطي عائلتي الحالات: القديمة CamelCase والجديدة lowercase)
(SELECT COUNT(*) FROM ride WHERE LOWER(status) IN ('wait','waiting','new','nothing','pending','searching')) AS ongoing_rides,
-- الحالات الفعلية في قاعدة الإنتاج (فحص 2026-08-03): nothing 930،
-- Begin 624، start 170، waiting 2. كانت Begin و start خارج كل الدلاء
-- الثلاثة، أي أن 794 رحلة (46% من الإجمالي) لا تظهر في أي إحصائية.
-- 'جارية' تشمل المنتظرة للسائق والمنفَّذة فعلياً معاً.
(SELECT COUNT(*) FROM ride WHERE LOWER(status) IN
('wait','waiting','new','nothing','pending','searching',
'begin','start','arrived','apply')) AS ongoing_rides,
(SELECT COUNT(*) FROM ride WHERE LOWER(status) IN ('finished','completed')) AS completed_rides,
(SELECT COUNT(*) FROM ride WHERE LOWER(status) 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
+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) {
// ✅ الحقول المشفرة اللي لازم تنفك:
@@ -24,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);
+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,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);
}
+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);
+6 -3
View File
@@ -76,7 +76,9 @@ if (function_exists('logAudit')) {
}
// الاستدعاء الداخلي لخدمة FCM
$fcmUrl = getenv('FCM_INTERNAL_URL') ?: 'http://127.0.0.1/backend/ride/firebase/send_fcm.php';
// من داخل حاوية php لا يوجد خادم ويب على 127.0.0.1 — الويب في حاوية nginx
// منفصلة، وتُعرف داخل شبكة Compose باسم الخدمة. هذا كان سبب فشل كل إشعار.
$fcmUrl = getenv('FCM_INTERNAL_URL') ?: 'http://nginx/backend/ride/firebase/send_fcm.php';
$payload = json_encode([
'target' => $topic,
'title' => $title,
@@ -106,8 +108,9 @@ $curlErr = curl_error($ch);
curl_close($ch);
if ($response === false || $httpCode >= 400) {
error_log("[Broadcast] FCM call failed (HTTP $httpCode): " . ($curlErr ?: $response));
jsonError("Notification service rejected the request (HTTP $httpCode).", 502);
$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);
@@ -29,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 {
+1 -1
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 {
+15 -4
View File
@@ -1,6 +1,10 @@
<?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']);
@@ -23,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);
// حدد نوع المستخدم
@@ -147,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);
}
@@ -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, 0750, 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);
}
?>
@@ -4,7 +4,7 @@ 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";
+10 -2
View File
@@ -1,5 +1,5 @@
<?php
require_once __DIR__ . '/../../../connect.php';
require_once __DIR__ . '/../../connect.php';
// 🔥 [Fix Broken Access Control] كان يتحقق من صلاحية التوكن فقط — أي مستخدم
// مسجّل دخول (راكب/سائق آخر) كان يقدر يجلب بيانات أي سائق مفكوكة التشفير
@@ -10,7 +10,15 @@ if ($role !== 'admin' && $role !== 'super_admin') {
exit;
}
$driverId = filterRequest("id");
// filterRequest() تقرأ من POST أو JSON body فقط ولا تلمس $_GET
// (core/helpers.php). شاشة مراجعة الوثائق تنادي هذه النقطة بـ
// ?id=... في الـ query string، فكانت تُرجع "driver_id is required"
// دائماً رغم إرسال المعرّف. نقبل الشكلين، ونقبل driver_id أيضاً
// لأن رسالة الخطأ نفسها تسمّيه هكذا.
$driverId = filterRequest("id")
?: filterRequest("driver_id")
?: (isset($_GET['id']) ? trim((string) $_GET['id']) : null)
?: (isset($_GET['driver_id']) ? trim((string) $_GET['driver_id']) : null);
if (empty($driverId)) {
jsonError("driver_id is required.");
+4 -1
View File
@@ -1,5 +1,8 @@
<?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] كان يتحقق من صلاحية التوكن فقط بدون التحقق
// من الدور — أي توكن صالح (حتى راكب) كان يقدر يسحب قائمة السائقين المعلّقين
+2 -2
View File
@@ -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 {
// الاستعلام عن السائق حسب رقم الهاتف وحالة التحقق
+67 -10
View File
@@ -2,13 +2,45 @@
require_once __DIR__ . '/../../connect.php';
global $blindIndex;
$email = filterRequest('email');
$phone = filterRequest('phone');
$password = filterRequest('password');
// تشفير الحقول المطلوبة قبل الاستعلام
$email = $encryptionHelper->encryptData($email);
$phone = $encryptionHelper->encryptData($phone);
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,
@@ -25,19 +57,44 @@ $sql = "SELECT
driver.maritalStatus,
driver.created_at,
driver.updated_at,
email_verifications.verified
driver.email AS _email_enc
FROM
driver
LEFT JOIN email_verifications ON email_verifications.email = driver.email
WHERE
driver.phone = :phone AND driver.email = :email";
$whereClause";
/**
* حالة توثيق البريد.
*
* كان الاستعلام يربط email_verifications.email بعمود البريد في الحساب، لكن
* الأول يُخزَّن نصاً صريحاً والثاني مشفّراً — فالربط لم يكن يطابق شيئاً أصلاً
* وكانت verified تعود NULL دائماً. نجلبها هنا بالبريد الأصلي.
*/
function fetchEmailVerified(PDO $con, ?string $plainEmail): ?int
{
if (!$plainEmail) return null;
try {
$st = $con->prepare("SELECT verified FROM email_verifications WHERE email = ? LIMIT 1");
$st->execute([$plainEmail]);
$v = $st->fetchColumn();
return $v === false ? null : (int) $v;
} catch (PDOException $e) {
error_log('[email_verifications] ' . $e->getMessage());
return null;
}
}
$stmt = $con->prepare($sql);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':phone', $phone);
$stmt->execute();
$stmt->execute($params);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
$count = count($data);
if ($count > 0) {
$plainEmail = $encryptionHelper->decryptData($data[0]['_email_enc'] ?? null) ?: null;
$data[0]['verified'] = fetchEmailVerified($con, $plainEmail);
unset($data[0]['_email_enc']);
}
if ($count > 0) {
$stored_password = $data[0]['password'];
+1 -1
View File
@@ -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
@@ -11,18 +11,16 @@ $password = filterRequest('password');
$audience = filterRequest('aud') ?? 'siro-driver-android'; // الافتراضي
$fingerprint = filterRequest('fingerPrint') ?? filterRequest('fingerprint');
// 1. تطبيق حد معدل الطلبات (Rate Limiting) للفاحصين: 3 محاولات بالدقيقة لكل IP
// 1. حد معدل الطلبات مطبّق على الجميع (الحد مرفوع إلى 30/دقيقة في RateLimiter)
$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)));
// 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',
@@ -30,21 +28,21 @@ if (empty($allowedEmails)) {
];
}
$cleanEmail = strtolower(trim($email));
$isTester = in_array($cleanEmail, $allowedEmails) ||
substr($cleanEmail, -13) === '@siromove.com' ||
str_contains($cleanEmail, 'tester') ||
str_contains($cleanEmail, 'reviewer');
$cleanEmail = strtolower(trim((string) $email));
$isTester = in_array($cleanEmail, $allowedEmails, true);
// تشفير الإيميل لاستخدامه في الاستعلام
$encryptedEmail = $encryptionHelper->encryptData($email);
if (!$email || !$password) {
echo json_encode(["status" => "failure", "message" => "Email and password are required"]);
exit();
}
try {
$con = Database::get('main');
// Auto-seed/create tester driver logic removed for security
// SQL لاسترجاع المستخدم بناءً على البريد الإلكتروني المشفر
$encryptedEmail = $encryptionHelper->encryptData($email);
global $blindIndex;
$emailBidx = $blindIndex ? $blindIndex->index('driver.email', $email) : null;
$sql = "SELECT
driver.*,
phone_verification.is_verified,
@@ -52,49 +50,49 @@ try {
CarRegistration.model,
CarRegistration.year
FROM driver
LEFT JOIN phone_verification ON phone_verification.phone_number = driver.phone
LEFT JOIN phone_verification ON phone_verification.phone_number = driver.phone_key
LEFT JOIN CarRegistration ON CarRegistration.driverID = driver.id
WHERE
driver.email = :email
LIMIT 1";
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->bindParam(':email', $encryptedEmail);
$stmt->execute();
$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();
}
// فحص الباسورد (في نظامنا، يمكن أن يكون الباسورد هو HMAC أو نص عادي للفاحصين)
// لنفترض أن الفاحص له باسورد عادي أو مشفر بـ bcrypt
if (password_verify($password, $data['password'])) {
if (password_verify($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']);
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']);
// توليد الـ JWT بصلاحية (tester) لتميزهم عن السائقين الفعليين
$jwtService = new JwtService($redis);
$jwt = $jwtService->generateAccessToken($data['id'], 'tester', $audience, $fingerprint);
echo json_encode([
"status" => "success",
"jwt" => $jwt,
"data" => [$data] // مطابق لنسق التطبيق الذي يتوقع مصفوفة
"data" => [$data]
], JSON_UNESCAPED_UNICODE);
} else {
jsonError("Incorrect password.");
@@ -102,9 +100,9 @@ try {
} else {
jsonError("User does not exist.");
}
} catch (Exception $e) {
error_log("[Tester Login Error] " . $e->getMessage());
jsonError("Server error occurred.");
} 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;
+34 -6
View File
@@ -7,7 +7,7 @@
*/
//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
@@ -128,7 +128,7 @@ try {
// ======================================================
// Step 1.5: التحقق الفعلي من ملكية رقم الهاتف قبل إكمال المعالجة (سد الثغرة)
// ======================================================
require_once __DIR__ . '/../../../core/Auth/EncryptionHelper.php';
require_once __DIR__ . '/../../core/Security/EncryptionHelper.php';
$tempEncryptionHelper = new EncryptionHelper($redis);
$phoneNumber_encrypted_check = $tempEncryptionHelper->encryptData($data['phone']);
@@ -383,6 +383,18 @@ Therefore, do NOT assume a specific field is on the front or the back of a card.
$pwdHashed = password_hash($rawSecret, PASSWORD_DEFAULT);
/* ================== 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"
@@ -402,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.");
@@ -418,14 +440,16 @@ Therefore, do NOT assume a specific field is on the front or the back of a card.
address, licenseIssueDate, status, birthdate, site,
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);
@@ -456,6 +480,10 @@ Therefore, do NOT assume a specific field is on the front or the back of a card.
':maritalStatus' => !empty($data['maritalStatus']) ? $data['maritalStatus'] : 'yet',
':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();
+2 -2
View File
@@ -51,8 +51,8 @@ $sentOK = ($httpCode === 200 && ($decoded['success'] ?? false));
if ($sentOK) {
/* 3) تشفير البيانات وحفظها في DB ----------------------------------- */
$receiver_enc = $encryptionHelper->encryptData($receiver);
$otp_enc = $encryptionHelper->encryptData($otp);
$receiver_enc = otpPhoneKey($receiver);
$otp_enc = otpPhoneKey($otp); // يجب أن يطابق صيغة المقارنة في verify_otp
$exp = date('Y-m-d H:i:s', strtotime('+5 minutes'));
$now = date('Y-m-d H:i:s');
+3 -2
View File
@@ -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']);
+16 -9
View File
@@ -119,7 +119,10 @@ switch (strtolower($country)) {
// 6. DB Storage on Success
if ($sentSuccessfully) {
$encryptedPhone = $encryptionHelper->encryptData($receiver); // Deterministic CBC
$encryptedPhone = otpPhoneKey($receiver); // مفتاح بحث ثابت مستقل عن نمط التشفير
// نسخة قابلة للاسترجاع: خدمة العملاء تتابع من طلب رمزاً ولم يُكمل تسجيله،
// والمفتاح أعلاه أحادي الاتجاه فلا يُستخرج منه الرقم.
$phoneEncStored = $encryptionHelper->encryptData($receiver);
$encryptedOtp = $encryptionHelper->encryptDataGCM($otp); // Random GCM
$encryptedEmail = !empty($email) ? $encryptionHelper->encryptData($email) : '';
@@ -135,11 +138,12 @@ 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') {
@@ -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
]);
}
+73 -6
View File
@@ -59,7 +59,7 @@ try {
// 3. Encrypt data to query
// 4. Verify based on user type
try {
$encryptedPhoneSearch = $encryptionHelper->encryptData($phone_number);
$encryptedPhoneSearch = otpPhoneKey($phone_number);
if ($user_type === 'admin') {
$sql = "SELECT * FROM token_verification_admin
@@ -147,7 +147,70 @@ 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.");
}
@@ -177,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)
@@ -273,8 +338,10 @@ try {
$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) {
+6 -2
View File
@@ -4,6 +4,10 @@ require_once __DIR__ . '/../connect.php';
$platform = filterRequest("platform");
$appName = filterRequest("appName");
// ‏كان platform وappName يُحقنان مباشرة في نص الاستعلام ثم يُمرَّر إلى prepare
// ‏بلا معاملات مربوطة — حقن SQL مكتمل الأركان. وfilterRequest لا تنظّف النص
// ‏عمداً (انظر core/helpers.php: "بدون htmlspecialchars — نتركه لـ PDO")،
// ‏فالحماية الوحيدة المفترضة هنا هي الربط، ولم تكن موجودة.
$sql = "SELECT
`id`,
`platform`,
@@ -13,10 +17,10 @@ $sql = "SELECT
FROM
`packageInfo`
WHERE
platform='$platform' and appName='$appName';";
`platform` = ? AND `appName` = ?";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->execute([$platform, $appName]);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0) {
+1 -1
View File
@@ -45,7 +45,7 @@ $sql = "SELECT
t.fingerPrint AS fcm_fingerprint
FROM passengers p
LEFT JOIN phone_verification_passenger
ON phone_verification_passenger.phone_number = p.phone
ON phone_verification_passenger.phone_number = p.phone_key
LEFT JOIN invitesToPassengers
ON invitesToPassengers.inviterPassengerPhone = p.phone
LEFT JOIN promos
@@ -9,18 +9,16 @@ $password = filterRequest("password");
$fingerprint = filterRequest('fingerPrint') ?? filterRequest('fingerprint');
$audience = filterRequest('aud') ?: 'siro_passenger';
// 1. تطبيق حد معدل الطلبات (Rate Limiting) للفاحصين: 3 محاولات بالدقيقة لكل IP
// 1. حد معدل الطلبات مطبّق على الجميع (الحد مرفوع إلى 30/دقيقة في RateLimiter)
$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)));
// 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',
@@ -28,18 +26,21 @@ if (empty($allowedEmails)) {
];
}
$cleanEmail = strtolower(trim((string) $email));
$isTester = in_array($cleanEmail, $allowedEmails, true);
$cleanEmail = strtolower(trim($email));
$isTester = in_array($cleanEmail, $allowedEmails) ||
substr($cleanEmail, -13) === '@siromove.com' ||
str_contains($cleanEmail, 'tester') ||
str_contains($cleanEmail, 'reviewer');
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('passengers.email', $email) : null;
// Auto-seed/create tester passenger logic removed for security
@@ -51,14 +52,15 @@ try {
invitesToPassengers.isGiftToken
FROM passengers p
LEFT JOIN phone_verification_passenger
ON phone_verification_passenger.phone_number = p.phone
ON phone_verification_passenger.phone_number = p.phone_key
LEFT JOIN invitesToPassengers
ON invitesToPassengers.inviterPassengerPhone = p.phone
WHERE p.email = :email
WHERE p.email = :email OR (:email_bidx IS NOT NULL AND p.email_bidx = :email_bidx)
LIMIT 1";
$stmt = $con->prepare($sql);
$stmt->bindParam(':email', $encryptedEmail);
$stmt->bindParam(':email_bidx', $emailBidx);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);
@@ -118,7 +120,7 @@ try {
http_response_code(500);
echo json_encode([
"status" => "failure",
"message" => "Server error: " . $e->getMessage() . " in " . basename($e->getFile()) . " on line " . $e->getLine()
"message" => "Server error. Please try again."
]);
}
exit();
+24 -7
View File
@@ -63,7 +63,7 @@ try {
$firstName_encrypted = $encryptionHelper->encryptData($firstName);
$lastName_encrypted = $encryptionHelper->encryptData($lastName);
$email_encrypted = $encryptionHelper->encryptData($email);
$uniqueId = substr(md5($phoneNumber), 0, 20);
$uniqueId = substr(md5($phoneNumber), 0, 16);
$password_hashed = password_hash($email . $uniqueId, PASSWORD_DEFAULT);
$unknown_encrypted = $encryptionHelper->encryptData("unknown yet");
@@ -77,12 +77,13 @@ try {
// (مهلة أوسع من صلاحية الرمز نفسه [5 دقائق] لإعطاء وقت كافٍ لإكمال
// نموذج التسجيل بعد التحقق مباشرة).
$step = 4.5;
$otpSearchKey = otpPhoneKey($phoneNumber);
$verifyCheckStmt = $con->prepare(
"SELECT id FROM phone_verification_passenger
WHERE phone_number = ? AND verified = 1 AND created_at > DATE_SUB(NOW(), INTERVAL 30 MINUTE)
LIMIT 1"
);
$verifyCheckStmt->execute([$phoneNumber_encrypted]);
$verifyCheckStmt->execute([$otpSearchKey]);
if ($verifyCheckStmt->rowCount() === 0) {
error_log("$logTag Step 4.5 Error: Phone number not verified via OTP.");
jsonError("Phone number must be verified before registration.");
@@ -103,8 +104,19 @@ try {
// Step 6: التحقق من وجود المستخدم (Database Check)
// ======================================================
$step = 6;
$checkStmt = $con->prepare("SELECT id FROM passengers WHERE phone = ?");
$checkStmt->execute([$phoneNumber_encrypted]);
// كشف التكرار عبر الفهرس الأعمى + المقارنة القديمة: بدون الفهرس يفشل
// الكشف بعد الانتقال إلى GCM فيُسمح بتسجيل نفس الرقم مرتين.
global $blindIndex;
$phoneBidx = $blindIndex ? $blindIndex->index('passengers.phone', $phoneNumber) : null;
$emailBidx = $blindIndex ? $blindIndex->index('passengers.email', $email) : null;
$nameBidx = $blindIndex ? $blindIndex->index('passengers.name', trim("$firstName $lastName")) : null;
// مفتاح ربط جداول التحقق — يجب أن يطابق otpPhoneKey() حرفياً
$phoneKey = otpPhoneKey($phoneNumber);
$checkStmt = $con->prepare(
"SELECT id FROM passengers WHERE phone = ? OR (? IS NOT NULL AND phone_bidx = ?)"
);
$checkStmt->execute([$phoneNumber_encrypted, $phoneBidx, $phoneBidx]);
if ($checkStmt->rowCount() > 0) {
error_log("$logTag Step 6 Error: User already exists.");
@@ -119,8 +131,8 @@ try {
error_log("$logTag Step 7: Inserting into passengers table...");
$insertStmt = $con->prepare("
INSERT INTO passengers (id, first_name, last_name, email, phone, password, gender, birthdate, site, sosPhone, education, employmentType, maritalStatus, status, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW(), NOW())
INSERT INTO passengers (id, first_name, last_name, email, phone, password, gender, birthdate, site, sosPhone, education, employmentType, maritalStatus, status, created_at, updated_at, phone_bidx, email_bidx, name_bidx, phone_key)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW(), NOW(), ?, ?, ?, ?)
");
$success = $insertStmt->execute([
$uniqueId,
@@ -135,7 +147,12 @@ try {
$unknown_encrypted,
$unknown_encrypted,
$unknown_encrypted,
$unknown_encrypted
$unknown_encrypted,
// فهارس البحث: تُكتب مع السجل حتى يكون قابلاً للبحث فوراً
$phoneBidx,
$emailBidx,
$nameBidx,
$phoneKey
]);
if (!$success) {
+3 -3
View File
@@ -1,6 +1,6 @@
<?php
// File: send_otp.php (بديل عن النسخة المعتمدة على RaseelPlus)
require_once __DIR__ . '/../../connect.php';
require_once __DIR__ . '/../../../connect.php';
/* 1) توليد رمز التحقق (3 خانات) */
$otp = (string)random_int(100, 999);
@@ -51,8 +51,8 @@ $sentOK = ($httpCode === 200 && ($decoded['success'] ?? false));
if ($sentOK) {
/* 3) حفظ الرمز في Redis + قاعدة البيانات */
$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');
+4 -3
View File
@@ -1,7 +1,7 @@
<?php
// File: verify_otp.php (with enhanced logging)
// siro_v1/auth/token_passenger
require_once __DIR__ . '/../../connect.php';
require_once __DIR__ . '/../../../connect.php';
// --- Start of Script Execution ---
error_log("--- [verify_otp.php] Script execution started. ---");
@@ -18,8 +18,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 {
// 1. التحقق من Redis بدلاً من MySQL
+7 -9
View File
@@ -4,9 +4,8 @@ require_once __DIR__ . '/../connect.php';
$email = filterRequest("email");
$token = filterRequest("token");
$sql = "SELECT * FROM `email_verifications` WHERE `email` = '$email'";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt = $con->prepare("SELECT * FROM `email_verifications` WHERE `email` = ?");
$stmt->execute([$email]);
$rowCount = $stmt->rowCount();
@@ -41,9 +40,9 @@ SEFER Team.
if ($rowCount > 0) {
// The email already exists, so update the data
$sql = "UPDATE `email_verifications` SET `token` = '$token' WHERE `email` = '$email'";
$stmt = $con->prepare($sql);
$stmt->execute();
// كانت القيم تُدمج في نص الاستعلام مباشرةً — حقن SQL عبر البريد أو الرمز.
$stmt = $con->prepare("UPDATE `email_verifications` SET `token` = ? WHERE `email` = ?");
$stmt->execute([$token, $email]);
if ($stmt->rowCount() > 0) {
// The update was successful
@@ -55,9 +54,8 @@ if ($rowCount > 0) {
}
} else {
// The email does not exist, so insert the data
$sql = "INSERT INTO `email_verifications` (`email`, `token`) VALUES ('$email', '$token')";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt = $con->prepare("INSERT INTO `email_verifications` (`email`, `token`) VALUES (?, ?)");
$stmt->execute([$email, $token]);
if ($stmt->rowCount() > 0) {
// The insertion was successful
+8
View File
@@ -19,6 +19,14 @@ try {
die("Connection failed: " . $e->getMessage() . "\n");
}
// getRedisConnection() لا ترمي استثناءً — تُعيد null عند تعذّر الاتصال.
// كل مخرجات هذا المحرّك تُكتب في Redis (مقارنة السائقين، ملخّص ذروة
// المنافسين، المناطق الساخنة)، فلا معنى لمتابعة التشغيل بدونه.
if (!$redis) {
error_log('[AI Engine] ABORT: Redis unavailable — no cache target to write to.');
die("Redis unavailable — aborting AI engine run.\n");
}
echo "Starting Siro AI Engine v2 (Powered by Pricing Engine)...\n";
// ==========================================
@@ -26,6 +26,14 @@ try {
die("Database connection failed: " . $e->getMessage() . "\n");
}
// getRedisConnection() لا ترمي استثناءً — تُعيد null عند تعذّر الاتصال.
// مفتاح مكافحة التكرار (TTL يوم كامل) يعيش في Redis؛ بدونه يُعاد إرسال
// نفس الحملة التسويقية كل ساعة.
if (!$redis) {
error_log('[AutoMarketingPusher] ABORT: Redis unavailable — anti-spam guard would fail open.');
die("Redis unavailable — aborting to avoid duplicate campaign pushes.\n");
}
echo "Starting Auto Marketing Pusher Engine...\n";
// 1. استخراج الركاب الخاملين في آخر ساعتين (الذين لم يقموا بأي طلب اليوم)
+145
View File
@@ -0,0 +1,145 @@
<?php
/**
* cron_driver_score.php
* ─────────────────────────────────────────────────────────────
* يغذّي إشارات ترتيب محرك الإسناد في مفاتيح driver:score:* على Redis.
*
* بدون هذا الكرون يعمل المحرك بالقرب وملاءمة الوجهة فقط، وتُحسب بقية
* المكوّنات محايدة (٠٫٥) — أي أن ٥٠٪ من وزن الترتيب معطّل عملياً:
* • معدّل القبول ٢٠٪ ← يُحسب هنا
* • التقييم ١٥٪ ← يُحسب هنا
* • مدة الخمول ١٥٪ ← يختمها finish_ride_updates.php، لا نلمسها
*
* ── معدّل القبول ──
* لا يوجد في MySQL أي سجل لعرضٍ لم يُقبل: driver_orders يسجّل المقبول
* فقط. لذلك يُعدّ العرض في السوكِت (حقل offers) والقبول في acceptRide.php
* (حقل accepts)، وهذا الكرون يحوّلهما لنسبة.
*
* الاضمحلال: نضرب العدّادين بمعامل كل تشغيل، فتصير النسبة نافذة متحرّكة
* تعكس السلوك الأخير لا سجلّ العمر كله. سائق أصلح سلوكه يتعافى خلال أيام
* بدل أن يظل مسجوناً في ماضيه.
*
* تنعيم Laplace: سائق عُرض عليه عرضان وقَبِل واحداً لا يستحق ٥٠٪ بثقة
* كاملة. نضيف عروضاً وهمية محايدة فتقترب نسبته من المحايد حتى تتراكم
* بيانات كافية.
*
* جدولة مقترحة (crontab): كل ربع ساعة — الإشارات بطيئة التغيّر ولا تستحق أكثر.
* الحقل الأول في السطر: الشرطة المائلة ثم 15
* ثم: docker compose exec -T php php /var/www/backend/bot/cron_driver_score.php
*
* ⚠️ يجب أن يعمل داخل حاوية php: Redis لا ينشر منافذ، فتشغيله على المضيف
* يعطي $redisLocation = null ويخرج بلا عمل.
*/
require_once __DIR__ . '/../core/bootstrap.php';
// ── معاملات المعايرة ──
const SCORE_DECAY = 0.85; // ‏ما يبقى من العدّادات كل تشغيل
const SCORE_PRIOR_OFFERS = 4.0; // ‏عروض وهمية للتنعيم
const SCORE_PRIOR_ACCEPTS = 2.0; // ‏منها مقبولة — أي محايد ٠٫٥
const SCORE_KEY_TTL = 2592000; // 30 يوماً: سائق اختفى يُنسى وحده
if (!isset($redisLocation) || !$redisLocation) {
fwrite(STDERR, "[driver_score] Redis غير متاح — هل يعمل الكرون داخل حاوية php؟\n");
exit(1);
}
try {
$con = Database::get('main');
} catch (Exception $e) {
fwrite(STDERR, "[driver_score] DB unavailable: " . $e->getMessage() . "\n");
exit(1);
}
// ═══════════════════════════════════════════════════════════════
// ١) التقييمات — استعلام واحد مجمّع لكل السائقين
// ‏نافذة ٩٠ يوماً: تقييم قبل سنة لا يصف السائق اليوم.
// ═══════════════════════════════════════════════════════════════
$ratings = [];
try {
$stmt = $con->query("
SELECT driver_id, AVG(rating) AS avg_rating, COUNT(*) AS cnt
FROM ratingDriver
WHERE driver_id IS NOT NULL
AND rating IS NOT NULL
AND created_at >= NOW() - INTERVAL 90 DAY
GROUP BY driver_id
");
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
// ‏تقييم واحد أو اثنان لا يكفيان لحكم — ننعّمه نحو المحايد (٣٫٥/٥)
$n = (int) $row['cnt'];
$avg = (float) $row['avg_rating'];
$ratings[$row['driver_id']] = round((($avg * $n) + (3.5 * 3)) / ($n + 3), 3);
}
} catch (PDOException $e) {
fwrite(STDERR, "[driver_score] تعذّر جلب التقييمات: " . $e->getMessage() . "\n");
}
// ═══════════════════════════════════════════════════════════════
// ٢) المرور على مفاتيح الدرجات الموجودة
// ‏scan لا keys: keys تحجب Redis بالكامل على قاعدة كبيرة.
// ═══════════════════════════════════════════════════════════════
$processed = 0;
$iterator = null;
// ‏بلا هذا الضبط يرجع phpredis false عند دفعة فارغة فتتوقف الحلقة مبكراً
$redisLocation->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
while (($keys = $redisLocation->scan($iterator, 'driver:score:*', 200)) !== false) {
foreach ($keys as $key) {
$driverId = substr($key, strlen('driver:score:'));
if ($driverId === '') continue;
try {
$row = $redisLocation->hGetAll($key) ?: [];
$offers = (float) ($row['offers'] ?? 0);
$accepts = (float) ($row['accepts'] ?? 0);
// ‏لا يتجاوز المقبول المعروض — يحدث لو أُعيد ضبط أحدهما وحده.
$accepts = min($accepts, $offers);
$rate = ($accepts + SCORE_PRIOR_ACCEPTS) / ($offers + SCORE_PRIOR_OFFERS);
$update = ['accept_rate' => round($rate, 4)];
if (isset($ratings[$driverId])) {
$update['rating'] = $ratings[$driverId];
}
// ‏الاضمحلال: نافذة متحرّكة بدل سجل العمر كله.
$update['offers'] = round($offers * SCORE_DECAY, 3);
$update['accepts'] = round($accepts * SCORE_DECAY, 3);
$redisLocation->hMSet($key, $update);
$redisLocation->expire($key, SCORE_KEY_TTL);
$processed++;
} catch (Throwable $e) {
fwrite(STDERR, "[driver_score] خطأ على $key: " . $e->getMessage() . "\n");
}
}
}
// ═══════════════════════════════════════════════════════════════
// ٣) سائقون لهم تقييم ولم يُعرض عليهم شيء بعد
// ‏بلا هذه الخطوة يظل التقييم معطّلاً حتى أول عرض — أي أن السائق
// ‏الممتاز الجديد لا يستفيد من تقييمه في أول ترتيب له.
// ═══════════════════════════════════════════════════════════════
$seeded = 0;
foreach ($ratings as $driverId => $rating) {
$key = "driver:score:$driverId";
try {
if (!$redisLocation->exists($key)) {
$redisLocation->hMSet($key, [
'rating' => $rating,
'accept_rate' => round(SCORE_PRIOR_ACCEPTS / SCORE_PRIOR_OFFERS, 4),
]);
$redisLocation->expire($key, SCORE_KEY_TTL);
$seeded++;
}
} catch (Throwable $e) {
// تجاهُل — المرور القادم يعالجه
}
}
echo "[driver_score] حُدِّث $processed سائق، وأُنشئ $seeded من التقييمات."
. " تقييمات محمّلة: " . count($ratings) . "\n";
@@ -14,6 +14,13 @@ try {
die("Connection failed: " . $e->getMessage() . "\n");
}
// getRedisConnection() لا ترمي استثناءً — تُعيد null عند تعذّر الاتصال.
// الهدف الوحيد لهذا السكربت هو الكتابة إلى مفتاح Redis للكاش.
if (!$redis) {
error_log('[HeatmapCache] ABORT: Redis unavailable — nothing to cache into.');
die("Redis unavailable — aborting heatmap cache generation.\n");
}
echo "Starting Heatmap Cache Generation (Redis)...\n";
// مربعات المدن الكبرى لتمثيل الدول (لتجنب حساب المضلعات المعقدة)
+112
View File
@@ -0,0 +1,112 @@
<?php
/**
* cron_insurance_premiums.php — قيد أقساط التأمين
* ─────────────────────────────────────────────────────────────
* ‏يقيّد قسط كل وثيقة نشطة بلغت دورتها. لا يخصم من رصيد أحد:
*
* ‏رصيد السائق يعيش في payment_server لا في هذه القاعدة، والخصم
* ‏المباشر من هنا كان سيعني كتابةً عابرة للحدود بلا معاملة موحّدة —
* ‏أي خطر رصيد ناقص بلا قيد يقابله، أو قيد بلا خصم. فنقيّد استحقاقاً
* ‏هنا، ويقرأه محرك التسوية `cron_obligation_settlement.php`.
*
* ‏تحديث (٢٠٢٦-٠٨-٠٨): صار هذا الملف **مُصدِر استحقاق** في محرك
* ‏الالتزامات العام، فيكتب في `obligation_ledger` لا في
* ‏`insurance_premium_ledger`. سبب النقل أن الدفتر القديم لم يكن يقرأه
* ‏أحد إطلاقاً — «تقرأه التسوية» كان وعداً بلا منفّذ، وكل قسط قُيّد منذ
* ‏الإطلاق بقي معلّقاً بلا تحصيل. جداول التأمين تبقى كما هي شاهداً
* ‏تاريخياً، وقد رُحّلت بياناتها في
* ‏`migrations/2026_08_08_obligations_engine.sql`.
*
* ‏الحماية من الاحتساب المزدوج طبقتان:
* ١. `last_charged_on` في الالتزام — نفلتر به قبل العمل
* ٢. مفتاح فريد (obligation_id, charge_date) في الدفتر — يحسم السباق
* لو عملت نسختان من الكرون معاً
*
* ‏الأولى وحدها لا تكفي: بين القراءة والكتابة نافذة، والمفتاح الفريد
* ‏هو ما يجعل تكرار القيد مستحيلاً لا نادراً.
*
* جدولة: مرة يومياً بعد منتصف الليل.
* 15 0 * * * docker compose exec -T php php /var/www/backend/bot/cron_insurance_premiums.php
*/
require_once __DIR__ . '/../core/bootstrap.php';
try {
$con = Database::get('main');
} catch (Exception $e) {
fwrite(STDERR, '[insurance] DB unavailable: ' . $e->getMessage() . "\n");
exit(1);
}
$today = date('Y-m-d');
// ‏الشهري يُقيَّد على أول الشهر لا على يوم الاشتراك: دفتر تتوزّع فيه
// ‏تواريخ القيد على ثلاثين يوماً يستحيل تسويته مع الشريك.
$monthStart = date('Y-m-01');
$charged = 0;
$skipped = 0;
try {
// ‏المصدر الآن الالتزامات لا الوثائق. القيد على `kind = 'recurring'`
// ‏لا على المنتج التأميني تحديداً: أي منتج دوري يُضاف لاحقاً يُقيَّد
// ‏بالمنطق نفسه بلا سطر جديد هنا.
$st = $con->query("
SELECT o.id, o.driver_id, o.last_charged_on, o.cycle_amount,
pr.code AS product_code, pr.currency, pr.billing_cycle
FROM driver_obligations o
JOIN obligation_products pr ON pr.id = o.product_id
WHERE o.status = 'active'
AND pr.kind = 'recurring'
AND pr.billing_cycle <> 'none'
ORDER BY o.id ASC
");
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $policy) {
$chargeDate = $policy['billing_cycle'] === 'monthly' ? $monthStart : $today;
// ‏الفلترة الرخيصة أولاً — تجنّبنا محاولة إدراج لكل التزام كل يوم.
if ($policy['last_charged_on'] === $chargeDate) {
$skipped++;
continue;
}
try {
$con->beginTransaction();
$con->prepare("
INSERT INTO obligation_ledger
(obligation_id, driver_id, product_code, charge_date,
amount, amount_collected, amount_remaining, currency, status)
VALUES (?, ?, ?, ?, ?, 0, ?, ?, 'pending')
")->execute([
$policy['id'], $policy['driver_id'], $policy['product_code'], $chargeDate,
$policy['cycle_amount'], $policy['cycle_amount'], $policy['currency'],
]);
$con->prepare("
UPDATE driver_obligations SET last_charged_on = ? WHERE id = ?
")->execute([$chargeDate, $policy['id']]);
$con->commit();
$charged++;
} catch (PDOException $e) {
if ($con->inTransaction()) $con->rollBack();
// ‏23000 = خرق المفتاح الفريد: نسخة أخرى سبقتنا للقيد نفسه.
// ‏هذه ليست حالة خطأ — هي بالضبط ما صُمّم المفتاح لمنعه.
if ($e->getCode() === '23000') {
$con->prepare("
UPDATE driver_obligations SET last_charged_on = ? WHERE id = ?
")->execute([$chargeDate, $policy['id']]);
$skipped++;
} else {
error_log("[insurance] تعذّر قيد استحقاق الالتزام #{$policy['id']}: " . $e->getMessage());
}
}
}
} catch (PDOException $e) {
fwrite(STDERR, '[insurance] فشل المرور: ' . $e->getMessage() . "\n");
exit(1);
}
echo "[insurance] قُيِّد {$charged} قسطاً، تُخطّي {$skipped}\n";
+8
View File
@@ -18,6 +18,14 @@ try {
die("Connection failed: " . $e->getMessage() . "\n");
}
// getRedisConnection() تُعيد المتغير العام $redis فقط، وbootstrap.php يتركه null
// عند فشل الاتصال — فهي لا ترمي استثناءً والـ try/catch أعلاه لا يلتقط شيئاً.
// بدون هذا الفحص كان السكربت ينهار فوراً بـ "call to a member function get() on null".
if (!$redis) {
error_log('[cron_kazan_adjuster] ABORT: Redis unavailable — Kazan discounts left untouched.');
die("Redis unavailable — aborting without touching Kazan discounts.\n");
}
$countries = ['SY', 'JO', 'EG', 'IQ'];
foreach ($countries as $country) {
+194
View File
@@ -0,0 +1,194 @@
<?php
/**
* cron_leak_detection.php
* ─────────────────────────────────────────────────────────────
* كشف التسرب خارج المنصة — الرحلة تحصل فعلاً والعمولة لا تصل.
*
* ── لماذا خادمياً ──
* جدول driver_ride_scam يملؤه تطبيق السائق عن نفسه، فنسخة معدّلة لا
* ترسل شيئاً. هذا الكرون يستنتج النمط من بيانات لا يملك السائق تزويرها:
* سجل القبول في driver_orders، وحالة الرحلة في ride.
*
* ── النمط ──
* قَبِل السائق → أُلغيت الرحلة → ولم تبدأ قط
* مرة واحدة قد تكون صدفة. تكرار نفس زوج (سائق، راكب) ليس صدفة.
*
* ── العقوبة ──
* لا حظر. تُكتب درجة الاشتباه في driver:score:$id (حقل leak_penalty)
* فتخفض ترتيب السائق في محرك الإسناد — يخسر السبق والرحلات الأقرب
* تدريجياً. موجع بلا حرمان، وقابل للتراجع فوراً إن تبيّن الخطأ.
* الحالات عالية الثقة تُترك في driver_leak_events لمراجعة بشرية.
*
* جدولة مقترحة (crontab): كل ساعة.
* docker compose exec -T php php /var/www/backend/bot/cron_leak_detection.php
*
* ⚠️ يجب أن يعمل داخل حاوية php — Redis لا ينشر منافذ.
*/
require_once __DIR__ . '/../core/bootstrap.php';
// ── معاملات المعايرة ──
const LEAK_WINDOW_DAYS = 30; // ‏نافذة احتساب التكرار
const LEAK_SCAN_HOURS = 48; // ‏عمق الفحص في كل مرور (بهامش للتأخر)
const LEAK_PENALTY_MAX = 1.0; // ‏سقف العقوبة
const LEAK_REVIEW_THRESHOLD = 0.70; // ‏فوقها تستحق مراجعة بشرية
// ‏الحالات التي تعني "أُلغيت بعد القبول"
const LEAK_CANCEL_STATUSES = ['CancelFromDriverAfterApply', 'cancelled_by_passenger'];
// ‏الحالات التي تعني أن الرحلة بدأت أو اكتملت — وجودها ينفي الاشتباه.
// ‏'arrived' ليست منها عمداً: الوصول ثم الإلغاء هو النمط المشتبه نفسه،
// ‏لا نفيه. (عملياً الإلغاء يكتب فوق الحالة، فالفلتر يعمل على النهائية.)
const LEAK_STARTED_STATUSES = ['started', 'Begin', 'Finished', 'finished'];
if (!isset($redisLocation) || !$redisLocation) {
fwrite(STDERR, "[leak] Redis غير متاح — هل يعمل الكرون داخل حاوية php؟\n");
exit(1);
}
try {
$con = Database::get('main');
} catch (Exception $e) {
fwrite(STDERR, "[leak] DB unavailable: " . $e->getMessage() . "\n");
exit(1);
}
// ═══════════════════════════════════════════════════════════════
// ١) الرحلات المشتبهة في النافذة الأخيرة
//
// ‏ملاحظة: cancel_ride_by_driver.php يصفّر ride.driver_id عند الإلغاء،
// ‏فالسائق لا يُعرف من جدول ride. driver_orders هو من يحتفظ بالربط.
// ═══════════════════════════════════════════════════════════════
$cancelPlaceholders = implode(',', array_fill(0, count(LEAK_CANCEL_STATUSES), '?'));
$startedPlaceholders = implode(',', array_fill(0, count(LEAK_STARTED_STATUSES), '?'));
$sql = "
SELECT dord.driver_id, dord.order_id AS ride_id, dord.status AS cancel_status,
r.passenger_id
FROM driver_orders dord
JOIN ride r ON r.id = dord.order_id
WHERE dord.status IN ($cancelPlaceholders)
AND dord.created_at >= NOW() - INTERVAL " . LEAK_SCAN_HOURS . " HOUR
AND r.status NOT IN ($startedPlaceholders)
AND dord.driver_id <> '0'
AND r.passenger_id <> ''
";
try {
$stmt = $con->prepare($sql);
$stmt->execute(array_merge(LEAK_CANCEL_STATUSES, LEAK_STARTED_STATUSES));
$suspects = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
fwrite(STDERR, "[leak] فشل الفحص: " . $e->getMessage() . "\n");
exit(1);
}
// ═══════════════════════════════════════════════════════════════
// ٢) تقييم كل حالة وتسجيلها
// ═══════════════════════════════════════════════════════════════
$pairStmt = $con->prepare("
SELECT COUNT(*) FROM driver_leak_events
WHERE driver_id = ? AND passenger_id = ?
AND created_at >= NOW() - INTERVAL " . LEAK_WINDOW_DAYS . " DAY
");
$appStmt = $con->prepare("
SELECT COUNT(*) FROM driver_ride_scam
WHERE driverID = ? AND rideID = ?
");
$insertStmt = $con->prepare("
INSERT IGNORE INTO driver_leak_events
(driver_id, passenger_id, ride_id, cancel_status, pair_repeat, app_reported, confidence)
VALUES (?, ?, ?, ?, ?, ?, ?)
");
$inserted = 0;
$flagged = 0;
foreach ($suspects as $s) {
try {
$pairStmt->execute([$s['driver_id'], $s['passenger_id']]);
$pairRepeat = ((int) $pairStmt->fetchColumn()) + 1;
$appStmt->execute([$s['driver_id'], $s['ride_id']]);
$appReported = ((int) $appStmt->fetchColumn()) > 0 ? 1 : 0;
// ── الثقة ──
// ‏حالة منفردة ضعيفة عمداً: الإلغاء بعد القبول له أسباب مشروعة
// ‏كثيرة (عطل، خطأ في العنوان، راكب غيّر رأيه). التكرار مع نفس
// ‏الراكب هو ما يحوّلها من حادثة إلى نمط.
$confidence = 0.25;
if ($pairRepeat >= 2) $confidence = 0.60;
if ($pairRepeat >= 3) $confidence = 0.85;
// ‏بلاغ التطبيق (اتصل ثم أُلغيت) يرفع الثقة ولا يصنعها وحده.
if ($appReported) $confidence = min(1.0, $confidence + 0.15);
$insertStmt->execute([
$s['driver_id'], $s['passenger_id'], $s['ride_id'],
$s['cancel_status'], $pairRepeat, $appReported, round($confidence, 3),
]);
if ($insertStmt->rowCount() > 0) {
$inserted++;
if ($confidence >= LEAK_REVIEW_THRESHOLD) $flagged++;
}
} catch (PDOException $e) {
fwrite(STDERR, "[leak] خطأ على الرحلة {$s['ride_id']}: " . $e->getMessage() . "\n");
}
}
// ═══════════════════════════════════════════════════════════════
// ٣) تحويل السجل إلى عقوبة في محرك الإسناد
//
// ‏العقوبة تُحسب من مجموع ثقة أحداث السائق في النافذة، لا من عددها —
// ‏فحالتان ضعيفتان لا تساويان حالة واحدة مؤكدة.
// ═══════════════════════════════════════════════════════════════
$penalized = 0;
try {
$scoreStmt = $con->prepare("
SELECT driver_id, SUM(confidence) AS total
FROM driver_leak_events
WHERE created_at >= NOW() - INTERVAL " . LEAK_WINDOW_DAYS . " DAY
GROUP BY driver_id
");
$scoreStmt->execute();
foreach ($scoreStmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
// ‏يُشبَع عند مجموع 3 — أي ثلاث حالات مؤكدة تقريباً = العقوبة كاملة.
$penalty = min(LEAK_PENALTY_MAX, ((float) $row['total']) / 3.0);
$redisLocation->hSet("driver:score:{$row['driver_id']}", 'leak_penalty', round($penalty, 3));
$penalized++;
}
} catch (Throwable $e) {
fwrite(STDERR, "[leak] تعذّر تطبيق العقوبات: " . $e->getMessage() . "\n");
}
// ‏تصفير عقوبة من خرج من النافذة: بلا هذا تبقى العقوبة أبدية في Redis
// ‏حتى لو نظُف سجل السائق تماماً — أي عقوبة بلا انتهاء.
try {
$iterator = null;
$redisLocation->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
$activeStmt = $con->prepare("
SELECT DISTINCT driver_id FROM driver_leak_events
WHERE created_at >= NOW() - INTERVAL " . LEAK_WINDOW_DAYS . " DAY
");
$activeStmt->execute();
$active = array_flip($activeStmt->fetchAll(PDO::FETCH_COLUMN));
while (($keys = $redisLocation->scan($iterator, 'driver:score:*', 200)) !== false) {
foreach ($keys as $key) {
$driverId = substr($key, strlen('driver:score:'));
if ($driverId === '' || isset($active[$driverId])) continue;
if ($redisLocation->hExists($key, 'leak_penalty')) {
$redisLocation->hDel($key, 'leak_penalty');
}
}
}
} catch (Throwable $e) {
fwrite(STDERR, "[leak] تعذّر تنظيف العقوبات المنتهية: " . $e->getMessage() . "\n");
}
echo "[leak] فُحص " . count($suspects) . " حالة، سُجّل $inserted جديدة،"
. " منها $flagged تستحق مراجعة بشرية. عوقب $penalized سائق.\n";
+199
View File
@@ -0,0 +1,199 @@
<?php
/**
* cron_obligation_settlement.php — محرك تسوية الالتزامات
* ─────────────────────────────────────────────────────────────
* ‏الجهة **الوحيدة** التي تحوّل قيداً في `obligation_ledger` إلى خصم فعلي
* ‏من محفظة السائق. مُصدِرو الاستحقاق (التأمين، الوقود، الصيانة) يقيّدون
* ‏فقط ولا يلمسون مالاً — وهذا ما يجعل إضافة منتج جديد لا تمسّ أخطر
* ‏منطق في المنصة.
*
* ‏هذا الملف يغلق ثغرة إنتاج قائمة: `cron_insurance_premiums.php` يقيّد
* ‏الأقساط منذ إطلاقه وتعليقه يقول «تقرأه التسوية» — ولم تكن التسوية
* ‏موجودة. كل قسط قُيّد حتى اليوم بقي `pending` بلا تحصيل.
*
* ‏لماذا كرون منفصل لا خصم عند إنهاء الرحلة؟
* ‏لأن `finish_ride_updates.php` مسار حرج والسائق ينتظر رده. نداء شبكي
* ‏إلى سيرفر المحفظة داخله يعني تعليق شاشة السائق على بطء طرف ثالث،
* ‏وفشلاً في التسوية يظهر للسائق كفشل في إنهاء رحلته.
*
* ‏ضمانات عدم التكرار طبقتان:
* ١. `last_attempt_on` في القيد — محاولة واحدة لكل قيد في اليوم
* ٢. `settlement_ref` فريد في سيرفر المحفظة — يحسم السباق ويجعل
* ‏إعادة النداء بعد انقطاع شبكي آمنة بالتعريف
*
* ‏الأولى وحدها لا تكفي: نداء قد ينجح في المحفظة ثم ينقطع قبل أن يصل
* ‏الرد، فيبقى القيد بلا تحديث. الطبقة الثانية تجعل إعادة المحاولة تُرجع
* ‏نتيجة الخصم الأول بدل خصم ثانٍ.
*
* ‏جدولة: مرة يومياً في آخر اليوم لا بعد قيد الاستحقاقات مباشرة —
* ‏السقف نسبة من أرباح اليوم، وقراءتها بعد منتصف الليل تعني سقفاً صفرياً
* ‏كل ليلة وتحصيلاً لا يقع أبداً.
* 30 23 * * * docker compose exec -T php php /var/www/backend/bot/cron_obligation_settlement.php
*/
require_once __DIR__ . '/../core/bootstrap.php';
require_once __DIR__ . '/../obligations/functions.php';
try {
$con = Database::get('main');
} catch (Exception $e) {
fwrite(STDERR, '[obligation] DB unavailable: ' . $e->getMessage() . "\n");
exit(1);
}
$sharedKey = getenv('S2S_SHARED_KEY') ?: '';
if ($sharedKey === '') {
// ‏بلا مفتاح لن ينجح أي نداء. الخروج المبكر أوضح من مئة محاولة
// ‏تعود 401 وتزيد `attempts` بلا سبب حقيقي.
fwrite(STDERR, "[obligation] S2S_SHARED_KEY غير معرّف — لا تسوية\n");
exit(1);
}
/**
* ‏ينادي نقطة الخصم ويُرجع ما خُصم فعلاً، أو null عند فشل لا يمكن تفسيره.
*
* ‏التمييز بين «خُصم صفر» و«فشل» جوهري: الأول حالة طبيعية (لا أرباح
* ‏اليوم) تُسجَّل محاولةً، والثاني لا يجوز أن يُحسب محاولة — وإلا ضاع
* ‏يوم تحصيل بسبب عطل شبكي عابر.
*/
function obligationDeduct(string $ref, string $driverId, string $productCode,
float $amount, float $capPercent): ?float
{
$payload = obligationWalletCall(
'/v2/main/ride/driverWallet/deduct_s2s_obligation.php',
[
'settlement_ref' => $ref,
'driverID' => $driverId,
'product_code' => $productCode,
'amount' => number_format($amount, 3, '.', ''),
'cap_percent' => number_format($capPercent, 2, '.', ''),
]
);
if ($payload === null || !isset($payload['deducted'])) {
error_log("[obligation] تعذّر الحصول على نتيجة خصم ($ref)");
return null;
}
return round((float) $payload['deducted'], 3);
}
$today = date('Y-m-d');
$settled = 0;
$partial = 0;
$idle = 0;
$failed = 0;
$total = 0.0;
try {
// ‏الترتيب مقصود: السائق أولاً ليكون سقفه اليومي مُستهلَكاً بترتيب
// ‏معلوم، ثم أولوية المنتج (التأمين قبل الوقود قبل الصيانة)، ثم
// ‏الأقدم فالأحدث — الدَّين الأقدم أولى بالسداد.
$st = $con->query("
SELECT l.id, l.obligation_id, l.driver_id, l.product_code,
l.amount_remaining, l.amount_collected, l.amount, l.attempts,
p.daily_cap_percent, p.kind
FROM obligation_ledger l
JOIN driver_obligations o ON o.id = l.obligation_id
JOIN obligation_products p ON p.id = o.product_id
WHERE l.status IN ('pending', 'partial')
AND l.amount_remaining > 0
AND (l.last_attempt_on IS NULL OR l.last_attempt_on <> CURDATE())
ORDER BY l.driver_id ASC, p.priority ASC, l.charge_date ASC
");
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
$ledgerId = (int) $row['id'];
$remaining = round((float) $row['amount_remaining'], 3);
// ‏المرجع مبنيّ على عدّاد المحاولات لا على تاريخ اليوم. الفرق ليس
// ‏تجميلياً: `attempts` لا يزيد إلا بعد تحديث الدفتر بنجاح، فنداء
// ‏نجح في المحفظة وضاع ردّه يُعاد لاحقاً — ولو بعد أيام — بالمرجع
// ‏نفسه، فتُرجع المحفظة خصمه الأول بدل تنفيذ خصم ثانٍ. مرجعٌ
// ‏مبنيّ على التاريخ كان سيخصم المبلغ مرتين في هذه الحالة بالضبط.
$ref = "obl_{$ledgerId}_{$row['attempts']}";
$deducted = obligationDeduct(
$ref, $row['driver_id'], $row['product_code'],
$remaining, (float) $row['daily_cap_percent']
);
if ($deducted === null) {
// ‏لا نلمس القيد إطلاقاً — ولا حتى `attempts`. قد يكون الخصم
// ‏تمّ في المحفظة وضاع الرد، وإبقاء العدّاد كما هو يضمن أن
// ‏المحاولة القادمة تحمل المرجع نفسه فتستردّ نتيجة الأولى.
$failed++;
continue;
}
$collected = round((float) $row['amount_collected'] + $deducted, 3);
$newRemaining = round((float) $row['amount'] - $collected, 3);
if ($newRemaining < 0) {
$newRemaining = 0.0;
}
if ($newRemaining <= 0) {
$status = 'settled';
} elseif ($collected > 0) {
$status = 'partial';
} else {
$status = 'pending';
}
try {
$con->beginTransaction();
$con->prepare("
UPDATE obligation_ledger
SET amount_collected = ?, amount_remaining = ?, status = ?,
attempts = attempts + 1, last_attempt_on = ?,
settled_at = CASE WHEN ? = 'settled' THEN NOW() ELSE settled_at END
WHERE id = ?
")->execute([$collected, $newRemaining, $status, $today, $status, $ledgerId]);
// ‏المقسّط وحده يراكم أصلاً مسدَّداً. الدوري بلا نهاية فلا
// ‏معنى لأصلٍ ينفد عنده.
if ($deducted > 0 && $row['kind'] === 'installment') {
$con->prepare("
UPDATE driver_obligations
SET principal_paid = principal_paid + ?
WHERE id = ?
")->execute([$deducted, (int) $row['obligation_id']]);
// ‏سداد الأصل كاملاً يُنهي الالتزام. بدون هذا يبقى قرض
// ‏مسدَّد «نشطاً» فيظهر للسائق ويزاحم غيره على السقف.
$con->prepare("
UPDATE driver_obligations
SET status = 'completed', ended_at = CURDATE()
WHERE id = ? AND status = 'active'
AND principal_amount > 0
AND principal_paid >= principal_amount
")->execute([(int) $row['obligation_id']]);
}
$con->commit();
} catch (PDOException $e) {
if ($con->inTransaction()) $con->rollBack();
// ‏الخصم تمّ فعلاً والقيد لم يُحدَّث — أخطر حالة هنا. لا إعادة
// ‏محاولة تلقائية: المرجع نفسه سيُرجع الخصم الأول لا خصماً
// ‏جديداً، لكن التباين بين الدفترين يحتاج عيناً بشرية.
error_log("[obligation] خُصم {$deducted} للقيد #{$ledgerId} ولم يُحدَّث الدفتر: " . $e->getMessage());
$failed++;
continue;
}
$total += $deducted;
if ($status === 'settled') $settled++;
elseif ($deducted > 0) $partial++;
else $idle++;
}
} catch (PDOException $e) {
fwrite(STDERR, '[obligation] فشل المرور: ' . $e->getMessage() . "\n");
exit(1);
}
printf(
"[obligation] سُوِّي %d، جزئي %d، بلا خصم %d، فشل %d — إجمالي %.3f\n",
$settled, $partial, $idle, $failed, $total
);
@@ -28,6 +28,14 @@ try {
die("[ReEngagement] Connection failed: " . $e->getMessage() . "\n");
}
// getRedisConnection() لا ترمي استثناءً — تُعيد null عند تعذّر الاتصال.
// مفتاح مكافحة التكرار يعيش في Redis؛ بدونه يفشل الفحص "مفتوحاً"
// فيتلقّى كل راكب نفس رسالة الاستعادة في كل تشغيل.
if (!$redis) {
error_log('[ReEngagement] ABORT: Redis unavailable — anti-spam guard would fail open.');
die("[ReEngagement] Redis unavailable — aborting to avoid duplicate pushes.\n");
}
echo "[ReEngagement] Starting Passenger Re-engagement Engine...\n";
$REDIS_TTL = 72 * 3600; // anti-spam: 72 ساعة
+8
View File
@@ -34,6 +34,14 @@ try {
die("[PredictiveDemand] Connection failed: " . $e->getMessage() . "\n");
}
// getRedisConnection() لا ترمي استثناءً — تُعيد null عند تعذّر الاتصال.
// الإيقاف هنا مقصود: مفتاح مكافحة التكرار يعيش في Redis، وبدونه سيُعاد
// إرسال نفس الإشعارات للركاب في كل تشغيل.
if (!$redis) {
error_log('[PredictiveDemand] ABORT: Redis unavailable — anti-spam guard would fail open.');
die("[PredictiveDemand] Redis unavailable — aborting to avoid duplicate pushes.\n");
}
echo "[PredictiveDemand] Starting...\n";
$GRID_SIZE = 0.01; // حجم الخلية (~1.1km)
+324
View File
@@ -0,0 +1,324 @@
<?php
/**
* cron_scheduled_rides.php
* ─────────────────────────────────────────────────────────────
* يحوّل الحجوزات المستحقة إلى رحلات فعلية، ويغذّي توقّع الطلب.
*
* ── لماذا لا تُنشأ الرحلة وقت الحجز ──
* رحلة تُنشأ الآن لموعد بعد ست ساعات ستدور في السوق ست ساعات: تُربك
* الإسناد، وتشوّه الخريطة الحرارية، وتُحتسب في كثافة الطلب اللحظية.
* الحجز يبقى نيّة حتى يقترب موعده.
*
* ── وظيفتان ──
* ١. تذكير الراكب قبل موعده (ساعة، ثم ربع ساعة)
* ٢. إطلاق المستحق: الحجوزات التي بلغ موعدها ناقص هامش البحث
* ٣. نشر التوقّع: عدد الحجوزات القادمة لكل خلية جغرافية في Redis،
* ليقرأها cron_predictive_demand والخريطة الحرارية
*
* ‏الثانية هي القيمة الحقيقية: حجز مؤكد لبعد ست ساعات معلومة يقينية،
* ‏أدق من أي تنبؤ إحصائي، وتسمح بتوجيه السائقين **قبل** الذروة.
*
* جدولة مقترحة (crontab): **كل دقيقتين**، لا كل دقيقة.
*
* ‏الاستعلامات كلها مفهرسة على (status, scheduled_at) وتكلفتها مهملة،
* ‏لكن كل تشغيل يعني إنشاء عملية PHP جديدة داخل الحاوية — وهذا هو الحمل
* ‏الحقيقي لا الاستعلام. وهوامش الإطلاق ١٥-٤٠ دقيقة، فدقيقة تأخير في
* ‏الاستحقاق لا أثر لها إطلاقاً.
*
* *\/2 * * * * (كل دقيقتين)
* docker compose exec -T php php /var/www/backend/bot/cron_scheduled_rides.php
*
* ⚠️ يجب أن يعمل داخل حاوية php — Redis لا ينشر منافذ.
*/
require_once __DIR__ . '/../core/bootstrap.php';
// ‏حجز فات موعده بهذا القدر بلا إطلاق يُعتبر منتهياً: الراكب لم يعد
// ‏ينتظره، وإطلاقه الآن يرسل له سائقاً لموعد مضى.
const SCHEDULE_EXPIRE_GRACE_MINUTES = 30;
// ‏دقة خلية التوقّع — نفس شبكة cron_predictive_demand (0.01° ≈ 1.1 كم).
const SCHEDULE_GRID = 0.01;
try {
$con = Database::get('main');
} catch (Exception $e) {
fwrite(STDERR, '[scheduled] DB unavailable: ' . $e->getMessage() . "\n");
exit(1);
}
// ═══════════════════════════════════════════════════════════════
// ١) انتهاء صلاحية الحجوزات المهملة
// ═══════════════════════════════════════════════════════════════
$expired = 0;
try {
$st = $con->prepare("
UPDATE scheduled_rides
SET status = 'expired'
WHERE status = 'scheduled'
AND scheduled_at < NOW() - INTERVAL " . SCHEDULE_EXPIRE_GRACE_MINUTES . " MINUTE
");
$st->execute();
$expired = $st->rowCount();
} catch (PDOException $e) {
fwrite(STDERR, '[scheduled] تعذّر تعليم المنتهية: ' . $e->getMessage() . "\n");
}
// ═══════════════════════════════════════════════════════════════
// ١.٥) تذكير الراكب
//
// ‏تذكيران: قبل ساعة ليرتّب أمره، وقبل ربع ساعة ليستعد للنزول.
// ‏الختم في العمود يمنع التكرار — بدونه يصل التذكير على كل مرور للكرون.
// ═══════════════════════════════════════════════════════════════
$reminded = 0;
foreach ([[60, 'reminded_60_at', 'رحلتك المحجوزة بعد ساعة'],
[15, 'reminded_15_at', 'رحلتك المحجوزة بعد ربع ساعة']] as [$mins, $col, $title]) {
try {
$st = $con->prepare("
SELECT id, passenger_id, scheduled_at, start_name, end_name
FROM scheduled_rides
WHERE status = 'scheduled'
AND `$col` IS NULL
AND scheduled_at BETWEEN NOW() AND NOW() + INTERVAL $mins MINUTE
LIMIT 100
");
$st->execute();
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
// ‏الختم أولاً ثم الإرسال: لو انقطع التنفيذ بينهما، أسوأ نتيجة
// ‏تذكير لم يصل — لا تذكير يصل مئة مرة.
$con->prepare("UPDATE scheduled_rides SET `$col` = NOW() WHERE id = ?")
->execute([$row['id']]);
scheduleNotifyPassenger(
$con,
$row['passenger_id'],
$title,
'من ' . ($row['start_name'] ?: 'موقعك') . ' في '
. date('H:i', strtotime($row['scheduled_at'])),
['category' => 'scheduled_reminder', 'scheduled_id' => (string) $row['id']]
);
$reminded++;
}
} catch (PDOException $e) {
fwrite(STDERR, "[scheduled] تعذّر تذكير $mins د: " . $e->getMessage() . "\n");
}
}
// ═══════════════════════════════════════════════════════════════
// ٢) الحجوزات المستحقة للإطلاق
//
// ‏المستحق: بلغ الوقت موعدَه ناقص هامشه. الهامش مشتقّ من المسافة وقت
// ‏الحجز (رحلة مطار تحتاج وقتاً أطول لإيجاد سائق وللوصول).
// ═══════════════════════════════════════════════════════════════
$dispatched = 0;
$failed = 0;
try {
$due = $con->prepare("
SELECT * FROM scheduled_rides
WHERE status = 'scheduled'
AND NOW() >= scheduled_at - INTERVAL lead_minutes MINUTE
AND scheduled_at >= NOW() - INTERVAL " . SCHEDULE_EXPIRE_GRACE_MINUTES . " MINUTE
ORDER BY scheduled_at ASC
LIMIT 100
");
$due->execute();
$bookings = $due->fetchAll(PDO::FETCH_ASSOC);
foreach ($bookings as $b) {
// ‏قفل تفاؤلي: مرور ثانٍ للكرون (أو نسخة ثانية منه) لا يطلق نفس
// ‏الحجز مرتين. الرحلة المزدوجة تعني سائقين وراكباً واحداً.
$lock = $con->prepare("
UPDATE scheduled_rides SET status = 'dispatching'
WHERE id = ? AND status = 'scheduled'
");
$lock->execute([$b['id']]);
if ($lock->rowCount() === 0) {
continue;
}
$rideId = scheduleCreateRide($b);
if ($rideId) {
$con->prepare("
UPDATE scheduled_rides SET status = 'dispatched', ride_id = ?
WHERE id = ?
")->execute([$rideId, $b['id']]);
$dispatched++;
error_log("[scheduled] حجز #{$b['id']} → رحلة #$rideId");
} else {
// ‏نعيده 'scheduled' لا 'failed': المرور القادم يحاول ثانيةً،
// ‏وفشل شبكي عابر لا يجوز أن يحرم الراكب رحلته المحجوزة.
$con->prepare("
UPDATE scheduled_rides SET status = 'scheduled' WHERE id = ?
")->execute([$b['id']]);
$failed++;
error_log("[scheduled] تعذّر إنشاء رحلة للحجز #{$b['id']} — ستُعاد المحاولة");
}
}
} catch (PDOException $e) {
fwrite(STDERR, '[scheduled] فشل الإطلاق: ' . $e->getMessage() . "\n");
}
// ═══════════════════════════════════════════════════════════════
// ٣) نشر التوقّع المؤكد
//
// ‏هذه هي القيمة التي تتجاوز راحة الراكب: طلب معروف مسبقاً بمكانه
// ‏ووقته. يُنشر في Redis ليقرأه التنبؤ والخريطة الحرارية.
// ═══════════════════════════════════════════════════════════════
$cells = 0;
try {
if (isset($redisLocation) && $redisLocation) {
// ‏نافذة ٦ ساعات: أبعد من ذلك لا يفيد توجيه السائقين اليوم.
$st = $con->query("
SELECT start_location, scheduled_at
FROM scheduled_rides
WHERE status = 'scheduled'
AND scheduled_at BETWEEN NOW() AND NOW() + INTERVAL 6 HOUR
");
$buckets = [];
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
[$lat, $lng] = array_pad(
array_map('trim', explode(',', (string) $row['start_location'], 2)), 2, null
);
if (!is_numeric($lat) || !is_numeric($lng)) continue;
// ‏المفتاح: خلية جغرافية + الساعة المتوقعة. التجميع بالساعة
// ‏يكفي لقرار "أين يجب أن يكون السائقون الساعة السابعة".
$cell = round((float) $lat / SCHEDULE_GRID) * SCHEDULE_GRID
. ',' . round((float) $lng / SCHEDULE_GRID) * SCHEDULE_GRID;
$hour = date('Y-m-d H:00', strtotime($row['scheduled_at']));
$buckets["$cell|$hour"] = ($buckets["$cell|$hour"] ?? 0) + 1;
}
$key = 'demand:scheduled';
$redisLocation->del($key);
if (!empty($buckets)) {
$redisLocation->hMSet($key, $buckets);
// ‏عمر ساعتين: الكرون يعيد بناءه كل دقيقة، والانتهاء يمنع
// ‏بقاء توقّع قديم لو توقّف الكرون.
$redisLocation->expire($key, 7200);
}
$cells = count($buckets);
}
} catch (Throwable $e) {
fwrite(STDERR, '[scheduled] تعذّر نشر التوقّع: ' . $e->getMessage() . "\n");
}
// ‏الأقواس ضرورية: الفاصلة العربية `،` بايتاتها ≥ 0x80، وPHP يعدّها جزءاً
// ‏صالحاً من اسم المتغيّر — فبدونها يُقرأ "$dispatched،" متغيّراً آخر فارغاً.
echo "[scheduled] أُطلق {$dispatched}، تعذّر {$failed}، انتهى {$expired}،"
. " ذُكِّر {$reminded}، وخلايا التوقّع {$cells}\n";
/**
* ‏ينشئ الرحلة الفعلية من الحجز عبر add_ride.php.
*
* ‏نستدعي النقطة ذاتها لا نكرّر منطقها: add_ride يسعّر، ويبني الحمولة،
* ‏ويشغّل الإسناد (بالدفعات أو البثّ الحر)، ويكتب للقاعدتين. تكرار ذلك
* ‏هنا كان سينتج نسخة تتباعد عن الأصل مع أول تعديل.
*
* ‏السعر يُحسب لحظة الإنشاء لا وقت الحجز: سعر ما قبل ست ساعات لا يعرف
* ‏الذروة ولا الطقس ولا كثافة السائقين.
*
* @return string|null ‏رقم الرحلة، أو null عند الفشل.
*/
function scheduleCreateRide(array $b): ?string
{
$url = getenv('INTERNAL_API_BASE') ?: 'http://nginx';
$url .= '/ride/rides/add_ride.php';
[$startLat, $startLng] = array_pad(
array_map('trim', explode(',', (string) $b['start_location'], 2)), 2, ''
);
[$endLat, $endLng] = array_pad(
array_map('trim', explode(',', (string) $b['end_location'], 2)), 2, ''
);
$fields = [
'passenger_id' => $b['passenger_id'],
'start_location' => $b['start_location'],
'end_location' => $b['end_location'],
'start_lat' => $startLat,
'start_lng' => $startLng,
'end_lat' => $endLat,
'end_lng' => $endLng,
'start_name' => $b['start_name'] ?? '',
'end_name' => $b['end_name'] ?? '',
'car_type' => $b['car_type'],
'distance' => $b['distance'],
'duration' => $b['duration'],
// ‏السعر يُتجاهَل: add_ride يسعّر داخلياً لحظة الإنشاء. نمرّره
// ‏للتوثيق فقط — تقدير وقت الحجز لا يعرف الذروة ولا الطقس.
'price' => $b['estimated_price'],
'scheduled_at' => $b['scheduled_at'],
// ‏وسم المصدر: add_ride قد يعامل الرحلة المحجوزة بأولوية أو
// ‏هامش مختلف لاحقاً، والوسم يجعل ذلك ممكناً بلا تخمين.
'source' => 'scheduled',
'scheduled_id' => $b['id'],
];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($fields),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'X-S2S-Api-Key: ' . getenv('S2S_SHARED_KEY'),
],
]);
$body = curl_exec($ch);
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code !== 200 || !$body) {
error_log("[scheduled] add_ride رمز=$code رد=" . substr((string) $body, 0, 200));
return null;
}
$json = json_decode($body, true);
// ‏add_ride يرد بـ printSuccess($insertedId) — الرقم في message.
$rideId = $json['message'] ?? $json['data'] ?? null;
return ($rideId && is_scalar($rideId)) ? (string) $rideId : null;
}
/**
* ‏يرسل إشعاراً للراكب. توكنه مشفَّر في جدول tokens — نفكّه كما يفعل
* ‏cancel_ride_by_driver.php بالضبط.
*
* ‏لا يرمي: فشل التذكير لا يُسقط الكرون ولا يمنع إطلاق الحجوزات.
*/
function scheduleNotifyPassenger(PDO $con, string $passengerId,
string $title, string $body, array $data): void
{
global $encryptionHelper;
try {
$st = $con->prepare("SELECT token FROM tokens WHERE passengerID = ? ORDER BY id DESC LIMIT 1");
$st->execute([$passengerId]);
$raw = $st->fetchColumn();
if (!$raw) return;
$token = $raw;
if (!empty($encryptionHelper)) {
try {
$dec = $encryptionHelper->decryptData($raw);
if ($dec !== false && $dec !== '') $token = trim($dec);
} catch (Throwable $e) { /* نستخدم الخام */ }
}
if (function_exists('sendFCM_Internal')) {
sendFCM_Internal($token, $title, $body, $data, 'scheduled_reminder', false);
}
} catch (Throwable $e) {
error_log('[scheduled] تعذّر إرسال التذكير: ' . $e->getMessage());
}
}
+7
View File
@@ -15,6 +15,13 @@ try {
die("Connection failed: " . $e->getMessage() . "\n");
}
// getRedisConnection() لا ترمي استثناءً — تُعيد null عند تعذّر الاتصال.
// المُعاملات الموسمية تُنشر عبر Redis وحده ليقرأها محرّك التسعير.
if (!$redis) {
error_log('[SeasonalPricing] ABORT: Redis unavailable — seasonal multipliers not published.');
die("Redis unavailable — aborting seasonal pricing run.\n");
}
$countries = ['SY' => 'Asia/Damascus', 'JO' => 'Asia/Amman', 'EG' => 'Africa/Cairo', 'IQ' => 'Asia/Baghdad'];
// Simulated Calendar of Events
+114
View File
@@ -0,0 +1,114 @@
<?php
/**
* cron_sms_requests.php — شبكة الأمان لمسار الطلب بالرسائل
* ─────────────────────────────────────────────────────────────
* ‏المعالجة الأصلية تتم فورياً داخل webhook_sms/webhook.php، لأن الراكب
* ‏واقف ينتظر رداً ودقيقة تأخير تعني أنه ظنّ الرقم معطّلاً. هذا الكرون
* ‏لا يعالج المسار السعيد إذن — وظيفته ما يسقط منه:
*
* ١. طلبات بقيت 'pending' (فشل شبكي عابر وقت الإنشاء)
* ٢. طلبات عَلِقت في 'dispatching' (مات التنفيذ بين القفل والنتيجة)
* ٣. رحلات لم يقبلها أحد — نخبر الراكب بدل تركه ينتظر بلا خبر
*
* ‏الثالثة هي الأهم: راكب التطبيق يرى الخريطة فيعرف أن البحث جارٍ.
* ‏راكب الرسائل لا يرى شيئاً — صمتنا عنده يساوي عطلاً.
*
* جدولة: كل دقيقة.
* *\/1 * * * * docker compose exec -T php php /var/www/backend/bot/cron_sms_requests.php
*/
require_once __DIR__ . '/../core/bootstrap.php';
require_once __DIR__ . '/../sms/ride_request.php';
// ‏طلب عَلِق في 'dispatching' أطول من هذا يُعتبر ميتاً ويُعاد للطابور.
const SMS_STUCK_MINUTES = 3;
// ‏بعد هذه المدة بلا سائق نخبر الراكب. أقصر من مهلة التطبيق عمداً:
// ‏من ينتظر بلا شاشة يفقد صبره أسرع.
const SMS_NO_DRIVER_MINUTES = 6;
try {
$con = Database::get('main');
} catch (Exception $e) {
fwrite(STDERR, '[sms-cron] DB unavailable: ' . $e->getMessage() . "\n");
exit(1);
}
// ═══════════════════════════════════════════════════════════════
// ١) تحرير العالق
// ═══════════════════════════════════════════════════════════════
$freed = 0;
try {
$st = $con->prepare("
UPDATE sms_ride_requests
SET status = 'pending'
WHERE status = 'dispatching'
AND updated_at < NOW() - INTERVAL " . SMS_STUCK_MINUTES . " MINUTE
");
$st->execute();
$freed = $st->rowCount();
} catch (PDOException $e) {
fwrite(STDERR, '[sms-cron] تعذّر تحرير العالق: ' . $e->getMessage() . "\n");
}
// ═══════════════════════════════════════════════════════════════
// ٢) إعادة محاولة المعلّق
// ═══════════════════════════════════════════════════════════════
$retried = 0;
$created = 0;
try {
$st = $con->query("
SELECT id, sender_norm, passenger_id, start_location, end_location,
start_name, end_name, distance, duration, attempts
FROM sms_ride_requests
WHERE status = 'pending' AND passenger_id IS NOT NULL
ORDER BY id ASC
LIMIT 50
");
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $req) {
$retried++;
if (smsProcessRequest($con, $req)) $created++;
}
} catch (PDOException $e) {
fwrite(STDERR, '[sms-cron] فشل إعادة المحاولة: ' . $e->getMessage() . "\n");
}
// ═══════════════════════════════════════════════════════════════
// ٣) إبلاغ من لم يجد سائقاً
//
// ‏نعتمد على حالة الرحلة نفسها لا على مؤقّت منفصل: ما دامت 'waiting'
// ‏فلا سائق قَبِل. والوسم في fail_reason يمنع تكرار الإبلاغ كل دقيقة.
// ═══════════════════════════════════════════════════════════════
$notified = 0;
try {
$st = $con->prepare("
SELECT s.id, s.sender_norm, s.ride_id
FROM sms_ride_requests s
JOIN ride r ON r.id = s.ride_id
WHERE s.status = 'dispatched'
AND (s.fail_reason IS NULL OR s.fail_reason <> 'no_driver_notified')
AND r.status IN ('waiting', 'wait')
AND s.updated_at < NOW() - INTERVAL " . SMS_NO_DRIVER_MINUTES . " MINUTE
LIMIT 50
");
$st->execute();
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
// ‏الوسم أولاً ثم الإرسال: لو انقطع التنفيذ بينهما، أسوأ نتيجة
// ‏رسالة لم تصل — لا رسالة تصل كل دقيقة.
$con->prepare("UPDATE sms_ride_requests SET fail_reason='no_driver_notified' WHERE id=?")
->execute([$row['id']]);
smsEnqueue($con, $row['sender_norm'],
'سيرو: ما زلنا نبحث عن سائق قريب منك. سنرسل لك رسالة فور قبول أحدهم،'
. ' أو أعد إرسال طلبك بعد قليل.',
'no_driver_yet', (string) $row['ride_id']);
$notified++;
}
} catch (PDOException $e) {
fwrite(STDERR, '[sms-cron] تعذّر إبلاغ من بلا سائق: ' . $e->getMessage() . "\n");
}
echo "[sms-cron] حُرِّر {$freed}، أُعيدت محاولة {$retried}، أُنشئ {$created}،"
. " أُبلغ {$notified}\n";
+42 -13
View File
@@ -23,7 +23,15 @@ if (!$SECRET_KEY) {
echo json_encode(['status' => 'failure', 'message' => 'Server configuration error: BOT_SECRET_KEY not set in environment']);
exit;
}
$ALLOWED_DEVICES = ['SHAM_CASH_BOT_01', 'PRICE_SCRAPER_BOT_01', '77a9528112ef7c2a'];
// أجهزة البوت المسموح بها — تُضبط عبر BOT_ALLOWED_DEVICES (مفصولة بفواصل)
// حتى لا يتطلب ضم جهاز جديد تعديل الكود ونشره.
$ALLOWED_DEVICES = array_values(array_filter(array_map(
'trim',
explode(',', (string)(getenv('BOT_ALLOWED_DEVICES') ?: ''))
)));
if (!$ALLOWED_DEVICES) {
$ALLOWED_DEVICES = ['SHAM_CASH_BOT_01', 'PRICE_SCRAPER_BOT_01', '77a9528112ef7c2a'];
}
$method = $_SERVER['REQUEST_METHOD'];
@@ -43,9 +51,12 @@ if ($method === 'GET') {
// ---------------------------------------------------------
// GET: Fetch Pending Task for the Bot
// ---------------------------------------------------------
$device_id = filterRequest('device_id');
$ts = filterRequest('ts');
$sig = filterRequest('sig');
// ملاحظة: filterRequest() تقرأ من POST أو JSON body فقط ولا تلمس $_GET
// (backend/core/helpers.php) — والبوت يرسل بارامترات التوقيع في الـ query
// string، لذا تُقرأ هنا من $_GET مباشرة.
$device_id = isset($_GET['device_id']) ? trim((string)$_GET['device_id']) : null;
$ts = isset($_GET['ts']) ? (int)$_GET['ts'] : null;
$sig = isset($_GET['sig']) ? trim((string)$_GET['sig']) : null;
if (!$device_id || !$ts || !$sig) {
jsonError("Missing security parameters");
@@ -64,6 +75,14 @@ if ($method === 'GET') {
// Check Redis Queue for tasks
// Queue Name: queue:bot:tasks (Using Main Redis)
// bootstrap.php يترك $redis = null إذا فشل الاتصال — بدون هذا الفحص
// كان الطلب ينهار بخطأ 500 غامض بدل رسالة واضحة.
if (!$redis) {
http_response_code(503);
echo json_encode(['status' => 'failure', 'message' => 'Task queue unavailable']);
exit;
}
$taskJson = $redis->rpop('queue:bot:tasks');
if ($taskJson) {
@@ -144,18 +163,28 @@ if ($method === 'GET') {
}
// ------------------------------------------------------
// العملة تتبع الدولة بدل تثبيتها على JOD — البوت يعمل على أكثر من سوق
$currencyByCountry = ['JO' => 'JOD', 'SY' => 'SYP', 'EG' => 'EGP'];
$currency = $currencyByCountry[strtoupper($country_code)] ?? 'JOD';
// 1. Save to MySQL
$stmt = $con->prepare("
INSERT INTO scraped_competitor_prices
(task_id, app_name, competitor_name, start_location, end_location, start_lat, start_lng, end_lat, end_lng, price_amount, price_per_km, distance_km, duration_min, currency, country_code)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$start_loc = "Lat: $start_lat, Lng: $start_lng";
$end_loc = "Lat: $end_lat, Lng: $end_lng";
$stmt->execute([$task_id, $app_name, $app_name, $start_loc, $end_loc, (string)$start_lat, (string)$start_lng, (string)$end_lat, (string)$end_lng, $price, $pricePerKm, $distance_km, $duration_min, 'JOD', $country_code]);
try {
$stmt = $con->prepare("
INSERT INTO scraped_competitor_prices
(task_id, app_name, competitor_name, start_location, end_location, start_lat, start_lng, end_lat, end_lng, price_amount, price_per_km, distance_km, duration_min, currency, country_code)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$start_loc = "Lat: $start_lat, Lng: $start_lng";
$end_loc = "Lat: $end_lat, Lng: $end_lng";
$stmt->execute([$task_id, $app_name, $app_name, $start_loc, $end_loc, (string)$start_lat, (string)$start_lng, (string)$end_lat, (string)$end_lng, $price, $pricePerKm, $distance_km, $duration_min, $currency, $country_code]);
} catch (PDOException $e) {
// لا نُسقط الطلب: نسجّل الخطأ ونكمل إلى Redis حتى لا تضيع العيّنة
// من محرّك التسعير بسبب عطل في الكتابة إلى MySQL.
error_log("[Bot Worker] MySQL insert failed for task $task_id: " . $e->getMessage());
}
// 2. Save to Redis (Calculate Price Per KM)
if ($distance_km > 0 && $price > 0) {
if ($redis && $distance_km > 0 && $price > 0) {
// Store in Redis (Main) to be used by Pricing Engine
// Store recent 50 prices for the app
$redis->lpush("competitor:price_history:$app_name", $pricePerKm);
+3 -3
View File
@@ -1,12 +1,12 @@
{
"require": {
"vlucas/phpdotenv": "^5.6",
"firebase/php-jwt": "^6.0"
"firebase/php-jwt": "^7.0"
},
"prefer-stable": true,
"config": {
"audit": {
"ignore": ["PKSA-y2cr-5h3j-g3ys"]
"platform": {
"php": "8.2"
}
}
}
+21 -15
View File
@@ -4,20 +4,20 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "e192df06759c90826eeb518a1ea5f0c8",
"content-hash": "e5589fd14ce83adda13b8b9cebed44fa",
"packages": [
{
"name": "firebase/php-jwt",
"version": "v6.11.1",
"version": "v7.1.0",
"source": {
"type": "git",
"url": "https://github.com/googleapis/php-jwt.git",
"reference": "d1e91ecf8c598d073d0995afa8cd5c75c6e19e66"
"reference": "b374a5d1a4f1f67fadc2165cdb284645945e2fc0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/googleapis/php-jwt/zipball/d1e91ecf8c598d073d0995afa8cd5c75c6e19e66",
"reference": "d1e91ecf8c598d073d0995afa8cd5c75c6e19e66",
"url": "https://api.github.com/repos/googleapis/php-jwt/zipball/b374a5d1a4f1f67fadc2165cdb284645945e2fc0",
"reference": "b374a5d1a4f1f67fadc2165cdb284645945e2fc0",
"shasum": ""
},
"require": {
@@ -25,6 +25,8 @@
},
"require-dev": {
"guzzlehttp/guzzle": "^7.4",
"phpfastcache/phpfastcache": "^9.2",
"phpseclib/phpseclib": "~3.0",
"phpspec/prophecy-phpunit": "^2.0",
"phpunit/phpunit": "^9.5",
"psr/cache": "^2.0||^3.0",
@@ -33,7 +35,8 @@
},
"suggest": {
"ext-sodium": "Support EdDSA (Ed25519) signatures",
"paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present"
"paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present",
"phpseclib/phpseclib": "Support PS256 (RSASSA-PSS) signatures"
},
"type": "library",
"autoload": {
@@ -58,16 +61,16 @@
}
],
"description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
"homepage": "https://github.com/firebase/php-jwt",
"homepage": "https://github.com/googleapis/php-jwt",
"keywords": [
"jwt",
"php"
],
"support": {
"issues": "https://github.com/googleapis/php-jwt/issues",
"source": "https://github.com/googleapis/php-jwt/tree/v6.11.1"
"source": "https://github.com/googleapis/php-jwt/tree/v7.1.0"
},
"time": "2025-04-09T20:32:01+00:00"
"time": "2026-06-11T17:54:14+00:00"
},
{
"name": "graham-campbell/result-type",
@@ -460,16 +463,16 @@
},
{
"name": "vlucas/phpdotenv",
"version": "v5.6.3",
"version": "v5.6.4",
"source": {
"type": "git",
"url": "https://github.com/vlucas/phpdotenv.git",
"reference": "955e7815d677a3eaa7075231212f2110983adecc"
"reference": "416df702837983f8d5ff48c9c3fee4f5f57b980b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/955e7815d677a3eaa7075231212f2110983adecc",
"reference": "955e7815d677a3eaa7075231212f2110983adecc",
"url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/416df702837983f8d5ff48c9c3fee4f5f57b980b",
"reference": "416df702837983f8d5ff48c9c3fee4f5f57b980b",
"shasum": ""
},
"require": {
@@ -528,7 +531,7 @@
],
"support": {
"issues": "https://github.com/vlucas/phpdotenv/issues",
"source": "https://github.com/vlucas/phpdotenv/tree/v5.6.3"
"source": "https://github.com/vlucas/phpdotenv/tree/v5.6.4"
},
"funding": [
{
@@ -540,7 +543,7 @@
"type": "tidelift"
}
],
"time": "2025-12-27T19:49:13+00:00"
"time": "2026-07-06T19:11:50+00:00"
}
],
"packages-dev": [],
@@ -551,5 +554,8 @@
"prefer-lowest": false,
"platform": {},
"platform-dev": {},
"platform-overrides": {
"php": "8.2"
},
"plugin-api-version": "2.9.0"
}
+69
View File
@@ -33,6 +33,75 @@ $decoded = $jwtService->authenticate();
$user_id = $decoded->user_id ?? null;
$role = $decoded->role ?? 'passenger';
// ============================================================
// 2. بوّابة صلاحيات افتراضية لمسار /Admin
// ============================================================
// النموذج السابق كان «آمن إن تذكّرت»: كل نقطة تحت Admin/ تفحص الدور بنفسها،
// ومن يُغفل الفحص يصبح مكشوفاً. وقد وُجد فعلاً أن getPassengerDetails.php
// و getPassengerDetailsByPassengerID.php و getPassengerbyEmail.php كانت بلا
// أي فحص، فكان أي حامل JWT صالح — بما فيه راكب عادي — يقرأ بيانات ركّاب
// مفكوكة التشفير.
//
// هنا نقلب النموذج إلى «آمن افتراضاً»: كل ملف تحت Admin/ يمرّ عبر connect.php
// يتطلب دور admin أو super_admin، ما لم يكن في قائمة استثناء صريحة.
//
// نقاط تسجيل الدخول (Admin/auth/*, jwtService.php) لا تستدعي connect.php
// أصلاً، فلا تتأثر بهذه البوّابة ولا يمكن أن تُقفل على نفسها.
//
// ‏2026-08-07: وُسِّعت البوّابة لتشمل serviceapp/ أيضاً. كان 34 من 39 ملفاً
// ‏هناك بلا أي فحص دور — بينها getDriverByPhone و getPassengersByPhone و
// ‏update_complaint — أي أن أي حامل JWT صالح (راكب عادي) يقرأ بيانات
// ‏السائقين والركّاب ويغلق الشكاوى. تحققنا أن siro_rider و siro_driver لا
// ‏يستدعيان أي نقطة تحت serviceapp/، فالإغلاق لا يكسر تطبيقات الجوال.
//
// ⚠️ ‏لكل مجلد أدواره: تسجيل دخول تطبيق الخدمة (Admin/jwtService.php:51)
// ‏يصدر الدور 'service' لا 'admin'. فرضُ admin على serviceapp/ كان
// ‏سيمنع كل موظفي خدمة العملاء من كل نقاطهم.
$gatedDirs = array_filter([
realpath(__DIR__ . '/Admin') => ['admin', 'super_admin'],
realpath(__DIR__ . '/serviceapp') => ['service', 'admin', 'super_admin'],
], fn($k) => $k !== false, ARRAY_FILTER_USE_KEY);
$script = realpath($_SERVER['SCRIPT_FILENAME'] ?? '');
$gateRoles = null;
if ($script) {
foreach ($gatedDirs as $dir => $roles) {
if (str_starts_with($script, $dir . DIRECTORY_SEPARATOR)) {
$gateRoles = $roles;
break;
}
}
}
if ($gateRoles !== null) {
// نقاط تحت Admin/ تستدعيها تطبيقات الجوال بأدوار غير إدارية.
// تم التحقق من مواضع الاستدعاء الفعلية في siro_rider و siro_driver:
// errorApp.php → التطبيقان يبلّغان عن الأخطاء
// sendEmailToDrivertransaction.php → تطبيق السائق
// بقية روابط Admin/ المعرّفة في التطبيقين غير مستدعاة إطلاقاً.
$adminGateExempt = [
'errorApp.php',
'sendEmailToDrivertransaction.php',
];
if (!in_array(basename($script), $adminGateExempt, true)
&& !in_array($role, $gateRoles, true)
) {
securityLog('Admin gate blocked non-admin request', [
'script' => basename($script),
'role' => $role,
'user_id' => $user_id ?? 'unknown',
'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
]);
http_response_code(403);
exit(json_encode([
'status' => 'failure',
'message' => 'Forbidden. Admin access required.',
], JSON_UNESCAPED_UNICODE));
}
}
// 3. Database Connection
try {
+12 -3
View File
@@ -156,7 +156,9 @@ class JwtService
// 3. Issuer (Only check if configured)
if (!empty($this->issuer) && ($decoded->iss ?? '') !== $this->issuer) {
self::abort(401, 'Invalid token issuer: expected ' . $this->issuer . ' but got ' . ($decoded->iss ?? 'none'));
// التفاصيل في اللوج فقط — لا تُكشف في الرد.
error_log('[SECURITY] Issuer mismatch | expected: ' . $this->issuer . ' | got: ' . ($decoded->iss ?? 'none'));
self::abort(401, 'Invalid token issuer');
}
// 3.1 App Signature Verification (Service Only)
@@ -228,8 +230,15 @@ class JwtService
}
if ($fpInToken === null || $fpHeader === null) {
$allHeaders = json_encode(getallheaders());
error_log("[SECURITY] Fingerprint missing | user: $userId | fpInToken: " . ($fpInToken ?? 'NULL') . " | fpHeader: " . ($fpHeader ?? 'NULL') . " | Headers: $allHeaders");
// ملاحظة: ممنوع تسجيل الهيدرز كاملة — كانت تُسرّب الـ
// Authorization: Bearer <token> بالنص الصريح إلى error_log.
// نسجّل فقط أيّ الطرفين ناقص، دون أي قيمة.
error_log(sprintf(
"[SECURITY] Fingerprint missing | user: %s | inToken: %s | inHeader: %s",
$userId,
$fpInToken === null ? 'no' : 'yes',
$fpHeader === null ? 'no' : 'yes'
));
self::abort(403, 'Device verification required');
}
+10 -2
View File
@@ -11,7 +11,7 @@ class RateLimiter
// حدود مختلفة لكل نوع endpoint
private const LIMITS = [
'login' => ['requests' => 5, 'window' => 60], // 5 محاولات / دقيقة
'tester_login' => ['requests' => 3, 'window' => 60], // 3 محاولات / دقيقة
'tester_login' => ['requests' => 30, 'window' => 60], // 30 محاولة / دقيقة (مراجعو المتاجر يكرّرون الدخول بسرعة)
'otp' => ['requests' => 3, 'window' => 300], // 3 محاولات / 5 دقائق
'register' => ['requests' => 3, 'window' => 3600], // 3 محاولات / ساعة
'api' => ['requests' => 180, 'window' => 60], // 180 طلب / دقيقة (الإنتاج الرسمى)
@@ -79,7 +79,15 @@ class RateLimiter
// ── بناء معرّف المستخدم ────────────────────────────────────
public static function identifier(?string $userId = null): string
{
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
// كان REMOTE_ADDR وحده، وهو خلف دوكر دائماً عنوان الوسيط نفسه
// (172.24.0.1) — فيتشارك كل المستخدمين دلواً واحداً، ومحاولات دخول
// فاشلة من عميل واحد تحجب الجميع بـ 429 (ظهر ذلك في سجل الإنتاج).
// clientIp() تستخرج العميل الحقيقي من X-Forwarded-For ولا تثق به
// إلا إذا كان REMOTE_ADDR وسيطاً موثوقاً.
$ip = function_exists('clientIp')
? clientIp()
: ($_SERVER['REMOTE_ADDR'] ?? 'unknown');
return $userId ? "{$ip}:{$userId}" : $ip;
}
+15 -1
View File
@@ -34,6 +34,12 @@ class Database
'user' => 'DB_TRANSIT_USER',
'pass' => 'DB_TRANSIT_PASS',
],
'food' => [
'name' => 'DB_FOOD_NAME',
'host' => 'DB_FOOD_HOST',
'user' => 'DB_FOOD_USER',
'pass' => 'DB_FOOD_PASS',
],
];
public static function get(string $name = 'main'): PDO
@@ -67,7 +73,15 @@ class Database
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_PERSISTENT => true,
// الاتصالات الدائمة أُوقفت: كانت تُنتج "Packets out of order.
// Expected 1 received 0" بتكرار في الإنتاج — وهو عرض معروف لإعادة
// استخدام اتصال دائم تُرك في حالة غير نظيفة، أو أغلقه MySQL عند
// wait_timeout بينما ما زال PHP يعدّه حياً. والأسوأ أن التحذير
// يُطبع قبل الرؤوس فيُفسد الاستجابة بـ "headers already sent".
//
// الكلفة اتصال جديد لكل طلب، وهي مقبولة هنا: MySQL على شبكة دوكر
// نفسها و max-connections=300. الاستقرار أولى من هذا التوفير.
PDO::ATTR_PERSISTENT => false,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
PDO::ATTR_TIMEOUT => 10,
];
+101
View File
@@ -0,0 +1,101 @@
<?php
/**
* core/Security/BlindIndex.php
*
* فهرس أعمى للبحث فوق حقول مشفّرة.
*
* المشكلة: التشفير الآمن (AES-GCM) عشوائي — نفس النص ينتج تشفيراً مختلفاً في
* كل مرة، فلا يمكن البحث بمقارنة النص المشفّر. والحل القديم (CBC بـ IV ثابت)
* يجعل التشفير حتمياً فينجح البحث، لكنه يسرّب المساواة والبادئات المشتركة.
*
* الحل: نفصل التخزين عن البحث.
* - التخزين: AES-GCM عشوائي (لا يسرّب شيئاً).
* - البحث: عمود إضافي يحمل HMAC-SHA256 حتمياً للقيمة بعد تطبيعها.
*
* لماذا HMAC وليس sha256 عارياً؟ لأن مساحة أرقام الهواتف صغيرة (ملايين
* قليلة) — جدول عكسي لكل الأرقام يُبنى في ثوانٍ. المفتاح السرّي (pepper)
* المخزَّن في البيئة وحده يمنع ذلك، فمن يسرق قاعدة البيانات لا يملكه.
*/
final class BlindIndex
{
private string $pepper;
public function __construct(?string $pepper = null)
{
$pepper = $pepper ?: (getenv('BLIND_INDEX_PEPPER') ?: '');
if ($pepper === '') {
throw new RuntimeException(
'BLIND_INDEX_PEPPER is not set. Generate one with: openssl rand -hex 32'
);
}
$this->pepper = $pepper;
}
/**
* يحسب الفهرس لقيمة داخل حقل محدد.
*
* $scope يشمل الجدول والحقل (مثل "driver.phone") عمداً: بدونه يكون فهرس
* نفس الرقم متطابقاً في جدول السائقين والركاب، فيستطيع من يقرأ القاعدة
* ربط الحسابات ببعضها دون فك أي تشفير.
*/
public function index(string $scope, ?string $value): ?string
{
$normalized = self::normalize($scope, $value);
if ($normalized === null || $normalized === '') {
return null;
}
return hash_hmac('sha256', $scope . ':' . $normalized, $this->pepper);
}
/**
* فهرس مبتور للبحث الجزئي (مثل الأسماء).
*
* البتر مقصود: يُنتج تطابقات كاذبة تُصفّى بعد فك التشفير، وهذه الضبابية
* هي ما يمنع استخدام الفهرس نفسه في تحليل التكرارات.
*/
public function bucket(string $scope, ?string $value, int $length = 8): ?string
{
$full = $this->index($scope, $value);
return $full === null ? null : substr($full, 0, $length);
}
/**
* التطبيع قبل الحساب — بدونه يُنتج 0791234567 و+962791234567 فهرسين
* مختلفين ويفشل البحث.
*/
public static function normalize(string $scope, ?string $value): ?string
{
if ($value === null) return null;
$value = trim($value);
if ($value === '') return null;
if (str_contains($scope, 'phone')) {
$digits = preg_replace('/\D+/', '', $value);
// توحيد الصيغة المحلية والدولية على شكل واحد
$digits = preg_replace('/^00/', '', $digits);
if (str_starts_with($digits, '0')) {
$cc = getenv('DEFAULT_COUNTRY_CODE') ?: '962';
$digits = $cc . substr($digits, 1);
}
return $digits;
}
if (str_contains($scope, 'email')) {
return mb_strtolower($value, 'UTF-8');
}
// الأسماء: توحيد حالة الأحرف والمسافات، وتوحيد أشكال الألف والياء
// والتاء المربوطة العربية حتى لا يتوقف البحث على شكل الكتابة.
$value = mb_strtolower($value, 'UTF-8');
$value = preg_replace('/\s+/u', ' ', $value);
$value = str_replace(
['أ', 'إ', 'آ', 'ٱ', 'ى', 'ة', 'ؤ', 'ئ'],
['ا', 'ا', 'ا', 'ا', 'ي', 'ه', 'و', 'ي'],
$value
);
// إزالة التشكيل
$value = preg_replace('/[\x{064B}-\x{0652}\x{0640}]/u', '', $value);
return trim($value);
}
}
+35 -2
View File
@@ -14,7 +14,16 @@ class EncryptionHelper
private const TAG_LEN = 16;
private const PREFIX_GCM = 'GCM:'; // للتمييز بين الجديد والقديم
public function __construct(string $key, ?string $cbcIv = null)
/**
* وضع الكتابة: 'cbc' (افتراضي) أو 'gcm'.
*
* القراءة غير متأثرة بهذا الوضع إطلاقاً — decryptData تتعرّف على الصيغتين
* عبر البادئة، فالسجلات القديمة تبقى مقروءة بلا ترحيل، والرجوع عن التحويل
* لا يُفقد أي سجل كُتب بـ GCM.
*/
private string $writeMode;
public function __construct(string $key, ?string $cbcIv = null, ?string $writeMode = null)
{
if (strlen($key) !== 32) {
throw new InvalidArgumentException('Encryption key must be exactly 32 bytes.');
@@ -22,10 +31,34 @@ class EncryptionHelper
$this->key = $key;
// IV القديم للتوافقية أثناء مرحلة المايغريشن
$this->cbcIv = $cbcIv ?: getenv('initializationVector') ?: str_repeat('0', 16);
$mode = strtolower($writeMode ?: (getenv('ENCRYPTION_MODE') ?: 'cbc'));
$this->writeMode = $mode === 'gcm' ? 'gcm' : 'cbc';
}
// ─── تشفير نص باستخدام AES-256-CBC الحتمي ──
public function writeMode(): string
{
return $this->writeMode;
}
/**
* نقطة التشفير الموحّدة لكل التطبيق.
*
* حتى الآن كانت CBC بـ IV ثابت، أي حتمية: نفس النص ينتج نفس التشفير، وهو
* ما كان يسمح بالبحث عبر مقارنة النص المشفّر، لكنه يسرّب المساواة
* والبادئات المشتركة. مع ENCRYPTION_MODE=gcm يصبح التشفير عشوائياً
* وموثَّقاً، ويتكفّل الفهرس الأعمى (BlindIndex) بالبحث.
*/
public function encryptData(string $plainText): string
{
if ($this->writeMode === 'gcm') {
return $this->encryptDataGCM($plainText);
}
return $this->encryptDataCBC($plainText);
}
// ─── تشفير نص باستخدام AES-256-CBC الحتمي (للتوافقية والرجوع) ──
public function encryptDataCBC(string $plainText): string
{
$plainText = mb_convert_encoding($plainText, 'UTF-8');
$padded = $this->addPadding($plainText);
+40 -1
View File
@@ -371,9 +371,48 @@ class SiroGeminiService {
return null;
}
$data = json_decode($response, true);
$text = $data['candidates'][0]['content']['parts'][0]['text'] ?? '';
return trim(preg_replace('/```html|```/', '', $text));
}
/**
* Answers a driver support inquiry acting as Siro's smart assistant.
*/
public function answerSupportInquiry(
string $question,
array $driverContext,
string $model = 'gemini-flash-lite-latest'
): ?string {
if (!$this->apiKey) return null;
$contextJson = json_encode($driverContext, JSON_UNESCAPED_UNICODE);
$prompt = "
أنت مساعد الدعم الفني الذكي لتطبيق 'سيرو' (Siro) لنقل الركاب.
وظيفتك مساعدة السائقين (الكباتن) والإجابة على استفساراتهم باحترافية، ودقة، وبلهجة ودية ومهذبة جداً.
بيانات السائق الحالية (سياق مهم للإجابة على سؤاله):
$contextJson
سؤال السائق:
\"$question\"
المطلوب منك:
1. الإجابة مباشرة على سؤال السائق بناءً على السياق المعطى إذا كان يخص رحلاته أو رصيده المذكور في السياق.
2. إذا سأل عن إجراءات عامة، أجب كخبير في سيرو.
3. اجعل الإجابة ودية وواضحة جداً وقصيرة.
4. الرد يكون باللغة العربية حصراً.
5. لا تذكر تفاصيل تقنية (مثل json أو database)، بل تحدث كإنسان يقدم الدعم.
";
$prompt .= "\n\nالرجاء إرجاع الإجابة بصيغة JSON فقط كالتالي:\n{\n \"reply\": \"نص الإجابة هنا\"\n}";
$response = $this->callGemini($prompt, $model);
if ($response && isset($response['reply'])) {
return $response['reply'];
}
return null;
}
}
}
+16 -2
View File
@@ -42,7 +42,9 @@ header("X-XSS-Protection: 1; mode=block");
// CORS مع التحقق من المصدر المسموح
$allowedOrigins = array_map('trim', explode(',', getenv('CORS_ALLOWED_ORIGINS') ?: 'https://siromove.com,https://admin.siromove.com'));
$envOrigins = array_map('trim', explode(',', getenv('CORS_ALLOWED_ORIGINS') ?: ''));
$defaultOrigins = ['https://siromove.com', 'https://admin.siromove.com', 'https://jordan-siro.intaleqapp.com', 'http://localhost', 'http://127.0.0.1'];
$allowedOrigins = array_unique(array_merge($envOrigins, $defaultOrigins));
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, $allowedOrigins)) {
header("Access-Control-Allow-Origin: $origin");
@@ -51,7 +53,8 @@ if (in_array($origin, $allowedOrigins)) {
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Device-FP, X-HMAC-Auth, X-Internal-Key');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
// REQUEST_METHOD غير معرّف عند التشغيل من سطر الأوامر (سكربتات الترحيل)
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
http_response_code(200);
exit;
}
@@ -157,6 +160,17 @@ try {
// 5. تحميل الـ Services الأساسية
require_once __DIR__ . '/Security/EncryptionHelper.php';
require_once __DIR__ . '/Security/BlindIndex.php';
// فهرس البحث الأعمى — اختياري: إن لم يُضبط BLIND_INDEX_PEPPER تبقى نقاط
// البحث تعمل بأسلوبها القديم بدل أن تفشل.
$blindIndex = null;
try {
$blindIndex = new BlindIndex();
} catch (Throwable $e) {
error_log('[BlindIndex] disabled: ' . $e->getMessage());
}
require_once __DIR__ . '/Database/Database.php';
require_once __DIR__ . '/Auth/RateLimiter.php';
require_once __DIR__ . '/Auth/JwtService.php';
+96
View File
@@ -38,6 +38,31 @@ function filterRequest(string $name, string $type = 'string'): mixed
};
}
/**
* مفتاح بحث ثابت لجداول التحقق (token_verification*, phone_verification*).
*
* هذه الجداول تستخدم رقم الهاتف كمفتاح بحث لا كبيان يُعرض: يُكتب عند الإرسال
* ويُقرأ عند التحقق. تخزينه مشفّراً كان يعمل فقط لأن التشفير حتمي — ومع
* AES-GCM العشوائي يُنتج الإرسال والتحقق قيمتين مختلفتين فلا ينجح أي رمز.
*
* البديل: بصمة HMAC حتمية للرقم بعد تطبيعه. لا تحتاج تعديل المخطط (العمود
* نصي أصلاً)، وتوحّد صيغ الرقم المحلية والدولية، ولا يمكن عكسها بلا المفتاح.
*/
function otpPhoneKey(?string $phone): string
{
if ($phone === null || trim($phone) === '') return '';
global $blindIndex, $encryptionHelper;
if ($blindIndex) {
return 'K:' . $blindIndex->index('otp.phone', $phone);
}
// بلا BLIND_INDEX_PEPPER نعود للسلوك القديم حتى لا يتعطل التحقق
return $encryptionHelper ? $encryptionHelper->encryptData($phone) : $phone;
}
// ── ردود JSON موحدة ─────────────────────────────────────────
function jsonSuccess(mixed $data = null, string $message = 'success', int $code = 200): never
{
@@ -263,3 +288,74 @@ function normalizePhone(string $phone): string
return $d; // رقم خارج النطاق — يُعاد كما هو
}
/**
* إخفاء جزء من رقم الهاتف قبل عرضه لدور لا يملك صلاحية رؤيته كاملاً.
*
* نموذج الصلاحيات في اللوحة: `admin` يراقب بأرقام مُخفاة جزئياً،
* و`super_admin` وحده يرى الرقم كاملاً.
*
* يُبقي مقدّمة الدولة وآخر رقمين حتى يبقى الرقم مميّزاً للمتابعة التشغيلية
* دون كشف هوية صاحبه.
*/
function maskPhone(?string $phone): ?string
{
if ($phone === null || $phone === '') return $phone;
$d = preg_replace('/\D+/', '', $phone);
$len = strlen($d);
if ($len < 5) return str_repeat('*', max(0, $len));
$head = substr($d, 0, 3);
$tail = substr($d, -2);
return $head . str_repeat('*', $len - 5) . $tail;
}
/**
* عنوان العميل الحقيقي خلف الوسطاء.
*
* سلسلة الطلب: العميل ← nginx المضيف ← nginx الحاوية ← php-fpm، فيصل
* REMOTE_ADDR دائماً كعنوان الوسيط. الاعتماد عليه وحده جعل RateLimiter يضع
* كل المستخدمين في دلو واحد، فمحاولات دخول فاشلة من عميل واحد تحجب الجميع.
*
* X-Forwarded-For قابل للتزوير من العميل، لذا لا نثق به إلا إذا كان
* REMOTE_ADDR نفسه وسيطاً موثوقاً (شبكات خاصة/لوكال). خلاف ذلك نعيد
* REMOTE_ADDR كما هو.
*/
function clientIp(): string
{
$remote = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$isTrustedProxy = $remote !== 'unknown' && (
filter_var(
$remote,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
) === false
);
if (!$isTrustedProxy) {
return $remote;
}
$forwarded = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
if ($forwarded === '') {
return $remote;
}
// أول عنوان عام في السلسلة هو العميل؛ نتخطّى العناوين الخاصة التي
// أضافها الوسطاء.
foreach (explode(',', $forwarded) as $candidate) {
$candidate = trim($candidate);
if ($candidate === '') continue;
if (filter_var(
$candidate,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
) !== false) {
return $candidate;
}
}
return $remote;
}
+18 -9
View File
@@ -2,16 +2,22 @@
require_once __DIR__ . '/../connect.php';
// Get the values from the request
$driver_id = filterRequest("driver_id");
$assured = filterRequest("assured"); // إذا كانت قيمة حساسة يجب تشفيرها
$health_insurance_provider = filterRequest("health_insurance_provider"); // إذا كانت حساسة، شفرها
// ‏المسار القديم للتأمين الصحي. المسار الجديد (خطط، أهلية، أقساط) في
// ‏plans.php و subscribe.php و get.php — هذا يبقى لمن سُجّل هنا سابقاً.
// إذا تحتاج تشفير، فعّل التالي:
// $assured = $encryptionHelper->encryptData($assured);
// $health_insurance_provider = $encryptionHelper->encryptData($health_insurance_provider);
// ‏الهوية من الـJWT لا من الطلب. كان الملف يقرأ driver_id من المدخلات
// ‏بلا أي فحص، فأي حامل رمز صالح يكتب سجل تأمين باسم أي سائق.
$driver_id = $user_id ?? '';
if (empty($driver_id) || ($role ?? '') !== 'driver') {
jsonError('Unauthorized', 401);
}
// SQL using bind parameters
$assured = filterRequest("assured");
$health_insurance_provider = filterRequest("health_insurance_provider");
// ‏upsert لا insert: العمود driver_id عليه مفتاح فريد، فأي حفظ ثانٍ
// ‏لنفس السائق كان يفشل بخرق المفتاح — والحفظ الثاني هو الحالة
// ‏الطبيعية (تعديل مزوّد التأمين) لا الاستثناء.
$sql = "INSERT INTO `driver_health_assurance` (
`driver_id`,
`assured`,
@@ -20,7 +26,10 @@ $sql = "INSERT INTO `driver_health_assurance` (
:driver_id,
:assured,
:health_insurance_provider
)";
)
ON DUPLICATE KEY UPDATE
`assured` = VALUES(`assured`),
`health_insurance_provider` = VALUES(`health_insurance_provider`)";
$stmt = $con->prepare($sql);
$stmt->bindParam(':driver_id', $driver_id);
+68
View File
@@ -0,0 +1,68 @@
<?php
/**
* driver_assurance/cancel.php — إلغاء وثيقة التأمين
*
* ‏الإلغاء يوقف الأقساط القادمة ولا يمسّ الماضي: القيود المستحقّة تبقى
* ‏مستحقّة. تصفيرها عند الإلغاء كانت ستجعل الإلغاء وسيلة للتهرّب من
* ‏أيام تغطية استفاد منها السائق فعلاً.
*/
require_once __DIR__ . '/../connect.php';
require_once __DIR__ . '/eligibility.php';
require_once __DIR__ . '/../obligations/functions.php';
$driverId = $user_id ?? '';
if (empty($driverId) || ($role ?? '') !== 'driver') {
jsonError('Unauthorized', 401);
}
$policy = assuranceActivePolicy($con, $driverId);
if (!$policy) {
jsonError('لا توجد وثيقة نشطة');
}
$reason = filterRequest('reason') ?: 'بطلب السائق';
// ‏الوثيقة والالتزام يُغلقان معاً. التزام يبقى نشطاً بعد إلغاء وثيقته
// ‏يعني قسطاً يُقيَّد كل ليلة على سائقٍ بلا تغطية — عكس الثغرة السابقة
// ‏تماماً، وأسوأ منها: هناك مال يضيع على الشركة، وهنا مال يُؤخذ ظلماً.
try {
$con->beginTransaction();
// ‏الشرط على driver_id إلى جانب المعرّف: الوثيقة أتت من استعلام
// ‏مقيَّد بالسائق أصلاً، لكن الشرط هنا يجعل الاستعلام آمناً بذاته
// ‏لو أعيد استعماله يوماً في سياق آخر.
$st = $con->prepare("
UPDATE driver_insurance_policies
SET status = 'cancelled', ended_at = CURDATE(), cancel_reason = ?
WHERE id = ? AND driver_id = ? AND status = 'active'
");
$st->execute([mb_substr($reason, 0, 255), $policy['id'], $driverId]);
if ($st->rowCount() === 0) {
$con->rollBack();
jsonError('تعذّر إلغاء الوثيقة');
}
obligationClose($con, $driverId, $policy['code'], $reason);
$con->commit();
} catch (Throwable $e) {
if ($con->inTransaction()) $con->rollBack();
error_log('[assurance/cancel] ' . $e->getMessage());
jsonError('Server error');
}
// ‏المستحق يُقرأ من الدفتر الموحّد لا من دفتر التأمين القديم: القديم
// ‏مجمَّد بعد الترحيل، وقراءته تعني رقماً لا يتغيّر مهما سدّد السائق.
$pending = obligationPendingTotal($con, $driverId, $policy['code']);
error_log("[assurance] أُلغيت وثيقة #{$policy['id']} للسائق $driverId");
jsonSuccess([
'cancelled' => true,
'pending_balance' => $pending,
'currency' => $policy['currency'],
], $pending > 0
? 'أُلغيت الوثيقة. يبقى عليك مستحق أقساط سابقة قدره ' . $pending . ' ' . $policy['currency']
: 'أُلغيت الوثيقة');
+110
View File
@@ -0,0 +1,110 @@
<?php
/**
* driver_assurance/eligibility.php — حساب أهلية السائق للتأمين
* ─────────────────────────────────────────────────────────────
* ‏قرار المالك: التأمين ليس خدمة تُمنح لكل من سجّل، بل مكافأة استمرار.
* ‏لا يستحقّه السائق إلا بعد عدد رحلات مكتملة وتقييم جيد.
*
* ‏المنطق التجاري خلفه: القسط كلفة متكررة تتحمّلها الشركة عن السائق أو
* ‏تخصمها من أرباحه. منحه لمن قد يختفي بعد أسبوع يحوّل الأداة من
* ‏ولاء إلى نزيف — والسائق الذي أتمّ مئتي رحلة بتقييم جيد أثبت أنه
* ‏باقٍ، وهو بالضبط من نريد قفله معنا.
*
* ‏الأرقام في جدول الخطط لا في هذا الملف: الشريك سيغيّرها، ومصر تختلف
* ‏عن الأردن، وتعديل صف أرخص من نشر إصدار.
*/
/**
* ‏يقيس السائق مقابل شروط خطة.
*
* @return array{
* eligible: bool,
* rides: int, rating: float, account_days: int,
* reasons: string[]
* }
*/
function assuranceCheckEligibility(PDO $con, string $driverId, array $plan): array
{
$rides = 0;
$rating = 0.0;
$days = 0;
try {
// ‏الرحلات المكتملة فقط. الحالة مكتوبة بحرفين مختلفين في
// ‏الجدول تاريخياً ('Finished' و'finished')، وإغفال أحدهما
// ‏يُنقص عدّاد السائق إلى النصف تقريباً.
$st = $con->prepare("
SELECT COUNT(*) FROM ride
WHERE driver_id = ? AND status IN ('Finished', 'finished')
");
$st->execute([$driverId]);
$rides = (int) $st->fetchColumn();
$st = $con->prepare("SELECT AVG(rating) FROM ratingDriver WHERE driver_id = ?");
$st->execute([$driverId]);
$avg = $st->fetchColumn();
// ‏سائق بلا تقييمات ليس سيئاً — لكنه أيضاً غير مثبَت. عدد
// ‏الرحلات المطلوب يضمن أن تقييماته وصلت على أي حال.
$rating = $avg === null || $avg === false ? 0.0 : round((float) $avg, 2);
$st = $con->prepare("SELECT DATEDIFF(NOW(), created_at) FROM driver WHERE id = ? LIMIT 1");
$st->execute([$driverId]);
$d = $st->fetchColumn();
$days = ($d === false || $d === null) ? 0 : (int) $d;
} catch (PDOException $e) {
error_log('[assurance] تعذّر حساب الأهلية: ' . $e->getMessage());
return [
'eligible' => false, 'rides' => 0, 'rating' => 0.0, 'account_days' => 0,
'reasons' => ['تعذّر التحقق حالياً'],
];
}
$minRides = (int) ($plan['min_completed_rides'] ?? 200);
$minRating = (float) ($plan['min_rating'] ?? 4.50);
$minDays = (int) ($plan['min_account_days'] ?? 30);
// ‏نجمع كل الأسباب لا أوّلها: السائق يستحق أن يعرف كل ما ينقصه
// ‏دفعةً واحدة، لا أن يعالج شرطاً فيُفاجأ بالتالي.
$reasons = [];
if ($rides < $minRides) {
$reasons[] = "أكمل $minRides رحلة (لديك $rides)";
}
if ($rating < $minRating) {
$reasons[] = "تقييمك يجب ألّا يقل عن $minRating (تقييمك " . ($rating ?: '—') . ')';
}
if ($days < $minDays) {
$reasons[] = "مضيّ $minDays يوماً على حسابك (مضى $days)";
}
return [
'eligible' => empty($reasons),
'rides' => $rides,
'rating' => $rating,
'account_days' => $days,
'reasons' => $reasons,
];
}
/**
* ‏الوثيقة النشطة للسائق مع بيانات خطتها، أو null.
*/
function assuranceActivePolicy(PDO $con, string $driverId): ?array
{
try {
$st = $con->prepare("
SELECT p.*, pl.code, pl.name_ar AS plan_name, pl.premium, pl.currency,
pl.billing_cycle, pl.coverage_summary,
pr.name AS provider_name, pr.name_ar AS provider_name_ar
FROM driver_insurance_policies p
JOIN insurance_plans pl ON pl.id = p.plan_id
JOIN insurance_providers pr ON pr.id = pl.provider_id
WHERE p.driver_id = ? AND p.status = 'active'
ORDER BY p.id DESC LIMIT 1
");
$st->execute([$driverId]);
return $st->fetch(PDO::FETCH_ASSOC) ?: null;
} catch (PDOException $e) {
error_log('[assurance] تعذّر جلب الوثيقة: ' . $e->getMessage());
return null;
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
/**
* driver_assurance/get.php — حالة تأمين السائق
*
* ‏كان هذا الملف فارغاً (صفر بايت) — يُستدعى فيرد بلا شيء.
*
* ‏يرد بالوثيقة النشطة، وملخّص دفتر أقساطها، وآخر القيود. الدفتر جزء
* ‏من الرد لا نقطة منفصلة: السائق الذي يُخصم من أرباحه يجب أن يرى
* ‏مقابل ماذا في الشاشة نفسها، وإلا صار الخصم مفاجأة تُفقد الثقة.
*/
require_once __DIR__ . '/../connect.php';
require_once __DIR__ . '/eligibility.php';
$driverId = $user_id ?? '';
if (empty($driverId) || ($role ?? '') !== 'driver') {
jsonError('Unauthorized', 401);
}
$policy = assuranceActivePolicy($con, $driverId);
if (!$policy) {
jsonSuccess([
'has_policy' => false,
'policy' => null,
'ledger' => ['pending_total' => 0, 'settled_total' => 0, 'currency' => null],
'entries' => [],
], 'لا توجد وثيقة نشطة');
}
$summary = ['pending_total' => 0.0, 'settled_total' => 0.0,
'currency' => $policy['currency']];
$entries = [];
// ‏المصدر هو الدفتر الموحّد لا دفتر التأمين القديم (المجمَّد بعد ترحيل
// ‏2026_08_08). المفتاح صار (السائق + رمز المنتج) بدل رقم الوثيقة:
// ‏الدفتر الموحّد لا يعرف الوثائق، يعرف التزامات.
try {
// ‏المستحق من `amount_remaining` والمحصَّل من `amount_collected`:
// ‏قيدٌ حُصِّل نصفه يظهر في الرقمين معاً بحصّته الصحيحة، بينما جمع
// ‏`amount` حسب الحالة كان سيعدّه كاملاً في أحدهما ويكذب في كليهما.
$st = $con->prepare("
SELECT COALESCE(SUM(amount_remaining), 0) AS pending_total,
COALESCE(SUM(amount_collected), 0) AS settled_total
FROM obligation_ledger
WHERE driver_id = ? AND product_code = ?
");
$st->execute([$driverId, $policy['code']]);
if ($row = $st->fetch(PDO::FETCH_ASSOC)) {
$summary['pending_total'] = (float) $row['pending_total'];
$summary['settled_total'] = (float) $row['settled_total'];
}
// ‏آخر ثلاثين قيداً: كافية لشهر يومي، وتمنع رداً ينمو بلا حد.
$st = $con->prepare("
SELECT charge_date, amount, amount_collected, amount_remaining,
currency, status, note
FROM obligation_ledger
WHERE driver_id = ? AND product_code = ?
ORDER BY charge_date DESC
LIMIT 30
");
$st->execute([$driverId, $policy['code']]);
$entries = $st->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
error_log('[assurance/get] تعذّرت قراءة الدفتر: ' . $e->getMessage());
}
jsonSuccess([
'has_policy' => true,
'policy' => [
'id' => (int) $policy['id'],
'plan' => $policy['plan_name'],
'provider' => $policy['provider_name_ar'] ?: $policy['provider_name'],
'policy_number' => $policy['policy_number'],
'coverage' => $policy['coverage_summary'],
'billing_cycle' => $policy['billing_cycle'],
'premium' => (float) $policy['premium'],
'currency' => $policy['currency'],
'started_at' => $policy['started_at'],
'last_charged_on' => $policy['last_charged_on'],
],
'ledger' => $summary,
'entries' => $entries,
], 'success');
+87
View File
@@ -0,0 +1,87 @@
<?php
/**
* driver_assurance/plans.php — الخطط المتاحة وأهلية السائق لكلٍّ منها
*
* ‏نرد بكل الخطط لا المؤهَّل لها فقط، ومع كل واحدة سبب عدم الأهلية إن
* ‏وُجد. إخفاء ما لا يستحقه السائق يجعل التأمين مجهولاً عنده؛ إظهاره
* ‏مع «ينقصك ٤٠ رحلة» يحوّله إلى هدف يسعى إليه — وهذا هو مقصد الشرط
* ‏أصلاً: ربط السائق بالمنصّة.
*/
require_once __DIR__ . '/../connect.php';
require_once __DIR__ . '/eligibility.php';
require_once __DIR__ . '/../obligations/functions.php';
// ‏الهوية من الـJWT لا من الطلب — الأهلية معلومة عن السائق نفسه،
// ‏وقراءتها بمعرّف مُرسَل تكشف أرقام غيره.
$driverId = $user_id ?? '';
if (empty($driverId) || ($role ?? '') !== 'driver') {
jsonError('Unauthorized', 401);
}
$country = getenv('APP_COUNTRY') ?: 'Jordan';
try {
$st = $con->prepare("
SELECT pl.*, pr.name AS provider_name, pr.name_ar AS provider_name_ar
FROM insurance_plans pl
JOIN insurance_providers pr ON pr.id = pl.provider_id
WHERE pl.is_active = 1 AND pr.is_active = 1 AND pr.country = ?
ORDER BY pl.premium ASC
");
$st->execute([$country]);
$plans = $st->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
error_log('[assurance/plans] ' . $e->getMessage());
jsonError('Server error');
}
$current = assuranceActivePolicy($con, $driverId);
// ‏نداء واحد للمحفظة لكل الشاشة: الملخّص عن السائق لا عن الخطة.
// ‏بدونه كانت الشاشة تعرض «مؤهَّل» ثم يُرفض الطلب عند الضغط — وهو أسوأ
// ‏من الرفض المبكر: يعد السائق بشيء ثم يسحبه.
$incomeSummary = obligationWalletIncomeSummary($driverId);
$out = [];
foreach ($plans as $plan) {
$check = assuranceCheckEligibility($con, $driverId, $plan);
// ‏بوابة الائتمان تُقاس على منتج الالتزام المقابل للخطة. غيابه يعني
// ‏خطة لم تُرحَّل بعد — لا نحجبها ولا ندّعي أهليةً لها، بل نتركها
// ‏لحكم شروط الخطة وحدها ونسجّل الحالة.
$product = obligationProduct($con, $plan['code']);
if ($product) {
$gate = obligationCheckWalletIncome($product, $driverId, $incomeSummary);
if (!$gate['eligible']) {
$check['eligible'] = false;
$check['reasons'] = array_merge($check['reasons'], $gate['reasons']);
}
} else {
error_log("[assurance/plans] لا منتج التزام للخطة {$plan['code']}");
}
$out[] = [
'id' => (int) $plan['id'],
'code' => $plan['code'],
'name' => $plan['name_ar'],
'description' => $plan['description_ar'],
'provider' => $plan['provider_name_ar'] ?: $plan['provider_name'],
'billing_cycle' => $plan['billing_cycle'],
'premium' => (float) $plan['premium'],
'currency' => $plan['currency'],
'coverage' => $plan['coverage_summary'],
'eligible' => $check['eligible'],
'missing' => $check['reasons'],
'is_current' => $current && (int) $current['plan_id'] === (int) $plan['id'],
// ‏تقدّم السائق نحو الشرط — رقم يفهمه بلا شرح.
'progress_rides' => $check['rides'],
'required_rides' => (int) $plan['min_completed_rides'],
];
}
jsonSuccess([
'plans' => $out,
'has_policy' => (bool) $current,
'driver_rating' => $current ? (float) $current['rating_at_signup'] : null,
], 'success');
+109
View File
@@ -0,0 +1,109 @@
<?php
/**
* driver_assurance/subscribe.php — اشتراك السائق في خطة تأمين
*
* ‏الأهلية تُحسب هنا من جديد لا يُوثق بما أرسله التطبيق: الشاشة قد تكون
* ‏مفتوحة منذ ساعة، وقد يُعدَّل الطلب يدوياً. النقطة التي تمنح تغطية
* ‏مالية لا تصدّق عميلها.
*/
require_once __DIR__ . '/../connect.php';
require_once __DIR__ . '/eligibility.php';
require_once __DIR__ . '/../obligations/functions.php';
$driverId = $user_id ?? '';
if (empty($driverId) || ($role ?? '') !== 'driver') {
jsonError('Unauthorized', 401);
}
$planId = (int) (filterRequest('plan_id', 'int') ?: 0);
if ($planId <= 0) {
jsonError('plan_id is required');
}
try {
$st = $con->prepare("
SELECT pl.*, pr.is_active AS provider_active
FROM insurance_plans pl
JOIN insurance_providers pr ON pr.id = pl.provider_id
WHERE pl.id = ? AND pl.is_active = 1 LIMIT 1
");
$st->execute([$planId]);
$plan = $st->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
error_log('[assurance/subscribe] ' . $e->getMessage());
jsonError('Server error');
}
if (!$plan || (int) $plan['provider_active'] !== 1) {
jsonError('Plan not available');
}
// ‏وثيقة نشطة قائمة: لا نشترك مرتين ولا نستبدل بصمت. تبديل الخطة
// ‏قرار مالي — يمرّ بإلغاء صريح ثم اشتراك جديد، ليبقى في السجل أثر.
if (assuranceActivePolicy($con, $driverId)) {
jsonError('لديك وثيقة تأمين نشطة بالفعل. ألغِها أولاً لتغيير الخطة.');
}
$check = assuranceCheckEligibility($con, $driverId, $plan);
if (!$check['eligible']) {
jsonError('لم تستوفِ شروط هذه الخطة بعد: ' . implode('، ', $check['reasons']));
}
// ‏بوابة الائتمان تُفحص هنا صراحةً رغم أن `obligationOpen` تفحصها أيضاً:
// ‏الفحص هناك حارسٌ أخير يرمي استثناءً، ورسالته تصل للسائق كخطأ عام.
// ‏السائق الذي يُرفض طلبه يستحق أن يعرف السبب وما يفعله ليستوفيه.
$product = obligationProduct($con, $plan['code']);
if (!$product) {
error_log("[assurance/subscribe] منتج الالتزام مفقود للخطة {$plan['code']}");
jsonError('تعذّر تفعيل الوثيقة حالياً');
}
$walletGate = obligationCheckWalletIncome($product, $driverId);
if (!$walletGate['eligible']) {
jsonError(
'التأمين يُخصم قسطه من أرباحك في المحفظة، ولذلك يشترط أن تمرّ أرباحك بها: '
. implode('، ', $walletGate['reasons'])
);
}
// ‏كتابتان في معاملة واحدة: الوثيقة (السجل التأميني الذي يقرأه التطبيق)
// ‏والالتزام (ما يراه محرك القيد والتسوية). وثيقة بلا التزام تعني تغطية
// ‏تُمنح ولا يُحصَّل قسطها أبداً — وهي بالضبط الثغرة التي جاء هذا المحرك
// ‏ليغلقها، فلا يجوز أن نعيد فتحها من باب الاشتراكات الجديدة.
try {
$con->beginTransaction();
$con->prepare("
INSERT INTO driver_insurance_policies
(driver_id, plan_id, status, started_at, rides_at_signup, rating_at_signup)
VALUES (?, ?, 'active', CURDATE(), ?, ?)
")->execute([$driverId, $planId, $check['rides'], $check['rating']]);
$policyId = (int) $con->lastInsertId();
obligationOpen($con, $driverId, $plan['code'], [
'cycle_amount' => (float) $plan['premium'],
'rides' => $check['rides'],
'rating' => $check['rating'],
]);
$con->commit();
} catch (Throwable $e) {
if ($con->inTransaction()) $con->rollBack();
error_log('[assurance/subscribe] تعذّر إنشاء الوثيقة: ' . $e->getMessage());
jsonError('تعذّر تفعيل الوثيقة حالياً');
}
error_log("[assurance] السائق $driverId اشترك في الخطة {$plan['code']} — وثيقة #$policyId");
jsonSuccess([
'policy_id' => $policyId,
'plan' => $plan['name_ar'],
'premium' => (float) $plan['premium'],
'currency' => $plan['currency'],
'billing_cycle' => $plan['billing_cycle'],
// ‏أول قسط يُقيَّد في تشغيل الكرون القادم لا الآن: الاشتراك ليس
// ‏دفعاً، والقيد يجب أن يكون له تاريخ واضح يوافق دورة الفوترة.
'starts_on' => date('Y-m-d'),
], 'تم تفعيل وثيقة التأمين');
+1 -1
View File
@@ -4,7 +4,7 @@
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../core/bootstrap.php';
// 1. فرض المصادقة (Auth Required)
+18 -1
View File
@@ -1,7 +1,17 @@
<?php
//encrypt_decrypt.php
// ⚠️ هذا الملف للتوافقية فقط. استخدم core/Security/EncryptionHelper.php للتشفير الجديد
require_once realpath(__DIR__ . '/../vendor/autoload.php');
// vendor يقع داخل backend/ لا فوقه. المسار السابق '/../vendor/autoload.php'
// يشير إلى /var/www/vendor غير الموجود، و realpath() تُعيد false عندئذٍ،
// فيصبح الاستدعاء require_once('') ويسقط بخطأ قاتل يُحلّ من مجلد العمل
// الحالي — وهو ما ظهر في السجل كـ "Failed opening required ''".
$autoloadPath = __DIR__ . '/vendor/autoload.php';
if (!file_exists($autoloadPath)) {
$autoloadPath = __DIR__ . '/../vendor/autoload.php';
}
if (file_exists($autoloadPath)) {
require_once $autoloadPath;
}
require_once 'load_env.php';
$siteUser = get_current_user();
@@ -34,6 +44,12 @@ if (!$key) {
$iv = getenv('initializationVector'); // 16 bytes
// ‏الصنف نفسه معرَّف أيضاً في core/Security/EncryptionHelper.php، وأي ملف
// ‏يحمّل bootstrap.php ثم يصل إلى هنا كان ينهار بـ "Cannot declare class
// ‏EncryptionHelper, because the name is already in use" — وهو ما أسقط
// ‏blacklist_manager.php. نُبقي أول تعريف محمَّل (النسخة الحديثة في core)
// ‏ونتخطّى هذه النسخة القديمة المتروكة للتوافقية.
if (!class_exists('EncryptionHelper', false)) {
class EncryptionHelper {
private $key;
private $iv;
@@ -150,6 +166,7 @@ class EncryptionHelper {
return $decrypted;
}
}
} // نهاية حارس class_exists
// ✅ Load the key and IV from .env or use default values
// ✅ Ensure the lengths are correct

Some files were not shown because too many files have changed in this diff Show More