Sindbad~EG File Manager
<?php
// Common functions for Church Conference Management Platform
require_once __DIR__ . '/../config/database.php';
// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Authentication functions
function isLoggedIn() {
return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}
function requireLogin() {
if (!isLoggedIn()) {
header('Location: ' . BASE_URL . 'login.php');
exit();
}
}
function hasRole($requiredRole) {
if (!isLoggedIn()) {
return false;
}
$userRole = $_SESSION['user_role'] ?? null;
if (!$userRole) {
// Try to get role from database if not in session
$user = getCurrentUser();
$userRole = $user ? $user['role'] : null;
if ($userRole) {
$_SESSION['user_role'] = $userRole;
}
}
$roleHierarchy = [
'superuser' => 5,
'area_admin' => 4,
'district_admin' => 3,
'assembly_admin' => 2,
'member' => 1
];
// Handle array of roles (check if user has any of the roles)
if (is_array($requiredRole)) {
foreach ($requiredRole as $role) {
if (isset($roleHierarchy[$userRole]) && isset($roleHierarchy[$role]) &&
$roleHierarchy[$userRole] >= $roleHierarchy[$role]) {
return true;
}
}
return false;
}
// Handle single role
return isset($roleHierarchy[$userRole]) && isset($roleHierarchy[$requiredRole]) &&
$roleHierarchy[$userRole] >= $roleHierarchy[$requiredRole];
}
function getCurrentUser() {
if (!isLoggedIn()) {
return null;
}
$db = new CopMadinaDB();
$conn = $db->getConnection();
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
return $stmt->fetch();
}
// Utility functions
function sanitizeInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function generateRandomCode($length = 8) {
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $characters[rand(0, strlen($characters) - 1)];
}
return $code;
}
function formatDate($date, $format = 'Y-m-d H:i:s') {
return date($format, strtotime($date));
}
function formatCurrency($amount) {
return 'GH₵ ' . number_format($amount, 2);
}
// File upload functions
function uploadFile($file, $uploadDir = 'uploads/') {
if (!isset($file['error']) || is_array($file['error'])) {
return ['success' => false, 'message' => 'Invalid file upload'];
}
switch ($file['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
return ['success' => false, 'message' => 'No file sent'];
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
return ['success' => false, 'message' => 'File size exceeds limit'];
default:
return ['success' => false, 'message' => 'Unknown upload error'];
}
if ($file['size'] > MAX_FILE_SIZE) {
return ['success' => false, 'message' => 'File size exceeds maximum allowed size'];
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($file['tmp_name']);
$allowedTypes = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp'
];
if (!array_key_exists($mimeType, $allowedTypes)) {
return ['success' => false, 'message' => 'Invalid file type'];
}
$extension = $allowedTypes[$mimeType];
$filename = sprintf('%s.%s', sha1_file($file['tmp_name']), $extension);
$destination = SITE_ROOT . $uploadDir . $filename;
if (!move_uploaded_file($file['tmp_name'], $destination)) {
return ['success' => false, 'message' => 'Failed to move uploaded file'];
}
return ['success' => true, 'filename' => $filename, 'path' => $uploadDir . $filename];
}
// Database helper functions
function executeQuery($sql, $params = []) {
$db = new CopMadinaDB();
$conn = $db->getConnection();
try {
$stmt = $conn->prepare($sql);
$result = $stmt->execute($params);
if ($result) {
return $stmt;
} else {
error_log("Database execution failed: " . print_r($stmt->errorInfo(), true));
return false;
}
} catch (PDOException $e) {
error_log("Database error: " . $e->getMessage());
error_log("SQL: " . $sql);
error_log("Params: " . print_r($params, true));
return false;
}
}
function getSettings() {
$stmt = executeQuery("SELECT setting_key, setting_value FROM settings");
$settings = [];
if ($stmt) {
while ($row = $stmt->fetch()) {
$settings[$row['setting_key']] = $row['setting_value'];
}
}
return $settings;
}
function getSetting($key, $default = null) {
$stmt = executeQuery("SELECT setting_value FROM settings WHERE setting_key = ?", [$key]);
if ($stmt && $row = $stmt->fetch()) {
return $row['setting_value'];
}
return $default;
}
function updateSetting($key, $value, $userId = null) {
$sql = "INSERT INTO settings (setting_key, setting_value, updated_by)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE
setting_value = VALUES(setting_value),
updated_by = VALUES(updated_by)";
return executeQuery($sql, [$key, $value, $userId]);
}
// Notification functions
function addNotification($type, $message, $userId = null) {
// If userId is not provided, use current session user
if ($userId === null && isset($_SESSION['user_id'])) {
$userId = $_SESSION['user_id'];
}
// For backward compatibility, handle old 4-parameter calls
if (func_num_args() === 4) {
$userId = func_get_arg(0);
$title = func_get_arg(1);
$message = func_get_arg(2);
$type = func_get_arg(3);
} else {
$title = ucfirst($type);
}
if ($userId) {
$sql = "INSERT INTO notifications (user_id, title, message, type) VALUES (?, ?, ?, ?)";
return executeQuery($sql, [$userId, $title, $message, $type]);
}
return false;
}
function getUnreadNotifications($userId) {
$sql = "SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC";
$stmt = executeQuery($sql, [$userId]);
if ($stmt) {
return $stmt->fetchAll();
}
return [];
}
function getNotifications($userId, $limit = 10) {
$sql = "SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT ?";
$stmt = executeQuery($sql, [$userId, $limit]);
if ($stmt) {
$notifications = $stmt->fetchAll();
// Mark notifications as read after fetching
if (!empty($notifications)) {
$notificationIds = array_column($notifications, 'id');
$placeholders = str_repeat('?,', count($notificationIds) - 1) . '?';
$updateSql = "UPDATE notifications SET is_read = 1 WHERE id IN ($placeholders)";
executeQuery($updateSql, $notificationIds);
}
return $notifications;
}
return [];
}
function clearNotifications($userId) {
$sql = "UPDATE notifications SET is_read = 1 WHERE user_id = ?";
return executeQuery($sql, [$userId]);
}
// Audit logging
function logAudit($action, $tableName, $recordId = null, $oldValues = null, $newValues = null) {
if (!isLoggedIn()) {
return;
}
$sql = "INSERT INTO audit_logs (user_id, action, table_name, record_id, old_values, new_values, ip_address, user_agent)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
$params = [
$_SESSION['user_id'],
$action,
$tableName,
$recordId,
$oldValues ? json_encode($oldValues) : null,
$newValues ? json_encode($newValues) : null,
$_SERVER['REMOTE_ADDR'] ?? null,
$_SERVER['HTTP_USER_AGENT'] ?? null
];
return executeQuery($sql, $params);
}
function logActivity($userId, $action, $description = null) {
$sql = "INSERT INTO activity_logs (user_id, action, description, ip_address, user_agent, created_at)
VALUES (?, ?, ?, ?, ?, NOW())";
$params = [
$userId,
$action,
$description,
$_SERVER['REMOTE_ADDR'] ?? null,
$_SERVER['HTTP_USER_AGENT'] ?? null
];
return executeQuery($sql, $params);
}
// Event functions
function getEvents($type = 'area', $limit = null, $status = 'published') {
$sql = "SELECT e.*,
a.name as area_name,
d.name as district_name,
as.name as assembly_name,
u.first_name, u.last_name
FROM events e
LEFT JOIN areas a ON e.area_id = a.id
LEFT JOIN districts d ON e.district_id = d.id
LEFT JOIN assemblies as ON e.assembly_id = as.id
LEFT JOIN users u ON e.created_by = u.id
WHERE e.event_type = ? AND e.status = ?
ORDER BY e.start_date ASC";
if ($limit) {
$sql .= " LIMIT " . intval($limit);
}
$stmt = executeQuery($sql, [$type, $status]);
if ($stmt) {
return $stmt->fetchAll();
}
return [];
}
function getUpcomingEvents($limit = 5) {
$sql = "SELECT e.*,
a.name as area_name,
d.name as district_name,
as.name as assembly_name
FROM events e
LEFT JOIN areas a ON e.area_id = a.id
LEFT JOIN districts d ON e.district_id = d.id
LEFT JOIN assemblies as ON e.assembly_id = as.id
WHERE e.status = 'published' AND e.start_date > NOW()
ORDER BY e.start_date ASC
LIMIT ?";
$stmt = executeQuery($sql, [$limit]);
if ($stmt) {
return $stmt->fetchAll();
}
return [];
}
function getFeaturedEvent() {
$sql = "SELECT e.*,
a.name as area_name,
d.name as district_name,
as.name as assembly_name
FROM events e
LEFT JOIN areas a ON e.area_id = a.id
LEFT JOIN districts d ON e.district_id = d.id
LEFT JOIN assemblies as ON e.assembly_id = as.id
WHERE e.status = 'published' AND e.featured = 1 AND e.start_date > NOW()
ORDER BY e.start_date ASC
LIMIT 1";
$stmt = executeQuery($sql);
if ($stmt) {
return $stmt->fetch();
}
return null;
}
// Registration functions
function isUserRegisteredForEvent($userId, $eventId) {
$sql = "SELECT id FROM event_registrations WHERE user_id = ? AND event_id = ? AND status != 'cancelled'";
$stmt = executeQuery($sql, [$userId, $eventId]);
return $stmt && $stmt->fetch();
}
function getEventRegistrationCount($eventId) {
$sql = "SELECT COUNT(*) as count FROM event_registrations WHERE event_id = ? AND status != 'cancelled'
UNION ALL
SELECT COUNT(*) as count FROM nonmember_registrations WHERE event_id = ? AND status != 'cancelled'";
$stmt = executeQuery($sql, [$eventId, $eventId]);
$count = 0;
if ($stmt) {
while ($row = $stmt->fetch()) {
$count += $row['count'];
}
}
return $count;
}
// Error handling
function handleError($message, $redirect = null) {
error_log($message);
$_SESSION['error'] = $message;
if ($redirect) {
header('Location: ' . $redirect);
exit();
}
}
function handleSuccess($message, $redirect = null) {
$_SESSION['success'] = $message;
if ($redirect) {
header('Location: ' . $redirect);
exit();
}
}
// Flash messages
function getFlashMessage($type) {
if (isset($_SESSION[$type])) {
$message = $_SESSION[$type];
unset($_SESSION[$type]);
return $message;
}
return null;
}
// Time ago function
function timeAgo($datetime) {
$time = time() - strtotime($datetime);
if ($time < 60) return 'just now';
if ($time < 3600) return floor($time/60) . ' minutes ago';
if ($time < 86400) return floor($time/3600) . ' hours ago';
if ($time < 2592000) return floor($time/86400) . ' days ago';
if ($time < 31536000) return floor($time/2592000) . ' months ago';
return floor($time/31536000) . ' years ago';
}
?>
Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists