SecurityHelper.php

3.75 KB
08/07/2025 12:55
PHP
SecurityHelper.php
<?php

class SecurityHelper
{
    /**
     * กรองและทำความสะอาดข้อมูล input
     */
    public static function sanitizeInput($input, $type = 'general')
    {
        if (empty($input)) {
            return '';
        }

        $input = trim($input);

        switch ($type) {
            case 'name':
                // อนุญาตเฉพาะอักษรไทย, อังกฤษ, เว้นวรรค, จุด, ยัติภังค์
                return preg_replace('/[^a-zA-Zก-๙\s\.\-]/u', '', $input);

            case 'email':
                return filter_var($input, FILTER_SANITIZE_EMAIL);

            case 'text':
                // ลบ HTML tags และ control characters
                $input = strip_tags($input);
                $input = preg_replace('/[\x00-\x1F\x7F]/u', '', $input);
                return $input;

            case 'general':
            default:
                return htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
        }
    }

    /**
     * Escape special characters สำหรับ Telegram Markdown
     */
    public static function escapeMarkdown($text)
    {
        if (empty($text)) {
            return '';
        }

        // Telegram Markdown V2 special characters
        $specialChars = ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!'];
        foreach ($specialChars as $char) {
            $text = str_replace($char, '\\'.$char, $text);
        }
        return $text;
    }

    /**
     * ตรวจสอบความปลอดภัยของ file path
     */
    public static function securePath($path)
    {
        // ป้องกัน directory traversal
        $path = str_replace(['../', '.\\', '..\\'], '', $path);
        $path = preg_replace('/[^a-zA-Z0-9_\-\/\.]/', '', $path);
        return $path;
    }

    /**
     * สร้าง hash สำหรับการเข้ารหัสข้อมูล
     */
    public static function generateHash($data)
    {
        return hash('sha256', $data.(defined('SECURITY_SALT') ? SECURITY_SALT : 'default_salt'));
    }

    /**
     * ตรวจสอบความแข็งแรงของข้อมูล
     */
    public static function validateInput($input, $type, $minLength = 1, $maxLength = 255)
    {
        if (empty($input) || strlen($input) < $minLength || strlen($input) > $maxLength) {
            return false;
        }

        switch ($type) {
            case 'name':
                // ตรวจสอบว่ามีเฉพาะอักษรที่อนุญาต
                return preg_match('/^[a-zA-Zก-๙\s\.\-]+$/u', $input);

            case 'email':
                return filter_var($input, FILTER_VALIDATE_EMAIL) !== false;

            case 'text':
                // ตรวจสอบว่าไม่มี control characters อันตราย
                return !preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', $input);

            default:
                return true;
        }
    }

    /**
     * Log security events
     */
    public static function logSecurityEvent($event, $userId = null, $details = [])
    {
        $logFile = __DIR__.'/../../logs/security.log';
        $timestamp = date('Y-m-d H:i:s');
        $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

        $logEntry = [
            'timestamp' => $timestamp,
            'event' => $event,
            'user_id' => $userId,
            'ip' => $ip,
            'details' => $details
        ];

        if (!file_exists(dirname($logFile))) {
            mkdir(dirname($logFile), 0755, true);
        }

        file_put_contents($logFile, json_encode($logEntry)."\n", FILE_APPEND | LOCK_EX);
    }
}