<?php
define("v","3.0");
header("gLarkServer: ".v);
session_start();
$deb = 1;
if ($deb == 1){
	error_reporting(E_ALL | E_STRICT);
	ini_set('display_errors','On');
} else {
	error_reporting(0);
	ini_set('display_errors','Off');
}
define("ROOT",$_SERVER["DOCUMENT_ROOT"]);
function preName($s){
	if ($s == "core" || $s == "database"){
		return "sys_".$s.".lm";
	} elseif ($s == "rss"){
		return "lenta.lm";
	} elseif ($s == "ceditor"){
		return "ConfigManager_FileMGR.lm";
	} elseif ($s == "twig"){
		return "EllyNet_v3.lm";
	}
	return "application_".$s.".lm";
}
function ErrorHandler($errno,$errstr,$errfile,$errline){
	global $deb;
	$wl = [];
	$wl["application_ServerStatus.lm"][32] = 1;
	$wl["application_ServerStatus.lm"][42] = 1;
	$wl["application_ServerStatus.lm"][52] = 1;
	$wl["application_ServerStatus.lm"][63] = 1;
	$errstr = htmlspecialchars($errstr);
	$apps_name = pathinfo($errfile);
	$apps_name = (preName($apps_name["filename"]));
	$errstr = str_replace(ROOT,"/var/gLarkServer/",$errstr);
	if (isset($wl[$apps_name][$errline])){
		//echo '<div class="error">1Ошибка модуля '.$apps_name.':'.$errline.'. Сообщите администратору о данной проблеме!</div>';
		return true;
	}
	if ($deb==0){
		echo '<div class="error">Ошибка модуля '.$apps_name.':'.$errline.'. Сообщите администратору о данной проблеме!</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"]));
	$errstr = $e->getMessage();
	$errstr = str_replace(ROOT,"/var/gLarkServer/",$errstr);
	if ($apps_name == "application_SecurityPolicy.lm"){
		echo '<div class="error critical" style="color: #F44336;border: 1px solid #f44336;padding: 0.5em;margin: 0;">Нарушение безопастности: '.$errstr.'</div>';
		return false;
	}
	if ($apps_name == "application_Filesystem.lm"){
		echo '<div class="error critical" style="color: #F44336;border: 1px solid #f44336;padding: 0.5em;margin: 0;">Ошибка чтения: '.$errstr.'</div>';
		return false;

	}
	if ($deb==0){
		echo '<div class="error critical" style="color: #F44336;border: 1px solid #f44336;padding: 0.5em;margin: 0;">Ошибка модуля '.$apps_name.':'.$e->getLine().'.<br>Сообщите администратору о данной проблеме!</div>';
		return true;
	}
	echo '<div class="error critical" style="color: #F44336;border: 1px solid #f44336;padding: 0.5em;margin: 0;">Ошибка модуля '.$apps_name.':'.$e->getLine().'<br>Подробности: '.$errstr.'</div>';
}
$reDefineErrorHandler = set_error_handler("ErrorHandler");
set_exception_handler("ExceptionHandler");
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';
class Core {
	private $db = null;
	public  $Quota = null;
	private $errorList = [];
	private $cfg;
	private $smiles = [];
	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,$ua=0){
		$ch = curl_init();
		if ($ua == 0){
			$userAgent = 'gLarkRuBOT/1.0 (http://glark.ru/)';
		} else {
			$userAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36";
		}
		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 GoToPage($url="/"){
		header("Location: ".$url);
		exit();
	}
	
	public function drawString($string){
		global $site;
		if ($site->forum_bbcodes == 0 && $this->getPath() == "/forum.lm"){
			$string = $this->Smiles($string);
			$bb = array(
			'/\\r\\n/si'	=> '<br>',
			);
			$string = preg_replace(array_keys($bb), array_values($bb), $string);
			$string = str_replace('\r\n','<br>',$string);
			return $string;
		}
		$bb = array('~\[url=(.*?)?\](.*?)\[\/url\]~si' => '<a href="$1" target="_blank" class="bb_url">$2</a>',
        '/\[b\](.+)\[\/b\]/isU' => '<b>$1</b>',
        '/\[u\](.+)\[\/u\]/isU' => '<span style="text-decoration:underline;">$1</span>',
        '/\[img\](.+)\[\/img\]/isU' => '<img src="$1" class="bb_code" alt="">',
        '/\[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);
		$string = $this->Smiles($string);
		$string = str_replace('\r\n','<br>',$string);

		$string = preg_replace_callback('/\[userID\](.+)\[\/userID\]/isU',function($d){
			#var_dump($d);
			if (!is_numeric($d[1])){
				return '';
			} else {
				return getUserLink(intval($d[1]));
			}
		}, $string);

		return $string;
	}
	
	public function drawADS(){
		global $site;
			$ads_home = [
			["http://glark.ru/?out=".$site->domain."&ref=".$site->id,"gLark - Конструктор сайтов"],
			["http://glark.ru/?out=".$site->domain."&ref=".$site->id,"Создать свой сайт бесплатно"],
			["http://glark.ru/?out=".$site->domain."&ref=".$site->id,"Бесплатный конструктор сайтов"],
		];
		$ads_vies = $ads_home[rand(0,count($ads_home)-1)];
		$msg = '<div style="font-size: x-small;text-align: center;margin: 4px;"><a href="'.$ads_vies[0].'">'.$ads_vies[1].'</a></div>';
		return $msg;
	}
	
	public function Smiles($string){
		if (count($this->smiles) == 0){
			$a = $this->db->Query("SELECT * FROM `smiles` ORDER BY `id` DESC"); 
			while ($d = mysqli_fetch_assoc($a)){
				$ex = explode(",",$d["code"]);
				foreach ($ex as $dx){
					$this->smiles[] = [
						"id"	=>	$d["id"],
						"code"	=>	$dx,
						"type"	=>	$d["types"],
						"path"	=>	$d["path"]
					];
				}
			}
		}
		//$string = preg_replace($this->smiles["code"], $this->smiles["path"], $string);
		foreach ($this->smiles as $s){
			$string =str_replace($s["code"],"<img src='/smiles.lm?id=".$s["id"]."' alt='".$s["code"]."' class='i_sml'>",$string);
		}
		return $string;
	}
	
	public function RandomString($strings=[],$count=1){
		if (count($strings)<=0){
			return NULL;
		}
		
		$key = array_rand($strings,$count);
		if ($count == 1){
			return $strings[$key];
		} else {
			$_key = [];
			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,
		"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){
		return trim(htmlspecialchars(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 getSiteURL(){
		$url = strtolower($this->FilterString($_SERVER["SERVER_NAME"]));
		$url = str_replace("www.","",$url);
		if ($this->checkAPI()){
			return $this->checkAPI(1);
		}
		return $url;
	}
	
	public function checkAPI($mode=0){
		$url = strtolower($this->FilterString($_SERVER["SERVER_NAME"]));
		$url = str_replace("www.","",$url);
		if ($url == "api.glark.ru" || $url == "api.h6m.ru") return ($mode != 0?$url:false);
		if ($mode != 0){
			$url = str_replace("api.","",$url);
			return $url;
		}
		if (strpos($url,"api.") !== false){
			return true;
		}
		return false;
	}
	
	
	public function rootPath($path=false){
		return ROOT."/sites/".$this->getSiteURL().(!$path?$this->getPath():$path);
	}
	
	public function getPath(){
		$debug = 0;
		if ($this->_debug["enabled"] == 1 && $this->_debug["showPath"] == 1){
			$this->_debug["showPath"] = 2;
			$debug = 1;
		}
		$full_path = $this->FilterString($_SERVER["REQUEST_URI"]);
		$full_path = str_replace("?".$this->FilterString($_SERVER["QUERY_STRING"]),"",$full_path);
		echo ($debug?'<div>FP: -> '.$full_path.'</div>':null);
		if ($full_path == "/"){
			return "/index.html";
		}
		$old_path = explode("/",$full_path);
		$old_path = array_slice($old_path,1);
		if (isset($pi["extension"]) && end($old_path) == ""){
			//var_dump(isset($pi["extension"]),end($old_path));
			array_pop($old_path);
		}
		
		$pi = pathinfo($full_path);
		//var_dump($pi);

		$path = "";
		foreach ($old_path as $p){
			if ($p == ""){
				$path .= '/';
				echo ($debug?'<div>1: -> '.$p.' -> '.$path.'</div>':null);
			} elseif (isset($pi["extension"])){
				$path .= "/".$p;
				echo ($debug?'<div>2: -> '.$p.' -> '.$path.'</div>':null);
			} elseif (end($old_path) == $p && !isset($pi["extension"])){
				$path .= $p."/index.html";
				echo ($debug?'<div>3: -> '.$p.' -> '.$path.'</div>':null);
			} else {
				$path .= "/".$p."";
				echo ($debug?'<div>4: -> '.$p.' -> '.$path.'</div>':null);
			}
		}
		echo ($debug?'<div>P: -> '.$path.'</div><hr>':null);
		return ($path);
	}
	
	public function getVersion(){
		return v;
	}
	
	public function mediaCache(){
		header("Cache-control: public");
		header("Expires: " . gmdate("D, d M Y H:i:s", time() + 60*60*24*7) . " GMT");
	}
	
	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 == "json"){
			header("Content-Type:application/json; charset=UTF-8");
			header('Content-Transfer-Encoding: binary');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
			// Даже дату в будущем указываю
			$dt_tmp=getdate(date('U'));
			header('Expires: '.gmdate('D, d M Y H:i:s',date('U')-(86400*($dt_tmp['wday']-8))).' GMT');
			header('Cache-Control: public, must-revalidate');
			header('Pragma: public');
			return true;
		}  elseif ($ext == "js"){
			header("Content-Type:text/javascript; charset=UTF-8");
			return true;
		} elseif ($ext == "mid"){
			header("Content-Type:audio/midi; charset=UTF-8");
			header('Content-Transfer-Encoding: binary');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
			// Даже дату в будущем указываю
			$dt_tmp=getdate(date('U'));
			header('Expires: '.gmdate('D, d M Y H:i:s',date('U')-(86400*($dt_tmp['wday']-8))).' GMT');
			header('Cache-Control: public, must-revalidate');
			header('Pragma: public');
			$this->mediaCache();
			readfile($path);
			die();
			return true;
		} elseif ($ext == "midi"){
			$this->mediaCache();
			header("Content-Type:audio/x-midi; charset=UTF-8");
			header('Content-Transfer-Encoding: binary');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
			// Даже дату в будущем указываю
			$dt_tmp=getdate(date('U'));
			header('Expires: '.gmdate('D, d M Y H:i:s',date('U')-(86400*($dt_tmp['wday']-8))).' GMT');
			header('Cache-Control: public, must-revalidate');
			header('Pragma: public');
			readfile($path);
			die();
			return true;
		} elseif ($ext == "mp3"){
			$this->mediaCache();
			header("Content-Type:audio/mpeg; charset=UTF-8");
			header('Content-Transfer-Encoding: binary');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
			// Даже дату в будущем указываю
			$dt_tmp=getdate(date('U'));
			header('Expires: '.gmdate('D, d M Y H:i:s',date('U')-(86400*($dt_tmp['wday']-8))).' GMT');
			header('Cache-Control: public, must-revalidate');
			header('Pragma: public');
			readfile($path);
			die();
			return true;
		} elseif ($ext == "css"){
			$this->mediaCache();
			header("Content-Type:text/css; charset=UTF-8");
			header('Content-Transfer-Encoding: binary');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
			// Даже дату в будущем указываю
			$dt_tmp=getdate(date('U'));
			header('Expires: '.gmdate('D, d M Y H:i:s',date('U')-(86400*($dt_tmp['wday']-8))).' GMT');
			header('Cache-Control: public, must-revalidate');
			header('Pragma: public');
			return true;
		} elseif ($ext == "zip" || $ext == "apk"){
			$this->mediaCache();
			header("Content-Type:application/zip");
			header("Content-Transfer-Encoding: Binary");
			header("Content-length: ".filesize($path));
			header('Content-Disposition: attachment; filename="'.basename($path).'"');
			readfile($path);
			die();
			//header("Content-disposition:attachment; filename=".basename($path)."");
			return true;
		} elseif ($ext == "tar"){
			$this->mediaCache();
			header("Content-Type:application/x-tar");
			header("Content-Transfer-Encoding: Binary");
			header("Content-length: ".filesize($path));
			header('Content-Disposition: attachment; filename="'.basename($path).'"');
			readfile($path);
			die();
			//header("Content-disposition:attachment; filename=".basename($path)."");
			return true;
		} elseif ($ext == "7z"){
			$this->mediaCache();
			header("Content-Type:application/x-7z-compressed");
			header("Content-Transfer-Encoding: Binary");
			header("Content-length: ".filesize($path));
			header('Content-Disposition: attachment; filename="'.basename($path).'"');
			readfile($path);
			die();
			//header("Content-disposition:attachment; filename=".basename($path)."");
			return true;
		} elseif ($ext == "cab") {
			$this->mediaCache();
			header("Content-Type: application/vnd.ms-cab-compressed");
			header("Content-Transfer-Encoding: Binary");
			header("Content-length: ".filesize($path));
			header('Content-Disposition: attachment; filename="'.basename($path).'"');
			readfile($path);
			die();
			return true;
		} elseif ($ext == "exe"){
		  $this->mediaCache();
		  header("Content-Type: application/octet-stream");
		  header("Content-Transfer-Encoding: Binary");
		  header("Content-length: ".filesize($path));
		  header('Content-Disposition: attachment; filename="'.basename($path).'"');
		  readfile($path);
		  die();
		  return true;
		} elseif ($ext == "gz"){
			$this->mediaCache();
			header("Content-Type:application/gzip");
			header("Content-Transfer-Encoding: Binary");
			header("Content-length: ".filesize($path));
			header('Content-Disposition: attachment; filename="'.basename($path).'"');
			readfile($path);
			die();
			//header("Content-disposition:attachment; filename=".basename($path)."");
			return true;
		} elseif ($ext == "xml"){
			header("Content-Type:text/xml; charset=UTF-8");
			$this->mediaCache();
			return true;
		} elseif ($ext == "png"){
			header("Content-Type:image/png");
			header('Content-Transfer-Encoding: binary');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
			// Даже дату в будущем указываю
			$dt_tmp=getdate(date('U'));
			header('Expires: '.gmdate('D, d M Y H:i:s',date('U')-(86400*($dt_tmp['wday']-8))).' GMT');
			header('Cache-Control: public, must-revalidate');
			header('Pragma: public');
			$this->mediaCache();
			readfile($path);
			die();
			return true;
		} elseif ($ext == "jpg"){
			header("Content-Type:image/jpeg");
			header('Content-Transfer-Encoding: binary');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
			// Даже дату в будущем указываю
			$dt_tmp=getdate(date('U'));
			header('Expires: '.gmdate('D, d M Y H:i:s',date('U')-(86400*($dt_tmp['wday']-8))).' GMT');
			header('Cache-Control: public, must-revalidate');
			header('Pragma: public');
			$this->mediaCache();
			readfile($path);
			die();
			return true;
		} elseif ($ext == "svg"){
			header("Content-Type:image/svg+xml");
			header('Content-Transfer-Encoding: binary');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
			// Даже дату в будущем указываю
			$dt_tmp=getdate(date('U'));
			header('Expires: '.gmdate('D, d M Y H:i:s',date('U')-(86400*($dt_tmp['wday']-8))).' GMT');
			header('Cache-Control: public, must-revalidate');
			header('Pragma: public');
			$this->mediaCache();
			readfile($path);
			die();
			return true;
		} elseif ($ext == "webp"){
			header("Content-Type:image/webp");
			header('Content-Transfer-Encoding: binary');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
			// Даже дату в будущем указываю
			$dt_tmp=getdate(date('U'));
			header('Expires: '.gmdate('D, d M Y H:i:s',date('U')-(86400*($dt_tmp['wday']-8))).' GMT');
			header('Cache-Control: public, must-revalidate');
			header('Pragma: public');
			$this->mediaCache();
			readfile($path);
			die();
			return true;
		} elseif ($ext == "gif"){
			header("Content-Type:image/gif");
			header('Content-Transfer-Encoding: binary');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
			// Даже дату в будущем указываю
			$dt_tmp=getdate(date('U'));
			header('Expires: '.gmdate('D, d M Y H:i:s',date('U')-(86400*($dt_tmp['wday']-8))).' GMT');
			header('Cache-Control: public, must-revalidate');
			header('Pragma: public');
			$this->mediaCache();
			readfile($path);
			die();
			return true;
		} elseif ($ext == "wepb"){
			header("Content-Type:image/webp");
			header('Content-Transfer-Encoding: binary');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
			// Даже дату в будущем указываю
			$dt_tmp=getdate(date('U'));
			header('Expires: '.gmdate('D, d M Y H:i:s',date('U')-(86400*($dt_tmp['wday']-8))).' GMT');
			header('Cache-Control: public, must-revalidate');
			header('Pragma: public');
			$this->mediaCache();
			readfile($path);
			die();
			return true;
		} elseif ($ext == "ico"){
			header("Content-Type: image/x-icon");
			header('Content-Transfer-Encoding: binary');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
			// Даже дату в будущем указываю
			$dt_tmp=getdate(date('U'));
			header('Expires: '.gmdate('D, d M Y H:i:s',date('U')-(86400*($dt_tmp['wday']-8))).' GMT');
			header('Cache-Control: public, must-revalidate');
			header('Pragma: public');
			$this->mediaCache();
			readfile($path);
			die();
			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_9 nav_link" href="'. $link .'page='. ($page + 1) .'"aria-label="Далее"><span aria-hidden="true">»</span></a>';
		echo '</div>';
	}

	function GetInput($unset_keys = []){
		$clone = $_GET;
		foreach ($unset_keys as $cxz){
			if (isset($_GET[$cxz])) unset($_GET[$cxz]);
		}
		$x = 0;
		$link = '';
		foreach ($_GET as $key => $val){
			$key = $this->FilterString($key);
			$val = $this->FilterString($val);
			$link .= "&".$key."=".$val;
		}
		return $link;
	}

	function twig_page_mod($k_page = 1, $page = 1, $disabled_input = []) {
		$link = '?';

		if ($page < 1) $page = 1;

		$_x = [];
		if ($page > 1) $_x[] = ["page"	=>	($page - 1), "text"	=> "«"];
		if ($page != 1) $_x[] = ["page"	=>	1, "text"	=> "1"];
		else $_x[] = ["page"	=>	1, "text"	=> "1"];
		for ($ot = -3; $ot <= 3; $ot++) {
			if ($page + $ot > 1 && $page + $ot < $k_page) {
				#if ($ot == -3 && $page + $ot > 3) $_x[] = ["page"	=>	"#", "text"	=> "..."];
				if ($ot != 0) $_x[] = ["page"	=>	($page + $ot), "text"	=> ($page + $ot)];
				else $_x[] = ["page"	=>	($page + $ot), "text"	=> ($page + $ot)];;
			}
		}
		if ($page != $k_page) $_x[] = ["page"	=>	"end", "text"	=> $k_page];
		elseif ($k_page > 1) $_x[] = ["page"	=>	$k_page, "text"	=> $k_page];
			if ($page < $k_page) $_x[] = ["page"	=>	($page + 1), "text"	=> "»"];
		return ["current" => $page, "isView" => ($k_page > 1?true:false), "list" => $_x, "url" => $this->GetInput(["page"] + $disabled_input)];
	}
	
	function api_str($k_page = 1, $page = 1) {
		if ($page < 1) $page = 1;
		$c = $page;
		$l = [];
		//$l[$c] = $c;
		if ($page > 1) $l[($page - 1)] = "Назад";
		if ($page != 1) $l[1] = "1";
		else $c = 1;
		for ($ot = -3; $ot <= 3; $ot++) {
			if ($page + $ot > 1 && $page + $ot < $k_page) {
				if ($ot != 0) $l[($page + $ot)] = ($page + $ot);
				else $c = ($page + $ot);
			}
		}
		if ($page != $k_page) $l[$k_page] = $k_page;
		elseif ($k_page > 1)$c = $k_page; 
			if ($page < $k_page)$l[$page + 1] = $page + 1;
		return [
			"current"	=>	$c,
			"isView"	=>	(count($l) > 0?true:false),
			"list"		=>	$l
		];
	}
	
	function getIP($mode=false){
		$xmode = "1nginx";
		$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 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 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 textTrimmer($string){
		$string = preg_replace('/\s+/','',$string);
		return $string;
	}
	
	function addAlert($who,$text,$site,$url = NULL,$utext = NULL){
		$this->db->Query("INSERT INTO `alert`(`sid`, `uid`, `timeadd`, `sms`".($url != NULL?", `url`, `url_text`":null).") VALUES ('".$site."','".$who."','".(time())."','".$text."'".($url != NULL?",'".$url."','".$utext."'":null).")");
	}
	
}
class User {
	private $db = null;
	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){
		return $this->db->getObject("SELECT * FROM `users` WHERE `id` = '".$id."' AND `sid` = '".$this->sid."'");
	}
	
	public function getBalls($id = -1){
		if ($id == -1) $id = $this->uid;
		$chat = $this->db->Count("chat","WHERE `sid` = '".$this->sid."' AND `uid` = '".$id."'");
		$comm = $this->db->Count("comments","WHERE `sid` = '".$this->sid."' AND `uid` = '".$id."'");
		$file = $this->db->Count("downloads_file","WHERE `sid` = '".$this->sid."' AND `uid` = '".$id."'");
		$fmess = $this->db->Count("forum_message","WHERE `sid` = '".$this->sid."' AND `uid` = '".$id."'");
		$ftop = $this->db->Count("forum_topics","WHERE `sid` = '".$this->sid."' AND `uid` = '".$id."'");
		$gb = $this->db->Count("gb","WHERE `sid` = '".$this->sid."' AND `uid` = '".$id."'");
		
		$balls = (
			($chat*1)+
			($comm*1)+
			($file*25)+
			($fmess*2)+
			($ftop*5)+
			($gb*1)
		);
		return $balls;
	}
	
	// Вывести ссылку на профиль
	function linkUser($id,$back=false){
		$ank = $this->fullInfoID($id);
		return '<a href="/profile.lm?id='.$id.'" class="user_link">'.$ank["login"].'</a>';
	}
	
	// Получить информацию по Login
	public function getUser($login){
		return $this->db->getObject("SELECT * FROM `users` WHERE `login` = '".$login."' AND `sid` = '".$this->sid."'");
	}
	
	// Получить информацию по email
	public function getEmail($email){
		return $this->db->getObject("SELECT * FROM `users` WHERE `email` = '".$email."' AND `sid` = '".$this->sid."'");
	}
	// Проверка наличия пользователя по ID
	public function checkID($id=0){
		$this->id = intval($id);
		if ($this->db->Count("users","WHERE `id` = '".$this->id."' AND `sid` = '".$this->sid."'") == 0){
			return false;
		} else {
			return true;
		}
	}
	
	function fullInfoID($id=0){
		if ($id == -1){
			return [
				"id"		=>	$id,
				"login"		=>	"Система",
				"access" 	=>	4,
				"online"	=>	0,
				"vip"		=>	0,
			];
		} elseif ($this->checkID($id)){
			$u = $this->getID($id);
			return [
				"id"		=>	$id,
				"login"		=>	$u->login,
				"access" 	=>	$u->access,
				"online"	=>	($u->lastAction > time()-300?1:0),
				"vip"		=>	($u->vip > time()?1:0),
			];
		} else {
			return [
				"id"		=>	$id,
				"login"		=>	"Удален",
				"access" 	=>	1,
				"online"	=>	0,
				"vip"		=>	0,
			];
		}
	}
	
	function getUsername(){
		return $this->auth()?$this->getData()->login:'Гость';
	}
	
	public function authUser($l,$p){
		if ($this->db->Count("users","WHERE `login` = '".$l."' AND `password` = '".$p."' AND `sid` = '".$this->sid."'") == 0){
			return false;
		} else {
			$this->uobject = $this->db->getObject("SELECT * FROM `users` WHERE `login` = '".$l."' AND `password` = '".$p."' AND `sid` = '".$this->sid."'");
			$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){
		$xmode = "1nginx";
		$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"]);
	}
	
	public function FilterString($string){
		return trim(htmlspecialchars(mysqli_real_escape_string($this->db->link,$string)));
	}
	
	public function updateOnline(){
		$this->db->Query("UPDATE `users` SET `lastVisit`='".(time())."',`ip`='".($this->getIP(1))."',`ua`='".($this->getUA(1))."' ".($this->getData()->ipreg == null?",`ipreg`='".$this->getIP(1)."'":null)." WHERE `id` = '".$this->uid."' AND `sid` = '".$this->sid."'");
	}
	
	
	
	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 'Гость';
			}
		}
	}
	
	public function checkAccess($lvl){
		if (!$this->auth()){
			return false;
		}
		if ($this->getData()->access >= $lvl){
			return true;
		} else {
			return false;
		}
	}
	
	public function textLastURL($url=null){
		$url = ($url===null?$this->getData()->lastURL:$url);
		switch ($url){
			case "/users.lm":{
				return ["Просматривает список пользователей","/users.lm"];
			}
			case "/news.lm":{
				return ["Смотрит новости сайта","/news.lm"];
			}
			case "/gb.lm":{
				return ["В гостевой книге","/gb.lm"];
			}
			case "/uchat.lm":{
				return ["В чате","/uchat.lm"];
			}
			case "/lk.lm":{
				return ["В личном кабинете","/lk.lm"];
			}
			case "/comments.lm":{
				return ["Читает комментарии",false];
			}
			case "/profile.lm":{
				return ["Смотрит чей-то профиль","/profile.lm"];
			}
			case "/avatar.lm":{
				return ["Смотрит на свой аватар","/avatar.lm"];
			}
			case "/forum.lm":{
				return ["Читает форум","/forum.lm"];
			}
			case "/downloads.lm":{
				return ["Ищет файлы в загруз-центре","/downloads.lm"];
			}
			case "/" or "/index.html":{
				return ["На домашней странице","/"];
			}
			default:{
				return ["Где-то на сайте",false];
			}
		}
	}
	
	public function updateLastURL(){
		global $core;
		$full_path = $core->FilterString($_SERVER["REQUEST_URI"]);
		$full_path = str_replace("?".$core->FilterString($_SERVER["QUERY_STRING"]),"",$full_path);
		$this->db->Query("UPDATE `users` SET `lastURL`='".($full_path)."' WHERE `id` = '".$this->uid."' AND `sid` = '".$this->sid."'");
	}
	
	public function isVip(){
		return ($this->auth() && $this->getData()->vip > time());
	}
	
	public function spamUpdate(){
		$this->db->Query("UPDATE `users` SET `lastAction` = '".time()."' WHERE `id` = '".$this->uid."' AND `sid` = '".$this->sid."'");
	}
	
	public function checkSpam(){
		if ($this->getData()->lastAction+15 > time()){
			return true;
		} else {
			return false;
		}
		
	}
}
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 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;
		}
		$current = $this->getCurrentSpace()+$byte;
		if ($current > $this->getMaxSpace()){
			return false;
		}
		return true;
	}
}

function linkGen($href="#",$name="Link",$attr=[],$count=false){
	global $site;
	$a = "";
	if (isset($attr["data-id"]) && !isset($attr["id"])){
		$attr["id"] = $attr["data-id"];
		unset($attr["data-id"]);
	}
	
	$_img = ($site != false && $site->linkImg == 1?'<img src="/images/icons/'.$attr["id"].'.png" alt="* " class="link"/> ':null);
	foreach($attr as $k => $v){
		$a .= " ".$k.'="'.$v.'"';
	}
	if (!$site || $site->linkGen == 0){
		return '<a '.$a.' href="'.$href.'" '.(isset($attr["class"])?' class="'.$attr["class"].'"':' class="link"').' data-type="link">'.$_img.''.$name.' '.($count?'<span class="count">'.$count.'</span>':null).'</a>';
	} else {
		return '<div class="link"><a '.$a.' href="'.$href.'" '.(isset($attr["class"])?' class="'.$attr["class"].'"':' class="link"').' data-type="link">'.$_img.''.$name.' '.($count?'<span class="count">'.$count.'</span>':null).'</a></div>';
	}
}

$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);
$time = time();
$id = isset($_GET["id"]) && !empty($_GET["id"])?intval($_GET["id"]):0;
$act = isset($_GET["act"]) && !empty($_GET["act"])?$core->FilterString($_GET["act"]):false;
$back = isset($_GET["back"]) && !empty($_GET["back"])?$core->FilterString($_GET["back"]):false;
// Проверяем наличие сайта по файлам
$real_name = $core->FilterString($_SERVER["SERVER_NAME"]);
$dom_sh_exec = false;
$dom_sh = $db->getObject("SELECT `sites`.* FROM `domains`,`sites` WHERE `domains`.`sid` = `sites`.`id` AND `domains`.`name` = '".$core->getSiteURL()."'");
if (!file_exists(ROOT."/sites/".$core->getSiteURL()."/") || $db->Count("sites","WHERE `domain` = '".$core->getSiteURL()."'") == 0){
	// Остановочка, так как папка или сайт не создан
	if (!$dom_sh){
		http_response_code(404);
		include_once 'default/siteNoFound.php';
		die();
	} else {
		$dom_sh_exec = true;
		$_SERVER["SERVER_NAME"] = $dom_sh->domain;
	}
}

$site = ($dom_sh_exec?$dom_sh:$db->getObject("SELECT * FROM `sites` WHERE `domain` = '".$core->getSiteURL()."'"));

ini_set('date.timezone', $site->timezone);
if ($site->block == 1){
	http_response_code(403);
	include_once 'default/Block.php';
	die();
}
$VarIO = new Vars($db, $site->id);
$Quota = new Quota(ROOT."/sites/".$site->domain."/");
$Quota->setCurrentSpace($Quota->SizeDir());
$Quota->setMaxSpace($site->hdd);
$core->Quota = $Quota;
$user->setSiteID($site->id);
if (isset($_COOKIE['gLL']) && isset($_COOKIE['gLP'])) {
	if (!$user->authUser($core->FilterString($_COOKIE['gLL']),$core->FilterString($_COOKIE['gLP']))){
		setcookie('gLL', "", time() - 3600,'/');
		setcookie('gLP', "", time() - 3600,'/');
		session_destroy();
		$core->GoToPage("?");
	}
	$user->updateOnline();
	$acl = $db->getObject("SELECT * FROM `users_groups` WHERE `ugid` = '".$user->getData()->userGroup."' LIMIT 1");
} else {
	if ($db->Count("hosts","WHERE `sid` = '".$site->id."' AND `IP` = '".$core->getIP(1)."'") == 0){
		$db->Query("INSERT INTO `hosts`(`sid`, `time`,`timelast`, `IP`, `UA`, `operator`) VALUES ('".$site->id."','".$time."','".$time."','".$core->getIP(1)."','".$core->getUA(1)."','0');");
	} else {
		$db->Query("UPDATE `hosts` SET `timelast`='".$time."',`UA`='".$core->getUA(1)."' WHERE `sid`='".$site->id."' AND `IP`='".$core->getIP(1)."'");
	}
}
if ($db->Count("stats","WHERE `sid` = '".$site->id."'") == 0){
	$db->Query("INSERT INTO `stats`(`sid`) VALUES ('".$site->id."')");
}
$stats_site = $db->getObject("SELECT * FROM `stats` WHERE `sid` = '".$site->id."'");
$c_guest = $db->Count("hosts","WHERE `sid` = '".$site->id."' AND `timelast` > '".(time()-300)."'"); 
$c_users = $db->Count("users","WHERE `sid` = '".$site->id."' AND `lastVisit` > '".(time()-300)."'");
if ($stats_site->mo_u < $c_users || $stats_site->mo_g < $c_guest){
	$mo_u = $stats_site->mo_u < $c_users?$c_users:$stats_site->mo_u;
	$mo_g = $stats_site->mo_g < $c_guest?$c_guest:$stats_site->mo_g;
	$db->Query("UPDATE `stats` SET `mo_u`='".$mo_u."',`mo_g`='".$mo_g."' WHERE `sid`='".$site->id."'");
}
$c_guest = $db->Count("hosts","WHERE `sid` = '".$site->id."' AND `timelast` > '".(time()-86400)."'"); $c_users = $db->Count("users","WHERE `sid` = '".$site->id."' AND `lastVisit` > '".(time()-86400)."'");
if ($stats_site->lastUpdate > time()+86400){
	$db->Query("UPDATE `stats` SET `l_u`='".$stats_site->c_u."',`l_g`='".$stats_site->c_g."',`a_u`=`a_u`+'".$stats_site->c_u."',`a_g`=`a_g`+'".$stats_site->c_g."',`lastUpdate`='".$time."' WHERE `sid`='".$site->id."'");
	$db->Query("DELETE FROM `hosts` WHERE `sid`='".$site->id."'");
} 
if ($stats_site->c_u < $c_users || $stats_site->c_g < $c_guest){
	$mo_u = $stats_site->c_u < $c_users?$c_users:$stats_site->c_u;
	$mo_g = $stats_site->c_g < $c_guest?$c_guest:$stats_site->c_g;
	$db->Query("UPDATE `stats` SET `c_u`='".$mo_u."',`c_g`='".$mo_g."' WHERE `sid`='".$site->id."'");
}

function xldr_path_fix($path){
	$path = str_replace('\\', "",$path);
	$path = str_replace('//', "/",$path);
	$path = str_replace('../', "",$path);
	$path = str_replace('./', "",$path);
	$path = str_replace('\..\\', "",$path);
	$path = str_replace('\.\\', "",$path);
	return $path;
}

function getUserBalls($userID = 0){
	global $site, $VarIO, $db;
	if ($userID <= 0) return 0;
	$news 	= $db->Count("news","WHERE `sid` = '".$site->id."' AND `uid` = '".$userID."'");
	$chat 	= $db->Count("chat","WHERE `sid` = '".$site->id."' AND `uid` = '".$userID."'");
	$comm 	= $db->Count("comments","WHERE `sid` = '".$site->id."' AND `uid` = '".$userID."'");
	$file 	= $db->Count("downloads_file","WHERE `sid` = '".$site->id."' AND `uid` = '".$userID."'");
	$fmess 	= $db->Count("forum_message","WHERE `sid` = '".$site->id."' AND `uid` = '".$userID."'");
	$ftop 	= $db->Count("forum_topics","WHERE `sid` = '".$site->id."' AND `uid` = '".$userID."'");
	$gb 	= $db->Count("gb","WHERE `sid` = '".$site->id."' AND `uid` = '".$userID."'");
		
	$balls 	= (
		($chat 		* intval($VarIO->DefS("module_balls_chat", 1))) +
		($comm 		* intval($VarIO->DefS("module_balls_comments", 1))) +
		($file 		* intval($VarIO->DefS("module_balls_download_file", 25))) +
		($fmess 	* intval($VarIO->DefS("module_balls_forum_message", 5))) +
		($ftop 		* intval($VarIO->DefS("module_balls_forum_topics", 10))) +
		($gb 		* intval($VarIO->DefS("module_balls_guestbook", 1))) +
		($news		* intval($VarIO->DefS("module_balls_news", 3))) +
		0
	);
	return $balls;
}

function getUserInfo($userID = 0){
	global $db, $site;
	$info = [];
	if ($userID <= 0) return $info;
	$user = $db->getAssoc("SELECT `id`,`login`,`email`,`lastVisit`,`regTime`,`access`,`lastURL`,`vip`,`lastAction`,`ipreg`,`ip`,`ua`,`userGroup` FROM `users` WHERE `id` = '".$userID."' AND `sid` = '".$site->id."' LIMIT 1");
	if ($user == NULL) return $info;
	$access = $db->getAssoc("SELECT * FROM `users_groups` WHERE `ugid` = '".$user["userGroup"]."' LIMIT 1");
	unset($user["userGroup"]);
	if ($access != NULL){
		unset($access["ugid"]);
		unset($access["sid"]);
	}
	$user["isOnline"] = ($user["lastVisit"] > time()-300?1:0);
	$user["isVip"] = ($user["vip"] > time()?1:0);
	$user["balls"] = getUserBalls($userID);
	$info = $info + $user;
	$info["acl"] = $access;
	return $info;
}

function getUserLink($userID = 0){
	if ($userID == 0) return '[Система]';
	$user = getUserInfo($userID);
	if (count($user) == 0) return '[УДАЛЕН]';
	return '<a class="gul_info" href="/profile.lm?id='.$user["id"].'">'.$user["login"].'</a>';
}


function user_alert($type = "", $userID = 0, $title = "", $msg ="", $url = ""){
	global $site, $db;
	if ($userID <= 0) return '';
	$time = time();
	#echo "INSERT INTO `alerts`(`sid`, `uid`, `type`, `timeAdd`, `title`, `message`, `url`) VALUES ('".$site->id."', '".$userID."', '".$type ."', '".$time."', '".$title."', '".$msg."', '".$url."')";
	$db->Query("INSERT INTO `alerts`(`sid`, `uid`, `type`, `timeAdd`, `title`, `message`, `url`) VALUES ('".$site->id."', '".$userID."', '".$type ."', '".$time."', '".$title."', '".$msg."', '".$url."')");
	# 
	
}

?>
