/home/techb158/workloadmatch.com/includes
Edit: /home/techb158/workloadmatch.com/includes/functions.php (31330B)
prepare("SELECT {$c[1]} FROM {$c[0]} WHERE {$c[2]} = ? LIMIT 1")) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id);
$stmt->fetch();
if ($stmt->num_rows == 1) {
$_SESSION['UserDB'] = $c[0];
$_SESSION['Profile_ID'] = $c[1];
return true;
}
}
}
return false;
}
function login($email, $password, $mysqli) {
$ip= $_SERVER["REMOTE_ADDR"];
$agent =$_SERVER["HTTP_USER_AGENT"];
$datetime =date("Y/m/d") . ' ' . date('H:i:s') ;
if (checkuser($email, $mysqli)) {
$UserDB = $_SESSION['UserDB'];
$UA = 1;
$getID = function($mysqli, $UserDB, $col, $email, $UA) {
$q = "SELECT * FROM $UserDB WHERE $col = ? AND User_Access = ?";
$s = $mysqli->prepare($q);
if ($s) {
$s->bind_param('ss', $email, $UA);
$s->execute();
$r = $s->get_result();
$row = $r->fetch_assoc();
$s->close();
return $row;
}
return null;
};
$Managers = $getID($mysqli, $UserDB, 'Email', $email, $UA);
if (!$Managers) {
$Managers = $getID($mysqli, $UserDB, 'User_Name', $email, $UA);
}
$ID = $Managers ? $Managers['User_Access'] : 0;
$prof_lang = $Managers['prof_lang'];
if ($ID == 1) {
$Profile_ID = $_SESSION['Profile_ID'];
$getUser = function($mysqli, $UserDB, $col, $email, $Profile_ID) {
$q = "SELECT $Profile_ID, User_Name, Password, salt FROM $UserDB WHERE $col = ? LIMIT 1";
$s = $mysqli->prepare($q);
if ($s) {
$s->bind_param('s', $email);
$s->execute();
$s->store_result();
$s->bind_result($uid, $uname, $pwd, $slt);
$s->fetch();
if ($s->num_rows == 1) {
$s->close();
return [$uid, $uname, $pwd, $slt];
}
$s->close();
}
return null;
};
$userRow = $getUser($mysqli, $UserDB, 'Email', $email, $Profile_ID);
if (!$userRow) {
$userRow = $getUser($mysqli, $UserDB, 'User_Name', $email, $Profile_ID);
}
if ($userRow) {
list($user_id, $username, $db_password, $salt) = $userRow;
$client_hash = $password;
$password = hash('sha512', $password . $salt);
if (checkbrute($user_id, $mysqli) == true) {
header("Location: ../error.php?err=error: your account is locked");
exit();
}else
{
// Check if the password in the database matches
// the password the user submitted.
$input_hash = $password;
$stored_hash = $db_password;
if (strlen($stored_hash) === 60 && strpos($stored_hash, '$2y$') === 0) {
$passwordValid = password_verify($client_hash, $stored_hash);
if (!$passwordValid) {
$passwordValid = password_verify($input_hash, $stored_hash);
if ($passwordValid) {
$new_hash = password_hash($client_hash, PASSWORD_BCRYPT);
$rehash_stmt = $mysqli->prepare("UPDATE $UserDB SET Password = ?, salt = '' WHERE $Profile_ID = ?");
if ($rehash_stmt) {
$rehash_stmt->bind_param('ss', $new_hash, $user_id);
$rehash_stmt->execute();
$rehash_stmt->close();
$db_password = $new_hash;
}
}
}
} else {
$passwordValid = ($stored_hash === $input_hash);
if ($passwordValid) {
$new_hash = password_hash($client_hash, PASSWORD_BCRYPT);
$rehash_stmt = $mysqli->prepare("UPDATE $UserDB SET Password = ?, salt = '' WHERE $Profile_ID = ?");
if ($rehash_stmt) {
$rehash_stmt->bind_param('ss', $new_hash, $user_id);
$rehash_stmt->execute();
$rehash_stmt->close();
$db_password = $new_hash;
}
}
}
if ($passwordValid) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
$_SESSION['myusername'] = $username;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);
$_SESSION['username'] = $username;
$_SESSION['User_type'] = $UserDB;
$_SESSION['login_string'] = hash('sha512', $db_password . $user_browser);
language($prof_lang, $mysqli);
if ($UserDB === 'teacher_profile') {
$upd_stmt = $mysqli->prepare("UPDATE $UserDB SET Login_Date = ?, User_IP = ?, User_agent = ? WHERE $Profile_ID = ?");
if ($upd_stmt) {
$upd_stmt->bind_param('ssss', $datetime, $ip, $agent, $user_id);
$upd_stmt->execute();
$upd_stmt->close();
}
} else {
$upd_stmt = $mysqli->prepare("UPDATE $UserDB SET Login_Date = ? WHERE $Profile_ID = ?");
if ($upd_stmt) {
$upd_stmt->bind_param('ss', $datetime, $user_id);
$upd_stmt->execute();
$upd_stmt->close();
}
}
$LoginDate =date("Y/m/d");
$LoginTime =date('H:i:s');
$logins=1;
//$context = stream_context_create(
// array(
// "http" => array(
// "header" => "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
// )
// )
//);
//
//$HTML = file_get_contents("https://whatismyipaddress.com/ip/$ip", false,$context);
//preg_match_all('/
(.*?)<\/th> | (.*?)<\/td>/s', $HTML, $Matches, PREG_SET_ORDER);
//
//$isp=$Matches[5][2]; //Videotron Ltee
//$city=$Matches[14][2]; //Saint-Lambert
//$state=$Matches[13][2]; // Quebec
//$zipcode=$Matches[17][2]; //Postal Code
//$country=$Matches[12][2]; //Canada
//$Continent=$Matches[11][2]; //North America
// Set a stream context with a User-Agent header (if needed)
$context = stream_context_create([
"http" => [
"header" => "User-Agent: Mozilla/5.0 (compatible; YourAppName/1.0)"
]
]);
// Try to retrieve IP info from ipapi.co
$ipApiUrl = "https://ipapi.co/{$ip}/json/";
$ipInfo = @file_get_contents($ipApiUrl, false, $context);
$isp = "Unknown";
$city = "Unknown";
$state = "Unknown";
$zipcode = "Unknown";
$country = "Unknown";
$Continent = "Unknown";
if ($ipInfo !== false) {
$ipData = json_decode($ipInfo, true);
if (is_array($ipData)) {
$isp = isset($ipData['org']) ? $ipData['org'] : "Unknown";
$city = isset($ipData['city']) ? $ipData['city'] : "Unknown";
$state = isset($ipData['region']) ? $ipData['region'] : "Unknown";
$zipcode = isset($ipData['postal']) ? $ipData['postal'] : "Unknown";
$country = isset($ipData['country_name']) ? $ipData['country_name'] : "Unknown";
// ipapi.co does not directly provide a continent value
}
} else {
// Log an error if needed
error_log("Unable to retrieve IP information from ipapi.co for $ip. Using default values.");
}
// Now you can use $isp, $city, $state, $zipcode, $country, $Continent safely.
// For example:
//echo "ISP: " . $isp . " ";
//echo "City: " . $city . " ";
//echo "State: " . $state . " ";
//echo "Zipcode: " . $zipcode . " ";
//echo "Country: " . $country . " ";
//echo "Continent: " . $Continent . " ";
$bytes = openssl_random_pseudo_bytes(16);
$Token_User = ($bytes !== false) ? mb_strtoupper(bin2hex($bytes)) : mb_strtoupper(bin2hex(random_bytes(16)));
$_SESSION['Token_User'] = $Token_User;
if ($UserDB === 'teacher_profile') {
$upd_stmt = $mysqli->prepare("UPDATE $UserDB SET Login_Date = ?, User_IP = ?, User_agent = ?, ISP = ?, Token_User = ? WHERE $Profile_ID = ?");
if ($upd_stmt) {
$upd_stmt->bind_param('ssssss', $datetime, $ip, $agent, $isp, $Token_User, $user_id);
$upd_stmt->execute();
$upd_stmt->close();
}
} else {
$upd_stmt = $mysqli->prepare("UPDATE $UserDB SET Login_Date = ? WHERE $Profile_ID = ?");
if ($upd_stmt) {
$upd_stmt->bind_param('ss', $datetime, $user_id);
$upd_stmt->execute();
$upd_stmt->close();
}
}
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$ins_stmt = $mysqli->prepare("INSERT INTO Login_log(User_ID, User_Type, Date_Time, User_IP, User_agent, Time) VALUES (?, ?, ?, ?, ?, ?)");
if ($ins_stmt) {
$ins_stmt->bind_param('ssssss', $user_id, $UserDB, $datetime, $ip, $agent, $now);
$ins_stmt->execute();
$ins_stmt->close();
} else {
header("Location: ../error.php?err=Database error: login_attempts");
exit();
}
//if (!$mysqli->query("INSERT INTO Login_log(User_ID, time)
// VALUES ('$user_id', '$now')")) {
// header("Location: ../error.php?err=Database error: login_attempts");
// exit();
//}
return false;
}
}
}
}else{
header("Location: ../error.php?err=error: Access denid");
exit();
}
}else{
// Could not create a prepared statement
header("Location: ../index.php?err=you are not allow to login");
exit();
}
}
function checkbrute($user_id, $mysqli) {
$now = time();
$valid_attempts = $now - (2 * 60 * 60);
$UserDB = $_SESSION['UserDB'];
if ($stmt = $mysqli->prepare("SELECT time FROM Login_log WHERE User_ID = ? AND time > ? AND User_Type = ?")) {
$stmt->bind_param('iis', $user_id, $valid_attempts, $UserDB);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 5) {
return true;
} else {
return false;
}
} else {
header("Location: ../error.php?err=Database error: cannot prepare statement 1");
exit();
}
}
function login_check($mysqli) {
// Check if all session variables are set
if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
$Profile_ID = $_SESSION['Profile_ID'];
$UserDB = $_SESSION['UserDB'];
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
if ($stmt = $mysqli->prepare("SELECT Password
FROM $UserDB
WHERE $Profile_ID = ? LIMIT 1")) {
// Bind "$user_id" to parameter.
$stmt->bind_param('s', $user_id);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
if ($stmt->num_rows == 1) {
// If the user exists get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
$login_check = hash('sha512', $password . $user_browser);
if ($login_check == $login_string) {
// Logged In!!!!
return true;
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Could not prepare statement
header("Location: ../error.php?err=Database error: cannot prepare statement 2");
exit();
}
} else {
// Not logged in
return false;
}
}
function require_role($mysqli, $required_role) {
if (login_check($mysqli) !== true) {
header('Location: ' . dirname($_SERVER['SCRIPT_NAME']) . '/../authorized.php');
exit;
}
$role = $_SESSION['User_type'] ?? '';
if ($role !== $required_role) {
header('Location: ' . dirname($_SERVER['SCRIPT_NAME']) . '/../authorized.php');
exit;
}
return true;
}
/**
* Get the effective Manager ID when a Master is operating as a Manager.
* Returns the managed Manager_ID if set, otherwise the logged-in user_id.
*/
function get_effective_id() {
if (!empty($_SESSION['manage_as'])) {
return $_SESSION['manage_as'];
}
return $_SESSION['user_id'] ?? null;
}
/**
* Get the effective Manager ID cast to int for queries.
*/
function eff_id() {
return (int)get_effective_id();
}
function esc_url($url) {
if ('' == $url) {
return $url;
}
$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
$strip = array('%0d', '%0a', '%0D', '%0A');
$url = (string) $url;
$count = 1;
while ($count) {
$url = str_replace($strip, '', $url, $count);
}
$url = str_replace(';//', '://', $url);
$url = htmlentities($url, ENT_QUOTES, "UTF-8");
$url = str_replace('&', '&', $url);
$url = str_replace("'", ''', $url);
if ($url[0] !== '/') {
// We're only interested in relative links from $_SERVER['PHP_SELF']
return '';
} else {
return $url;
}
}
function addinfo($page, $mysqli){
if ($stmt = $mysqli->prepare("SELECT page FROM hits WHERE page = ?")) {
$stmt->bind_param('s', $page);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows != 0) {
$stmt->close();
if ($stmt2 = $mysqli->prepare("UPDATE hits SET count = count+1 WHERE page = ?")) {
$stmt2->bind_param('s', $page);
$stmt2->execute();
$stmt2->close();
}
} else {
$stmt->close();
$act = 1;
if ($insert_stmt = $mysqli->prepare("INSERT INTO hits (page, count) VALUES (?, ?)")) {
$insert_stmt->bind_param('ss', $page, $act);
$insert_stmt->execute();
$insert_stmt->close();
}
}
}
$ip= get_client_ip();
$getCountryFromIP= getCountryFromIP($ip, " NamE ");
$agent =$_SERVER["HTTP_USER_AGENT"];
$HTTP_X_FORWARDED_FOR = "";
$host_name_by_address = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$datetime =date("Y/m/d") . ' ' . date('H:i:s') ;
$view_date =date("Y/m/d");
if ($stmt = $mysqli->prepare("SELECT ip_address FROM info_page WHERE page = ? AND ip_address = ? AND view_date = ?")) {
$stmt->bind_param('sss', $page, $ip, $view_date);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 0) {
$stmt->close();
$act = 1;
if ($insert_stmt = $mysqli->prepare("INSERT INTO info_page (page, country, ip_address, user_agent, HTTP_X_FORWARDED_FOR, host_name_by_address, count, datetime, view_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
$insert_stmt->bind_param('sssssssss', $page, $getCountryFromIP, $ip, $agent, $HTTP_X_FORWARDED_FOR, $host_name_by_address, $act, $datetime, $view_date);
$insert_stmt->execute();
$insert_stmt->close();
}
} else {
$stmt->close();
if ($stmt2 = $mysqli->prepare("UPDATE info_page SET count = count+1 WHERE page = ? AND ip_address = ? AND view_date = ?")) {
$stmt2->bind_param('sss', $page, $ip, $view_date);
$stmt2->execute();
$stmt2->close();
}
}
}
if ($stmt = $mysqli->prepare("SELECT ip_address FROM info WHERE ip_address = ?")) {
$stmt->bind_param('s', $ip);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 0) {
$stmt->close();
if ($insert_stmt = $mysqli->prepare("INSERT INTO info (country, ip_address, user_agent, HTTP_X_FORWARDED_FOR, host_name_by_address, datetime) VALUES (?, ?, ?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssssss', $getCountryFromIP, $ip, $agent, $HTTP_X_FORWARDED_FOR, $host_name_by_address, $datetime);
$insert_stmt->execute();
$insert_stmt->close();
}
} else {
$stmt->close();
}
}
if($getCountryFromIP != "Canada")
{
}
}
function getUserIP()
{
$client = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
function get_client_ip()
{
return $_SERVER["REMOTE_ADDR"];
//// Nothing to do without any reliable information
//if (!isset ($_SERVER['REMOTE_ADDR'])) {
// return NULL;
//}
//
//// Header that is used by the trusted proxy to refer to
//// the original IP
//$proxy_header = "HTTP_X_FORWARDED_FOR";
//
//// List of all the proxies that are known to handle 'proxy_header'
//// in known, safe manner
//$trusted_proxies = array ("10.81.200.4");
//
//if (in_array ($_SERVER['REMOTE_ADDR'], $trusted_proxies)) {
//
// // Get the IP address of the client behind trusted proxy
// if (array_key_exists ($proxy_header, $_SERVER)) {
//
// // Header can contain multiple IP-s of proxies that are passed through.
// // Only the IP added by the last proxy (last IP in the list) can be trusted.
// $proxy_list = explode (",", $_SERVER[$proxy_header]);
// $client_ip = trim (end ($proxy_list));
//
// // Validate just in case
// if (filter_var ($client_ip, FILTER_VALIDATE_IP)) {
// return $client_ip;
// } else {
// // Validation failed - beat the guy who configured the proxy or
// // the guy who created the trusted proxy list?
// // TODO: some error handling to notify about the need of punishment
// }
// }
//}
//
//// In all other cases, REMOTE_ADDR is the ONLY IP we can trust.
//return $_SERVER['HTTP_X_FORWARDED_FOR'];
}
function BlacklistIP($page,$User_ID,$My_Name, $mysqli){
$ip= get_client_ip();
$getCountryFromIP= getCountryFromIP($ip, " NamE ");
$agent =$_SERVER["HTTP_USER_AGENT"];
//$HTTP_X_FORWARDED_FOR = $_SERVER["HTTP_X_FORWARDED_FOR"];
$HTTP_X_FORWARDED_FOR = $_SERVER['HTTP_REFERER'];
$host_name_by_address = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$datetime =date("Y/m/d") . ' ' . date('H:i:s') ;
$view_date =date("Y/m/d");
$sel_stmt = $mysqli->prepare("SELECT ip_address FROM ip_blacklist WHERE user_id = ? AND ip_address = ?");
if ($sel_stmt) {
$sel_stmt->bind_param('ss', $User_ID, $ip);
$sel_stmt->execute();
$sel_stmt->store_result();
$hasRow = $sel_stmt->num_rows > 0;
$sel_stmt->close();
} else {
$hasRow = false;
}
if (!$hasRow) {
$act=1;
if ($insert_stmt = $mysqli->prepare("INSERT INTO ip_blacklist (user_id, user_name, page, country, ip_address, user_agent, HTTP_X_FORWARDED_FOR, host_name_by_address, count, datetime,view_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
$insert_stmt->bind_param('sssssssssss', $User_ID, $My_Name, $page, $getCountryFromIP, $ip, $agent, $HTTP_X_FORWARDED_FOR, $host_name_by_address,$act, $datetime, $view_date);
if (! $insert_stmt->execute()) {
//echo $mysqli->error;
}
}
//header('Location: ../index.php?err=You are not allowed to view this page!');
//exit();
}else{
$upd_stmt = $mysqli->prepare("UPDATE ip_blacklist SET count = count+1 WHERE page = ? AND ip_address = ? AND view_date = ?");
if ($upd_stmt) {
$upd_stmt->bind_param('sss', $page, $ip, $view_date);
$upd_stmt->execute();
$upd_stmt->close();
}
}
if($getCountryFromIP != "Canada" && $ip !== '127.0.0.1' && $ip !== '::1')
{
// Destroy session
$_SESSION = array();
session_destroy();
header('Location: ../index.php?err=You need permission to perform this action!');
exit();
}
}
function language($lang, $mysqli) {
//if (isset($_POST)) {
// Getting all language variables into array as global variable
$i=1;
$query = "SELECT * FROM tbl_language";
$result = $mysqli->query($query);
$results = $result->fetch_assoc();
$langs= 'lang_'.$lang;
//foreach ($results as $row) {
while($results = $result->fetch_assoc())
{
if (!defined('LANG_VALUE_'.$i)) {
define('LANG_VALUE_'.$i,$results[$langs]);
}
$i++;
}
//}
$Profile_ID= $_SESSION['Profile_ID'];
$UserDB= $_SESSION['UserDB'];
if ($stmt = $mysqli->prepare("SELECT prof_lang
FROM $UserDB
WHERE $Profile_ID = ? LIMIT 1")) {
// Bind "$user_id" to parameter.
$stmt->bind_param('i', $lang);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
if ($stmt->num_rows != 1) {
$datetime =date("Y/m/d") . ' ' . date('H:i:s') ;
$upd_stmt = $mysqli->prepare("UPDATE $UserDB SET prof_lang = ?, Login_Date = ? WHERE User_Name = ? AND $Profile_ID = ?");
if ($upd_stmt) {
$upd_stmt->bind_param('ssss', $lang, $datetime, $_SESSION['username'], $_SESSION['user_id']);
$upd_stmt->execute();
$upd_stmt->close();
}
}
}
}
function encrypt_decrypt($action, $string) {
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = ENCRYPTION_SECRET_KEY;
$secret_iv = ENCRYPTION_SECRET_IV;
// hash
$key = hash('sha256', $secret_key);
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if ( $action == 'encrypt' ) {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} else if( $action == 'decrypt' ) {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
/*===============================================================================================================================*/
/*=============================================== ANTI SQL INJECTION Function ===================================================*/
/*===============================================================================================================================*/
function antiSQLInjection($texto){
// Words for search
$check[1] = chr(34); // simbol "
$check[2] = chr(39); // simbol '
$check[3] = chr(92); // simbol /
$check[4] = chr(96); // simbol `
$check[5] = "drop table";
$check[6] = "update";
$check[7] = "alter table";
$check[8] = "drop database";
$check[9] = "drop";
$check[10] = "select";
$check[11] = "delete";
$check[12] = "insert";
$check[13] = "alter";
$check[14] = "destroy";
$check[15] = "table";
$check[16] = "database";
$check[17] = "union";
$check[18] = "TABLE_NAME";
$check[19] = "1=1";
$check[20] = 'or 1';
$check[21] = 'exec';
$check[22] = 'INFORMATION_SCHEMA';
$check[23] = 'like';
$check[24] = 'COLUMNS';
$check[25] = 'into';
$check[26] = 'VALUES';
// Creates if the variables $ y and $ x to control in WHILE that will make the search and substitution
$y = 1;
$x = sizeof($check);
// WHILE is done, looking for any of the words specified above, if you find any of them, this script will replace it with a blank space " ".
while($y <= $x){
$target = strpos($texto,$check[$y]);
if($target !== false){
$texto = str_replace($check[$y], "", $texto);
}
$y++;
}
// Returns the harmless clean variable from SQL Injection
return $texto;
}
function set_flash_msg($msg, $type = 'success') {
$_SESSION['flash_msg'] = $msg;
$_SESSION['flash_type'] = $type;
}
function display_flash_msg() {
if (isset($_SESSION['flash_msg'])) {
$type = isset($_SESSION['flash_type']) ? $_SESSION['flash_type'] : 'success';
echo " Notification!" . htmlspecialchars($_SESSION['flash_msg'], ENT_QUOTES, 'UTF-8') . "";
unset($_SESSION['flash_msg'], $_SESSION['flash_type']);
}
}
/**
* Check if the currently logged-in user has permission for a given module/action.
* $module: module name (e.g. 'masters', 'managers', 'teachers', 'roles')
* $action: 'view', 'create', 'edit', 'delete', 'enable', 'disable'
*/
function has_permission($mysqli, $module, $action) {
$userType = $_SESSION['User_type'] ?? '';
$roleId = $_SESSION['role_id'] ?? null;
// Admin always has full access
if ($userType === 'admin_profile') {
return true;
}
if (!$roleId) {
return false;
}
$actionCol = 'can_' . $action;
$stmt = $mysqli->prepare("SELECT $actionCol FROM role_permissions WHERE role_id = ? AND module = ? LIMIT 1");
if ($stmt) {
$stmt->bind_param('is', $roleId, $module);
$stmt->execute();
$stmt->bind_result($allowed);
$stmt->fetch();
$stmt->close();
return (bool)$allowed;
}
return false;
}
/**
* Require permission or redirect to authorized page.
*/
function require_permission($mysqli, $module, $action) {
if (!has_permission($mysqli, $module, $action)) {
$_SESSION['flash_error'] = 'You do not have permission to perform this action.';
header('Location: ' . BASE_URL . '/authorized');
exit;
}
return true;
}
/**
* Check if a page is enabled for access.
* $pageKey: unique page identifier (e.g. 'admin_masters', 'master_dashboard')
*/
function is_page_enabled($mysqli, $pageKey) {
$stmt = $mysqli->prepare("SELECT status FROM pages_control WHERE page_key = ? LIMIT 1");
if ($stmt) {
$stmt->bind_param('s', $pageKey);
$stmt->execute();
$stmt->bind_result($status);
$stmt->fetch();
$stmt->close();
return ($status == 1);
}
return true; // default to enabled if page not found
}
/**
* Log an activity.
*/
function log_activity($mysqli, $action, $targetType = null, $targetId = null, $targetName = null, $details = null, $status = 'success') {
$userId = $_SESSION['user_id'] ?? 'unknown';
$userRole = $_SESSION['User_type'] ?? 'unknown';
$ip = $_SERVER['REMOTE_ADDR'] ?? '';
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
$stmt = $mysqli->prepare("INSERT INTO activity_logs (user_id, user_role, action, target_type, target_id, target_name, details, status, ip_address, user_agent) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
if ($stmt) {
$stmt->bind_param('ssssssssss', $userId, $userRole, $action, $targetType, $targetId, $targetName, $details, $status, $ip, $ua);
$stmt->execute();
$stmt->close();
}
}
/**
* Check if user is disabled (User_Access != 1) and prevent access.
*/
function check_user_disabled($mysqli) {
$userType = $_SESSION['User_type'] ?? '';
$userId = $_SESSION['user_id'] ?? null;
if (!$userId) return false;
$tableMap = [
'admin_profile' => ['admin_profile', 'Admin_ID'],
'master_profile' => ['master_profile', 'Master_ID'],
'manager_profile' => ['manager_profile', 'Manager_ID'],
'teacher_profile' => ['teacher_profile', 'Teacher_ID'],
];
if (isset($tableMap[$userType])) {
list($table, $idCol) = $tableMap[$userType];
$stmt = $mysqli->prepare("SELECT User_Access FROM $table WHERE $idCol = ? LIMIT 1");
if ($stmt) {
$stmt->bind_param('s', $userId);
$stmt->execute();
$stmt->bind_result($access);
$stmt->fetch();
$stmt->close();
if ($access != 1) {
// User is disabled - log them out
$_SESSION = array();
session_destroy();
header('Location: ' . BASE_URL . '/?err=Your account has been disabled.');
exit;
}
}
}
return true;
}
/**
* Get user's role name from role_id
*/
function get_role_name($mysqli, $roleId) {
if (!$roleId) return 'Unknown';
$stmt = $mysqli->prepare("SELECT role_name FROM roles WHERE role_id = ? LIMIT 1");
if ($stmt) {
$stmt->bind_param('i', $roleId);
$stmt->execute();
$stmt->bind_result($name);
$stmt->fetch();
$stmt->close();
return $name ?: 'Unknown';
}
return 'Unknown';
}
/**
* Get all available modules for role permissions
*/
function get_permission_modules() {
return ['masters','managers','teachers','roles','pages','logs','reports','settings','users','courses','schedule','groups','assignments','chat'];
}
/**
* Get all permissions actions
*/
function get_permission_actions() {
return ['view','create','edit','delete','enable','disable'];
}
/**
* Toggle user enable/disable status
*/
function toggle_user_status($mysqli, $table, $idCol, $userId, $newStatus) {
$stmt = $mysqli->prepare("UPDATE $table SET User_Access = ? WHERE $idCol = ?");
if ($stmt) {
$stmt->bind_param('is', $newStatus, $userId);
$result = $stmt->execute();
$stmt->close();
return $result;
}
return false;
} |