Mini Shell
<?php
session_start();
// Set memory and execution limits
ini_set('memory_limit', '128M');
ini_set('max_execution_time', 300);
set_time_limit(300);
// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
try {
$rootPath = realpath(dirname(__FILE__) . '/..');
$requiredFiles = [
$rootPath . '/Portal/config/config.php',
$rootPath . '/Portal/AccessControl.php',
$rootPath . '/Portal/include/auth_validate.php'
];
foreach ($requiredFiles as $file) {
if (!file_exists($file)) {
throw new Exception("Required file not found: " . $file);
}
}
require_once $rootPath . '/Portal/config/config.php';
require_once $rootPath . '/Portal/AccessControl.php';
require_once $rootPath . '/Portal/include/auth_validate.php';
if (!isset($conn) || !$conn) {
throw new Exception("Database connection not established");
}
if (!isset($_SESSION['id'])) {
header('Location: login.php');
exit();
}
$User = $_SESSION['id'];
$stmt = mysqli_prepare($conn, "SELECT Access_Level, Full_Name FROM admin_accounts WHERE id = ?");
if ($stmt) {
mysqli_stmt_bind_param($stmt, "i", $User);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $UserAccessName, $StudentName);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
} catch (Exception $e) {
die("Initialization Error: " . htmlspecialchars($e->getMessage()));
}
// Configuration
$maxFileSize = 5 * 1024 * 1024;
$allowedExtensions = ['csv'];
$uploadDir = "StudentsUpload/";
$maxRecords = 5000;
// Email configuration - USING YOUR ACTUAL EMAIL
$domain = 'edgeviewacademy.com'; // Your domain
$emailConfig = [
'from_email' => 'it@edgeviewacademy.com', // Your actual email
'from_name' => 'Edgeview Academy Management System',
'subject' => 'Your Student Account Credentials - Edgeview Academy',
'reply_to' => 'it@edgeviewacademy.com',
// Additional from addresses to try if needed
'alternative_from_emails' => [
'noreply@edgeviewacademy.com',
'admin@edgeviewacademy.com',
'support@edgeviewacademy.com'
]
];
// Generate random password
function generateRandomPassword($length = 8) {
$chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$password = '';
$charLength = strlen($chars);
for ($i = 0; $i < $length; $i++) {
$password .= $chars[rand(0, $charLength - 1)];
}
return $password;
}
// Send email with your actual email - FIXED: Removed plain text sending
function sendEmailFromIT($toEmail, $fullName, $username, $password, $config) {
$subject = $config['subject'];
$loginUrl = "https://edgeviewacademy.com/Portal/login";
// HTML email content ONLY - no plain text version
$htmlMessage = "
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Edgeview Academy - Student Account Credentials</title>
<style>
body { font-family: 'Arial', sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; }
.container { max-width: 600px; margin: 0 auto; background-color: #ffffff; }
.header { background-color: #1a237e; color: white; padding: 20px; text-align: center; }
.logo { font-size: 24px; font-weight: bold; margin-bottom: 10px; }
.content { padding: 30px; }
.credentials-box { background-color: #f5f5f5; border-left: 4px solid #1a237e; padding: 20px; margin: 20px 0; border-radius: 4px; }
.credential-item { margin: 10px 0; }
.credential-label { font-weight: bold; color: #1a237e; display: inline-block; width: 120px; }
.credential-value { font-family: 'Courier New', monospace; background-color: #fff; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; }
.button { display: inline-block; background-color: #1a237e; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; font-weight: bold; margin: 20px 0; }
.footer { background-color: #f5f5f5; padding: 20px; text-align: center; color: #666; font-size: 12px; border-top: 1px solid #ddd; }
.important { background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px; }
</style>
</head>
<body>
<div class='container'>
<div class='header'>
<div class='logo'>Edgeview Academy</div>
<div>Student Portal Access</div>
</div>
<div class='content'>
<p>Dear <strong>$fullName</strong>,</p>
<p>Welcome to Edgeview Academy! Your student account has been successfully created in our School Management System.</p>
<div class='credentials-box'>
<h3 style='color: #1a237e; margin-top: 0;'>Your Login Credentials:</h3>
<div class='credential-item'>
<span class='credential-label'>Login Portal:</span>
<a href='$loginUrl' style='color: #1a237e;'>$loginUrl</a>
</div>
<div class='credential-item'>
<span class='credential-label'>Username:</span>
<span class='credential-value'>$username</span>
</div>
<div class='credential-item'>
<span class='credential-label'>Password:</span>
<span class='credential-value' style='font-weight: bold;'>$password</span>
</div>
</div>
<div class='important'>
<h4 style='color: #856404; margin-top: 0;'>🔒 Important Security Instructions:</h4>
<ol>
<li><strong>Login immediately</strong> using the credentials above</li>
<li><strong>Change your password</strong> after your first login for security</li>
<li>Keep your login details confidential</li>
<li>Do not share your password with anyone</li>
<li>Contact IT support if you encounter any issues</li>
</ol>
</div>
<div style='text-align: center;'>
<a href='$loginUrl' class='button'>Access Your Student Portal Now</a>
</div>
<p>We're excited to have you join our academic community!</p>
<p>Best regards,<br>
<strong>Edgeview Academy Administration</strong><br>
<em>Educate for Excellence</em></p>
</div>
<div class='footer'>
<p>This is an automated message from Edgeview Academy IT Department.</p>
<p>For assistance, please contact: IT Department - it@edgeviewacademy.com</p>
<p>© " . date('Y') . " Edgeview Academy. All rights reserved.</p>
</div>
</div>
</body>
</html>
";
// Try multiple from addresses
$fromEmails = array_merge([$config['from_email']], $config['alternative_from_emails']);
$lastError = '';
foreach ($fromEmails as $fromEmail) {
// Headers for HTML email
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: " . $config['from_name'] . " <" . $fromEmail . ">\r\n";
$headers .= "Reply-To: " . $config['reply_to'] . "\r\n";
$headers .= "Return-Path: " . $fromEmail . "\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();
$headers .= "X-Priority: 1 (Highest)\r\n";
$headers .= "X-MSMail-Priority: High\r\n";
$headers .= "Importance: High\r\n";
// Try to send with error suppression - SINGLE EMAIL SEND
$sent = @mail($toEmail, $subject, $htmlMessage, $headers, "-f" . $fromEmail);
if ($sent) {
// Log success
error_log("Email sent successfully from $fromEmail to $toEmail");
return [
'success' => true,
'message' => "Email sent from $fromEmail",
'from_email' => $fromEmail
];
} else {
$lastError = error_get_last();
error_log("Failed to send email from $fromEmail to $toEmail: " . print_r($lastError, true));
}
usleep(100000); // 0.1 second delay
}
// All attempts failed
return [
'success' => false,
'message' => "Email failed: " . ($lastError['message'] ?? 'Unknown error'),
'from_email' => $config['from_email'],
'error' => $lastError
];
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$errors = [];
$successMessages = [];
try {
if (empty($_POST['Glade'])) {
$errors[] = "Grade/Level is required";
} else {
$Glade = mysqli_real_escape_string($conn, $_POST['Glade']);
}
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
$errors[] = "Please select a valid CSV file to upload";
} else {
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$tmpName = $_FILES['file']['tmp_name'];
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
if ($fileSize > $maxFileSize) {
$errors[] = "File size exceeds maximum limit of 5MB";
}
if (!in_array($fileExt, $allowedExtensions)) {
$errors[] = "Only CSV files are allowed";
}
}
if (empty($errors)) {
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
$fname = date("YmdHis") . '_' . uniqid() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $fileName);
$targetPath = $uploadDir . $fname;
if (move_uploaded_file($tmpName, $targetPath)) {
mysqli_begin_transaction($conn);
$processedCount = 0;
$failedCount = 0;
$isFirstRow = true;
$emailSentCount = 0;
$emailFailedCount = 0;
$emailDetails = [];
$file = fopen($targetPath, "r");
if ($file !== FALSE) {
ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload Results - Edgeview Academy</title>
<style>
body { font-family: 'Arial', sans-serif; margin: 20px; background-color: #f8f9fa; }
.container { max-width: 1200px; margin: 0 auto; background-color: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
h1 { color: #1a237e; border-bottom: 3px solid #1a237e; padding-bottom: 15px; }
h2 { color: #1a237e; }
table { width: 100%; border-collapse: collapse; margin: 25px 0; }
th, td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #ddd; }
th { background-color: #1a237e; color: white; font-weight: bold; }
tr:hover { background-color: #f5f5f5; }
.success { color: #28a745; font-weight: bold; }
.warning { color: #ffc107; font-weight: bold; }
.error { color: #dc3545; font-weight: bold; }
.summary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 25px; border-radius: 10px; margin: 30px 0; }
.summary-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin: 20px 0; }
.stat-box { background: rgba(255,255,255,0.9); color: #333; padding: 20px; border-radius: 8px; text-align: center; }
.stat-number { font-size: 36px; font-weight: bold; margin-bottom: 10px; }
.btn { display: inline-block; padding: 12px 25px; background-color: #1a237e; color: white; text-decoration: none; border-radius: 5px; margin: 8px; font-weight: bold; transition: all 0.3s; }
.btn:hover { background-color: #0d1b5e; transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
.btn-secondary { background-color: #6c757d; }
.btn-success { background-color: #28a745; }
.debug-panel { background-color: #fff3cd; border: 1px solid #ffeaa7; padding: 20px; border-radius: 8px; margin: 20px 0; }
.password-display { font-family: 'Courier New', monospace; background-color: #f8f9fa; padding: 5px 10px; border-radius: 4px; border: 1px solid #ddd; }
.status-badge { display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 12px; margin-left: 5px; }
.badge-success { background-color: #d4edda; color: #155724; }
.badge-warning { background-color: #fff3cd; color: #856404; }
.badge-error { background-color: #f8d7da; color: #721c24; }
</style>
</head>
<body>
<div class="container">
<h1>📊 Student Upload Results - Edgeview Academy</h1>
<table>
<thead>
<tr>
<th>#</th>
<th>Student Name</th>
<th>Level</th>
<th>Student No</th>
<th>Email</th>
<th>Password</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
ob_flush();
flush();
$rowNumber = 0;
while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
$rowNumber++;
if ($isFirstRow) {
$isFirstRow = false;
continue;
}
if ($processedCount >= $maxRecords) {
$successMessages[] = "Upload limited to first {$maxRecords} records.";
break;
}
if (count($data) >= 4) {
$FullName = isset($data[0]) ? trim($data[0]) : '';
$Student_No = isset($data[1]) ? trim($data[1]) : '';
$email = isset($data[2]) ? trim($data[2]) : '';
$Parent_Phone = isset($data[3]) ? trim($data[3]) : '';
$escapedName = mysqli_real_escape_string($conn, $FullName);
$escapedNo = mysqli_real_escape_string($conn, $Student_No);
$escapedEmail = mysqli_real_escape_string($conn, $email);
$escapedPhone = mysqli_real_escape_string($conn, $Parent_Phone);
$status = "Success";
$statusClass = "success";
$statusBadge = "badge-success";
$plainPassword = '';
$emailStatus = '';
$emailDetail = '';
if (empty($FullName) || empty($Student_No)) {
$status = "Missing required fields";
$statusClass = "error";
$statusBadge = "badge-error";
$failedCount++;
} else {
$checkQuery = "SELECT Student_No FROM student WHERE Student_No = '$escapedNo'";
$checkResult = mysqli_query($conn, $checkQuery);
if ($checkResult && mysqli_num_rows($checkResult) > 0) {
$status = "Duplicate Student No";
$statusClass = "warning";
$statusBadge = "badge-warning";
$failedCount++;
} else {
$plainPassword = generateRandomPassword(8);
$encryptedPassword = md5($plainPassword);
// Insert into student table
$studentQuery = "INSERT INTO student (`Full Name`, Level, Student_No, email, Parent_Phone)
VALUES ('$escapedName', '$Glade', '$escapedNo', '$escapedEmail', '$escapedPhone')";
$studentInsert = mysqli_query($conn, $studentQuery);
if ($studentInsert) {
// Insert into admin_accounts
$adminQuery = "INSERT INTO admin_accounts (Full_Name, user_name, Phone, passwd, User_Type, Access_Level, email, StudentNo)
VALUES ('$escapedName', '$escapedNo', '$escapedPhone', '$encryptedPassword', 'Student', 'Student', '$escapedEmail', '$escapedNo')";
$adminInsert = mysqli_query($conn, $adminQuery);
if ($adminInsert) {
$processedCount++;
// Send email if valid
if (!empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailResult = sendEmailFromIT($email, $FullName, $Student_No, $plainPassword, $emailConfig);
if ($emailResult['success']) {
$emailSentCount++;
$emailStatus = "✓ Email sent";
$emailDetail = $emailResult['message'];
} else {
$emailFailedCount++;
$emailStatus = "✗ Email failed";
$emailDetail = $emailResult['message'];
$status = "Success (Email failed)";
$statusClass = "warning";
$statusBadge = "badge-warning";
}
$emailDetails[] = [
'to' => $email,
'status' => $emailResult['success'] ? 'sent' : 'failed',
'message' => $emailResult['message'],
'details' => $emailDetail
];
} else {
$emailStatus = "No valid email";
$status = "Success (No email)";
$statusClass = "warning";
$statusBadge = "badge-warning";
}
} else {
$status = "Admin account creation failed: " . mysqli_error($conn);
$statusClass = "error";
$statusBadge = "badge-error";
$failedCount++;
mysqli_query($conn, "DELETE FROM student WHERE Student_No = '$escapedNo'");
}
} else {
$status = "Student insert failed: " . mysqli_error($conn);
$statusClass = "error";
$statusBadge = "badge-error";
$failedCount++;
}
}
if ($checkResult) {
mysqli_free_result($checkResult);
}
}
echo "<tr>";
echo "<td>{$rowNumber}</td>";
echo "<td>" . htmlspecialchars($FullName) . "</td>";
echo "<td>" . htmlspecialchars($Glade) . "</td>";
echo "<td>" . htmlspecialchars($Student_No) . "</td>";
echo "<td>" . htmlspecialchars($email) . "</td>";
echo "<td><span class='password-display'>" . htmlspecialchars($plainPassword) . "</span></td>";
echo "<td class='{$statusClass}'>";
echo htmlspecialchars($status);
echo "<span class='status-badge {$statusBadge}'>{$statusBadge}</span>";
if ($emailStatus) {
echo "<br><small>{$emailStatus}</small>";
}
if ($emailDetail && isset($_GET['debug'])) {
echo "<br><small style='color: #666; font-size: 11px;'>{$emailDetail}</small>";
}
echo "</td>";
echo "</tr>";
if ($rowNumber % 50 == 0) {
ob_flush();
flush();
}
} else {
$failedCount++;
echo "<tr>";
echo "<td>{$rowNumber}</td>";
echo "<td colspan='6' class='error'>Invalid row - insufficient columns</td>";
echo "</tr>";
}
}
fclose($file);
mysqli_commit($conn);
?>
</tbody>
</table>
<div class="summary">
<h2 style="color: white; margin-top: 0;">📈 Upload Summary</h2>
<div class="summary-stats">
<div class="stat-box">
<div class="stat-number"><?php echo $processedCount; ?></div>
<div>✅ Records Processed</div>
</div>
<div class="stat-box">
<div class="stat-number"><?php echo $failedCount; ?></div>
<div>❌ Records Failed</div>
</div>
<div class="stat-box">
<div class="stat-number"><?php echo $emailSentCount; ?></div>
<div>📧 Emails Sent</div>
</div>
<div class="stat-box">
<div class="stat-number"><?php echo $emailFailedCount; ?></div>
<div>⚠️ Emails Failed</div>
</div>
</div>
<?php if ($emailFailedCount > 0): ?>
<div style="background-color: rgba(255,255,255,0.9); padding: 15px; border-radius: 8px; margin: 20px 0;">
<h4 style="color: #856404; margin-top: 0;">⚠️ Email Delivery Issues</h4>
<p>Some emails failed to send. Common solutions:</p>
<ol>
<li>Check that <strong>it@edgeviewacademy.com</strong> is a valid email account in your cPanel</li>
<li>Verify the email account exists and can send mail</li>
<li>Check spam folder - emails might be delivered but marked as spam</li>
<li>Contact InMotion support to verify mail() function is enabled</li>
</ol>
<p><a href="?debug=1" style="color: #1a237e; font-weight: bold;">🔍 Click for detailed email debug information</a></p>
</div>
<?php endif; ?>
<div style="text-align: center; margin-top: 30px;">
<a href="ManageStudents" class="btn">👥 View All Students</a>
<a href="admin_users" class="btn">👨💼 View User Accounts</a>
<a href="ManageStudents" class="btn btn-success">⬆️ Upload Another File</a>
<a href="AdminPortal" class="btn btn-success">🏠 Home</a>
<?php if ($emailFailedCount > 0): ?>
<a href="?debug=1" class="btn btn-secondary">🔍 Debug Email Issues</a>
<?php endif; ?>
</div>
<?php if (isset($_GET['debug']) && !empty($emailDetails)): ?>
<div style="background-color: rgba(255,255,255,0.9); padding: 20px; border-radius: 8px; margin-top: 20px;">
<h4 style="color: #1a237e;">📋 Detailed Email Delivery Report</h4>
<table style="width: 100%; font-size: 12px;">
<thead>
<tr>
<th>To Email</th>
<th>Status</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<?php foreach ($emailDetails as $detail): ?>
<tr>
<td><?php echo htmlspecialchars($detail['to']); ?></td>
<td>
<?php if ($detail['status'] == 'sent'): ?>
<span style="color: green; font-weight: bold;">✅ Sent</span>
<?php else: ?>
<span style="color: red; font-weight: bold;">❌ Failed</span>
<?php endif; ?>
</td>
<td><?php echo htmlspecialchars($detail['message']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</div>
</body>
</html>
<?php
$_SESSION['upload_results'] = [
'processed' => $processedCount,
'failed' => $failedCount,
'emails_sent' => $emailSentCount,
'emails_failed' => $emailFailedCount,
'email_details' => $emailDetails
];
} else {
throw new Exception("Failed to open uploaded file");
}
if (file_exists($targetPath)) {
unlink($targetPath);
}
} else {
throw new Exception("Failed to move uploaded file. Check directory permissions.");
}
}
} catch (Exception $e) {
if (isset($conn)) {
mysqli_rollback($conn);
}
$errors[] = "Error: " . $e->getMessage();
error_log("Upload error: " . $e->getMessage());
}
if (!empty($errors)) {
$_SESSION['Failure'] = $errors;
header('Location: ManageStudents.php');
exit();
}
} else {
header('Location: ManageStudents.php');
exit();
}
?>