<?php
session_start();
require_once("restricted/mysql.php");
$_SESSION["local"] =false;

function isLocal(){
    $ipv6_prefix = explode(":",$_SERVER['SERVER_ADDR'],5);
    $ipv6 = explode(":",$_SERVER['REMOTE_ADDR'],5);
    if(($ipv6_prefix[0] == $ipv6[0] && $ipv6_prefix[1] == $ipv6[1] && $ipv6_prefix[2] == $ipv6[2] && $ipv6_prefix[3] == $ipv6[3]) || str_starts_with($_SERVER['REMOTE_ADDR'],"192.168.179.")){
        $_SESSION["local"] =true;
        return true;
    }else{
        return false;
    }
}

function checkLogin(){
    $mysql = new mysqli($GLOBALS["mysql_server"],$GLOBALS["mysql_user"],$GLOBALS["mysql_pass"],$GLOBALS["mysql_db"]);
    if(isLocal()){
        $_SESSION["local"] =true;
        return true;
    }
    if(isset($_SESSION["authKey"])){
        $res = mysqli_query($mysql,"SELECT id FROM users WHERE lastAuth > DATE_SUB(NOW(), INTERVAL 2 DAY) AND authKey = '".mysqli_real_escape_string($mysql,$_SESSION["authKey"])."' AND name = '".mysqli_real_escape_string($mysql,$_SESSION["user"])."';");
        if(!$res){
            echo mysqli_error($mysql);
            return false;
        }
        if(mysqli_num_rows($res) == 1){
            return isset($_SESSION["Logged"]);
        }
    }else{
        return false;
    }
}

function checkAdduser(){
    $mysql = new mysqli($GLOBALS["mysql_server"],$GLOBALS["mysql_user"],$GLOBALS["mysql_pass"],$GLOBALS["mysql_db"]);
    if(!mysqli_query($mysql,"DELETE FROM addUser WHERE datetime < DATE_SUB(NOW(), INTERVAL 1 MINUTE);")){
        echo mysqli_error($mysql);
    }
    $result = mysqli_query($mysql,"SELECT * FROM addUser WHERE accesskey='".mysqli_real_escape_string($mysql,$_GET["addUser"])."';");
    if(!$result){
        return false;
    }
    if ($result->num_rows > 0) {
        return true;
    }
    return false;
}

?>