Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/attendance/config/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/attendance/config/config.php

<?php
// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Define constants
define('SITE_URL', './');
define('SITE_TITLE', 'Church Attendance Management System');
define('SITE_LOGO', 'assets/images/logo.png');
define('FOOTER_TITLE', 'Church Attendance System © 2024');

// Include database connection
require_once 'database.php';

// Timezone setting
date_default_timezone_set('UTC');

// Error reporting (disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Security headers
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// CSRF Token generation
function generateCSRFToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// CSRF Token validation
function validateCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Sanitize input
function sanitizeInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

// Check if user is logged in
function isLoggedIn() {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

// Check user role
function hasRole($role) {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === $role;
}

// Redirect function
function redirect($url) {
    // Handle absolute URLs
    if (strpos($url, 'http') === 0) {
        header("Location: " . $url);
        exit();
    }
    
    // For relative URLs, use simple relative redirect
    // This avoids path duplication issues with subdirectory deployments
    header("Location: " . $url);
    exit();
}

// Log activity function
function logActivity($user_id, $action, $details = '') {
    $db = new Database();
    $conn = $db->getConnection();
    
    $query = "INSERT INTO audit_logs (user_id, action, details, ip_address, user_agent, created_at) 
              VALUES (?, ?, ?, ?, ?, NOW())";
    $stmt = $conn->prepare($query);
    $stmt->execute([
        $user_id,
        $action,
        $details,
        $_SERVER['REMOTE_ADDR'],
        $_SERVER['HTTP_USER_AGENT']
    ]);
}

// Generate unique tracking code
function generateTrackingCode($length = 8) {
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $code;
}

// Generate unique tracking code for attendance
function generateUniqueTrackingCode($conn) {
    do {
        $code = generateTrackingCode();
        $query = "SELECT COUNT(*) FROM attendance_records WHERE tracking_code = ?";
        $stmt = $conn->prepare($query);
        $stmt->execute([$code]);
        $exists = $stmt->fetchColumn() > 0;
    } while ($exists);
    
    return $code;
}

// Handle logo upload
function handleLogoUpload($file) {
    $result = ['success' => false, 'error' => '', 'filename' => ''];
    
    // Check if file was uploaded
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $result['error'] = 'File upload failed.';
        return $result;
    }
    
    // Validate file type
    $allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    $file_type = mime_content_type($file['tmp_name']);
    
    if (!in_array($file_type, $allowed_types)) {
        $result['error'] = 'Invalid file type. Please upload a JPEG, PNG, GIF, or WebP image.';
        return $result;
    }
    
    // Validate file size (max 5MB)
    $max_size = 5 * 1024 * 1024; // 5MB
    if ($file['size'] > $max_size) {
        $result['error'] = 'File size too large. Maximum size is 5MB.';
        return $result;
    }
    
    // Create uploads directory if it doesn't exist
    $upload_dir = __DIR__ . '/../uploads/logos/';
    if (!is_dir($upload_dir)) {
        if (!mkdir($upload_dir, 0755, true)) {
            $result['error'] = 'Failed to create upload directory.';
            return $result;
        }
    }
    
    // Generate unique filename
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = 'logo_' . time() . '_' . uniqid() . '.' . $extension;
    $filepath = $upload_dir . $filename;
    
    // Move uploaded file
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        // Resize image if needed (optional)
        resizeImage($filepath, 200, 200);
        
        $result['success'] = true;
        $result['filename'] = 'uploads/logos/' . $filename;
    } else {
        $result['error'] = 'Failed to save uploaded file.';
    }
    
    return $result;
}

// Resize image to fit within specified dimensions
function resizeImage($filepath, $max_width, $max_height) {
    $image_info = getimagesize($filepath);
    if (!$image_info) return false;
    
    $width = $image_info[0];
    $height = $image_info[1];
    $type = $image_info[2];
    
    // Check if resize is needed
    if ($width <= $max_width && $height <= $max_height) {
        return true;
    }
    
    // Calculate new dimensions
    $ratio = min($max_width / $width, $max_height / $height);
    $new_width = intval($width * $ratio);
    $new_height = intval($height * $ratio);
    
    // Create image resource based on type
    switch ($type) {
        case IMAGETYPE_JPEG:
            $source = imagecreatefromjpeg($filepath);
            break;
        case IMAGETYPE_PNG:
            $source = imagecreatefrompng($filepath);
            break;
        case IMAGETYPE_GIF:
            $source = imagecreatefromgif($filepath);
            break;
        case IMAGETYPE_WEBP:
            $source = imagecreatefromwebp($filepath);
            break;
        default:
            return false;
    }
    
    if (!$source) return false;
    
    // Create new image
    $destination = imagecreatetruecolor($new_width, $new_height);
    
    // Preserve transparency for PNG and GIF
    if ($type == IMAGETYPE_PNG || $type == IMAGETYPE_GIF) {
        imagealphablending($destination, false);
        imagesavealpha($destination, true);
        $transparent = imagecolorallocatealpha($destination, 255, 255, 255, 127);
        imagefilledrectangle($destination, 0, 0, $new_width, $new_height, $transparent);
    }
    
    // Resize image
    imagecopyresampled($destination, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    
    // Save resized image
    switch ($type) {
        case IMAGETYPE_JPEG:
            imagejpeg($destination, $filepath, 90);
            break;
        case IMAGETYPE_PNG:
            imagepng($destination, $filepath);
            break;
        case IMAGETYPE_GIF:
            imagegif($destination, $filepath);
            break;
        case IMAGETYPE_WEBP:
            imagewebp($destination, $filepath, 90);
            break;
    }
    
    // Clean up memory
    imagedestroy($source);
    imagedestroy($destination);
    
    return true;
}

/**
 * Check if registration is open for a program
 * @param int $program_id Program ID to check
 * @return array Registration status information
 */
function checkRegistrationStatus($program_id) {
    $db = new Database();
    $conn = $db->getConnection();
    
    try {
        $query = "SELECT registration_status, registration_open_date, registration_close_date, registration_message 
                  FROM programs WHERE id = ? AND is_active = 1";
        $stmt = $conn->prepare($query);
        $stmt->execute([$program_id]);
        $program = $stmt->fetch();
        
        if (!$program) {
            return [
                'is_open' => false,
                'status' => 'not_found',
                'message' => 'Program not found or inactive.'
            ];
        }
        
        $now = new DateTime();
        $status = $program['registration_status'];
        $open_date = $program['registration_open_date'] ? new DateTime($program['registration_open_date']) : null;
        $close_date = $program['registration_close_date'] ? new DateTime($program['registration_close_date']) : null;
        $custom_message = $program['registration_message'];
        
        switch ($status) {
            case 'open':
                return [
                    'is_open' => true,
                    'status' => 'open',
                    'message' => 'Registration is open.'
                ];
                
            case 'closed':
                return [
                    'is_open' => false,
                    'status' => 'closed',
                    'message' => $custom_message ?: 'Registration is currently closed.'
                ];
                
            case 'scheduled':
                // Check if we're before the open date
                if ($open_date && $now < $open_date) {
                    return [
                        'is_open' => false,
                        'status' => 'scheduled_not_open',
                        'message' => $custom_message ?: 'Registration opens on ' . $open_date->format('F j, Y \a\t g:i A') . '.',
                        'open_date' => $open_date->format('Y-m-d H:i:s')
                    ];
                }
                
                // Check if we're after the close date
                if ($close_date && $now > $close_date) {
                    return [
                        'is_open' => false,
                        'status' => 'scheduled_closed',
                        'message' => $custom_message ?: 'Registration closed on ' . $close_date->format('F j, Y \a\t g:i A') . '.',
                        'close_date' => $close_date->format('Y-m-d H:i:s')
                    ];
                }
                
                // Registration is currently open (within scheduled window)
                $message = 'Registration is open.';
                if ($close_date) {
                    $message .= ' Registration closes on ' . $close_date->format('F j, Y \a\t g:i A') . '.';
                }
                
                return [
                    'is_open' => true,
                    'status' => 'scheduled_open',
                    'message' => $message,
                    'close_date' => $close_date ? $close_date->format('Y-m-d H:i:s') : null
                ];
                
            default:
                return [
                    'is_open' => false,
                    'status' => 'unknown',
                    'message' => 'Registration status is unknown.'
                ];
        }
        
    } catch (Exception $e) {
        return [
            'is_open' => false,
            'status' => 'error',
            'message' => 'Unable to check registration status.'
        ];
    }
}
?>

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists