<?php
define("SERVER_NUMBER","1");
define("SERVER_NAME","Elly");
define("v","3.0");
header("gLarkControl: ".v);
$deb = 1;
if ($deb == 1){
	error_reporting(E_ALL | E_STRICT);
	ini_set('display_errors','On');
} else {
	ini_set('display_errors','Off');
}
session_start();
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors','On');
$starttime=microtime();
$starttime=explode(" ",$starttime);
$starttime=$starttime[0]+$starttime[1];
function preName($s){
	if ($s == "core" || $s == "database"){
		return "sys_".$s.".lm";
	} elseif ($s == "FileIO"){
		return $s;
	} 
	return "application_".$s.".lm";
}
function ErrorHandler($errno,$errstr,$errfile,$errline){
	global $deb;
	$errstr = htmlspecialchars($errstr);
	$apps_name = pathinfo($errfile);
	$apps_name = (preName($apps_name["filename"]));
	$errstr = str_replace(SITES_ROOT,"/var/gLarkWWW/",$errstr);
	$errstr = str_replace(SERVER_ROOT,"/var/gLarkServer/",$errstr);
	$errstr = str_replace(ROOT,"/var/gLarkPanel/",$errstr);
	
	if ($deb==0){
		echo '<div class="error">Ошибка модуля '.$apps_name.':'.$errline.'.<br>Сообщите администратору о данной проблеме!</div>';
		return true;
	}
	switch($errno){
		case E_USER_ERROR:{
			echo '<div data-type="gLEEUE" class="error">
			Ошибка модуля '.$apps_name.':'.$errline.'<br>Подробности: '.$errstr.'<br></div>';
			die();
			break;
		}
		case E_USER_WARNING: {
			echo '<div data-type="gLEEUW" class="warning">
			Предупреждение от '.$apps_name.':'.$errline.'<br>Подробности: '.$errstr.'</div>';
			break;
		}
		case E_USER_NOTICE: {
			echo '<div data-type="gLEEUN" class="warning">
			Уведомление от '.$apps_name.':'.$errline.'<br>Подробности: '.$errstr.'</div>';
			break;
		}
		default: {
			echo '<div data-type="gLEEUD" class="error">
			Ошибка модуля '.$apps_name.':'.$errline.'<br>Подробности: '.$errstr.'<br></div>';
			break;
		}
	}
	return true;
}
function ExceptionHandler($e){
	global $deb;
	$apps_name = pathinfo($e->getFile());
	$apps_name = (preName($apps_name["filename"]));
	if ($deb==0){
		echo '<div class="error">Ошибка модуля '.$apps_name.':'.$e->getLine().'.<br>Сообщите администратору о данной проблеме!</div>';
		return true;
	}
	echo '<div class="error">Ошибка модуля '.$apps_name.':'.$e->getLine().'<br>Подробности: '.$e->getMessage().'</div>';
}
$reDefineErrorHandler = set_error_handler("ErrorHandler");
set_exception_handler("ExceptionHandler");
define("ROOT",$_SERVER["DOCUMENT_ROOT"]);
define("SERVER_ROOT",ROOT."/../server.glark.ru/");
define("SITES_ROOT",SERVER_ROOT."sites/");
include_once ROOT.'/core/INIStorage.php';
include_once ROOT.'/core/default.php';
include_once ROOT.'/core/database.php';
include_once ROOT.'/core/server.php';
include_once ROOT.'/core/Vars.php';

function sendMail($who,$title,$sms){
	global $db;
	$db->Query("INSERT INTO `mail_temp`( `mail`,`title`, `sms`) VALUES ('".$who."','".$title."','".$sms."')");
}
function sendVk($who,$sms){
	global $db;
	$db->Query("INSERT INTO `vk_bot`(`vk`, `msg`, `timeAdd`) VALUES ('".$who."','".$sms."','".(time())."');");
}

class Core {
	private $db = null;
	private $errorList = [];
	public $Quota = null;
	private $cfg;
	private $_debug = [
		"enabled"	=>	0,
		"showPath"	=>	0
	];
	public function __construct($db,$cfg){
		$this->db = $db;
		$this->cfg = $cfg;
		return true;
	}
	
	public function APIQuery($url,$json=true){
		$ch = curl_init();
		$userAgent = 'gLarkRuBOT/1.0 (http://glark.ru/)';
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		$returned = curl_exec($ch);
		curl_close($ch);
		return $json==true?json_decode($returned, true):$returned;
	}
	
	public function drawUpdate($msg){
		$bb = array('~\[url=(.*?)?\](.*?)\[\/url\]~si' => '<a href="$1" target="_blank">$2</a>',
        '/\[b\](.+)\[\/b\]/isU' => '<b>$1</b>',
        '/\[u\](.+)\[\/u\]/isU' => '<span style="text-decoration:underline;">$1</span>',
        '/\[s\](.+)\[\/s\]/isU' => '<s>$1</s>',
        '/\[i\](.+)\[\/i\]/isU' => '<i>$1</i>',
		'/\[\+\]/isU' => i("plus","chicon"),
		'/\[\*\]/isU' => i("exclamation","chicon"),
		'/\[F\]/isU' => i("wizard","chicon"),
		'/\[U\]/isU' => i("refresh","chicon"),
		'/\\r\\n/si'	=> '<br/>',
        '/\[color=(.+)\](.+)\[\/color\]/isU' => '<span style="color:$1;">$2</span>',
        '/\[quote\](.+)\[\/quote\]/isU' => '<div class="quote">$1</div>');
		$msg = preg_replace(array_keys($bb), array_values($bb), $msg);
		return $msg;
	}
	
	
	public function drawString($string){
		$bb = array('~\[url=(.*?)?\](.*?)\[\/url\]~si' => '<a href="$1" target="_blank">$2</a>',
        '/\[b\](.+)\[\/b\]/isU' => '<b>$1</b>',
        '/\[u\](.+)\[\/u\]/isU' => '<span style="text-decoration:underline;">$1</span>',
        '/\[s\](.+)\[\/s\]/isU' => '<s>$1</s>',
        '/\[i\](.+)\[\/i\]/isU' => '<i>$1</i>',
        '/\[color=(.+)\](.+)\[\/color\]/isU' => '<span style="color:$1;">$2</span>',
		'/\\r\\n/si'	=> '<br/>',
        '/\[quote\](.+)\[\/quote\]/isU' => '<div class="quote">$1</div>');
		$string = preg_replace(array_keys($bb), array_values($bb), $string);
		return $string;
	}
	public function drawBr($string){
		//$string = iconv('utf-8', 'utf-8//IGNORE', $string);
		$string = str_replace('\r\n', "<br>", $string);
		$string = str_replace('\n', "<br>", $string);
		$string = str_replace('\r', "<br>", $string);
		$string = str_replace('♪◙', "<br>", $string);
		
		$string = $this->drawString($string);
		return $string;
	}
	
	public function bl2nl($i){
		return preg_replace('/<br\\s*?\/??>/i',"",$i);
	}
	
	public function GoToPage($url="/"){
		header("Location: ".$url);
		exit();
	}
	
	public function RandomString($strings=[],$count=1){
		if (count($strings)<=0){
			return NULL;
		}
		
		$key = array_rand($strings,$count);
		if ($count == 1){
			return $strings[$key];
		} else {
			foreach($key as $k => $v){
				$_key[$k] = $strings[$v];
			}
			return $_key;
		}
	}
	
	public function StringHash($string){
		$pass = md5(md5($string));
        $count_1 = strlen($pass);
        $return = NULL;
        for($i = 1; $i <= $count_1; $i++) {
            $n = ($i == 1 ? 0 : $i-1);
            $return .= md5(md5(substr($pass, $n, $i)));
        }
        return md5($return);
	}
	// Регистириует ошибку
	public function regError($string="Error Code",$utxt="Error System",$code=-1,$module="System"){
		$this->errorList[] = array(
		"code"		=>	$code,
		"text"		=>	$string,
		"utxt"		=>	$utxt,
		"module"	=>	$module
		);
	}
	// Отчищает список ошибок
	public function cleanError($key=null){
		if ($key == null){
			$this->errorList = [];
		} else {
			unset($this->errorList[$key]);
		}	
	}
	// Выводит список ошибок
	public function showError(){
		return $this->errorList;
	}
	// Количество ошибок
	public function countError(){
		return count($this->errorList);
	}
	// Возращает true если есть ошибки
	public function isBooleanError(){
		return ($this->countError()>0?true:false);
	}
	// Фильтрует от XSS
	public function FilterString($string,$hsc=true){
		return ($hsc?trim(htmlspecialchars(mysqli_real_escape_string($this->db->link,$string))):trim(mysqli_real_escape_string($this->db->link,$string)));
	}
	
	// Генерирует новый CSRF ключ
	public function genCSRF(){
		$token = substr( str_shuffle( 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM' ), 0, 16);
		$_SESSION['csrf_token'] = $token;
		return $token;
	}
	// Проверяет на валидность CSRF
	public function checkCSRF(){
		if (!isset($_POST["csrf"]) || empty($_POST["csrf"]) || $_POST["csrf"] != $_SESSION['csrf_token']){
			return false;
		} else {
			return true;
		}
	}
	
	public function getVersion(){
		return v;
	}
	
	public function setHeaderFile($ext,$path){
		if ($ext == "html"){
			header("Content-Type:text/html; charset=UTF-8");
			return true;
		} elseif ($ext == "php"){
			header("Content-Type:text/plant; charset=UTF-8");
			return true;
		} elseif ($ext == "css"){
			header("Content-Type:text/css; charset=UTF-8");
			return true;
		} elseif ($ext == "zip"){
			header("Content-Type:application/zip");
			header("Content-Transfer-Encoding: Binary");
			header("Content-length: ".filesize($path));
			header("Content-disposition:attachment; filename='".basename($path)."'");
			return true;
		} elseif ($ext == "xml"){
			header("Content-Type:text/xml; charset=UTF-8");
			return true;
		} elseif ($ext == "png"){
			header("Content-Type:image/png");
			return true;
		} elseif ($ext == "jpg"){
			header("Content-Type:image/jpeg");
			return true;
		} elseif ($ext == "gif"){
			header("Content-Type:image/gif");
			return true;
		} elseif ($ext == "wepb"){
			header("Content-Type:image/webp");
			return true;
		} elseif ($ext == "ico"){
			header("Content-Type: image/x-icon");
			return true;
		} else {
			header("Content-Type:text/plant; charset=UTF-8");
			return true;
		}
		
	}
	
	public function RealTime($time=false){
		ini_set('date.timezone', "Europe/Moscow");
        if ($time == NULL) $time = time(); $settime = 1;
        $full_time = date('d.m.Y / H:i', $time);
        $date = date('d.m.Y', $time);
        $timep = date('H:i', $time);
        if ($date == date('d.m.Y')) $full_time = date('Сегодня H:i', $time);
        if ($date == date('d.m.Y', time()-60*60*24)) $full_time = date('Вчера, H:i', $time);
        if ($settime == 1 && $date == date('d.m.Y')) $full_time = date('Сегодня, H:i', $time);
        return $full_time;

	}
	
	# Навигация по страницам
	function page($k_page = 1) {
		$page = 1;
		if (isset($_GET['page'])) {
			if ($_GET['page'] == 'end') $page = intval($k_page);
			elseif (is_numeric($_GET['page'])) $page = intval($_GET['page']);
		}
		if ($page < 1) $page = 1;
		if ($page > $k_page) $page = $k_page;
		return $page;
	}
	function k_page($k_post = 0, $k_p_str = 10) {
		if ($k_post != 0) {
			$v_pages = ceil($k_post/$k_p_str);
			return $v_pages;
		} else {
			return 1;
		}
	}
	function str($link = '?', $k_page = 1, $page = 1) {
		if ($page < 1) $page = 1;
		echo '<div class="nav_list">';
		if ($page > 1) echo '<a class="nav nav_1" href="'. $link .'page='. ($page - 1) .' "aria-label="Назад"><span aria-hidden="true">«</span></a>';
		if ($page != 1) echo '<a class="nav nav_2" href="'. $link .'page=1">1</a>';
		else echo '<a class="nav nav_current" href="#">1</a>';
		for ($ot = -3; $ot <= 3; $ot++) {
			if ($page + $ot > 1 && $page + $ot < $k_page) {
				if ($ot == -3 && $page + $ot > 3) echo '<a class="nav nav_none" href="#">...</a>';
				if ($ot != 0) echo '<a class="nav nav_4" href="'. $link .'page='. ($page + $ot) .'">'. ($page + $ot) .'</a>';
				else echo '<a class="nav nav_current" href="#">'. ($page + $ot) .'</a>';
			}
		}
		if ($page != $k_page) echo '<a class="nav nav_link" href="'. $link .'page=end">'. $k_page .'</a>';
		elseif ($k_page > 1) echo '<a class="nav nav_current" href="#">'. $k_page .'</a>';
			if ($page < $k_page) echo '<a class="nav nav_link" href="'. $link .'page='. ($page + 1) .'"aria-label="Далее"><span aria-hidden="true">»</span></a>';
		echo '</div>';
	}
	
	function getIP($mode=false){
		$xmode = "nginx";
		$key = ($xmode == "nginx"?"HTTP_X_REAL_IP":"REMOTE_ADDR");
		if ($mode){
			return $this->FilterString(!isset($_SERVER[$key])?'* error *':$_SERVER[$key]);
		}
		return $this->FilterString(!isset($_SERVER[$key])?false:$_SERVER[$key]);
	}
	
	function getUA($mode=false){
		if ($mode){
			return $this->FilterString(!isset($_SERVER["HTTP_USER_AGENT"])?'* error *':$_SERVER["HTTP_USER_AGENT"]);
		}
		return $this->FilterString(!isset($_SERVER["HTTP_USER_AGENT"])?false:$_SERVER["HTTP_USER_AGENT"]);
	}
	
	function sverIPUA($IP,$UA,$U1=false,$U2=false){
		if ($U1 !== false && $U1 == $U2){
			return true;
		}
		if ($IP == $this->getIP() && $UA == $this->getUA()){
			return true;
		}
		return false;
	}

	function wwwValid($url){
		if ($url == "admin" || $url == "panel" || $url == "control" || $url == "porno"){
			return false;
		} elseif ($this->checkString($url,"hentai") || $this->checkString($url,"ero") || $this->checkString($url,"xxx") || $this->checkString($url,"porno") || $this->checkString($url,"porn")){
			return false;
		} else {
			return true;
		}
	}
	
	function checkString($s1,$s2){
		// PHP 8
		if (phpversion() >= 8){
			if (str_contains($s1,$s2)){
				return true;
			} else {
				return false;
			}
		} else {
			if (strpos($s1,$s2) !== false){
				return true;
			} else {
				return false;
			}
		}
	}
	
	function RealFileSize($data){
		if($data) {
                if( $data < 1024 ) {
                        return $data . " б";
                } else if( $data < 1048576 ) {
                        return round( ( $data / 1024 ), 2 ) . " кб";
                } else if( $data < 1073741824 ) {            
                        return round( ( $data / 1048576 ), 2 ) . " мб";
                } else {    
                        return round( ( $data / 1073741824 ), 2 ) . " гб";
                }
        }
		return "0 б";
	}
	
	function checkEdit($ext = "html"){
		$list_a = [
			"html"=>"html","css"=>"css","js"=>"js","json"=>"json","txt"=>"txt"
		];
		if (isset($list_a[$ext])){
			return true;
		} else {
			return false;
		}
	}
	
	
	function translist($text){
		$c = [
			'й'	=> 'y',		'ъ'	=> '',		'э'	=> 'io',
			'ц'	=> 'c',		'ф'	=> 'f',		'я'	=> 'ya',
			'у'	=> 'u',		'ы'	=> '',		'ч'	=> 'ch',
			'к'	=> 'k',		'в'	=> 'v',		'с'	=> 's',
			'е'	=> 'e',		'а'	=> 'a',		'м'	=> 'm',
			'н'	=> 'n',		'п'	=> 'p',		'и'	=> 'i',
			'г'	=> 'g',		'р'	=> 'r',		'т'	=> 't',
			'ш'	=> 'sh',	'о'	=> 'o',		'ь'	=> '',
			'щ'	=> 'sha',	'л'	=> 'l',		'б'	=> 'b',
			'з'	=> 'z',		'д'	=> 'd',		'ю'	=> 'yo',
			'х'	=> 'x',		'ж'	=> 'zh',	'ё'	=> 'e',
			
			'Й'	=> 'Y',		'Ъ'	=> '',		'Э'	=> 'IO',
			'Ц'	=> 'C',		'Ф'	=> 'F',		'Я'	=> 'YA',
			'У'	=> 'U',		'Ы'	=> '',		'Ч'	=> 'CH',
			'К'	=> 'K',		'В'	=> 'V',		'С'	=> 'S',
			'Е'	=> 'E',		'А'	=> 'A',		'М'	=> 'M',
			'Н'	=> 'N',		'П'	=> 'P',		'И'	=> 'I',
			'Г'	=> 'G',		'Р'	=> 'R',		'Т'	=> 'T',
			'Ш'	=> 'SH',	'О'	=> 'O',		'Ь'	=> '',
			'Щ'	=> 'SHA',	'Л'	=> 'L',		'Б'	=> 'B',
			'З'	=> 'Z',		'Д'	=> 'D',		'Ю'	=> 'YO',
			'Х'	=> 'X',		'Ж'	=> 'ZH',	'Ё'	=> 'E',
		];
		$result = strtr($text,$c);
		return $result;
	}
}
class User {
	private $db = null;
	// CurrentID
	public $uid = 0;
	private $sid = 0;
	private $uobject = null;
	public function __construct($db){
		$this->db = $db;
		return true;
	}
	// Установка ID-сайта
	public function setSiteID($id = 0){
		$this->sid = intval($id);
	}
	// Получить информацию по ID
	public function getID($id=0){
		#$this->id = intval($id);
		$this->uobject = $this->db->getObject("SELECT * FROM `sites` WHERE `id` = '".$this->id."' '");
	}
	
	// Получить информацию по Login
	public function getUser($login){
		$this->uobject = $this->db->getObject("SELECT * FROM `sites` WHERE `login` = '".$login."'");
		#$this->uid = $this->uobject->id;
	}
	
	// Получить информацию по email
	public function getEmail($email){
		$this->uobject = $this->db->getObject("SELECT * FROM `sites` WHERE `email` = '".$email."'");
		#$this->uid = $this->uobject->id;
	}
	// Проверка наличия пользователя по ID
	public function checkID($id=0){
		$this->id = intval($id);
		if ($this->db->Count("sites","WHERE `id` = '".$this->id."'") == 0){
			return false;
		} else {
			return true;
		}
	}
	
	function fullInfoID($id=0){
		if ($this->checkID($id)){
			$u = $this->getID($id);
			return [
				"id"	=>	$id,
				"login"	=>	$u->login
			];
		} else {
			return [
				"id"	=>	$id,
				"login"	=>	"Удален"
			];
		}
	}
	
	function getUsername(){
		return $this->auth()?$this->getData()->login:'Гость';
	}
	
	public function authUser($l,$p){
		if ($this->db->Count("sites","WHERE `domain` = '".$l."' AND `password` = '".$p."'") == 0){
			return false;
		} else {
			$this->uobject = $this->db->getObject("SELECT * FROM `sites` WHERE `domain` = '".$l."' AND `password` = '".$p."'");
			$this->uid = $this->uobject->id;
			return true;
		}
	}
	
	public function getData(){
		return $this->uobject;
	}
	
	public function auth(){
		return $this->uobject!=NULL?true:false;
	}
	
	function getIP($mode=false){
		if ($mode){
			return $this->FilterString(!isset($_SERVER["REMOTE_ADDR"])?'* error *':$_SERVER["REMOTE_ADDR"]);
		}
		return $this->FilterString(!isset($_SERVER["REMOTE_ADDR"])?false:$_SERVER["REMOTE_ADDR"]);
	}
	
	function getUA($mode=false){
		if ($mode){
			return $this->FilterString(!isset($_SERVER["HTTP_USER_AGENT"])?'* error *':$_SERVER["HTTP_USER_AGENT"]);
		}
		return $this->FilterString(!isset($_SERVER["HTTP_USER_AGENT"])?false:$_SERVER["HTTP_USER_AGENT"]);
	}
	
	public function FilterString($string){
		return trim(htmlspecialchars(mysqli_real_escape_string($this->db->link,$string)));
	}
	
	public function updateOnline(){
		$this->db->Query("UPDATE `sites` SET `lastVisit`='".(time())."' ,`ip`='".($this->getIP(1))."',`ua`='".($this->getUA(1))."' ".($this->getData()->ipreg == null?",`ipreg`='".$this->getIP(1)."'":null)." WHERE `id` = '".$this->uid."'");
	}
	
	public function currentDesign(){
		if ($this->auth()){
			return $this->getData()->panelDesign;
		}
		return "dark";
	}
	
	public function textGroup($lvl = null){
		$lvl = ($lvl===null?$this->getData()->access:$lvl);
		switch ($lvl){
			case 1: {
				return 'Пользователь';
			}
			case 2:{
				return 'VIP-пользователь';
			}
			case 3:{
				return 'Модератор';
			}
			case 4:{
				return 'Администратор';
			}
			default:{
				return 'Гость';
			}
		}
	}
	
}
class Quota {
	private $path = null;
	private $current = 0;
	private $max = 0;
	public function __construct($path,$maxMB=10){
		$this->path = $path;
		$this->max = 1024*$maxMB*1024;
		return true;
	}
	public function getCurrentSpace(){
		return $this->current;
	}
	public function getMaxSpace(){
		return $this->max;
	}
	
	public function getFreeSpace(){
		return $this->getMaxSpace()-$this->getCurrentSpace();
	}
	
	public function setMaxSpace($max){
		$this->max = $max;
	}
	public function setCurrentSpace($byte){
		$this->current = $byte;
	}
	public function RealSize($byte=0){
		if($byte) {
                if( $byte < 1024 ) {
                        return $byte . " б";
                } elseif( $byte < 1048576 ) {
                        return round( ( $byte / 1024 ), 2 ) . " кб";
                } elseif( $byte < 1073741824 ) {            
                        return round( ( $byte / 1048576 ), 2 ) . " мб";
                } else {    
                        return round( ( $byte / 1073741824 ), 2 ) . " гб";
                }
        }
		return "0 б";
	}
	
	public function SizeDir($path=false){
		$dir = (!$path?$this->path:$path);
		$f_size = 0;
		$dh = opendir ($dir);
		while ($file = readdir($dh)) {
			if($file!="." && $file!="..") {
				$fullpath = $dir."/".$file;
				if(!is_dir($fullpath)){
					$f_size = $f_size + filesize($fullpath);
				} else {
					$f_size = $f_size + $this->SizeDir($fullpath);
				}
			}
		}
		closedir ($dh);
		return ($f_size);
	}
	
	function getProcent(){
		$pr = round((($this->current*100)/($this->max)),2);
		return ($pr>100?100:$pr);
	}
	
	//  Проверяет возможность создавать, загружать, сохранять файлы
	function isWrite(){
		if ($this->max <= $this->current){
			return false;
		} else {
			return true;
		}
	}
	
	// Проверяет возможность загружать файлы
	function isLoad($byte=0){
		if (!$this->isWrite()){
			return false;
		}
		if ($this->current+$byte > $this->max){
			return false;
		}
		return true;
	}
}
if ($dbini->get("install","DataBase") == 0){
	echo '<div style="color: #fff;background: #ca6760;padding: 4px;border: 1px solid #ddd;border-radius: 4px;">Панель управления еще не готова к работе.</div>';
	die();
}
$db = new DataBase($dbini->get("host","DataBase"),$dbini->get("login","DataBase"),$dbini->get("pass","DataBase"),$dbini->get("name","DataBase"));
if (!$db->link) { 
	echo '<div style="color: #fff;background: #ca6760;padding: 4px;border: 1px solid #ddd;border-radius: 4px;">Неудалось подключиться к базе данных.<br>Повторите попытку позднее.</div>';
    exit; 
}
$core = new Core($db,$sys);
$user = new User($db);

$id = isset($_GET["id"]) && !empty($_GET["id"])?intval($_GET["id"]):0;
$act = isset($_GET["act"]) && !empty($_GET["act"])?$core->FilterString($_GET["act"]):false;
if (isset($_COOKIE['gLPD']) && isset($_COOKIE['gLPP'])) {
	if (!$user->authUser($core->FilterString($_COOKIE['gLPD']),$core->FilterString($_COOKIE['gLPP']))){
		setcookie('gLPD', "", time() - 3600,'/');
		setcookie('gLPP', "", time() - 3600,'/');
		session_destroy();
		$core->GoToPage("?");
	}
	$user->updateOnline();
	if (!is_dir(SITES_ROOT.$user->getData()->domain."/")){
		@mkdir(SITES_ROOT.$user->getData()->domain."/",0777,true);
		$__site_restored = 1;
	}
	$VarIO = new Vars($db, $user->getData()->id);
	$Quota = new Quota(SITES_ROOT.$user->getData()->domain."/");
	$Quota->setMaxSpace($user->getData()->hdd);
	$Quota->setCurrentSpace($Quota->SizeDir());
	$core->Quota = $Quota;
	$siteurl = 'http://'.$user->getData()->domain.'/';
	if ($user->getData()->captcha == NULL){
		$def_cfg_captcha = [
			'letters'	=>	'1234567890',
			'count'	=>	4,
			'path'	=>	'/media/fonts/Comfortaa-Light.ttf',
			'size'	=>	14,
			'minAngle'	=>	-25,
			'maxAngle'	=>	25,
			'minR'	=>	0,
			'maxR'	=>	100,
			'minG'	=>	0,
			'maxG'	=>	100,
			'minB'	=>	0,
			'maxB'	=>	100,
			'w'	=>	120,
			'h'	=>	40,
		];
		$j = json_encode($def_cfg_captcha);
		$db->Query("UPDATE `sites` SET `captcha`='".$j."' WHERE `id` = '".$user->getData()->id."'");
		
	}
	if ($db->Count("stats","WHERE `sid` = '".$user->getData()->id."'") == 0){
		$db->Query("INSERT INTO `stats`(`sid`) VALUES ('".$user->getData()->id."')");
	}
} else {
	$Quota = new Quota(SITES_ROOT);
}

function i($i="",$c="") {return '';}
function h(){return '';}
function hcp(){return '';}
function b($url="",$n="",$t=""){return '';}

function l($u="URL",$t="Text",$i="home",$c=false,$s=false,$text="",$showtext=0){
	return '<div class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
                        <a href="'.$u.'" class="panel panel-default thumbnail cm-thumbnail">
                            <div class="panel-body text-center">
                                <span class="svg-48">
                                    <img src="assets/img/sf/'.$i.'.svg" alt="lock-open">
                                </span>
                                <h4>'.$t.' '.($s!==false?'<span class="count">'.$s.'</span>':null).'</h4> <small>'.$text.'</small>
                            </div>
                        </a>
                    </div>';
}



function array_to_code($del, $array){
	$ret = "";
	foreach ($array as $data){
		$ret .= "<code>".$data."</code>".$del;
	}
	return $ret;
}

function slider_html_gen($header, $html){
	return '<div class="slider-container">
	<div class="slider-header">'.$header.'</div>
	<div class="slider-content">'.$html.'</div>
	</div>';
}

function tooltip_html_gen($text = "Tooltip"){
	return ' data-toggle="tooltip" data-placement="top" title="'.$text.'" ';
}

$_domains = [".glark.ru"];
?>