<?php
if(!isset($tek_dir)){ $tek_dir=dirname(__FILE__).'/admin'; }
if (strpos($_SERVER['REQUEST_URI'],'?')) { 
    if(!isset($_GET ['ed']) and !strpos($_SERVER['REQUEST_URI'],'?XDEBUG')) die(require ('_pages/404.php'));
    if(($_GET ['ed']!='=1')and($_GET ['ed']!='1')) {
		$_GET['dimg']= str_replace("=","",$_GET['ed']);
		if(mb_substr($_GET['dimg'], 0, 3)!='ed/') $_GET ['ed']=null;
                else $_GET['dimg']=mb_substr($_GET['dimg'],3);
		if(mb_substr($_GET['dimg'], 0, 1)=='_') {
			$getPHP=true;
			$_GET['dimg']=mb_substr($_GET['dimg'],1);
		}
	}
}
if (strpos($_SERVER['REQUEST_URI'],'php')) die(require ('_pages/404.php'));
//header("Access-Control-Allow-Origin:*"); 
session_start();
$my_ses_id=session_id();
if ($_SESSION['import_session']) $import_session=$_SESSION['import_session'];
if($_SESSION['user_admin']) {
	if($_SESSION['user_admin']==true) $_SES_user_admin=true;
}
if($_SESSION['chaynik']) $_SES_chaynik=true;
if($_SESSION['user_email']) $_SES_user_email=$_SESSION['user_email'];
if($_SESSION['type_email']) $_SES_type_email=$_SESSION['type_email'];
session_abort();

if(isset($_GET ['ed'])) {
	if(!$_SES_user_admin){
		if (isset($_POST['login']))
		{	sleep(1);
			require ("admin/user_passw.php");
			if($_POST['login'] != $login) die ("Вы ошиблись");
			if($_POST['pass'] != $pass)	die ("Вы ошиблись");}
		else { header("Location: enter.php?url=".$_SERVER['REQUEST_URI']);	die ("");}
		session_set_cookie_params(300);
		session_start();
			$_SESSION['user_admin'] = true;
			$_SES_user_admin = true;
		session_write_close();
	} 
} else {
	if($_SES_user_admin) unset($_SES_user_admin);
	session_set_cookie_params(6000); 
}
require('settings.php');
$site=$_SERVER['SERVER_NAME'];

if (isset($_GET ['id'])) { $id = $_GET ['id'];	}
	else { $id = "start";}

	if(!isset($_GET ['ed'])and(!isset($_SES_user_admin))and((!isset($_GET['dimg']))or(isset($getPHP)))) { // если не редактирование, то проверим кэш
try { 
		if (!file_exists ($tek_dir.DIRECTORY_SEPARATOR.'cash')) $newDB=true; else $newDB=false;
		$dbcash = new PDO('sqlite:'.$tek_dir.DIRECTORY_SEPARATOR.'cash');
		$dbcash->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
		if($newDB){	
			$res = $dbcash->query('create table if not exists PagesCash (id TEXT, html TEXT,ogranichenie INTEGER, typeogr TEXT)');
			$res = $dbcash->query("INSERT INTO PagesCash (id,html) values ('0', '')");
		}
		$res = $dbcash->query('SELECT id,html,ogranichenie,typeogr from PagesCash where (id="0" or id="'.$id.'") ORDER BY id');
		$res->setFetchMode(PDO::FETCH_ASSOC);
		$htmlid=false;
		while($row = $res->fetch()){
			if($row['id']=="0") $htmlid=true;
			if(($row['id']==$id) and ($htmlid==true)){
				if (($row['ogranichenie']>0)and(!$_SES_user_admin)) { //--------ограничение доступа к странице
				if($_SES_chaynik){
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
					if((mb_strpos($row['html'],'{PHP={')===false)and(mb_strpos($row['html'],'{JS={')===false)) echo $row['html'];
					else {
						include('debug_proba.php');
						echo getAllPhpFunction($id,$row['html']);
					}
					return;
				}
				if(!$_SES_user_email){ header("Location: ogranichenie.php?url=".$_SERVER['REQUEST_URI']); die (""); }
					if($_SES_user_email=="") die("Извините, но доступ к этой странице Вам закрыт!");
					if(($row['ogranichenie']==2)and($_SES_user_email!=$row['typeogr'])) die("Извините, но доступ к этой странице Вам закрыт!");
					if(($row['ogranichenie']==3)and($_SES_type_email!=$row['typeogr'])) die("Извините, но доступ к этой странице Вам закрыт!");
				}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
				if((mb_strpos($row['html'],'{PHP={')===false)and(mb_strpos($row['html'],'{JS={')===false)) echo $row['html'];
				else {
					include('debug_proba.php');
					echo getAllPhpFunction($id,$row['html']);
				}
				return;
			}
		}	
		if(!$htmlid) die("Извините, но этот ресурс сегодня закрыт!!!");
		$htmlid=$id;
	} catch (PDOException $e) { die($e->getMessage());   }
}
if (file_exists ("_pages/content/" . $id . ".php")) { require ("_pages/content/" . $id . ".php");}
else { 
	$links=file("_pages/menu.csv");
	foreach ( $links as $key=>$value) {
		$flag_found=false;
		$tt= explode('<!>',$value) ;
		//$id=mb_convert_encoding($id , "UTF-8", "CP-1251");
		if($id==$tt[1]) {
			$flag_found=true;
			$id=$tt[0];
			if (file_exists ("_pages/content/" . $id . ".php")) { $_GET ['id']=$id; require ("_pages/content/" . $id . ".php"); break;}
			else{ require ('_pages/404.php'); exit;}
		}
	}
	if($flag_found==false)	{ require ('_pages/404.php'); exit;}
}

if (file_exists ("templates/" . $curr_tmpl . "/skin.html")) { $templates = file_get_contents("templates/" . $curr_tmpl . "/skin.html");	}
	else {
		$links= explode('/',$_SERVER['DOCUMENT_ROOT']) ;
		$tt=count($links);
		$cms_root_path='';
		for($i=0;$i<$tt-1;$i++) $cms_root_path.=$links[$i].'/';
		if(!file_exists($cms_root_path."cms_root.php")){
			if(file_exists($cms_root_path."public_html/cms_root.php")) $cms_root_path.="public_html/";
			else if(file_exists($cms_root_path."www/cms_root.php")) $cms_root_path.="www/";
		}
		if (file_exists ($cms_root_path."templates/" . $curr_tmpl . "/skin.html")) { $templates = file_get_contents($cms_root_path."templates/" . $curr_tmpl . "/skin.html");	}
		else {	require ("_pages/error.html"); die ("");}
	}
include ("menu.php");

//require ("_pages/date.php");
$month_arr = array( 1 => 'января', 2 => 'февраля', 3 => 'марта', 4 => 'апреля', 5 => 'мая', 6 => 'июня', 7 => 'июля', 8 => 'августа', 9 => 'сентября', 10 => 'октября', 11 => 'ноября', 12 => 'декабря' );
$month = $month_arr[date('n')];
$day_arr = array(1 => 'понедельник', 2 => 'вторник', 3 => 'среда', 4 => 'четверг', 5 => 'пятница', 6 => 'суббота', 0 => 'воскресенье');
$day = $day_arr[date('w')];
$d = '<font size=1>'.date("Сегодня: $day j $month Y г.").'</font>';

include ("img_fold.php");

if((isset($_GET ['ed']))and($_SES_user_admin)) { 
	$out=str_replace ("</body>","<script>start_for_edit();</script></body>",$out);
	$out=str_replace ("</BODY>","<script>start_for_edit();</script></body>",$out);
	$out=str_replace ("</body>",'<script src="../templates/js/css_edit.js"></script><div align=left draggable="true" id=contextMenuId style="z-index:99;margin:0 !important; display:none;border:1px solid #BBB !important; position:absolute !important; padding:10px !important; background-color:#EEE !important; border-radius:5px;font-size:1em !important;color:#000 !important"></div></div></body>',$out);
}

if((!isset($_GET ['ed'])) and ((!isset($_GET['dimg']))or(isset($getPHP)))){
	if(isset($dbcash)){
	try{
		if(isset($ogranichenie)) $data = array( 'id' => $htmlid, 'html' => $out , 'ogranichenie'=>$ogranichenie,'typeogr'=>$ogranichenie_type);
		else $data = array( 'id' => $htmlid, 'html' => $out , 'ogranichenie'=>0,'typeogr'=>'');  
		$STH = $dbcash->prepare("INSERT INTO PagesCash (id,html,ogranichenie,typeogr) values (:id, :html,:ogranichenie,:typeogr)");  
		$STH->execute($data);
		} catch (PDOException $e) { die($e->getMessage());   }		
	}
}
if(!isset($ogranichenie)) {
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	if((mb_strpos($out,'{PHP={')===false)and(mb_strpos($out,'{JS={')===false)) echo $out;
	else {
		include('debug_proba.php');
		echo getAllPhpFunction($id,$out);
	}
	return;
}
if (($ogranichenie>0)and(!$_SES_user_admin)) { //--------ограничение доступа к странице
	if($_SES_chaynik) {
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	if((mb_strpos($out,'{PHP={')===false)and(mb_strpos($out,'{JS={')===false)) echo $out;
		else {
			include('debug_proba.php');
			echo getAllPhpFunction($id,$out);
		}
		return;
	}
	if(!$_SES_user_email){ header("Location: ogranichenie.php?url=".$_SERVER['REQUEST_URI']); die (""); }
	if($_SES_user_email=="") die("Извините, но доступ к этой странице Вам закрыт!");
	if(($ogranichenie==2)and($_SES_user_email!=$ogranichenie_type)) die("Извините, но доступ к этой странице Вам закрыт!");
	if(($ogranichenie==3)and($_SES_type_email!=$ogranichenie_type)) die("Извините, но доступ к этой странице Вам закрыт!");
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	if((mb_strpos($out,'{PHP={')===false)and(mb_strpos($out,'{JS={')===false)) echo $out;
	else {
		include('debug_proba.php');
		echo getAllPhpFunction($id,$out);
	}
?>