<?php
require_once ROOT.'/core/libs/Twig/Autoloader.php';
require_once ROOT.'/core/addon_twig_super.php';
Twig_Autoloader::register();

function ellynet($sms){
	echo '<code class="ellynet_debug">'.$sms.'</code>';
	return NULL;
}


function addon_twig_include($path){
	$pathinfo = pathinfo($path, PATHINFO_EXTENSION);
	if ($pathinfo != "html") return ellynet("Файл не является html-страницей");
	twig($path, [], true, false);
}

function addon_twig_hash($string){
	global $core;
	if (!is_string($string) && !is_numeric($string)){
		return ellynet("Объект не является строкой или числом");
	}
	return $core->StringHash("glark".$string."twig");
}

function addon_twig_array_random($array){
	global $core;
	if (!is_array($array)) return ellynet("Объект не является массивом");
	uksort($array, function(){
		return rand(-1, 1);
	});
	return $array;
}

function addon_twig_isEmpty($array){
	global $core;
	if (!is_array($array)) return false;
	return (count($array) <= 0?true:false);
}


function addon_twig_array_debug($array = []){
	global $core;
	if (!is_array($array)) return ellynet("Объект не является массивом");
	echo '<code class="ellynet_debug">';
	var_dump($array);
	echo '</code>';
	return '';
}

function addon_twig_xtime($time = 0){
	global $site;
	if (!is_numeric($time)) $time = 0;
	ini_set('date.timezone', $site->timezone);
	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 addon_twig_cut($string = "", $start = 0, $width = 0){
	if (!is_string($string) || !is_numeric($start) || !is_numeric($width)) return false;
	return mb_strimwidth($string, $start, $width);
}

function pre_twig($array = []){
	global $db, $core, $user, $t, $site, $VarIO;

	$auth = $user->auth()?[
		"auth"		=>	true,
		"id"		=>	$user->uid,
		"login"		=>	isset($user->getData()->login)?$user->getData()->login:"Guest",
		"balls"		=>	$user->getBalls(),
		"access"	=>	$user->getData()->access,
		"ip"		=>	$user->getIP(),
		"ua"		=>	$user->getUA(),
		"group"		=>	$user->textGroup(),
		"vip"		=>	$user->isVip(),
		"more"		=>	getUserInfo($user->uid),
	]:[
		"auth"		=>	false,
		"id"		=>	0,
		"login"		=>	"Guest",
		"balls"		=>	0,
		"access"	=>	0,
		"ip"		=>	$user->getIP(),
		"ua"		=>	$user->getUA(),
		"group"		=>	$user->textGroup(0),
		"vip"		=>	false,
		"more"		=>	null,
	];
	$counts = [];

	$counts["news"] = $db->Count("news","WHERE `sid` = '".$site->id."'");
	$counts["users"] = $db->Count("users","WHERE `sid` = '".$site->id."'");
	$counts["users24h"] = $db->Count("users","WHERE `sid` = '".$site->id."' AND `regTime` > '".(time()-86400)."'");
	$counts["online"] = $db->Count("users","WHERE `sid` = '".$site->id."' AND `lastVisit` > '".(time()-300)."'");
	$counts["chat"] = $db->Count("chat","WHERE `sid` = '".$site->id."'");
	$counts["chat24h"] = $db->Count("chat","WHERE `sid` = '".$site->id."' AND `timeadd` > '".(time()-86400)."'");
	$counts["guets"] = $db->Count("hosts","WHERE `sid` = '".$site->id."' AND `timelast` > '".(time()-300)."'");
	$counts["gb"] = $db->Count("gb","WHERE `sid` = '".$site->id."'");
	if ($user->auth()){
		$counts["notify"] = $db->Count("alert","WHERE `sid` = '".$site->id."' AND `uid` = '".$user->uid."' AND `ready` = '0'");
	} else {
		$counts["notify"] = 0;
	}
	$counts["forumtheme"] = $db->Count("forum_topics","WHERE `sid` = '".$site->id."'");
	$counts["forummess"] = $db->Count("forum_message","WHERE `sid` = '".$site->id."'");
	$counts["forumtheme24h"] = $db->Count("forum_topics","WHERE `sid` = '".$site->id."' AND `timeadd` > '".(time()-86400)."'");
	$counts["forummess24h"] = $db->Count("forum_message","WHERE `sid` = '".$site->id."' AND `timeadd` > '".(time()-86400)."'");
		
	$counts["downloads"] = $db->Count("downloads_file","WHERE `sid` = '".$site->id."'");
	$counts["downloads24h"] = $db->Count("downloads_file","WHERE `sid` = '".$site->id."' AND `timeAdd` > '".(time()-86400)."'");

	$input = [
		"get"	=>	[],
		"post"	=>	[]
	];

	foreach ($_GET as $key => $val){
		$key = $core->FilterString($key);
		$val = $core->FilterString($val);
		$input["get"][$key]	= $val;
	}

	
	foreach ($_POST as $key => $val){
		$key = $core->FilterString($key);
		$val = $core->FilterString($val);
		$input["post"][$key]	= $val;
	}

	$ads = [];
	$_pre_ads = $db->Query("SELECT * FROM `ads` WHERE `sid` = '".$site->id."' ORDER BY `aid` DESC"); 
	while ($ads_this = mysqli_fetch_assoc($_pre_ads)){
		$ads[] = [
			"enabled"	=>	$ads_this["enabled"],
			"name"		=>	$ads_this["name"],
			"url"		=>	$ads_this["url"],
			"data1"		=>	$ads_this["data1"],
			"data2"		=>	$ads_this["data2"],
			"data3"		=>	$ads_this["data3"]
		];
	}

	$legko = [
		"global"	=>	[
			"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),
			"title"		=>  $t,
		],
		"site"		=>	($site != NULL?[
			"id"				=>	$site->id,
			"domain"			=>	$site->domain,
			"name"				=>	$site->name,
			"title"				=>	$site->title,
			"timezone"			=>	$site->timezone,
			"disabledcomm"		=>	$site->disabledcomm,
			"disabledreg"		=>	$site->disabledreg,
			"onlyreg"			=>	$site->onlyreg,
			"hdd"				=>	$site->hdd,
			"changePhoto"		=>	$site->changePhoto,
			"changePhotoSize"	=>	$site->changePhotoSize,
			"balance"			=>	$site->balance,
			"maxFileLoad"		=>	$site->maxFileLoad,
			"forceSSL"			=>	$site->forceSSL,
			"rss"				=>	[
				"enabled"			=>	$site->module_rss_enable,
				"name"				=>	$site->rss_name,
				"desc"				=>	$site->rss_desc,
				"url"				=>	$site->rss_url,
				"author"			=>	$site->rss_author,
			],
			"env"				=>	$VarIO->site,
		]:NULL),
		"user"			=> $auth,
		"input"			=> $input,
		"count"			=> $counts,
		"age"			=> round((time()-$site->timeadd)/86400),
		"date"			=> date('d.m.Y'),
		"times"			=> date('H:i:s'),
		"time"			=> date('H:i'),
		"domain"		=> $core->getSiteURL(),
		"username"		=> $user->getUsername(),
		"ip"			=> $core->getIP(1),
		"ua"			=> $core->getUA(1),
		"ads"			=> $ads,
		"env"			=> $VarIO->personal,
		"error"			=> [
			"count"			=> $core->countError(),
			"list" 			=> $core->showError(),
		],
	];
	return $legko + $array;
}

function twig($file, $array = [], $onlyRoot = false, $die = true){
	global $core, $user, $t, $VarIO;

	$url = (is_file($core->rootPath($file))?$core->rootPath('/'):ROOT.'/default/twig/');
	if ($onlyRoot) {
		$url = $core->rootPath('/');
	}
	$loader = new Twig_Loader_Filesystem($url);
	$twig = new Twig_Environment($loader,[
		"strict_variables"	=> false,
	]);

	$twig->addFunction(new Twig_SimpleFunction('require', 'addon_twig_include'));
	$twig->addFunction(new Twig_SimpleFunction('import', 'addon_twig_include'));

	$twig->addFunction(new Twig_SimpleFunction('hash', 'addon_twig_hash'));
	$twig->addFunction(new Twig_SimpleFunction('xtime', 'addon_twig_xtime'));
	$twig->addFunction(new Twig_SimpleFunction('isEmpty', 'addon_twig_isEmpty'));
	
	$twig->addFunction(new Twig_SimpleFunction('array_debug', 'addon_twig_array_debug'));
	$twig->addFunction(new Twig_SimpleFunction('array_random', 'addon_twig_array_random'));

	
	$twig->addFunction(new Twig_SimpleFunction('cut', 'addon_twig_cut'));
	$twig->addFunction(new Twig_SimpleFunction('super', 'addon_twig_super'));
	

	$policy = new Twig_Sandbox_SecurityPolicy(
		['if', 'for', 'set'],
		['e', 'escape', 'date', 'upper', 'raw', 'lower', 'capitalize', 'title', 'length', 'default','number_format'],
		[],
		[],
		['require', 'array_random', 'hash', 'array_debug', 'xtime', 'isEmpty', 'cut', 'super']
	);

	$sandbox = new Twig_Extension_Sandbox($policy, true);
	$twig->addExtension($sandbox);
	
	$lexer = new Twig_Lexer($twig, [
		'tag_comment'     => array('[cmt.', ']'),
        'tag_block'       => array('[block.', ']'),
        'tag_variable'    => array('[legko.', ']'),
        'whitespace_trim' => '-',
        'interpolation'   => array('[ipl.', ']'),
	]);
	$twig->setLexer($lexer);
	if (isset($_GET["_GLARK_FORCE_API_"])){
		$EllyNet = $VarIO->GetS("ellynet_debug");
		if ($EllyNet != NULL && $EllyNet == 1){
			if ($VarIO->GetS("ellynet_debug_ip") != $core->getIP(0)){
				echo json_encode(["status"	=> "error", "msg"	=>	"IP-addres no allow!"], true);
				die();
			}
			echo json_encode(pre_twig($array), true);
			die();
		} else {
			echo json_encode(["status"	=> "error", "msg"	=>	"Module disabled!"], true);
			die();
		}
	}
	echo $twig->render($file, pre_twig($array));
	if ($die) die();
}

function twig_html($file, $array = []){
	global $core, $user, $t, $VarIO;
	
	$url = $core->rootPath('/');
	$loader = new Twig_Loader_Filesystem($url);
	$twig = new Twig_Environment($loader, [
		"strict_variables"	=> false,
	]);

	$twig->addFunction(new Twig_SimpleFunction('require', 'addon_twig_include'));
	$twig->addFunction(new Twig_SimpleFunction('import', 'addon_twig_include'));

	$twig->addFunction(new Twig_SimpleFunction('hash', 'addon_twig_hash'));
	$twig->addFunction(new Twig_SimpleFunction('xtime', 'addon_twig_xtime'));
	$twig->addFunction(new Twig_SimpleFunction('isEmpty', 'addon_twig_isEmpty'));
	
	$twig->addFunction(new Twig_SimpleFunction('array_debug', 'addon_twig_array_debug'));
	$twig->addFunction(new Twig_SimpleFunction('array_random', 'addon_twig_array_random'));

	
	$twig->addFunction(new Twig_SimpleFunction('cut', 'addon_twig_cut'));
	$twig->addFunction(new Twig_SimpleFunction('super', 'addon_twig_super'));

	$policy = new Twig_Sandbox_SecurityPolicy(
		['if','for','set'],
		['escape', 'date', 'upper', 'raw', 'lower', 'capitalize', 'title', 'length', 'default','number_format'],
		[],
		[],
		['require', 'array_random', 'hash', 'array_debug', 'xtime', 'isEmpty', 'cut', 'super']
	);

	$sandbox = new Twig_Extension_Sandbox($policy, true);
	$twig->addExtension($sandbox);
	$lexer = new Twig_Lexer($twig, [
		'tag_comment'     => array('[cmt.', ']'),
        'tag_block'       => array('[block.', ']'),
        'tag_variable'    => array('[legko.', ']'),
        'whitespace_trim' => '-',
        'interpolation'   => array('[ipl.', ']'),
	]);
	$twig->setLexer($lexer);
	if (isset($_GET["_GLARK_FORCE_API_"])){
		$EllyNet = $VarIO->GetS("ellynet_debug");
		if ($EllyNet != NULL && $EllyNet == 1){
			if ($VarIO->GetS("ellynet_debug_ip") != $core->getIP(0)){
				echo json_encode(["status"	=> "error", "msg"	=>	"IP-addres no allow!"], true);
				die();
			}
			echo json_encode(pre_twig($array), true);
			die();
		} else {
			echo json_encode(["status"	=> "error", "msg"	=>	"Module disabled!"], true);
			die();
		}
	}
	echo $twig->render($core->getPath(), pre_twig($array));
	die();
}