Server : LiteSpeed
System : Linux terra.hostitbro.com 5.14.0-611.54.3.el9_7.x86_64 #1 SMP PREEMPT_DYNAMIC Thu May 7 16:31:24 EDT 2026 x86_64
User : outerorb ( 1091)
PHP Version : 8.1.34
Disable Function : mail
Directory :  /home2/outerorb/emp.outerorbittech.in/admin/

📁 Create New:
⬆️ Upload File:
Current Dir [ Writable ] Root [ Writable ]


OR Upload from URL:
URL: Save as:

📄 File: import.php

Path: /home2/outerorb/emp.outerorbittech.in/admin/import.php

Size: 10.77 KB

Permissions: 0666

<?php
require __DIR__ . '/../includes/helpers.php';
require_admin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect_with_message('dashboard.php', 'Invalid request method.', 'error');
}

if (!isset($_FILES['import_file']) || $_FILES['import_file']['error'] !== UPLOAD_ERR_OK) {
    redirect_with_message('dashboard.php', 'No file uploaded or upload error.', 'error');
}

$csrf = $_POST['csrf_token'] ?? '';
if (!verify_csrf($csrf)) {
    redirect_with_message('dashboard.php', 'Invalid session token.', 'error');
}

$uploaded = $_FILES['import_file'];
$ext = strtolower(pathinfo($uploaded['name'], PATHINFO_EXTENSION));
if ($ext !== 'csv') {
    redirect_with_message('dashboard.php', 'Only CSV files are accepted.', 'error');
}

$destDir = __DIR__ . '/../uploads/imports';
if (!is_dir($destDir)) mkdir($destDir, 0755, true);
$destPath = $destDir . '/' . uniqid('import_', true) . '.csv';

if (!move_uploaded_file($uploaded['tmp_name'], $destPath)) {
    redirect_with_message('dashboard.php', 'Failed to save uploaded file.', 'error');
}

// Process CSV now: parse, validate, and insert rows into employees table.
$pdo = db();
$inserted = 0;
$failed = 0;
$errors = [];

// Mapping of acceptable CSV headers to DB columns
$headerMap = [
    'first_name' => 'first_name', 'firstname' => 'first_name', 'full_name' => 'first_name',
    'last_name' => 'last_name', 'lastname' => 'last_name', 'father_name' => 'last_name', 'father' => 'last_name',
    'mother_name' => 'mother_name',
    'email' => 'email',
    'phone' => 'phone', 'contact' => 'phone',
    'emergency_contact' => 'emergency_contact',
    'emergency_contact_name' => 'emergency_contact_name',
    'emergency_contact_number' => 'emergency_contact_number',
    'emergency_contact_relation' => 'emergency_contact_relation',
    'dob' => 'dob', 'date_of_birth' => 'dob',
    'date_of_joining' => 'date_of_joining', 'doj' => 'date_of_joining',
    'address' => 'address', 'permanent_address' => 'permanent_address',
    'zip' => 'zip', 'postal_code' => 'zip',
    'aadhaar_number' => 'aadhaar_number', 'aadhaar' => 'aadhaar_number',
    'pan_number' => 'pan_number', 'pan' => 'pan_number',
    'highest_qualification' => 'highest_qualification',
    'department' => 'department',
    'designation' => 'designation',
    'city' => 'city',
    'state' => 'state',
    // file path columns (optional)
    'aadhaar_path' => 'aadhaar_path', 'aadhaar_file' => 'aadhaar_path',
    'pan_path' => 'pan_path', 'pan_file' => 'pan_path',
    'qualification_path' => 'qualification_path', 'qualification_file' => 'qualification_path',
    'tenth_marksheet_path' => 'tenth_marksheet_path', 'tenth_marksheet_file' => 'tenth_marksheet_path',
    'twelfth_marksheet_path' => 'twelfth_marksheet_path', 'twelfth_marksheet_file' => 'twelfth_marksheet_path',
    'bank_proof_path' => 'bank_proof_path', 'bank_proof_file' => 'bank_proof_path',
    'photo_path' => 'photo_path', 'photo_file' => 'photo_path',
    'employee_status' => 'employee_status',
    'last_working_date' => 'last_working_date',
    'reason_for_leaving' => 'reason_for_leaving',
    'marital_status' => 'marital_status',
    'gender' => 'gender',
    'identity_mark' => 'identity_mark',
    'blood_group' => 'blood_group',
    'referred_by' => 'referred_by',
    'referral_name' => 'referral_name',
    'account_number' => 'account_number',
    'ifsc_code' => 'ifsc_code',
    'bank_name' => 'bank_name',
    'password' => 'password'
];

if (($handle = fopen($destPath, 'r')) === false) {
    redirect_with_message('dashboard.php', 'Could not open uploaded CSV.', 'error');
}

$rowNum = 0;
$headers = [];
while (($row = fgetcsv($handle)) !== false) {
    $rowNum++;
    if ($rowNum === 1) {
        // parse header
        foreach ($row as $h) {
            $key = strtolower(trim((string)$h));
            $key = preg_replace('/\s+/', '_', $key);
            $headers[] = $key;
        }
        continue;
    }

    // Skip empty rows
    $allEmpty = true;
    foreach ($row as $c) { if (trim((string)$c) !== '') { $allEmpty = false; break; } }
    if ($allEmpty) continue;

    // Map row to associative array using headers
    $data = [];
    foreach ($headers as $i => $h) {
        $val = isset($row[$i]) ? trim((string)$row[$i]) : '';
        if ($h === 'full_name' && !isset($data['first_name'])) {
            // try splitting full name into first/last
            $parts = preg_split('/\s+/', $val);
            $data['first_name'] = $parts[0] ?? '';
            $data['last_name'] = isset($parts[1]) ? implode(' ', array_slice($parts, 1)) : '';
            continue;
        }
        if (isset($headerMap[$h])) {
            $mapped = $headerMap[$h];
            $data[$mapped] = $val;
        } else {
            // Unknown header: ignore
        }
    }

    // Basic required fields
    $required = ['first_name' => 'First name', 'last_name' => 'Last name', 'phone' => 'Phone', 'date_of_joining' => 'Date of joining'];
    $rowErrors = [];
    foreach ($required as $field => $label) {
        if (empty($data[$field])) {
            $rowErrors[] = "$label is required";
        }
    }

    // Normalize dates
    if (!empty($data['dob'])) {
        $norm = normalize_date($data['dob']);
        if ($norm === null) $rowErrors[] = 'Invalid DOB format'; else $data['dob'] = $norm;
    } else {
        $data['dob'] = null;
    }
    if (!empty($data['date_of_joining'])) {
        $norm = normalize_date($data['date_of_joining']);
        if ($norm === null) $rowErrors[] = 'Invalid Date of Joining'; else $data['date_of_joining'] = $norm;
    }
    if (!empty($data['last_working_date'])) {
        $norm = normalize_date($data['last_working_date']);
        if ($norm === null) $rowErrors[] = 'Invalid Last Working Date'; else $data['last_working_date'] = $norm;
    }

    if ($rowErrors) {
        $failed++;
        $errors[] = ['row' => $rowNum, 'errors' => $rowErrors];
        continue;
    }

    // Prepare insert columns with defaults
    $insert = [
        'first_name' => $data['first_name'] ?? '',
        'last_name' => $data['last_name'] ?? '',
        'mother_name' => $data['mother_name'] ?? '',
        'email' => $data['email'] ?? '',
        'phone' => $data['phone'] ?? '',
        'emergency_contact' => $data['emergency_contact'] ?? '',
        'emergency_contact_name' => $data['emergency_contact_name'] ?? '',
        'emergency_contact_number' => $data['emergency_contact_number'] ?? '',
        'emergency_contact_relation' => $data['emergency_contact_relation'] ?? '',
        'dob' => $data['dob'] ?? null,
        'date_of_joining' => $data['date_of_joining'] ?? null,
        'address' => $data['address'] ?? '',
        'permanent_address' => $data['permanent_address'] ?? '',
        'city' => $data['city'] ?? '',
        'state' => $data['state'] ?? '',
        'zip' => $data['zip'] ?? '',
        'aadhaar_number' => $data['aadhaar_number'] ?? '',
        'pan_number' => $data['pan_number'] ?? '',
        'highest_qualification' => $data['highest_qualification'] ?? '',
        'department' => $data['department'] ?? '',
        'designation_id' => null,
        'employee_status' => $data['employee_status'] ?? 'Active',
        'last_working_date' => $data['last_working_date'] ?? null,
        'reason_for_leaving' => $data['reason_for_leaving'] ?? null,
        'marital_status' => $data['marital_status'] ?? '',
        'gender' => $data['gender'] ?? '',
        'identity_mark' => $data['identity_mark'] ?? '',
        'blood_group' => $data['blood_group'] ?? '',
        'referred_by' => $data['referred_by'] ?? '',
        'referral_name' => $data['referral_name'] ?? null,
        'account_number' => $data['account_number'] ?? '',
        'ifsc_code' => $data['ifsc_code'] ?? '',
        'bank_name' => $data['bank_name'] ?? '',
        'aadhaar_path' => '',
        'pan_path' => '',
        'qualification_path' => '',
        'tenth_marksheet_path' => '',
        'twelfth_marksheet_path' => '',
        'bank_proof_path' => '',
        'photo_path' => ''
    ];

    // Handle designation: find or create
    if (!empty($data['designation'])) {
        $desigName = trim($data['designation']);
        try {
            $stmt = $pdo->prepare('SELECT id FROM designations WHERE LOWER(name) = LOWER(?) LIMIT 1');
            $stmt->execute([$desigName]);
            $row = $stmt->fetch();
            if ($row) {
                $insert['designation_id'] = (int)$row['id'];
            } else {
                $ins = $pdo->prepare('INSERT INTO designations (name, status) VALUES (?, ?)');
                $ins->execute([$desigName, 'active']);
                $insert['designation_id'] = (int)$pdo->lastInsertId();
            }
        } catch (Throwable $e) {
            // ignore designation errors, leave null
        }
    }

    // Ensure department exists in departments table for filters
    if (!empty($insert['department'])) {
        try {
            ensure_departments_table();
            $check = $pdo->prepare('SELECT id FROM departments WHERE name = ? LIMIT 1');
            $check->execute([$insert['department']]);
            if (!$check->fetch()) {
                $pdo->prepare('INSERT INTO departments (name) VALUES (?)')->execute([$insert['department']]);
            }
        } catch (Throwable $e) {
            // non-fatal
        }
    }

    // Insert employee row
    try {
        $cols = array_keys($insert);
        $placeholders = array_map(fn($c) => ':' . $c, $cols);
        $sql = 'INSERT INTO employees (' . implode(', ', $cols) . ') VALUES (' . implode(', ', $placeholders) . ')';
        $stmt = $pdo->prepare($sql);
        foreach ($insert as $k => $v) {
            $stmt->bindValue(':' . $k, $v === null ? null : $v);
        }
        $stmt->execute();
        $empId = (int)$pdo->lastInsertId();

        // Create basic employee auth with default password if password column missing
        ensure_employee_auth_table();
        $passwordPlain = $data['password'] ?? 'ChangeMe123!';
        $hash = password_hash($passwordPlain, PASSWORD_DEFAULT);
        $authStmt = $pdo->prepare('INSERT INTO employee_auth (employee_id, password_hash, must_change_password, is_active) VALUES (?, ?, ?, ?)');
        $authStmt->execute([$empId, $hash, 1, 1]);

        $inserted++;
    } catch (Throwable $e) {
        $failed++;
        $errors[] = ['row' => $rowNum, 'errors' => ['DB error: ' . $e->getMessage()]];
        continue;
    }

}
fclose($handle);

$msg = "Import complete: {$inserted} inserted, {$failed} failed.";
if ($failed > 0) {
    // store errors in session for admin to review
    $_SESSION['import_errors'] = $errors;
    $msg .= ' See import errors.';
}

redirect_with_message('dashboard.php', $msg, 'success');

← Back to Directory Edit File 🔒 Chmod

WP File Manager