Initial commit with updated Auth and media ignored

This commit is contained in:
Hamza-Ayed
2026-04-28 13:04:27 +03:00
commit 67af97474c
477 changed files with 66444 additions and 0 deletions

75
auth/syria/auth_proxy.php Executable file
View File

@@ -0,0 +1,75 @@
<?php
// Start a session to store state and tokens.
session_start();
// 1. SETUP: Install the Google API Client Library
// Run this command in your project directory: composer require google/apiclient:^2.0
require_once __DIR__ . '/vendor/autoload.php';
// 2. CONFIGURATION: Replace with your credentials from Google Cloud Console
$clientID = '1086900987150-j8brn0i5s97315kh1ej9jr72grkfqgh5.apps.googleusercontent.com'; // Replace with your Client ID
$clientSecret = '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'; // Replace with your Client Secret
// This must be the exact URL of this script.
$redirectUri = 'https://api.tripz-egypt.com/tripz/auth/syria/auth_proxy.php'; // Replace with your script's URL
// 3. APP CONFIGURATION: Your Flutter app's custom URI scheme
// This is how the browser will redirect back to your app.
$appRedirectScheme = 'intaleqapp://auth'; // e.g., myapp://auth
// Create a new Google Client object
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
// 4. LOGIC: Handle the authentication flow
if (isset($_GET['code'])) {
// A. User has been redirected back from Google with an authorization code.
try {
// Exchange the authorization code for an access token.
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
if (isset($token['error'])) {
// Handle error from Google
throw new Exception('Error fetching access token: ' . $token['error_description']);
}
$client->setAccessToken($token['access_token']);
// Get user profile information from Google.
$google_oauth = new Google_Service_Oauth2($client);
$google_account_info = $google_oauth->userinfo->get();
$id = $google_account_info->id;
$email = $google_account_info->email;
$name = $google_account_info->name;
$picture = $google_account_info->picture;
// B. Redirect back to the Flutter app with the user data in the URL.
// We use urlencode to ensure data is passed correctly.
$redirectUrl = $appRedirectScheme .
'?status=success' .
'&id=' . urlencode($id) .
'&email=' . urlencode($email) .
'&name=' . urlencode($name) .
'&picture=' . urlencode($picture);
header('Location: ' . $redirectUrl);
exit();
} catch (Exception $e) {
// C. Handle any errors and redirect back to the app with an error status.
$error_message = urlencode($e->getMessage());
header('Location: ' . $appRedirectScheme . '?status=error&message=' . $error_message);
exit();
}
} else {
// D. This is the initial request from the Flutter app.
// Redirect the user to Google's OAuth 2.0 server for authentication.
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
exit();
}
?>

View File

@@ -0,0 +1,85 @@
<?php
/**
* delete_old_serial_docs.php
* يحذف صور الوثائق الأقدم من مدة محددة (افتراضي 48 ساعة) من private_uploads
* ضع الملف بجانب upload_serial_document.php ليستخدم نفس الشجرة.
*/
date_default_timezone_set('Asia/Damascus');
// === الإعدادات ===
// نفس ما في upload_serial_document.php:
const UPLOAD_ROOT = __DIR__ . "/../../private_uploads";
const ALLOWED_EXTS = ['jpg','png','webp'];
// المدة قبل الحذف (ثواني): افتراضي يومين، ويمكن تمريرها عبر CLI
$ttlSeconds = 2 * 24 * 60 * 60; // 48 ساعة
if (PHP_SAPI === 'cli' && isset($argv[1]) && ctype_digit($argv[1])) {
$ttlSeconds = (int)$argv[1];
}
// ملف لوج اختياري
$logFile = __DIR__ . '/delete_old_serial_docs.log';
$log = @fopen($logFile, 'ab');
// دالة بسيطة للّوج
$logln = function(string $msg) use ($log) {
$line = '[' . date('Y-m-d H:i:s') . '] ' . $msg . PHP_EOL;
if ($log) @fwrite($log, $line);
};
// تحقّق أن مجلد الرفع صحيح وموجود
$root = realpath(UPLOAD_ROOT);
if ($root === false || !is_dir($root)) {
$logln("❌ UPLOAD_ROOT not found: " . UPLOAD_ROOT);
exit(1);
}
$logln("===== Start cleanup in: {$root} | TTL={$ttlSeconds}s =====");
// مُكرّر آمن عبر RecursiveIterator
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
$now = time();
$deleted = 0;
$checked = 0;
// اسم الملف المتوقع: driverId__docType.ext
$docTypes = [
'driver_license_front','driver_license_back',
'car_license_front','car_license_back',
];
$docTypesRegex = implode('|', array_map('preg_quote', $docTypes));
foreach ($it as $node) {
if (!$node->isFile()) continue;
$checked++;
$path = $node->getPathname();
$ext = strtolower($node->getExtension());
// فلترة الامتدادات
if (!in_array($ext, ALLOWED_EXTS, true)) continue;
// فلترة اسم الملف (حماية من حذف ملفات أخرى)
$name = $node->getBasename();
if (!preg_match('/^[A-Za-z0-9_-]+__(' . $docTypesRegex . ')\.(jpg|png|webp)$/i', $name)) {
continue;
}
$age = $now - $node->getMTime();
if ($age >= $ttlSeconds) {
if (@unlink($path)) {
$deleted++;
$logln("🗑 Deleted: {$path} | age=" . round($age/3600, 1) . "h");
} else {
$logln("⚠️ Failed to delete: {$path}");
}
}
}
$logln("Done. checked={$checked}, deleted={$deleted}");
if ($log) @fclose($log);

View File

@@ -0,0 +1,49 @@
<?php
require_once __DIR__ . '/../../../connect.php';
$driverId = filterRequest("id");
if (empty($driverId)) {
jsonError("driver_id is required.");
exit;
}
try {
// تفاصيل السائق
$sql = "SELECT * FROM driver WHERE id = :id LIMIT 1";
$stmt = $con->prepare($sql);
$stmt->execute([':id' => $driverId]);
$driver = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$driver) {
jsonError("Driver not found.");
exit;
}
// فك التشفير للحقول الحساسة
foreach ($driver as $k => $v) {
if (in_array($k, ['phone',
'email',
'first_name',
'last_name',
'national_number',
'address','gender','site',
'birthdate',
'name_arabic'])) {
$driver[$k] = $encryptionHelper->decryptData($v);
}
}
// الوثائق
$sql2 = "SELECT doc_type, image_name, link FROM driver_documents WHERE driverID = :id";
$stmt2 = $con->prepare($sql2);
$stmt2->execute([':id' => $driverId]);
$docs = $stmt2->fetchAll(PDO::FETCH_ASSOC);
printSuccess([
"driver" => $driver,
"documents" => $docs
]);
} catch (PDOException $e) {
jsonError("Error: " . $e->getMessage());
}

View File

@@ -0,0 +1,20 @@
<?php
require_once __DIR__ . '/../../../connect.php';
try {
$sql = "SELECT id, first_name,last_name, phone FROM driver WHERE status <> 'active' ORDER BY id DESC";
$stmt = $con->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// فك التشفير
foreach ($rows as &$r) {
$r['phone'] = $encryptionHelper->decryptData($r['phone']);
$r['first_name'] = $encryptionHelper->decryptData($r['first_name']);
$r['last_name'] = $encryptionHelper->decryptData($r['last_name']);
}
jsonSuccess($rows); // يرجع كـ message: [...]
} catch (PDOException $e) {
jsonError("Error: " . $e->getMessage());
}

View File

@@ -0,0 +1,26 @@
<?php
require_once __DIR__ . '/../../../connect.php';
$phoneNumber = filterRequest("phone_number");
// تشفير الرقم قبل البحث
$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
try {
// الاستعلام عن السائق حسب رقم الهاتف وحالة التحقق
$stmt = $con->prepare("
SELECT * FROM phone_verification
WHERE phone_number = ? AND is_verified = 1
");
$stmt->execute([$phoneNumber_encrypted]);
$driver = $stmt->fetch(PDO::FETCH_ASSOC);
if ($driver) {
jsonSuccess(null, "Phone number is verified.");
} else {
jsonError("Phone number is not verified or does not exist.");
}
} catch (PDOException $e) {
jsonError("Database error: " . $e->getMessage());
}

View File

@@ -0,0 +1,391 @@
<?php
/**
* Endpoint: register_driver_and_car.php
* [MODIFIED] Added vehicle_category_id and fuel_type_id support.
* [MODIFIED] Fixed birthdate logic: Append -01-01 BEFORE encryption.
* [MODIFIED] Added Syrian phone number formatting logic.
*/
//register_driver_and_car.php
$allowRegistration = true;
require_once __DIR__ . '/../../../connect.php';
header('Content-Type: application/json; charset=utf-8');
try {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonError("Invalid method.");
exit;
}
/* ================== General Settings ================== */
$PUBLIC_BASE = "https://intaleq.xyz/driver_docs";
/* ================== 1) Input Fields ================== */
$raw_first_name = null;
$raw_last_name = null;
$required = ["phone", "password", "first_name", "last_name"];
$optional = [
"id","email","gender","license_type","national_number",
"name_arabic","issue_date","expiry_date","license_categories",
"address","licenseIssueDate","status","birthdate","site",
"employmentType","maritalStatus","fullNameMaritial","expirationDate"
];
$carRequired = [
"vin","car_plate","make","model","year","expiration_date",
"color","owner","color_hex","fuel"
];
// حقول اختيارية للسيارة (التصنيف والوقود الرقمي)
// vehicle_category_id, fuel_type_id
$docKeys = [
'driver_license_front',
'driver_license_back',
'car_license_front',
'car_license_back'
];
// Read driver fields
$data = [];
foreach ($required as $f) {
$v = filterRequest($f);
if ($v === null || $v === '') {
jsonError("Missing required field: $f");
exit;
}
$data[$f] = $v;
if ($f === 'first_name') $raw_first_name = $v;
if ($f === 'last_name') $raw_last_name = $v;
}
foreach ($optional as $f) {
$v = filterRequest($f);
$data[$f] = ($v === null || $v === '' || $v === 'Not specified') ? null : $v;
}
/* ================== 🟢 START PHONE FORMATTING LOGIC 🟢 ================== */
if (!empty($data['phone'])) {
$phone = $data['phone'];
// 1. إزالة المسافات والرموز
$phone = preg_replace('/[ \-\(\)\+]/', '', $phone);
$phone = trim($phone);
// 2. توحيد البادئات الدولية
if (strpos($phone, '00963') === 0) {
$phone = substr($phone, 2);
} elseif (strpos($phone, '0963') === 0) {
$phone = substr($phone, 1);
}
// 3. معالجة الحالات الخاصة بالصفر الزائد بعد الرمز الدولي
if (strpos($phone, '96309') === 0) {
$phone = '9639' . substr($phone, 5);
}
elseif (strpos($phone, '9630') === 0) {
$phone = '9639' . substr($phone, 4);
}
// 4. معالجة الأرقام المحلية
elseif (strpos($phone, '09') === 0) {
$phone = '963' . substr($phone, 1);
}
elseif (strpos($phone, '9') === 0 && strlen($phone) == 9) {
$phone = '963' . $phone;
}
elseif (strpos($phone, '0') === 0 && strlen($phone) == 10) {
$phone = '963' . substr($phone, 1);
}
// 5. التأكد من وجود 9 بعد الرمز الدولي
if (strpos($phone, '963') === 0 && strlen($phone) > 3) {
if (strpos($phone, '9639') !== 0) {
$phone = '9639' . substr($phone, 3);
}
}
$data['phone'] = $phone;
}
/* ================== 🔴 END PHONE FORMATTING LOGIC 🔴 ================== */
// تجهيز تاريخ الميلاد قبل التشفير
if (!empty($data['birthdate'])) {
$data['birthdate'] = trim($data['birthdate']);
$data['birthdate'] = $data['birthdate'] . '-01-01';
} else {
$data['birthdate'] = '1970-01-01';
}
// Read car fields
$car = [];
foreach ($carRequired as $f) {
$v = filterRequest($f);
if ($v === null || $v === '') {
jsonError("Missing required field: $f");
exit;
}
$car[$f] = $v;
}
// Read document links
$docUrls = [];
foreach ($docKeys as $k) {
$u = filterRequest($k);
if ($u === null || $u === '') {
jsonError("Missing document URL: $k");
exit;
}
if (!filter_var($u, FILTER_VALIDATE_URL)) {
jsonError("Invalid document URL: $k");
exit;
}
$docUrls[$k] = $u;
}
/* ================== 2) Generate default id/email ================== */
if (empty($data['id'])) {
$data['id'] = 'DRV' . date('YmdHis') . random_int(1000, 9999);
}
if ($data['email'] === null) {
$data['email'] = $data['phone'] . '@intaleqapp.com';
}
/* ================== 3) Encrypt sensitive fields ================== */
$toEncryptDriver = [
"phone","email","first_name","last_name","name_arabic","gender",
"national_number","address","site","fullNameMaritial","birthdate"
];
foreach ($toEncryptDriver as $f) {
if (!empty($data[$f])) {
$data[$f] = $encryptionHelper->encryptData($data[$f]);
}
}
// Encrypt car sensitive data
$car['vin'] = $encryptionHelper->encryptData($car['vin']);
$car['car_plate'] = $encryptionHelper->encryptData($car['car_plate']);
$car['owner'] = $encryptionHelper->encryptData($car['owner']);
/* ================== 4) Hash password (HMAC + password_hash) ================== */
// نقرأ الـ HMAC key من env
$pepper = getenv('SECRET_KEY_HMAC');
// نبني baseString من أكثر من بارامتر
// هنا نستخدم id + phone (بعد ما طبّقنا منطق تنسيق الهاتف)
$baseParts = [
$data['id'],
$data['phone'],
];
// نضيف رقم وطني أو سنة الميلاد إن توفروا (كما في الـ migration)
if (!empty($data['national_number'])) {
$baseParts[] = $data['national_number'];
} elseif (!empty($data['birthdate'])) {
// birthdate حالياً أصبح بصيغة YYYY-01-01
$year = substr($data['birthdate'], 0, 4);
if (preg_match('/^\d{4}$/', $year)) {
$baseParts[] = $year;
}
}
$baseString = implode('|', $baseParts);
// نشتق السر الخام باستخدام HMAC-SHA256 مع SECRET_KEY_HMAC
$rawSecret = hash_hmac('sha256', $baseString, $pepper, true);
// نخزّن فقط الهاش الناتج من password_hash في قاعدة البيانات
$pwdHashed = password_hash($rawSecret, PASSWORD_DEFAULT);
/* ================== 5) Start transaction ================== */
$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']]);
if ($dup->rowCount() > 0) {
$con->rollBack();
jsonError("Phone or email already registered.");
exit;
}
/* ================== 7) Insert Driver ================== */
$sqlDriver = "
INSERT INTO driver (
id, phone, email, password, 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, maritalStatus, fullNameMaritial, expirationDate,
created_at, updated_at
) 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, :maritalStatus, :fullNameMaritial, :expirationDate,
NOW(), NOW()
)
";
$insD = $con->prepare($sqlDriver);
$okD = $insD->execute([
':id' => $data['id'],
':phone' => $data['phone'],
':email' => $data['email'],
':pwd' => $pwdHashed,
':gender' => !empty($data['gender']) ? $data['gender'] : 'Male',
':license_type' => !empty($data['license_type']) ? $data['license_type'] : 'yet',
':national_number' => $data['national_number'],
':name_arabic' => $data['name_arabic'],
':issue_date' => !empty($data['issue_date']) ? $data['issue_date'] : '2020-01-01',
':expiry_date' => !empty($data['expiry_date']) ? $data['expiry_date'] : 'yet',
':license_categories' => !empty($data['license_categories']) ? $data['license_categories'] : 'B',
':address' => $data['address'],
':licenseIssueDate' => !empty($data['licenseIssueDate']) ? $data['licenseIssueDate'] : '2020-01-01',
':status' => !empty($data['status']) ? $data['status'] : 'yet',
':birthdate' => $data['birthdate'],
':site' => !empty($data['site']) ? $data['site'] : 'demascus',
':first_name' => $data['first_name'],
':last_name' => $data['last_name'],
':accountBank' => 'yet',
':bankCode' => 'yet',
':employmentType' => !empty($data['employmentType']) ? $data['employmentType'] : 'yet',
':maritalStatus' => !empty($data['maritalStatus']) ? $data['maritalStatus'] : 'yet',
':fullNameMaritial' => !empty($data['fullNameMaritial']) ? $data['fullNameMaritial'] : 'yet',
':expirationDate' => !empty($data['expirationDate']) ? $data['expirationDate'] : 'yet',
]);
if (!$okD) {
$con->rollBack();
jsonError("Failed to insert driver.");
exit;
}
$driverID = $data['id'];
/* ================== 8) Insert Vehicle ================== */
// ✅ استقبال القيم الجديدة (التصنيف والوقود) مع تعيين افتراضي 1
$vCatID = filterRequest("vehicle_category_id");
$vCatID = ($vCatID !== null && $vCatID !== '') ? $vCatID : 1; // 1 = Car
$fTypeID = filterRequest("fuel_type_id");
$fTypeID = ($fTypeID !== null && $fTypeID !== '') ? $fTypeID : 1; // 1 = Petrol
$hasCar = $con->prepare("SELECT 1 FROM CarRegistration WHERE driverID = :d LIMIT 1");
$hasCar->execute([':d' => $driverID]);
$isDefault = $hasCar->rowCount() === 0 ? 1 : 0;
$sqlCar = "
INSERT INTO CarRegistration (
driverID, vin, car_plate, make, model, year, expiration_date,
color, owner, color_hex, fuel,
vehicle_category_id, fuel_type_id,
isDefault, created_at, status
) VALUES (
:driverID, :vin, :car_plate, :make, :model, :year, :expiration_date,
:color, :owner, :color_hex, :fuel,
:vehicle_category_id, :fuel_type_id,
:isDefault, NOW(), 'yet'
)
";
$insC = $con->prepare($sqlCar);
$okC = $insC->execute([
':driverID' => $driverID,
':vin' => $car['vin'],
':car_plate' => $car['car_plate'],
':make' => $car['make'],
':model' => $car['model'],
':year' => $car['year'],
':expiration_date' => $car['expiration_date'],
':color' => $car['color'],
':owner' => $car['owner'],
':color_hex' => $car['color_hex'],
':fuel' => $car['fuel'], // النص القديم (للتوافق)
':vehicle_category_id' => $vCatID, // ✅ العمود الجديد
':fuel_type_id' => $fTypeID, // ✅ العمود الجديد
':isDefault' => $isDefault,
]);
if (!$okC) {
$con->rollBack();
jsonError("Failed to insert car registration.");
exit;
}
$carRegID = $con->lastInsertId();
/* ================== 9) Store document links ================== */
$insDoc = $con->prepare("
INSERT INTO driver_documents (driverID, doc_type, image_name, link, upload_date)
VALUES (:driverID, :doc_type, :image_name, :link, NOW())
");
foreach ($docKeys as $k) {
$url = $docUrls[$k];
$name = basename(parse_url($url, PHP_URL_PATH) ?? '');
if ($name === '') { $name = $k . '_' . time() . '.jpg'; }
$insDoc->execute([
':driverID' => $driverID,
':doc_type' => $k,
':image_name' => $name,
':link' => $url,
]);
}
/* ================== 10) Commit ================== */
$con->commit();
/* ================== 11) Notification ================== */
try {
$fcmSendUrl = 'https://api.intaleq.xyz/intaleq/ride/firebase/send_fcm.php';
$driverFullName = $raw_first_name . ' ' . $raw_last_name;
$notificationTitle = 'تسجيل سائق جديد';
$notificationBody = "سائق جديد ($driverFullName) سجل برقم ID: $driverID وهو بانتظار المراجعة والتفعيل.";
$notificationPayload = json_encode([
'target' => 'service',
'title' => $notificationTitle,
'body' => $notificationBody,
'isTopic' => true,
'category' => 'new_driver_registration'
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fcmSendUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=UTF-8']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $notificationPayload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_exec($ch);
curl_close($ch);
} catch (Exception $notifyEx) {
error_log("register_driver_and_car NOTIFY ERROR: " . $notifyEx->getMessage());
}
printSuccess([
'status' => 'success',
'driverID' => $driverID,
'carRegID' => $carRegID,
'documents' => $docUrls
]);
} catch (Exception $e) {
if (isset($con) && $con instanceof PDO && $con->inTransaction()) {
$con->rollBack();
}
error_log("register_driver_and_car ERROR: " . $e->getMessage());
jsonError("Server error: " . $e->getMessage());
} catch (PDOException $e) {
if (isset($con) && $con instanceof PDO && $con->inTransaction()) {
$con->rollBack();
}
error_log("register_driver_and_car PDO: " . $e->getMessage());
jsonError("Database error.");
}
?>

View File

@@ -0,0 +1,303 @@
<?php
/**
* Endpoint: register_driver_and_car.php (نسخة محدثة)
* Method: POST (multipart/form-data أو x-www-form-urlencoded)
* الوظيفة: إنشاء سائق + تسجيل مركبة + حفظ روابط الوثائق الموقّعة (من السيرفر السوري)
* ملاحظة: لا نتلقّى ملفات هنا. نتلقى فقط روابط secure_image.php الموقّعة.
*/
$allowRegistration = true;
require_once __DIR__ . '/../../../connect.php';
header('Content-Type: application/json; charset=utf-8');
try {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonError("Invalid method.");
exit;
}
/* ========== إعدادات عامة ========== */
// الدومينات المسموح بها للروابط الموقّعة (السيرفر السوري)
$ALLOWED_SIGNED_HOSTS = [
'syria.intaleq.xyz', // عدّل حسب بيئتك
'applink.syria', // مثال آخر إن كان لديك دومين إضافي
];
// توثيق شكل الروابط: secure_image.php?driver_id=...&doc_type=...&ext=jpg|png|webp&expires=...&signature=...
$allowedDocTypes = [
'driver_license_front',
'driver_license_back',
'car_license_front',
'car_license_back',
];
$allowedExts = ['jpg','png','webp'];
/* ========== 1) جلب الحقول ========== */
$required = ["phone", "password", "first_name", "last_name"];
$optional = [
"id","email","gender","license_type","national_number",
"name_arabic","issue_date","expiry_date","license_categories",
"address","licenseIssueDate","status","birthdate","site",
"employmentType","maritalStatus","fullNameMaritial","expirationDate"
];
// حقول السيارة (مطلوبة)
$carRequired = [
"vin","car_plate","make","model","year","expiration_date",
"color","owner","color_hex","fuel"
];
// روابط الوثائق (مطلوبة)
$docUrlKeys = [
'driver_license_front_url',
'driver_license_back_url',
'car_license_front_url',
'car_license_back_url'
];
$data = [];
foreach ($required as $f) {
$v = filterRequest($f);
if ($v === null || $v === '') {
jsonError("Missing required field: $f");
exit;
}
$data[$f] = $v;
}
foreach ($optional as $f) {
$v = filterRequest($f);
$data[$f] = ($v === null || $v === '' || $v === 'Not specified') ? null : $v;
}
$car = [];
foreach ($carRequired as $f) {
$v = filterRequest($f);
if ($v === null || $v === '') {
jsonError("Missing required field: $f");
exit;
}
$car[$f] = $v;
}
$docUrls = [];
foreach ($docUrlKeys as $k) {
$v = filterRequest($k);
if ($v === null || trim($v) === '') {
jsonError("Missing signed URL: $k");
exit;
}
$docUrls[$k] = trim($v);
}
/* ========== 2) توليد id إذا مفقود + بناء email افتراضي إن لزم ========== */
if (empty($data['id'])) {
$data['id'] = 'DRV' . date('YmdHis') . random_int(1000, 9999);
}
if ($data['email'] === null) {
$data['email'] = $data['phone'] . '@intaleqapp.com';
}
$driverID = $data['id'];
/* ========== 3) تشفير الحقول الحساسة ========== */
$toEncryptDriver = [
"phone","email","first_name","last_name","name_arabic","gender",
"national_number","address","site","fullNameMaritial"
];
foreach ($toEncryptDriver as $f) {
if (!empty($data[$f])) {
$data[$f] = $encryptionHelper->encryptData($data[$f]);
}
}
// حساسات السيارة
$car['vin'] = $encryptionHelper->encryptData($car['vin']);
$car['car_plate'] = $encryptionHelper->encryptData($car['car_plate']);
$car['owner'] = $encryptionHelper->encryptData($car['owner']);
/* ========== 4) هَش كلمة المرور ========== */
$pwdHashed = password_hash(filterRequest('password'), PASSWORD_DEFAULT);
/* ========== 5) بدء معاملة ========== */
$con->beginTransaction();
/* ========== 6) فحص تكرار هاتف/ايميل (المشفّرين) ========== */
$dup = $con->prepare("SELECT id FROM driver WHERE phone = :p OR email = :e");
$dup->execute([':p' => $data['phone'], ':e' => $data['email']]);
if ($dup->rowCount() > 0) {
$con->rollBack();
jsonError("Phone or email already registered.");
exit;
}
/* ========== 7) إدراج السائق ========== */
$sqlDriver = "
INSERT INTO driver (
id, phone, email, password, 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, maritalStatus, fullNameMaritial, expirationDate,
created_at, updated_at
) 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, :maritalStatus, :fullNameMaritial, :expirationDate,
NOW(), NOW()
)
";
$insD = $con->prepare($sqlDriver);
$okD = $insD->execute([
':id' => $driverID,
':phone' => $data['phone'],
':email' => $data['email'],
':pwd' => $pwdHashed,
':gender' => $data['gender'],
':license_type' => $data['license_type'],
':national_number' => $data['national_number'],
':name_arabic' => $data['name_arabic'],
':issue_date' => $data['issue_date'],
':expiry_date' => $data['expiry_date'],
':license_categories'=> !empty($data['license_categories']) ? $data['license_categories'] : 'B',
':address' => $data['address'],
':licenseIssueDate' => $data['licenseIssueDate'],
':status' => !empty($data['status']) ? $data['status'] : 'yet',
':birthdate' => $data['birthdate'],
':site' => $data['site'],
':first_name' => $data['first_name'],
':last_name' => $data['last_name'],
':accountBank' => 'yet',
':bankCode' => 'yet',
':employmentType' => !empty($data['employmentType']) ? $data['employmentType'] : 'yet',
':maritalStatus' => !empty($data['maritalStatus']) ? $data['maritalStatus'] : 'yet',
':fullNameMaritial' => !empty($data['fullNameMaritial']) ? $data['fullNameMaritial'] : 'yet',
':expirationDate' => !empty($data['expirationDate']) ? $data['expirationDate'] : 'yet',
]);
if (!$okD) { $con->rollBack(); jsonError("Failed to insert driver."); exit; }
/* ========== 8) إدراج السيارة ========== */
$hasCar = $con->prepare("SELECT 1 FROM CarRegistration WHERE driverID = :d LIMIT 1");
$hasCar->execute([':d' => $driverID]);
$isDefault = $hasCar->rowCount() === 0 ? 1 : 0;
$sqlCar = "
INSERT INTO CarRegistration (
driverID, vin, car_plate, make, model, year, expiration_date,
color, owner, color_hex, fuel, isDefault, created_at, status
) VALUES (
:driverID, :vin, :car_plate, :make, :model, :year, :expiration_date,
:color, :owner, :color_hex, :fuel, :isDefault, NOW(), 'yet'
)
";
$insC = $con->prepare($sqlCar);
$okC = $insC->execute([
':driverID' => $driverID,
':vin' => $car['vin'],
':car_plate' => $car['car_plate'],
':make' => $car['make'],
':model' => $car['model'],
':year' => $car['year'],
':expiration_date' => $car['expiration_date'],
':color' => $car['color'],
':owner' => $car['owner'],
':color_hex' => $car['color_hex'],
':fuel' => $car['fuel'],
':isDefault' => $isDefault,
]);
if (!$okC) { $con->rollBack(); jsonError("Failed to insert car registration."); exit; }
$carRegID = $con->lastInsertId();
/* ========== 9) التحقّق من الروابط الموقّعة وحفظها ========== */
// دالة مساعدة تتحقّق من شكل الرابط وتستخرج doc_type/ext
$validateSignedUrl = function(string $url) use ($allowedDocTypes, $allowedExts) {
$parts = parse_url($url);
if (!$parts || empty($parts['scheme']) || empty($parts['host']) || empty($parts['path'])) {
throw new Exception("Invalid URL format.");
}
if (!in_array($parts['host'], $ALLOWED_SIGNED_HOSTS, true)) {
throw new Exception("URL host not allowed: {$parts['host']}");
}
if (stripos($parts['path'], 'secure_image.php') === false) {
throw new Exception("URL path not allowed.");
}
if (empty($parts['query'])) {
throw new Exception("URL missing query string.");
}
parse_str($parts['query'], $q);
foreach (['driver_id','doc_type','ext','expires','signature'] as $k) {
if (empty($q[$k])) throw new Exception("URL missing param: $k");
}
if (!in_array($q['doc_type'], $allowedDocTypes, true)) {
throw new Exception("Invalid doc_type in URL.");
}
if (!in_array(strtolower($q['ext']), $allowedExts, true)) {
throw new Exception("Invalid ext in URL.");
}
return [
'doc_type' => $q['doc_type'],
'ext' => strtolower($q['ext']),
// بإمكانك التحقق من driver_id = $driverID إذا تحب تربطهما
'driver_id_in_url' => $q['driver_id'],
];
};
$docsToInsert = []; // [['doc_type'=>..., 'link'=>..., 'image_name'=>...], ...]
foreach ($docUrlKeys as $k) {
$link = $docUrls[$k];
$meta = $validateSignedUrl($link);
// image_name ليس ضروريًا هنا (الرابط موقّع إلى بوابة قراءة)، احفظ doc_type + link فقط
$docsToInsert[] = [
'doc_type' => $meta['doc_type'], // يجب أن يتطابق مع $k منطقيًا
'link' => $link,
'image_name' => $meta['doc_type'] . '.' . $meta['ext'], // اسماً رمزياً فقط
];
}
// إدراج في driver_documents
// CREATE TABLE driver_documents (
// id INT AUTO_INCREMENT PRIMARY KEY,
// driverID VARCHAR(64) NOT NULL,
// doc_type VARCHAR(64) NOT NULL,
// image_name VARCHAR(255) NULL,
// link VARCHAR(1024) NOT NULL,
// upload_date DATETIME NOT NULL,
// INDEX(driverID)
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
$insDoc = $con->prepare("
INSERT INTO driver_documents (driverID, doc_type, image_name, link, upload_date)
VALUES (:driverID, :doc_type, :image_name, :link, NOW())
");
foreach ($docsToInsert as $row) {
$insDoc->execute([
':driverID' => $driverID,
':doc_type' => $row['doc_type'],
':image_name' => $row['image_name'],
':link' => $row['link'],
]);
}
/* ========== 10) إنهاء المعاملة ========== */
$con->commit();
printSuccess([
'driverID' => $driverID,
'carRegID' => $carRegID,
'documents' => [
'driver_license_front_url' => $docUrls['driver_license_front_url'],
'driver_license_back_url' => $docUrls['driver_license_back_url'],
'car_license_front_url' => $docUrls['car_license_front_url'],
'car_license_back_url' => $docUrls['car_license_back_url'],
]
]);
} catch (Exception $e) {
if (isset($con) && $con->inTransaction()) { $con->rollBack(); }
error_log("register_driver_and_car ERROR: " . $e->getMessage());
jsonError("Server error: " . $e->getMessage());
} catch (PDOException $e) {
if (isset($con) && $con->inTransaction()) { $con->rollBack(); }
error_log("register_driver_and_car PDO: " . $e->getMessage());
jsonError("Database error.");
}

View File

@@ -0,0 +1,69 @@
<?php
require_once __DIR__ . '/../../../connect.php';
//sendWhatsAppDriver.php
error_log("--- [send_otp_driver.php] Started ---");
/**
* فحص البلاك ليست (خاصة بالسائقين)
* - يشفّر الهاتف الخام ويبحث عنه في جدول blacklist_driver
*/
function is_blacklisted_driver(PDO $con, $encryptionHelper, string $phone): bool {
$raw = trim($phone);
$enc_raw = $encryptionHelper->encryptData($raw);
$sql = "SELECT 1 FROM blacklist_driver WHERE phone = :ph LIMIT 1";
$q = $con->prepare($sql);
$q->execute(['ph' => $enc_raw]);
return (bool)$q->fetchColumn();
}
/* 0) استقبل الرقم وتحقق من البلاك ليست */
$receiver = filterRequest("receiver");
if (!$receiver) {
jsonError('Phone number is required.');
error_log("[send_otp_driver.php] Error: phone empty");
exit();
}
if (is_blacklisted_driver($con, $encryptionHelper, $receiver)) {
jsonError('This driver is blacklisted and cannot receive OTP.');
error_log("[send_otp_driver.php] BLOCKED (blacklisted): $receiver");
exit();
}
/* 1) توليد الـ OTP */
$otp = rand(10000, 99999);
$messageBody = "Your verification code for Intaleq is: " . $otp;
/* 🟢 2) تخطي الإرسال الفعلي */
error_log("[send_otp_driver.php] Skipping actual WhatsApp send. OTP for $receiver: $otp");
/* 3) حفظ الـ OTP في قاعدة البيانات */
$receiver_enc = $encryptionHelper->encryptData($receiver);
$otp_enc = $encryptionHelper->encryptData($otp);
$exp = date('Y-m-d H:i:s', strtotime('+5 minutes'));
$now = date('Y-m-d H:i:s');
try {
// حذف أي رموز سابقة لنفس الرقم
$con->prepare("DELETE FROM phone_verification WHERE phone_number = ?")
->execute([$receiver_enc]);
$stmt = $con->prepare("
INSERT INTO phone_verification
(phone_number, token_code, expiration_time, is_verified, created_at)
VALUES (?, ?, ?, 0, ?)
");
$stmt->execute([$receiver_enc, $otp_enc, $exp, $now]);
jsonSuccess(null, 'OTP generated and saved successfully (no message sent)');
error_log("[send_otp_driver.php] OTP saved for driver $receiver");
} catch (PDOException $e) {
error_log("[send_otp_driver.php] DB error: ".$e->getMessage());
jsonError('OTP generated but failed to save to database');
}
?>

69
auth/syria/driver/verifyOtp.php Executable file
View File

@@ -0,0 +1,69 @@
<?php
require_once __DIR__ . '/../../../connect.php';
$phoneNumber = filterRequest("phone_number");
$email = $phoneNumber . '@intaleqapp.com';
error_log("📥 [verifyOtp.php] Received phone number: $phoneNumber");
// 🔐 تشفير البيانات
$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
$email_encrypted = $encryptionHelper->encryptData($email);
try {
// 🧹 حذف أي رموز قديمة لنفس الرقم
$con->prepare("DELETE FROM phone_verification WHERE phone_number = ?")
->execute([$phoneNumber_encrypted]);
// 🧾 توليد driverID فريد
$raw = $phoneNumber;
$driverID = substr(md5($raw), 2, 20);
// 🔐 توليد رمز تجريبي (بدون OTP حقيقي لتجنب Null)
$dummyToken = $encryptionHelper->encryptData('AUTO');
// 🕒 الوقت الحالي
$now = date('Y-m-d H:i:s');
// ✅ إدخال سجل تحقق مباشر
$stmt = $con->prepare("
INSERT INTO phone_verification
(phone_number, token_code, email, driverId, expiration_time, is_verified, created_at)
VALUES (?, ?, ?, ?, NULL, 1, ?)
");
$stmt->execute([$phoneNumber_encrypted, $dummyToken, $email_encrypted, $driverID, $now]);
error_log("✅ [verifyOtp.php] Auto verification record inserted successfully for $phoneNumber");
// 🔍 التحقق إذا السائق موجود مسبقاً
$checkDriverStmt = $con->prepare("SELECT * FROM driver WHERE phone = ?");
$checkDriverStmt->execute([$phoneNumber_encrypted]);
$driver = $checkDriverStmt->fetch(PDO::FETCH_ASSOC);
if ($driver) {
error_log("👤 [verifyOtp.php] Driver already registered. Returning driver info.");
printSuccess([
"message" => "Driver already registered.",
"isRegistered" => true,
"driver" => [
"id" => $driver['id'],
"first_name" => $encryptionHelper->decryptData($driver['first_name']),
"last_name" => $encryptionHelper->decryptData($driver['last_name']),
"email" => $encryptionHelper->decryptData($driver['email']),
"phone" => $phoneNumber
]
]);
} else {
error_log("🆕 [verifyOtp.php] Phone verified automatically. Driver not found.");
printSuccess([
"message" => "Phone number verified automatically (no OTP required).",
"isRegistered" => false,
"driverID" => $driverID
]);
}
} catch (PDOException $e) {
error_log("💥 [verifyOtp.php] PDO ERROR: " . $e->getMessage());
jsonError("Database error: " . $e->getMessage());
}
?>

155
auth/syria/register_passenger.php Executable file
View File

@@ -0,0 +1,155 @@
<?php
// File: register_passenger.php
// إعدادات إظهار الأخطاء
ini_set('display_errors', 0);
error_reporting(E_ALL);
$allowRegistration = true;
require_once __DIR__ . '/../../connect.php';
// تعريف بادئة للوج (Tag) لسهولة البحث عنها في ملف الأخطاء
$logTag = "[Register_Debug_passenger]";
$step = 0;
try {
// ======================================================
// Step 1: استقبال البيانات
// ======================================================
$step = 1;
$phoneNumber = filterRequest("phone_number");
$firstName = filterRequest("first_name");
$lastName = filterRequest("last_name");
$email = filterRequest("email");
// طباعة وصول البيانات (مع إخفاء جزء من الرقم)
error_log("$logTag Step 1: Received request. Phone: " . substr($phoneNumber, 0, 7) . "*****");
// ======================================================
// Step 2: التحقق من المدخلات
// ======================================================
$step = 2;
if (empty($phoneNumber) || empty($firstName) || empty($lastName)) {
error_log("$logTag Step 2 Error: Missing required fields.");
jsonError("Required fields are missing.");
exit();
}
// ======================================================
// Step 3: معالجة الإيميل
// ======================================================
$step = 3;
if (empty($email)) {
$email = $phoneNumber . '@intaleqapp.com';
error_log("$logTag Step 3: Email was empty, generated default: " . substr($email, 0, 5) . "***");
}
// ======================================================
// Step 4: تشفير البيانات
// ======================================================
$step = 4;
error_log("$logTag Step 4: Encrypting data...");
if (!isset($encryptionHelper)) {
throw new Exception("Encryption Helper class is missing.");
}
$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
$firstName_encrypted = $encryptionHelper->encryptData($firstName);
$lastName_encrypted = $encryptionHelper->encryptData($lastName);
$email_encrypted = $encryptionHelper->encryptData($email);
$password_hashed = password_hash($email, PASSWORD_DEFAULT);
$unknown_encrypted = $encryptionHelper->encryptData("unknown yet");
// ======================================================
// Step 5: إنشاء ID فريد
// ======================================================
$step = 5;
// $uniqueId = substr(md5(uniqid(mt_rand(), true)), 0, 20);
$uniqueId = substr(md5($phoneNumber_encrypted), 0, 20);
error_log("$logTag Step 5: Generated Unique ID: $uniqueId");
// ======================================================
// Step 6: التحقق من وجود المستخدم (Database Check)
// ======================================================
$step = 6;
$checkStmt = $con->prepare("SELECT id FROM passengers WHERE phone = ?");
$checkStmt->execute([$phoneNumber_encrypted]);
if ($checkStmt->rowCount() > 0) {
error_log("$logTag Step 6 Error: User already exists.");
jsonError("User with this phone number or email already exists.");
exit();
}
// ======================================================
// Step 7: الإضافة (Insert User)
// ======================================================
$step = 7;
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())
");
$success = $insertStmt->execute([
$uniqueId,
$firstName_encrypted,
$lastName_encrypted,
$email_encrypted,
$phoneNumber_encrypted,
$password_hashed,
$unknown_encrypted,
$unknown_encrypted,
$unknown_encrypted,
$unknown_encrypted,
$unknown_encrypted,
$unknown_encrypted,
$unknown_encrypted
]);
if (!$success) {
$errorInfo = $insertStmt->errorInfo();
// طباعة تفاصيل خطأ الـ SQL في اللوج
error_log("$logTag Step 7 Error: SQL Insert Failed. Details: " . json_encode($errorInfo));
jsonError("Failed to create user account.");
exit();
}
// ======================================================
// Step 9: جلب البيانات لإعادتها
// ======================================================
$step = 9;
$userStmt = $con->prepare("SELECT * FROM passengers WHERE id = ?");
$userStmt->execute([$uniqueId]);
$newUser = $userStmt->fetch(PDO::FETCH_ASSOC);
// ======================================================
// Step 10: فك التشفير وإرسال الرد
// ======================================================
$step = 10;
if ($newUser) {
unset($newUser['password']);
foreach ($newUser as $key => &$value) {
if ($key !== 'id' && $key !== 'status' && $key !== 'created_at' && $key !== 'updated_at' && !is_null($value)) {
$value = $encryptionHelper->decryptData($value);
}
}
}
error_log("$logTag Success: User registered successfully.");
jsonSuccess(["status" => "registration_success", "data" => $newUser]);
} catch (PDOException $e) {
// طباعة خطأ قاعدة البيانات في اللوج
error_log("$logTag PDO Exception at Step $step: " . $e->getMessage());
jsonError("Database Error.");
} catch (Exception $e) {
// طباعة الأخطاء العامة في اللوج
error_log("$logTag General Exception at Step $step: " . $e->getMessage());
jsonError("General Error.");
}
?>

72
auth/syria/secure_image.php Executable file
View File

@@ -0,0 +1,72 @@
<?php
// File: secure_image.php
// يعرض الملف فقط إذا كان الرابط موقّع وصالح زمنياً.
// يعتمد نفس الثوابت/المسارات في upload_serial_document.php
require_once __DIR__ . '/../../connect.php';
const UPLOAD_ROOT = __DIR__ . "/../../private_uploads";
const SIGN_SECRET = getenv('SECRET_KEY_HMAC'); // نفس المفتاح
// استلام المعطيات من الرابط
$driverId = $_GET['driver_id'] ?? '';
$docType = $_GET['doc_type'] ?? '';
$extShort = $_GET['ext'] ?? '';
$expires = $_GET['expires'] ?? '';
$signature= $_GET['signature'] ?? '';
if ($driverId === '' || $docType === '' || $extShort === '' || $expires === '' || $signature === '') {
http_response_code(400); echo "Missing parameters."; exit;
}
// صلاحية الوقت
if ((int)$expires < time()) {
http_response_code(403); echo "Link expired."; exit;
}
// تحقق من doc_type
$allowedDocTypes = [
'driver_license_front',
'driver_license_back',
'car_license_front',
'car_license_back',
];
if (!in_array($docType, $allowedDocTypes, true)) {
http_response_code(403); echo "Invalid doc_type."; exit;
}
// تحقق من الامتداد
$allowedExts = ['jpg','png','webp'];
if (!in_array($extShort, $allowedExts, true)) {
http_response_code(403); echo "Invalid ext."; exit;
}
// إعادة توليد التوقيع للمقارنة
$driverIdSafe = preg_replace('/[^A-Za-z0-9_\-]/', '_', $driverId);
$message = $driverIdSafe . ':' . $docType . ':' . $extShort . ':' . $expires;
$expected = hash_hmac('sha256', $message, SIGN_SECRET);
if (!hash_equals($expected, $signature)) {
http_response_code(403); echo "Invalid signature."; exit;
}
// بناء المسار
$h = hash('sha1', $driverIdSafe);
$subdir = substr($h, 0, 2) . '/' . substr($h, 2, 2);
$serverName = "{$driverIdSafe}__{$docType}.{$extShort}";
$path = UPLOAD_ROOT . '/' . $subdir . '/' . $serverName;
if (!is_file($path)) {
http_response_code(404); echo "File not found."; exit;
}
// تحديد النوع
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($path) ?: 'application/octet-stream';
header('Content-Type: ' . $mime);
header('Content-Length: ' . filesize($path));
header('X-Content-Type-Options: nosniff');
// (اختياري) اطلب توكن وصول إضافي عبر Authorization للتحكم الأدق.
// مثال: تحقق من $_SERVER['HTTP_AUTHORIZATION'] هنا إن أردت.
readfile($path);

197
auth/syria/sendWhatsOpt.php Executable file
View File

@@ -0,0 +1,197 @@
<?php
$allowRegistration = true;
require_once __DIR__ . '/../../connect.php';
error_log("--- [send_otp_pass.php] Started ---");
/* Helpers */
function normalize_phone($s) { return preg_replace('/\D+/', '', (string)$s); }
/**
* Check blacklist by encrypted phone
*/
function is_blacklisted(PDO $con, $encryptionHelper, string $phone): bool {
$raw = trim($phone);
$norm = normalize_phone($raw);
$enc_raw = $encryptionHelper->encryptData($raw);
$enc_norm = $encryptionHelper->encryptData($norm);
$sql = "SELECT 1
FROM passenger_blacklist
WHERE phone IN (:enc_raw, :enc_norm)
AND (expires_at IS NULL OR expires_at > NOW())
LIMIT 1";
$q = $con->prepare($sql);
$q->execute([
'enc_raw' => $enc_raw,
'enc_norm' => $enc_norm,
]);
return (bool)$q->fetchColumn();
}
/* 0) Get phone number */
$receiver = filterRequest("receiver");
if (!$receiver) {
jsonError('Phone number is required.');
exit();
}
if (is_blacklisted($con, $encryptionHelper, $receiver)) {
jsonError('This phone is blacklisted and cannot receive OTP.');
error_log("[send_otp] BLOCKED (blacklisted): $receiver");
exit();
}
/* 1) Generate OTP */
$otp = rand(10000, 99999);
$messageBody = "Your verification code for Intaleq is: " . $otp;
/* 🟢 2) Skip sending and log instead */
error_log("[send_otp] Skipping actual send. OTP generated for $receiver: $otp");
/* 3) Save OTP (encrypted) */
$receiver_enc = $encryptionHelper->encryptData($receiver);
$otp_enc = $encryptionHelper->encryptData($otp);
$exp = date('Y-m-d H:i:s', strtotime('+5 minutes'));
$now = date('Y-m-d H:i:s');
try {
$con->prepare("DELETE FROM phone_verification_passenger WHERE phone_number = ?")
->execute([$receiver_enc]);
$stmt = $con->prepare("
INSERT INTO phone_verification_passenger
(phone_number, token, expiration_time, verified, created_at)
VALUES (?, ?, ?, 0, ?)
");
$stmt->execute([$receiver_enc, $otp_enc, $exp, $now]);
jsonSuccess(null, 'OTP generated and saved successfully (no message sent)');
error_log("[send_otp] OTP saved successfully for $receiver");
} catch (PDOException $e) {
error_log("[send_otp] DB error: ".$e->getMessage());
jsonError('OTP generated but failed to save to database');
}
/*
require_once __DIR__ . '/../../connect.php';
error_log("--- [send_otp.php] Started ---");
function normalize_phone($s) { return preg_replace('/\D+/', '', (string)$s); }
function is_blacklisted(PDO $con, $encryptionHelper, string $phone): bool {
$raw = trim($phone);
$norm = normalize_phone($raw);
// شَفِّر قبل السؤال
$enc_raw = $encryptionHelper->encryptData($raw);
$enc_norm = $encryptionHelper->encryptData($norm);
$sql = "SELECT 1
FROM passenger_blacklist
WHERE phone IN (:enc_raw, :enc_norm)
AND (expires_at IS NULL OR expires_at > NOW())
LIMIT 1";
$q = $con->prepare($sql);
$q->execute([
'enc_raw' => $enc_raw,
'enc_norm' => $enc_norm,
]);
return (bool)$q->fetchColumn();
}
$receiver = filterRequest("receiver");
if (!$receiver) { jsonError('Phone number is required.'); exit(); }
if (is_blacklisted($con, $encryptionHelper, $receiver)) {
jsonError('This phone is blacklisted and cannot receive OTP.');
error_log("[send_otp] BLOCKED (blacklisted): $receiver");
exit();
}
$otp = rand(10000, 99999);
$messageBody = "Your verification code for Intaleq is: " . $otp;
function normalize($raw) {
if (is_string($raw)) return json_decode($raw, true) ?: [];
if ($raw instanceof stdClass) return (array)$raw;
return is_array($raw) ? $raw : [];
}
$response = normalize(sendWhatsAppFromServer($receiver, $messageBody));
$sentOK = $response['success'] ?? false;
if (!$sentOK) {
error_log("[send_otp] WA-Server failed ⇒ ".(($response['message'] ?? null) ?: json_encode($response)));
$payload = [
"number" => $receiver,
"type" => "text",
"message" => $messageBody,
"instance_id" => getenv("RASEEL_DRIVER_INSTANCE_ID"),
"access_token" => getenv("RASEEL_DRIVER_ACCESS_TOKEN")
];
$response = callAPI("POST", "https://raseelplus.com/api/send", json_encode($payload));
$response = normalize($response);
$sentOK = ($response['status'] ?? '') === 'success';
if (!$sentOK) {
error_log("[send_otp] RaseelPlus failed ⇒ ".json_encode($response));
jsonError('Failed to send OTP: '.($response['message'] ?? 'Unknown error'));
exit();
}
}
$receiver_enc = $encryptionHelper->encryptData($receiver); // الهاتف المُرسل (خام) مُشفّر
$otp_enc = $encryptionHelper->encryptData($otp);
$exp = date('Y-m-d H:i:s', strtotime('+5 minutes'));
$now = date('Y-m-d H:i:s');
try {
$con->prepare("DELETE FROM phone_verification_passenger WHERE phone_number = ?")
->execute([$receiver_enc]);
$stmt = $con->prepare("
INSERT INTO phone_verification_passenger
(phone_number, token, expiration_time, verified, created_at)
VALUES (?, ?, ?, 0, ?)
");
$stmt->execute([$receiver_enc, $otp_enc, $exp, $now]);
jsonSuccess(null, 'OTP sent and saved successfully');
error_log("[send_otp] OTP saved for $receiver");
} catch (PDOException $e) {
error_log("[send_otp] DB error: ".$e->getMessage());
jsonError('OTP sent but failed to save to database');
}
function callAPI($method, $url, $data) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Accept: application/json"
],
]);
$body = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
return $err ? [] : json_decode($body, true);
}
*/

52
auth/syria/send_survey.php Executable file
View File

@@ -0,0 +1,52 @@
<?php
require_once __DIR__ . '/../../connect.php';
$receiver = filterRequest("receiver");
if (!$receiver) {
jsonError("رقم الهاتف مفقود");
exit;
}
// توليد تأخير عشوائي بين 45 و 90 ثانية
$delay = rand(45, 90);
sleep($delay);
// رسالة الاستطلاع مع أزرار
$surveyMessage = [
"type" => "buttons",
"header" => [
"type" => "text",
"text" => "استطلاع رأي سريع 🌟"
],
"body" => [
"text" => "هل كانت تجربة التسجيل في تطبيق *انطلق* سهلة بالنسبة لك؟\n\n👇 اضغط أحد الخيارات:"
],
"footer" => [
"text" => "للتواصل: +962 7XXXXXXX - رابط التطبيق: https://intaleq.xyz"
],
"buttons" => [
[
"type" => "reply",
"reply" => [
"id" => "feedback_yes",
"title" => "👍 نعم"
]
],
[
"type" => "reply",
"reply" => [
"id" => "feedback_no",
"title" => "👎 لا"
]
]
]
];
// استدعاء الدالة لإرسال الرسالة
$response = sendWhatsAppFromServer($receiver, $surveyMessage);
if ($response && isset($response["status"]) && $response["status"] === "sent") {
jsonSuccess(null, "تم إرسال استطلاع الرأي بنجاح بعد $delay ثانية.");
} else {
jsonError("فشل في إرسال استطلاع الرأي");
}
?>

129
auth/syria/uploadSyrianDocs.php Executable file
View File

@@ -0,0 +1,129 @@
<?php
// File: upload_serial_document.php
// يرفع صورة وثيقة إلى مسار خاص (خارج الويب العام) ويُرجع Signed URL مؤقّت.
// بيئتك
require_once __DIR__ . '/../../connect.php'; // يجب أن يوفّر: $con (اختياري) + printSuccess/printFailure + filterRequest
// --------- إعدادات ---------
const MAX_FILE_MB = 5;
const ALLOWED_MIMES = ['image/jpeg','image/png','image/webp']; // فقط صور
const UPLOAD_ROOT = __DIR__ . "/../../private_uploads"; // مجلد خاص (غير عام)
const SIGN_SECRET = getenv('SECRET_KEY_HMAC'); // غيّرها واقرأها من .env
const PUBLIC_BASE = 'https://syria.intaleq.xyz/intaleq'; // الدومين العلني
const SIGNED_TTL_SEC = 172800; // 2 days = 60*60*24
// أنشئ مجلد الرفع إن لم يكن موجودًا
if (!is_dir(UPLOAD_ROOT)) { @mkdir(UPLOAD_ROOT, 0700, true); }
// (اختياري) هيدرز أمان
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$hmacHeader = $_SERVER['HTTP_X_HMAC_AUTH'] ?? '';
// TODO: تحقّق حسب منطقك إن أردت فرض المصادقة هنا.
// --------- حقول مطلوبة من Flutter عبر filterRequest ---------
$driverId = filterRequest('driver_id');
$docType = filterRequest('doc_type');
$purpose = filterRequest('purpose'); // اختياري
if (empty($driverId) || empty($docType)) {
jsonError("driver_id and doc_type are required.");
exit;
}
// اسمح فقط بقيم محددة للوثائق
$allowedDocTypes = [
'driver_license_front',
'driver_license_back',
'car_license_front',
'car_license_back',
];
if (!in_array($docType, $allowedDocTypes, true)) {
jsonError("Invalid doc_type.");
exit;
}
// --------- التحقق من الملف ---------
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
jsonError("No file uploaded or upload error.");
exit;
}
$tmpPath = $_FILES['file']['tmp_name'];
$origName = $_FILES['file']['name'] ?? 'upload.bin';
$size = filesize($tmpPath);
if ($size === false || $size <= 0) {
jsonError("Invalid file size."); exit;
}
if ($size > MAX_FILE_MB * 1024 * 1024) {
jsonError("File too large. Max " . MAX_FILE_MB . " MB."); exit;
}
// MIME دقيق
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($tmpPath) ?: 'application/octet-stream';
if (!in_array($mime, ALLOWED_MIMES, true)) {
jsonError("Unsupported file type: $mime"); exit;
}
// لاحقة الامتداد
$extMap = [
'image/jpeg' => '.jpg',
'image/png' => '.png',
'image/webp' => '.webp',
];
$ext = $extMap[$mime];
// --------- توليد مسار حتمي بدون تاريخ ---------
// تنظيف driver_id لاسم ملف آمن
$driverIdSafe = preg_replace('/[^A-Za-z0-9_\-]/', '_', $driverId);
// شجرة مجلدات ثابتة من hash(driver_id) لتوزيع الملفات
$h = hash('sha1', $driverIdSafe);
$subdir = substr($h, 0, 2) . '/' . substr($h, 2, 2);
$destDir = UPLOAD_ROOT . '/' . $subdir;
if (!is_dir($destDir)) { @mkdir($destDir, 0700, true); }
// الاسم النهائي بدون تاريخ
$serverName = "{$driverIdSafe}__{$docType}{$ext}";
$destPath = $destDir . '/' . $serverName;
// استبدال أي نسخة قديمة عن قصد (overwrite)
if (is_file($destPath)) { @unlink($destPath); }
// نقل الملف
if (!move_uploaded_file($tmpPath, $destPath)) {
jsonError("Failed to save the uploaded file.");
exit;
}
@chmod($destPath, 0600);
// --------- Signed URL ---------
// سنضمّن driver_id و doc_type و ext في الرابط والتوقيع.
// ext بدون النقطة
$extShort = ltrim($ext, '.');
$expires = time() + SIGNED_TTL_SEC;
// الرسالة الموقّعة: driver_id:doc_type:ext:expires
$message = $driverIdSafe . ':' . $docType . ':' . $extShort . ':' . $expires;
$signature = hash_hmac('sha256', $message, SIGN_SECRET);
// رابط القراءة عبر البوابة الآمنة فقط
// ملاحظة: لا نُرجع المسار الحقيقي، فقط معطيات موقّعة
$fileUrl = PUBLIC_BASE . "/secure_image.php"
. "?driver_id={$driverIdSafe}"
. "&doc_type={$docType}"
. "&ext={$extShort}"
. "&expires={$expires}"
. "&signature={$signature}";
// --------- استجابة ---------
printSuccess([
"status" => "success",
"success_file" => true,
"file_url" => $fileUrl,
"file_name" => $serverName, // الاسم الفعلي المحفوظ
"driver_id" => $driverIdSafe,
"doc_type" => $docType,
"mime_type" => $mime,
"size_bytes" => $size,
"expires_at" => date('c', $expires)
]);

93
auth/syria/verifyOtp.php Executable file
View File

@@ -0,0 +1,93 @@
<?php
$allowRegistration = true;
require_once __DIR__ . '/../../connect.php';
// تسجيل بداية الطلب
error_log("[Auth_Debug] Start processing phone verification request.");
$phoneNumber = filterRequest("phone_number");
if (!$phoneNumber) {
error_log("[Auth_Error] Phone number is missing in the request.");
jsonError("Phone number is required");
exit();
}
// تسجيل الرقم (مشفر أو عادي حسب الحاجة، يفضل عدم تسجيله عادي لأسباب الخصوصية لكن هنا للتوضيح)
error_log("[Auth_Debug] Received phone number (Masked): " . substr($phoneNumber, 0, 7) . "*****");
// تشفير رقم الهاتف
$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
error_log("[Auth_Debug] Phone number encrypted successfully.");
try {
// ✅ 1. حذف أي رموز قديمة لنفس الرقم
error_log("[Auth_Step_1] Deleting old verification records for this phone...");
$stmtDelete = $con->prepare("DELETE FROM phone_verification_passenger WHERE phone_number = ?");
$stmtDelete->execute([$phoneNumber_encrypted]);
error_log("[Auth_Step_1] Old records deleted (if any).");
// ✅ 2. إدخال سجل جديد مع تحقق مباشر (بدون OTP)
$now = date('Y-m-d H:i:s');
error_log("[Auth_Step_2] Inserting new verified record at: " . $now);
$stmt = $con->prepare("
INSERT INTO phone_verification_passenger (phone_number, token, expiration_time, verified, created_at)
VALUES (?, NULL, NULL, 1, ?)
");
$stmt->execute([$phoneNumber_encrypted, $now]);
error_log("[Auth_Step_2] New record inserted successfully.");
// ✅ 3. فحص هل الراكب موجود مسبقاً
error_log("[Auth_Step_3] Checking if passenger exists in passengers table...");
$checkPassengerStmt = $con->prepare("
SELECT * FROM passengers WHERE phone = ?
");
$checkPassengerStmt->execute([$phoneNumber_encrypted]);
$passenger = $checkPassengerStmt->fetch(PDO::FETCH_ASSOC);
if ($passenger) {
// ✅ الراكب موجود
error_log("[Auth_Result] Passenger Found. ID: " . $passenger['id']);
printSuccess([
"message" => "Passenger already registered.",
"isRegistered" => true,
"passenger" => [
"id" => $passenger['id'],
"first_name" => $encryptionHelper->decryptData($passenger['first_name']),
"last_name" => $encryptionHelper->decryptData($passenger['last_name']),
"email" => $encryptionHelper->decryptData($passenger['email']),
"phone" => $phoneNumber
]
]);
} else {
// ✅ الراكب جديد
error_log("[Auth_Result] Passenger Not Found. Treating as new user.");
printSuccess([
"message" => "Phone number verified automatically (no OTP required).",
"isRegistered" => false
]);
}
} catch (PDOException $e) {
// تسجيل الخطأ بالتفصيل في ملف اللوج
error_log("[Auth_DB_Exception] Error: " . $e->getMessage() . " | File: " . $e->getFile() . " | Line: " . $e->getLine());
// طباعة رسالة الخطأ للمستخدم (يفضل عدم إظهار تفاصيل الـ SQL للمستخدم النهائي لأسباب أمنية)
jsonError("Database error occurred. Please contact support.");
} catch (Exception $e) {
// التقاط أي أخطاء عامة أخرى
error_log("[Auth_General_Exception] Error: " . $e->getMessage());
jsonError("An unexpected error occurred.");
}
// تسجيل نهاية الطلب
error_log("[Auth_Debug] Request processing finished.");
?>