Path : /home/vishqocm/pcib.in/admin/includes/
File Upload :
Current File : /home/vishqocm/pcib.in/admin/includes/functions.php

<?php
/**
 * Common utility functions for the admin panel
 */

/**
 * Display a formatted date
 * 
 * @param string $date The date string to format
 * @param string $format The format to use (default: 'M d, Y')
 * @return string The formatted date
 */
function format_date($date, $format = 'M d, Y') {
    return date($format, strtotime($date));
}

/**
 * Generate a slug from a string
 * 
 * @param string $string The string to convert to a slug
 * @return string The slugified string
 */
function generate_slug($string) {
    // Replace non letter or digit characters with dash
    $string = preg_replace('/[^\p{L}\p{N}]+/u', '-', $string);
    // Trim dashes from beginning and end
    $string = trim($string, '-');
    // Convert to lowercase
    $string = strtolower($string);
    
    return $string;
}

/**
 * Limit string length and add ellipsis if needed
 * 
 * @param string $string The string to limit
 * @param int $length The maximum length
 * @param string $append The string to append if truncated (default: '...')
 * @return string The truncated string
 */
function limit_string($string, $length, $append = '...') {
    if (strlen($string) <= $length) {
        return $string;
    }
    
    return substr($string, 0, $length) . $append;
}

/**
 * Get file extension from filename
 * 
 * @param string $filename The filename
 * @return string The file extension
 */
function get_file_extension($filename) {
    return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
}

/**
 * Generate a random string
 * 
 * @param int $length The length of the random string
 * @return string The random string
 */
function generate_random_string($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

/**
 * Format file size in human readable format
 * 
 * @param int $bytes The file size in bytes
 * @return string Formatted file size
 */
function format_file_size($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        return $bytes . ' bytes';
    } elseif ($bytes == 1) {
        return $bytes . ' byte';
    } else {
        return '0 bytes';
    }
}

/**
 * Check if a string contains another string
 * 
 * @param string $haystack The string to search in
 * @param string $needle The string to search for
 * @param bool $case_sensitive Whether to perform case-sensitive search (default: false)
 * @return bool True if needle is found, false otherwise
 */
function string_contains($haystack, $needle, $case_sensitive = false) {
    if ($case_sensitive) {
        return strpos($haystack, $needle) !== false;
    } else {
        return stripos($haystack, $needle) !== false;
    }
}

/**
 * Generate a status badge HTML
 * 
 * @param string $status The status value
 * @return string The HTML for the status badge
 */
function get_status_badge($status) {
    $badge_class = 'secondary';
    
    switch (strtolower($status)) {
        case 'active':
        case 'published':
        case 'approved':
        case 'completed':
            $badge_class = 'success';
            break;
        case 'inactive':
        case 'draft':
        case 'pending':
            $badge_class = 'warning';
            break;
        case 'suspended':
        case 'rejected':
        case 'cancelled':
            $badge_class = 'danger';
            break;
        case 'processing':
        case 'in-progress':
            $badge_class = 'info';
            break;
    }
    
    return '<span class="badge bg-' . $badge_class . '">' . ucfirst($status) . '</span>';
}

/**
 * Sanitize output to prevent XSS
 * 
 * @param string $string The string to sanitize
 * @return string The sanitized string
 */
function sanitize_output($string) {
    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}

/**
 * Check if a user has a specific role
 * 
 * @param string $role The role to check for
 * @return bool True if the user has the role, false otherwise
 */
function user_has_role($role) {
    return isset($_SESSION['role']) && $_SESSION['role'] === $role;
}

/**
 * Check if a user has admin privileges (admin or director role)
 * 
 * @return bool True if the user has admin privileges, false otherwise
 */
function user_has_admin_privileges() {
    return isset($_SESSION['role']) && ($_SESSION['role'] === 'admin' || $_SESSION['role'] === 'director' || $_SESSION['role'] === 'developer');
}

/**
 * Check if the current page should only be accessible to users with admin privileges
 * 
 * @param string $redirect URL to redirect to if not authorized
 * @return void
 */


/**
 * Upload a file with validation
 * 
 * @param array $file The file from $_FILES
 * @param string $destination The destination directory
 * @param array $allowed_types Array of allowed mime types
 * @param int $max_size Maximum file size in bytes
 * @return array|bool Array with file info on success, false on failure
 */
function upload_file($file, $destination, $allowed_types, $max_size) {
    // Check for errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return false;
    }
    
    // Validate file type
    if (!in_array($file['type'], $allowed_types)) {
        return false;
    }
    
    // Validate file size
    if ($file['size'] > $max_size) {
        return false;
    }
    
    // Create destination directory if it doesn't exist
    if (!is_dir($destination)) {
        mkdir($destination, 0755, true);
    }
    
    // Generate unique filename
    $extension = get_file_extension($file['name']);
    $new_filename = uniqid() . '.' . $extension;
    $filepath = $destination . '/' . $new_filename;
    
    // Move the uploaded file
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return [
            'filename' => $new_filename,
            'filepath' => $filepath,
            'filesize' => $file['size'],
            'filetype' => $file['type'],
            'original_name' => $file['name']
        ];
    }
    
    return false;
}

/**
 * Format a date/time in IST (Indian Standard Time)
 * 
 * @param string $datetime The datetime string to format
 * @param string $format The format to use (default: 'Y-m-d H:i:s')
 * @return string The formatted datetime in IST
 */
function format_ist_datetime($datetime, $format = 'Y-m-d H:i:s') {
    // Ensure the system timezone is set to IST
    $old_tz = date_default_timezone_get();
    date_default_timezone_set('Asia/Kolkata');
    
    // Format the date
    $formatted = date($format, strtotime($datetime));
    
    // Restore original timezone
    date_default_timezone_set($old_tz);
    
    return $formatted;
}