<?php
class Server
{
    private $html  = "<html><title>gLarkServer</title><body>gLarkServer ready!</body></html>";
	private $path  = "/virtual/";
	private $db = null;
	private $core = null;
	private $site = null;
	private $user = null;
	private $id = 0;
	private $act = "";
	public $afterBody = "";
	private $listErrors = [];
	private $counts = [];
	public $access = 0;
	public $sql = "";
    /**
     * Server инициализация
     * @param string $file - Путь к файлу
     */
    function __construct($file,$core,$db,$site,$user=false,$load=1)
    {
        if (is_readable($file)){
            $this->core = $core;
			$this->user = $user;
			$this->db = $db;
			$this->path = $file;
			$this->site = $site;
			if ($load){
				$this->load();
			}
		} else {
            new \Exception("Ошибка считывания файла. Недостаточно прав");
        }
    }

    /**
     * Загрузить файл
     */
    function load(){
       $line = @file_get_contents($this->path);
	   if (!$line){
		   new \Exception("Ошибка считывания файла. Ошибка на стороне сервера.");
	   }
	   $this->html = $line;
    }
	
	public function legkoError($str="",$sms="",$code=0,$trace=false){
		if ($this->site->legkoError == 1){
			$str = $this->core->FilterString($str);
			$sms = $this->core->FilterString($sms);
			$this->listErrors[] = ["line"=>$str,"sms"=>$sms,"code"=>$code,"trace"=>$trace];
		}
	}
	
	public function showLegkoErrors(){
		// 0 - Неизвестно
		// 1 - Ожидается значение из цифер
		// 2 - Ожидается значение из латинских символов
		// 3 - Ожидается значение из цифр и латинских символов
		$add = "";
		foreach ($this->listErrors as $le){
			
			//$add .= '<div id="legkoError-'.($le["trace"]?($le["line"]):$this->core->StringHash($le["line"])).'" data-code="'.$le["code"].'" style="color: #fff;background: #ca6760;padding: 4px;border: 1px solid #ddd;border-radius: 4px;">Ошибка модуля тегов<br>Строчка:'.$le["line"].'<br>Подробности: '.$le["sms"].'<br></div>';
			$add .= '<div id="legkoError-'.($le["trace"]?($le["line"]):$this->core->StringHash($le["line"])).'" data-code="'.$le["code"].'" data-type="legkoError" class="legkoerror">Ошибка модуля тегов<br>Строчка:'.$le["line"].'<br>Подробности: '.$le["sms"].'<br></div>';
		}
		if ($this->findString("<head><body>")){
			$this->html = str_replace("<head><body>","<head><body>".$add,$this->html);
		} elseif ($this->findString("<body>")){
			$this->html = str_replace("<body>","<body>".$add,$this->html);
		} else {
			$this->html .= $add;
		}
	}
	
	function legkoOnlineNick(){
		$_nick_online = "";
		$_nick_array = [];
		if ($this->counts["online"] > 0){
			$_tmp = $this->db->Query("SELECT `id`,`login` FROM `users` WHERE `sid` = '".$this->site->id."' AND `lastVisit` > '".(time()-300)."' LIMIT 10;");
			while ($data = mysqli_fetch_assoc($_tmp)){
				$_nick_array[] = ["id"=>$data["id"],"login"=>$data["login"]];
			}
			foreach ($_nick_array as $_nak => $_nav){
				$_nick_online .= $_nav["login"].(end($_nick_array)["login"] != $_nav["login"]?', ':"");
			}
			if ($this->counts["online"] > 10){
				$_nick_online .= " и еще ".($this->counts["online"]-10)." чел.";
			}
		} else {
			$_nick_online = "никого нет...";
		}
		return $_nick_online;
	}
	
	function legkoUnix(){
		$this->html = preg_replace_callback('/\[legko.unix,(.+)\]/isU',function($d){
			if ($d[1] == "now"){
				return time();
			} elseif (!is_numeric($d[1])){
				$this->legkoError($d[0],"Ожидается параметр в формате Unix.");
				return $this->core->FilterString($d[0]);
			} elseif ($d[1] < 0){
				$this->legkoError($d[0],"Значение должно быть больше нуля");
				return $this->core->FilterString($d[0]);
			}
			$k = intval($d[1]);
			return $this->core->RealTime($k);
		},$this->html);
	}
	
	function legkoNews(){
		if ($this->counts["news"] > 0){
			$news = $this->db->getObject("SELECT * FROM `news` WHERE `sid` = '".$this->site->id."' ORDER BY `nid` DESC LIMIT 1");
		}
		$this->html = preg_replace('/\[legko.news\]/isU', ($this->counts["news"] > 0?$news->ntitle:NULL), $this->html);
		$this->html = preg_replace('/\[legko.newsdate\]/isU', ($this->counts["news"] > 0?$this->core->RealTime($news->ntime):NULL), $this->html);
		$this->html = preg_replace('/\[legko.newstext\]/isU', ($this->counts["news"] > 0?$this->core->drawString($news->ntext):NULL), $this->html); 
	}
	
	function sqlDebugger(){
		if ($this->sql != ""){
			$this->html = preg_replace('/\[legko.debuggersql\]/isU', ($this->sql), $this->html);
		}
	}
	
	function legkoID(){
		$this->html = preg_replace('/\[legko.id\]/isU', $this->site->id, $this->html);
	}
	
	function legkoPrivet(){
		$d = date("H");
		if ($d >= 4 && $d < 12){
			$text = "Доброе утро";
		} elseif ($d >= 12 && $d < 18){
			$text = "Добрый день";
		} elseif ($d >= 18 && $d < 23) {
			$text = "Добрый вечер";
		} else {
			$text = "Доброй ночи";
		}
		$this->html = preg_replace('/\[legko.privet\]/isU', $text, $this->html);
	}
	
	function cleanEmpty(){
		$this->html = preg_replace('/\[legko.regonly\]/isU', "", $this->html);
	}
	
	function legkoIfID(){
		$this->html = preg_replace_callback('/\[legko.if.id \=\= (.+)\](.+)\[\/legko.if.id\]/isU',function($d){
			if (!is_numeric($d[1])){
				$this->legkoError($d[0],"Ожидается параметр в формате числа");
				return $this->core->FilterString($d[0]);
			} elseif (intval($d[1]) == $this->id){
				return $d[2];
			} else {
				return "";
			}
		},$this->html);
		
		$this->html = preg_replace_callback('/\[legko.if.id \!\= (.+)\](.+)\[\/legko.if.id\]/isU',function($d){
			if (!is_numeric($d[1])){
				$this->legkoError($d[0],"Ожидается параметр в формате числа");
				return $this->core->FilterString($d[0]);
			} elseif (intval($d[1]) != $this->id){
				return $d[2];
			} else {
				return "";
			}
		},$this->html);
		
		$this->html = preg_replace_callback('/\[legko.if.act \=\= (.+)\](.+)\[\/legko.if.act\]/isU',function($d){
			if ($this->core->FilterString($d[1]) == $this->act){
				return $d[2];
			} else {
				return "";
			}
		},$this->html);
		
		$this->html = preg_replace_callback('/\[legko.if.act \!\= (.+)\](.+)\[\/legko.if.act\]/isU',function($d){
			if ($this->core->FilterString($d[1]) != $this->act){
				return $d[2];
			} else {
				return "";
			}
		},$this->html);
		

	}
	
	
	function legkoIfVIP(){
		$this->html = preg_replace_callback('/\[legko.if.vip\](.+)\[\/legko.if.vip\]/isU',function($d){
			if ($this->user->isVip()){
				return $d[1];
			} else {
				return "";
			}
		},$this->html);
		
		$this->html = preg_replace_callback('/\[legko.if.novip\](.+)\[\/legko.if.novip\]/isU',function($d){
			if (!$this->user->isVip()){
				return $d[1];
			} else {
				return "";
			}
		},$this->html);
	}
	
	function legkoIfAuth(){
		$this->html = preg_replace_callback('/\[legko.if.auth\](.+)\[\/legko.if.auth\]/isU',function($d){
			if ($this->user->auth()){
				return $d[1];
			} else {
				return "";
			}
		},$this->html);
		
		$this->html = preg_replace_callback('/\[legko.if.noauth\](.+)\[\/legko.if.noauth\]/isU',function($d){
			if (!$this->user->auth()){
				return $d[1];
			} else {
				return "";
			}
		},$this->html);
	}
	
	function legkoIfAccess(){
		$this->html = preg_replace_callback('/\[legko.if.moder\](.+)\[\/legko.if.moder\]/isU',function($d){
			if ($this->user->checkAccess(3)){
				return $d[1];
			} else {
				return "";
			}
		},$this->html);
		
		$this->html = preg_replace_callback('/\[legko.if.admin\](.+)\[\/legko.if.admin\]/isU',function($d){
			if ($this->user->checkAccess(4)){
				return $d[1];
			} else {
				return "";
			}
		},$this->html);
	}
	
	function legkoCom(){
		$this->html = preg_replace_callback('/\[legko.com,(.+)\]/isU',function($d){
			if (!preg_match("#^([A-z0-9])+$#ui", $d[1])){
				$this->legkoError($d[0],"Неправильный индентификатор для комментариев");
				return $this->core->FilterString($d[0]);
			} 
			$v = $this->core->FilterString($d[1]);
			$co = $this->db->Count("comments","WHERE `aid` = '".$v."' AND `sid` = '".$this->site->id."'");
			$k = '<a data-type="link" id="link-comm-link" href="/comments.lm?id='.$v.'" class="comm_link">Комментарии <span class="comm_count">'.$co.'</span></a>';
			return $k;
		},$this->html);
	}
	
	function legkoInclude(){
		$this->html = preg_replace_callback('/\[legko.include.(.+)\]/isU',function($d){
			switch ($d[1]){
				case "head":{
					$this->html = preg_replace('/\[legko.include.head\]/isU', "", $this->html);
					$proHead = ($this->site->pro_header == -1?true:($this->site->pro_header > time()?true:false));
					if (!$proHead){
						//$this->legkoError($d[0],"Для использования данного тега, необходим модуль `Кастюмизация страниц`");
						return '<!DOCTYPE html><html lang="ru-RU"><head><meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8"><meta http-equiv="Content-Style-Type" content="text/css"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Страница</title><link rel="stylesheet" type="text/css" href="/css/style.css"><link rel="icon" href="/favicon.ico" type="image/x-icon"></head><body>';
					}
					$_l_path = $this->core->rootPath("/_head.html");
					if (file_exists($_l_path)){
						$server = new Server($_l_path,$this->core,$this->db,$this->site,$this->user);
						$server->legkoAccess();
						$server->legkoTag();
						$server->showLegkoErrors();
						return $server->getHTML();
					}
					return "";
					break;
				}
				case "foot":{
					$this->html = preg_replace('/\[legko.include.foot\]/isU', "", $this->html);
					$proHead = ($this->site->pro_header == -1?true:($this->site->pro_header > time()?true:false));
					if (!$proHead){
						//$this->legkoError($d[0],"Для использования данного тега, необходим модуль `Кастюмизация страниц`");
						return '</body></html>';
					}
					$_l_path = $this->core->rootPath("/_foot.html");
					if (file_exists($_l_path)){
						$server = new Server($_l_path,$this->core,$this->db,$this->site,$this->user);
						$server->legkoAccess();
						$server->legkoTag();
						$server->showLegkoErrors();
						/* if ($this->site->pro_noads < time() && $this->site->pro_noads != -1){
							echo $server->afterBody($this->core->drawADS());
						}
						$server->replaceBody(); */
						return $server->getHTML();
					}
					return "";
					break;
				}
				default: {
					$this->legkoError($d[0],"Неверно указан параметр.");
					return $this->core->FilterString($d[0]);
				}
			}
		},$this->html);
	}
	
	function legkoLastList(){
		$this->html = preg_replace_callback('/\[legko.list.(.+)\.(.+)\]/isU',function($d){
			$count = (isset($d[2]) && !empty($d[2]) && is_numeric($d[2])?intval($d[2]):0);
			if (($count <= 0 || $count > 10) && ($d[1] != "downloadscat")){
				$this->legkoError($d[0],"Количество строк может быть от 1 до 10.");
				return $this->core->FilterString($d[0]);
			}
			//echo $d[1];
			switch ($d[1]){
				case "forum":{
					$msg = "";
					if ($this->db->Count("forum_topics","WHERE `sid` = '".$this->site->id."'") == 0){
						return '<div class="error">Тем на форуме еще нет.</div>';
					}
					$_tmp = $this->db->Query("SELECT *, (SELECT COUNT(*) FROM `forum_message` WHERE `forum_topics`.`tid` = `forum_message`.`tid`) AS `ccc`, (SELECT `forum_message`.`sms` FROM `forum_message` WHERE `forum_topics`.`tid` = `forum_message`.`tid` ORDER BY `mid` DESC LIMIT 1) AS `msg` FROM `forum_topics` WHERE `sid` = '".$this->site->id."' ORDER BY `closed` ASC,`lastUpdate` DESC, `timeadd` DESC LIMIT ".$count.";");
					while ($data = mysqli_fetch_assoc($_tmp)){
						
						$msg .= linkGen('/forum.lm?id='.$data["tid"].'&act=read',$data["name"],[
							"id"			=>	"link-legko-forum",
							"data-id"		=>	$data["tid"],
							"data-name"		=>	htmlentities($data["name"]),
							"data-count"	=>	$data["ccc"],
							"data-closed"	=>	$data["closed"],
							"data-update"	=>	$data["lastUpdate"],
							"data-uid"		=>	$data["uid"],
							"data-miniDesk"	=>	mb_substr(htmlentities($data["msg"]),0,64)."..." ,
						],$data["ccc"]);
						//$msg .= '<a href="/forum.lm?id='.$data["tid"].'&act=read" data-type="link" id="link-legko-forum" class="link" data-id="'.$data["tid"].'" data-name="'.$data["name"].'" data-count="'.$data["ccc"].'" data-closed="'.$data["closed"].'" data-update="'.$data["lastUpdate"].'">'.$data["name"].' <span class="count">'.$data["ccc"].'</span></a>';
					}
					return $msg;
					break;
				}
				case "downloads":{
					$msg = "";
					if ($this->db->Count("downloads_file","WHERE `sid` = '".$this->site->id."'") == 0){
						return '<div class="error">Файлов еще нет.</div>';
					}
					$_tmp = $this->db->Query("SELECT * FROM `downloads_file` WHERE `sid` = '".$this->site->id."' ORDER BY `timeAdd` DESC LIMIT ".$count.";");
					while ($data = mysqli_fetch_assoc($_tmp)){
						$msg .= linkGen('/downloads.lm?id='.$data["dfid"].'&act=view',$data["file"],[
							"id"			=>	"link-legko-file",
							"data-id"		=>	$data["dfid"],
							"data-name"		=>	htmlentities($data["file"]),
							"data-size"		=>	$data["size"],
							//"data-closed"	=>	$data["closed"],
							"data-add"		=>	$data["timeAdd"],
							"data-miniDesk"	=>	mb_substr(htmlentities($data["msg"]),0,64)."..." ,
						],$this->core->Quota->RealSize($data["size"]));
						//$msg .= '<a href="/downloads.lm?id='.$data["dfid"].'&act=view" data-name="'.$data["file"].'" data-size="'.$data["size"].'">'.$data["file"].' <span class="count">'.$this->core->Quota->RealSize($data["size"]).'</span></a>';
					}
					return $msg;
					break;
				}
				case "downloadscat":{
					$msg = "";
					if ($this->db->Count("downloads_cat","WHERE `sid` = '".$this->site->id."' AND `root` = '$count'") == 0){
						return '<div class="error">Категорий еще нет.</div>';
					}
					
					$_tmp = $this->db->Query("SELECT *,`downloads_cat`.`dcid` AS `idx`,((SELECT COUNT(*) FROM `downloads_file` WHERE `downloads_file`.`dcid` = `downloads_cat`.`dcid`)+(SELECT COUNT(*) FROM `downloads_cat` WHERE `root` = `idx`)) AS `ccc` FROM `downloads_cat` WHERE `sid` = '".$this->site->id."' AND `root` = '$count' ORDER BY `name` ASC");
					while ($ns = mysqli_fetch_assoc($_tmp)){
						
						
						$msg .= linkGen('/downloads.lm?id='.$ns["dcid"],$ns["name"],[
						"id"			=>	"link-legko-file-cat",
						"data-type"		=>	"link" ,
						"data-frm"		=>	"folder" ,
						"data-id"		=>	$ns["dcid"],
						"data-name"		=>	$ns["name"],
						"data-count"	=>	$ns["ccc"],
						],$ns["ccc"]);
						//echo '<a data-type="link" id="link-file-cat" data-type="folder" data-id="'.$ns["dcid"].'" data-name="'.$ns["name"].'" data-count="'.$ns["ccc"].'" class="link" href="/downloads.lm?id='.$ns["dcid"].'">'.$ns["name"].'<span class="count">'.$ns["ccc"].'</span></a>';
					}

					return $msg;
					break;
				}
				case "chat":{
					$msg = "";
					if ($this->db->Count("chat","WHERE `sid` = '".$this->site->id."'") == 0){
						return '<div class="error">Сообщений в чате еще нет! Будь первым :)</div>';
					}
					$_tmp = $this->db->Query("SELECT * FROM `chat` WHERE `sid` = '".$this->site->id."' ORDER BY `timeadd` DESC LIMIT ".$count.";");
					while ($data = mysqli_fetch_assoc($_tmp)){
						$u = $this->user->fullInfoID($data["uid"]);
						$msg .= '<div id="legko-chat-list" class="text" data-time="'.$data["timeadd"].'" data-user="'.$u["login"].'" data-uid="'.$u["id"].'" data-msg="'.$this->core->drawString($data["sms"]).'">('.$this->core->RealTime($data["timeadd"]).') '.$this->user->linkUser($u["id"],"?").': '.$this->core->drawString($data["sms"]).'</div>';
						//$msg .= '<a href="/downloads.lm?id='.$data["dfid"].'&act=view" data-type="link" id="link-legko-file" class="link" data-id="'.$data["dfid"].'" data-name="'.$data["file"].'" data-size="'.$data["size"].'">'.$data["file"].' <span class="count">'.$this->core->Quota->RealSize($data["size"]).'</span></a>';
					}
					return $msg;
					break;
				}
				case "gb":{
					$msg = "";
					if ($this->db->Count("gb","WHERE `sid` = '".$this->site->id."' AND `moder` = '1'") == 0){
						return '<div class="error">Сообщений в книге еще нет! Будь первым :)</div>';
					}
					$_tmp = $this->db->Query("SELECT * FROM `gb` WHERE `sid` = '".$this->site->id."' AND `moder` = '1' ORDER BY `timeadd` DESC LIMIT ".$count.";");
					while ($data = mysqli_fetch_assoc($_tmp)){
						$u = $this->user->fullInfoID($data["uid"]);
						$msg .= '<div id="legko-gb-list" class="text" data-time="'.$data["timeadd"].'" data-user="'.$u["login"].'" data-uid="'.$u["id"].'" data-msg="'.$this->core->drawString($data["sms"]).'">('.$this->core->RealTime($data["timeadd"]).') '.$this->user->linkUser($u["id"],"?").': '.$this->core->drawString($data["sms"]).'</div>';
						//$msg .= '<a href="/downloads.lm?id='.$data["dfid"].'&act=view" data-type="link" id="link-legko-file" class="link" data-id="'.$data["dfid"].'" data-name="'.$data["file"].'" data-size="'.$data["size"].'">'.$data["file"].' <span class="count">'.$this->core->Quota->RealSize($data["size"]).'</span></a>';
					}
					return $msg;
					break;
				}
				case "news":{
					$msg = "";
					if ($this->db->Count("news","WHERE `sid` = '".$this->site->id."'") == 0){
						return '<div class="error">Новостей еще нет! Будь первым :)</div>';
					}
					$_tmp = $this->db->Query("SELECT * FROM `news` WHERE `sid` = '".$this->site->id."' ORDER BY `ntime` DESC LIMIT ".$count.";");
					while ($data = mysqli_fetch_assoc($_tmp)){
						
						$msg .= linkGen('/news.lm?id='.$data["nid"].'',$data["ntitle"],[
							"id"			=>	"link-news",
							"data-id"		=>	$data["nid"],
							"data-uid"		=>	$data["uid"],
							"data-title"	=>	$data["ntitle"],
							"data-msg"		=>	$this->core->drawString($data["ntext"]),
							"data-time"	=>	$data["ntime"],
						],$this->core->RealTime($data["ntime"]));
						//$msg .= '<a data-type="link" id="link-news" class="link" href="/news.lm?id='.$data["nid"].'" data-title="'.$data["ntitle"].'" data-msg="'.$this->core->drawString($data["ntext"]).'"> '.$data["ntitle"].' <span class="count">'.$this->core->RealTime($data["ntime"]).'</span></a>';
						//$msg .= '<a href="/downloads.lm?id='.$data["dfid"].'&act=view" data-type="link" id="link-legko-file" class="link" data-id="'.$data["dfid"].'" data-name="'.$data["file"].'" data-size="'.$data["size"].'">'.$data["file"].' <span class="count">'.$this->core->Quota->RealSize($data["size"]).'</span></a>';
					}
					return $msg;
					break;
				}
				default: {
					$this->legkoError($d[0],"Неверно указан параметр.");
					return $this->core->FilterString($d[0]);
				}
			}
		},$this->html);
	}
	
	function legkoTag() {
		global $id,$act,$t,$back,$back;
		$this->id = $id;
		$this->act = $act;
		$this->html = preg_replace('/\[legko.global.id\]/isU', $id, $this->html);
		$this->html = preg_replace('/\[legko.global.act\]/isU', (!$act?"null":$act), $this->html);
		$this->html = preg_replace('/\[legko.global.back\]/isU', (!$back?"null":$back), $this->html);
		$this->html = preg_replace('/\[legko.global.title\]/isU', $t, $this->html);
		$this->legkoInclude();	// Обработчик файлов
		$this->legkoLastList();	// Последние файлы
		$this->legkoDay();		// Обработчик времени дня
		$this->legkoCount();	// Обработка счетчиков
		$this->legkoNews();		// Обработка модуля новостей
		$this->cleanEmpty();	// Отчистка пустышек
		$this->legkoCom();		// Обработка модуля комментариев
		$this->legkoPrivet();	// Обработка модуля Привет
		$this->legkoID();		// LegkoID
		$this->legkoSite();		// Обновляем информацию о названии сайта
		$_nick_online = $this->legkoOnlineNick(); // Вывод списка онлайн
		$this->legkoUnix(); 	// Обработка модуля UNIX
		$this->html = preg_replace('/\[legko.age\]/isU', round((time()-$this->site->timeadd)/86400), $this->html);
		
		$this->html = preg_replace('/\[legko.date\]/isU', date('d.m.Y'), $this->html);
		$this->html = preg_replace('/\[legko.times\]/isU', date('H:i:s'), $this->html);
        $this->html = preg_replace('/\[legko.domain\]/isU', $this->core->getSiteURL(), $this->html);
		$this->html = preg_replace('/\[legko.menu\]/isU', ($this->user->auth()?'<a class="legkomenu" href="/lk.lm">Личный кабинет</a> <span class="legkorz"></span> <a class="legkomenu" href="/exit.lm">Выход</a>':'<a class="legkomenu" href="/login.lm">Войти</a> <span class="legkorz"></span> <a class="legkomenu" href="/reg.lm">Регистрация</a>'), $this->html);
		$this->html = preg_replace('/\[legko.time\]/isU', date('H:i'), $this->html);
		$this->html = preg_replace('/\[legko.online,nick\]/isU', $_nick_online, $this->html);
		$this->html = preg_replace('/\[legko.username\]/isU', $this->user->getUsername(), $this->html);
		$this->html = preg_replace('/\[legko.user.id\]/isU', ($this->user->auth()?$this->user->getData()->id:0), $this->html);
		$this->html = preg_replace('/\[legko.ip\]/isU', $this->core->getIP(1), $this->html);
		$this->html = preg_replace('/\[legko.ua\]/isU', $this->core->getUA(1), $this->html); 
		$this->legkoIfAuth();
		$this->legkoIfVIP();	// Включает условности для VIP
		$this->legkoIfAccess(); // Включает условности для Модераторов и Администраторов
		$this->legkoIfID();
		$this->legkoTrace();	// Включает пользовательскую трассировку
		$this->sqlDebugger();	// Откладка SQL запросов
	}

	function legkoRegOnly(){
		return $this->findString("[legko.regonly]");
	}
	
	function legkoSite(){
		$this->html = preg_replace_callback('/\[legko.site.(.+)\]/isU',function($d){
			switch ($d[1]){
				case "name":{
					return $this->site->name;
					break;
				}
				case "title":{
					return $this->site->title;
					break;
				}
				case "rss.name":{
					return $this->site->rss_name;
					break;
				}
				case "rss.desc":{
					return $this->site->rss_desc;
					break;
				}
				default: {
					$this->legkoError($d[0],"Неверно указан параметр.");
					return $this->core->FilterString($d[0]);
				}
			}
		},$this->html);
	}
	
	function legkoAccess(){
		$this->html = preg_replace_callback('/\[legko.access,(.+)\]/isU',function($d){
			if (!preg_match("#^([a,m,v])+$#ui", $d[1])){
				$this->legkoError($d[0],"Неправильный индентификатор для ограничения уровня доступа.");
				return $this->core->FilterString($d[0]);
			} 
			switch($d[1]){
				case "v":{
					$this->access = 2;
					break;
				}
				case "m":{
					$this->access = 3;
					break;
				}
				case "a":{
					$this->access = 4;
					break;
				}
				default: {
					$this->access = 1;
					break;
				}
			}
			return "";
		},$this->html);
	}
	
	function legkoTrace(){
		$this->html = preg_replace_callback('/\[legko.trace\](.+)\[\/legko.trace\]/isU',function($d){
			$this->legkoError("__emulation.lm:".$this->core->StringHash($d[0]),$d[1],-1,1);
		},$this->html);
	}
	
	function legkoDay(){
		$d = date("H");
		if ($d > $this->site->day1 && $this->site->day2 > $d){
			$v1 = "day";
			$v2 = 1;
		} else {
			$v1 = "night";
			$v2 = 0;
		}
		$this->html = preg_replace('/\[legko.day\]/isU', $v1, $this->html);
		$this->html = preg_replace('/\[legko.day,int\]/isU', $v2, $this->html);
	}
	
	function legkoCount(){
		$this->counts["news"] = $this->db->Count("news","WHERE `sid` = '".$this->site->id."'");
		$this->counts["users"] = $this->db->Count("users","WHERE `sid` = '".$this->site->id."'");
		$this->counts["users24h"] = $this->db->Count("users","WHERE `sid` = '".$this->site->id."' AND `regTime` > '".(time()-86400)."'");
		$this->counts["online"] = $this->db->Count("users","WHERE `sid` = '".$this->site->id."' AND `lastVisit` > '".(time()-300)."'");
		$this->counts["chat"] = $this->db->Count("chat","WHERE `sid` = '".$this->site->id."'");
		$this->counts["chat24h"] = $this->db->Count("chat","WHERE `sid` = '".$this->site->id."' AND `timeadd` > '".(time()-86400)."'");
		$this->counts["guets"] = $this->db->Count("hosts","WHERE `sid` = '".$this->site->id."' AND `timelast` > '".(time()-300)."'");
		$this->counts["gb"] = $this->db->Count("gb","WHERE `sid` = '".$this->site->id."'");
		if ($this->user->auth()){
			$this->counts["notify"] = $this->db->Count("alert","WHERE `sid` = '".$this->site->id."' AND `uid` = '".$this->user->uid."' AND `ready` = '0'");
		} else {
			$this->counts["notify"] = 0;
		}
		$this->counts["forumtheme"] = $this->db->Count("forum_topics","WHERE `sid` = '".$this->site->id."'");
		$this->counts["forummess"] = $this->db->Count("forum_message","WHERE `sid` = '".$this->site->id."'");
		$this->counts["forumtheme24h"] = $this->db->Count("forum_topics","WHERE `sid` = '".$this->site->id."' AND `timeadd` > '".(time()-86400)."'");
		$this->counts["forummess24h"] = $this->db->Count("forum_message","WHERE `sid` = '".$this->site->id."' AND `timeadd` > '".(time()-86400)."'");
		
		$this->counts["downloads"] = $this->db->Count("downloads_file","WHERE `sid` = '".$this->site->id."'");
		$this->counts["downloads24h"] = $this->db->Count("downloads_file","WHERE `sid` = '".$this->site->id."' AND `timeAdd` > '".(time()-86400)."'");
		#$this->sql = $this->counts["notify"];
		$data = $this->counts;
		$this->html = preg_replace_callback('/\[legko.count,(.+)\]/isU',function($d){
			switch ($d[1]){
				
				case "downloads":{
					$this->html = preg_replace('/\[legko.count,downloads\]/isU', $this->counts["downloads"], $this->html);
					return $this->counts["downloads"];
					break;
				}
				
				case "downloads24h":{
					$this->html = preg_replace('/\[legko.count,downloads24h\]/isU', $this->counts["downloads24h"], $this->html);
					return $this->counts["downloads24h"];
					break;
				}
				
				case "forumtheme":{
					$this->html = preg_replace('/\[legko.count,forumtheme\]/isU', $this->counts["forumtheme"], $this->html);
					return $this->counts["forumtheme"];
					break;
				}
				case "forummess":{
					$this->html = preg_replace('/\[legko.count,forummess\]/isU', $this->counts["forummess"], $this->html);
					return $this->counts["forummess"];
					break;
				}
				case "forumtheme24h":{
					$this->html = preg_replace('/\[legko.count,forumtheme24h\]/isU', $this->counts["forumtheme24h"], $this->html);
					return $this->counts["forumtheme24h"];
					break;
				}
				case "forummess24h":{
					$this->html = preg_replace('/\[legko.count,forummess24h\]/isU', $this->counts["forummess24h"], $this->html);
					return $this->counts["forummess24h"];
					break;
				}
				case "news":{
					$this->html = preg_replace('/\[legko.count,news\]/isU', $this->counts["news"], $this->html);
					return $this->counts["news"];
					break;
				}
				case "notify":{
					$this->html = preg_replace('/\[legko.count,notify\]/isU', $this->counts["notify"], $this->html);
					return $this->counts["notify"];
					break;
				}
				case "chat":{
					$this->html = preg_replace('/\[legko.count,chat\]/isU', $this->counts["chat"], $this->html);
					return $this->counts["chat"];
					break;
				}
				case "chat24h":{
					$this->html = preg_replace('/\[legko.count,chat24h\]/isU', $this->counts["chat24h"], $this->html);
					return $this->counts["chat24h"];
					break;
				}
				case "users":{
					$this->html = preg_replace('/\[legko.count,users\]/isU', $this->counts["users"], $this->html);
					return $this->counts["users"];
					break;
				}
				case "users24h":{
					$this->html = preg_replace('/\[legko.count,users24h\]/isU', $this->counts["users24h"], $this->html);
					return $this->counts["users24h"];
					break;
				}
				case "gb":{
					$this->html = preg_replace('/\[legko.count,gb\]/isU', $this->counts["gb"], $this->html);
					return $this->counts["gb"];
					break;
				}
				case "online":{
					$this->html = preg_replace('/\[legko.count,online\]/isU', $this->counts["online"], $this->html);
					return $this->counts["online"];
					break;
				}
				case "guets":{
					$this->html = preg_replace('/\[legko.count,guets\]/isU', $this->counts["guets"], $this->html);
					return $this->counts["guets"];
					break;
				}
				default: {
					$this->legkoError($d[0],"Неверно указан параметр.");
					return $this->core->FilterString($d[0]);
				}
			}
		},$this->html);
		
		
		$this->html = preg_replace('/\[legko.online\]/isU', $this->counts["online"], $this->html);
		$this->html = preg_replace('/\[legko.online,g\]/isU', $this->counts["guets"], $this->html);
		$this->html = preg_replace('/\[legko.online_test\]/isU', $this->counts["online"], $this->html);	
		$this->html = preg_replace('/\[legko.regcount\]/isU', $this->counts["users"], $this->html);
		$this->html = preg_replace('/\[legko.regcount,24h\]/isU', $this->counts["users24h"], $this->html);
	}

	function findString($str){
		if (phpversion() >= 8){
			if (str_contains($this->html,$str)){
				return true;
			} else {
				return false;
			}
		} else {
			if (strpos($this->html,$str) !== false){
				return true;
			} else {
				return false;
			}
		}
	}
	
    function setHTML($html){
		$this->html = $html;
	}
	
	function replaceBody(){
		if ($this->findString("</body></html>")){
			$this->html = str_replace("</body></html>",$this->afterBody."</body></html>",$this->html);
		} elseif ($this->findString("</body>")){
			$this->html = str_replace("</body>",$this->afterBody."</body></html>",$this->html);
		} else {
			$this->html .= $this->afterBody.'</body></html>';
		}
	}
	
	function afterBody($string){
		$this->afterBody .= $string;
	}
	
	function getHTML(){
		return $this->html;
	}
}
