Skip to content

Commit

Permalink
Update App.php
Browse files Browse the repository at this point in the history
  • Loading branch information
Jatbi authored Jan 10, 2025
1 parent c981297 commit 12c8bc2
Showing 1 changed file with 132 additions and 142 deletions.
274 changes: 132 additions & 142 deletions src/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ class App{
private $components = [];
private $controllers = [];
private $globalFile = null;
private $errorFile = null;
private $cookies = [];
private $sessions = [];
private $blockedIps = [];
Expand All @@ -32,18 +31,13 @@ public function __construct($dbConfig = null) {
$this->database = new Medoo($dbConfig);
}
}
// Cài đặt dữ liệu toàn cục

public function setValueData(string $key, $value) {
$this->valueData[$key] = $value;
}

// Lấy dữ liệu toàn cục
public function getValueData($key) {
return isset($this->valueData[$key]) ? $this->valueData[$key] : null;
}
// Phương thức để upload file
public function upload($fileField) {
return new Upload($fileField);
return $this->valueData[$key] ?? null;
}
// Thực hiện truy vấn cơ sở dữ liệu
public function __call($method, $args) {
Expand All @@ -58,80 +52,6 @@ public function __call($method, $args) {
}
throw new BadMethodCallException("$method does not exist.");
}
// Cấu hình PHP Mailer
public function Mail($options){
$mail = new PHPMailer(true);
try {
// Server settings
$mail->isSMTP(); // Gửi bằng SMTP
$mail->Host = $options['host']; // Địa chỉ SMTP server
$mail->SMTPAuth = true; // Kích hoạt xác thực SMTP
$mail->Username = $options['username']; // SMTP username
$mail->Password = $options['password']; // SMTP password
if (in_array($options['encryption'], ['tls', 'ssl', 'smtp'])) {
if($options['encryption']=='smtp'){
$options['encryption'] = PHPMailer::ENCRYPTION_SMTPS;
}
$mail->SMTPSecure = $options['encryption'];
} else {
throw new Exception('Invalid encryption type. Allowed values are tls, ssl, PHPMailer::ENCRYPTION_STARTTLS, or PHPMailer::ENCRYPTION_SMTPS.');
}
$mail->Port = isset($options['port']) ? $options['port'] : 587; // Cổng
// Sender info
$mail->setFrom($options['from_email'], $options['from_name']); // Người gửi email

return $mail; // Trả về đối tượng mail đã được cấu hình
} catch (Exception $e) {
throw new Exception("Mailer Error: " . $mail->ErrorInfo);
}
}
// Cấu hình JWT
public function JWT($key, $algorithm = 'HS256'){
$this->jwtKey = $key;
$this->jwtAlgorithm = $algorithm;
}
// Tạo JWT
public function addJWT($payload, $key = null, $algorithm = null, $keyId = null, $head = null){
// Sử dụng key và algorithm được cung cấp nếu có, nếu không sử dụng giá trị mặc định
$jwtKey = $key ?? $this->jwtKey;
$jwtAlgorithm = $algorithm ?? $this->jwtAlgorithm;

if (!$jwtKey) {
throw new \Exception('JWT key not configured');
}

// Gọi hàm encode với các tham số bổ sung
return JWT::encode($payload, $jwtKey, $jwtAlgorithm, $keyId, $head);
}
// Giải mã JWT
public function decodeJWT($token,$header = null){
if (!$this->jwtKey) {
throw new \Exception('JWT key not configured');
}
try {
// Đảm bảo rằng tham số thứ ba là mảng chứa thuật toán
if($header){
$headers = new \stdClass();
$decoded = JWT::decode($token, new Key($this->jwtKey, $this->jwtAlgorithm), $headers);
// Trả về một mảng chứa các giá trị giải mã và tiêu đề nếu cần
return [
'decoded' => $decoded,
'headers' => $headers
];
}
else {
return JWT::decode($token, new Key($this->jwtKey, $this->jwtAlgorithm));
}

} catch (\Exception $e) {
return null;
}
}
// Kiểm tra JWT
public function validateJWT($token)
{
return $this->decodeJWT($token) !== null;
}
// Đăng ký route với phương thức GET
public function router($route, $method, $callback = null){
return $this->registerRoute($method, $route, $callback);
Expand All @@ -141,19 +61,12 @@ public function setComponent($name, $callback){
$this->components[$name] = $callback;
return $this;
}
// Thiết lập header cho phản hồi
public function header($headers) {
foreach ($headers as $key => $value) {
header("$key: $value");
}
}
// Render component
public function component($name, $vars = []){
public function component($name, $vars = []) {
$vars = array_merge($this->valueData, $vars);
if (isset($this->components[$name])) {
ob_start();
$callback = $this->components[$name];
$callback($vars);
$this->components[$name]($vars);
return ob_get_clean();
}
return "Component not found";
Expand All @@ -178,14 +91,16 @@ private function registerRoute($method, $route, $callback = null){
return $this;
}
// Đăng ký controller với các route
public function request($prefix, $controllerPath){
public function request($prefix, $controllerPath) {
if (file_exists($controllerPath)) {
$app = $this;
$controller = require $controllerPath;
if (is_callable($controller)) {
$this->controllers[$prefix] = $controller;
$controller($this);
}
} else {
throw new RuntimeException("Controller not found: $controllerPath");
}
return $this;
}
Expand All @@ -194,50 +109,34 @@ public function setGlobalFile($filePath){
$this->globalFile = $filePath;
return $this;
}
// Đặt file lỗi
public function setErrorFile($filePath){
$this->errorFile = $filePath;
return $this;
}
// Đặt quyền hạn cho route
public function setPermissions($permissions){
public function setPermissions($permissions) {
if ($this->currentRoute) {
$this->setCurrentPermissions($this->currentRoute, $permissions);
// Không cần reset lại currentRoute ở đây vì đã lưu trong registerRoute
$this->permissions[$this->currentRoute] = $permissions;
}
return $this;
}
public function setCurrentPermissions($route, $permissions){
$this->permissions[$route] = $permissions;
return $this;
}
// Đăng nhập quyền hạn của người dùng
public function setUserPermissions($userPermissions){

public function setUserPermissions($userPermissions) {
$this->userPermissions = $userPermissions;
}
// Kiểm tra xem người dùng có quyền truy cập route không
private function checkPermission($route){

private function checkPermission($route) {
if (!isset($this->permissions[$route])) {
return true; // Nếu không có giới hạn, cho phép truy cập
return true;
}
if (is_array($this->permissions[$route]) || is_object($this->permissions[$route])) {
foreach ($this->permissions[$route] as $permission) {
if (!in_array($permission, $this->userPermissions)) {
return false; // Nếu không có quyền, từ chối truy cập
}
foreach ($this->permissions[$route] as $permission) {
if (!in_array($permission, $this->userPermissions)) {
return false;
}
}
return true; // Có quyền truy cập
return true;
}
// Chạy ứng dụng, xử lý route
public function run(){
// Kiểm tra và chặn IP trước khi xử lý yêu cầu
public function run() {
$this->checkBlockedIp();
$method = $_SERVER['REQUEST_METHOD'];
$path = $_SERVER['REQUEST_URI'];
// Xóa query string khỏi path
$path = strtok($path, '?');
// Xử lý route từ các controller đã đăng ký
$path = strtok($_SERVER['REQUEST_URI'], '?');

foreach ($this->controllers as $prefix => $controller) {
if (strpos($path, $prefix) === 0) {
$subPath = substr($path, strlen($prefix));
Expand All @@ -247,52 +146,143 @@ public function run(){
call_user_func($this->routes[$method][$routeVars['route']], $routeVars['vars']);
return;
} else {
include $this->errorFile;
$this->handleWildcardRoute();
return;
}
}
}
}
// Kiểm tra route trong GET, POST

$routeVars = $this->matchRoute($method, $path);
if ($routeVars !== false) {
if ($this->checkPermission($routeVars['route'])) {
call_user_func($this->routes[$method][$routeVars['route']], $routeVars['vars']);
} else {
include $this->errorFile;
$this->handleWildcardRoute();
}
} else {
include $this->errorFile;
$this->handleWildcardRoute();
}
}
// Hàm khớp route và lấy biến từ route
private function matchRoute($method, $path){

private function matchRoute($method, $path) {
foreach ($this->routes[$method] as $route => $callback) {
$pattern = '#^' . $route . '$#';
// Escape các ký tự đặc biệt trong route để đảm bảo nó là regex hợp lệ
$pattern = '#^' . preg_quote($route, '#') . '$#';

if (preg_match($pattern, $path, $matches)) {
return ['route' => $route, 'vars' => array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY)];
}
}
return false;
}
// Render HTML template
public function render($templatePath, $vars = [], $ajax = null){

private function handleWildcardRoute() {
if (isset($this->routes['GET']['*'])) {
$this->routes['GET']['*'](['path' => $_SERVER['REQUEST_URI']]);
} else {
echo "404 Not Found";
}
}

public function render($templatePath, $vars = [], $ajax = null) {
$vars = array_merge($this->valueData, $vars);
if (file_exists($templatePath)) {
extract($vars);
ob_start();
$app = $this;
if ($ajax != 'global') {
if ($ajax !== 'global') {
include $this->globalFile;
} else {
include $templatePath;
}

return ob_get_clean();
}
return "Template not found";
}
// Thiết lập header cho phản hồi
public function header($headers) {
foreach ($headers as $key => $value) {
header("$key: $value");
}
}
// Phương thức để upload file
public function upload($fileField) {
return new Upload($fileField);
}
// Cấu hình PHP Mailer
public function Mail($options){
$mail = new PHPMailer(true);
try {
// Server settings
$mail->isSMTP(); // Gửi bằng SMTP
$mail->Host = $options['host']; // Địa chỉ SMTP server
$mail->SMTPAuth = true; // Kích hoạt xác thực SMTP
$mail->Username = $options['username']; // SMTP username
$mail->Password = $options['password']; // SMTP password
if (in_array($options['encryption'], ['tls', 'ssl', 'smtp'])) {
if($options['encryption']=='smtp'){
$options['encryption'] = PHPMailer::ENCRYPTION_SMTPS;
}
$mail->SMTPSecure = $options['encryption'];
} else {
throw new Exception('Invalid encryption type. Allowed values are tls, ssl, PHPMailer::ENCRYPTION_STARTTLS, or PHPMailer::ENCRYPTION_SMTPS.');
}
$mail->Port = isset($options['port']) ? $options['port'] : 587; // Cổng
// Sender info
$mail->setFrom($options['from_email'], $options['from_name']); // Người gửi email

return $mail; // Trả về đối tượng mail đã được cấu hình
} catch (Exception $e) {
throw new Exception("Mailer Error: " . $mail->ErrorInfo);
}
}
// Cấu hình JWT
public function JWT($key, $algorithm = 'HS256'){
$this->jwtKey = $key;
$this->jwtAlgorithm = $algorithm;
}
// Tạo JWT
public function addJWT($payload, $key = null, $algorithm = null, $keyId = null, $head = null){
// Sử dụng key và algorithm được cung cấp nếu có, nếu không sử dụng giá trị mặc định
$jwtKey = $key ?? $this->jwtKey;
$jwtAlgorithm = $algorithm ?? $this->jwtAlgorithm;

if (!$jwtKey) {
throw new \Exception('JWT key not configured');
}

// Gọi hàm encode với các tham số bổ sung
return JWT::encode($payload, $jwtKey, $jwtAlgorithm, $keyId, $head);
}
// Giải mã JWT
public function decodeJWT($token,$header = null){
if (!$this->jwtKey) {
throw new \Exception('JWT key not configured');
}
try {
// Đảm bảo rằng tham số thứ ba là mảng chứa thuật toán
if($header){
$headers = new \stdClass();
$decoded = JWT::decode($token, new Key($this->jwtKey, $this->jwtAlgorithm), $headers);
// Trả về một mảng chứa các giá trị giải mã và tiêu đề nếu cần
return [
'decoded' => $decoded,
'headers' => $headers
];
}
else {
return JWT::decode($token, new Key($this->jwtKey, $this->jwtAlgorithm));
}

} catch (\Exception $e) {
return null;
}
}
// Kiểm tra JWT
public function validateJWT($token)
{
return $this->decodeJWT($token) !== null;
}
// Thiết lập cookie
public function setCookie($name, $value, $expire = 0, $path = '', $domain = '', $secure = false, $httponly = false) {
setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
Expand Down Expand Up @@ -409,14 +399,14 @@ public function diffTime($start, $end) {
$diff = $startDate->diff($endDate);
return $diff->format('%y years %m months %d days %h hours %i minutes %s seconds');
}
public function randomNumber($length = 11) {
$randomString = '';
$randomString .= mt_rand(1, 9);
for ($i = 1; $i < $length; $i++) {
$randomString .= mt_rand(0, 9);
}
return $randomString;
}
public function randomNumber($length = 11) {
$randomString = '';
$randomString .= mt_rand(1, 9);
for ($i = 1; $i < $length; $i++) {
$randomString .= mt_rand(0, 9);
}
return $randomString;
}
// Tạo chuỗi ký tự ngẫu nhiên với độ dài nhất định
public function randomString($length = 10, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') {
$str = '';
Expand Down

0 comments on commit 12c8bc2

Please sign in to comment.