<?php
define('TIMEALLOWED', (60*15));
define('TIME_MINUTE', (60));
define('TIME_HOUR', (60*60));
define('TIME_DAY', (60*60*24));
define('TIME_WEEK', (60*60*24*7));
define('TIME_MONTH', (60*60*24*7*5));
define('TIME_YEAR', (60*60*24*365));

define("SQL_DEFAULT_HOST_NAME", "localhost");
define("SQL_DEFAULT_USER", "root");
define("SQL_DEFAULT_PASSWORD", "root");

if(isLogForce()) doLoggerOnce(); 


if(isForced())
{
	if(isBanned(getip())) die();
	if(!isActive())
	{
		if(getAdminLevel(getip())===false) die();
	}
}
function setForceLog($fl)
{
	file_put_contents("/forcelog", $fl?"true":"false");
}
function isLogForce()
{
	$ar = file_get_contents("/forcelog");
	return streq($ar,"true");
	
}

function bcrypt_verify($name, $hash)
{
	return bcrypt($name) == $hash;
}

function bcrypt($str)
{
	return crypt($str, '_J9..rasm');
}

function pa($str)
{
	$out="";
	$col="";
	$level==0;
	$fonttags=0;
	$vr=0;
	for($i=0;$i<strlen($str);$i++)
	{
		if($str[$i] == "\n")
		{
			if($level==1) {
				$out .="<font color=#$col>";
				$vr+=1;
				$col="";
				$level-=1;
			}
			else
				$level+=1;
		}
		elseif($level==1)
		{
			$col.=$str[$i];
		}
		else {
			$out.=$str[$i];
		}
	}
	return $out.str_repeat("</font>", $vr);
}
function phplib($nm)
{
	require_once "/phplib/$nm";
}
function jtostring($val)
{
	$out = "{";
	$keys = array_keys($val);
	for($i=0;$i<count($keys);$i++)
	{
		$key = is_array($keys[$i])?jtostring($keys[$i]):$keys[$i];
		$value = is_array($val[$keys[$i]])?jtostring($val[$keys[$i]]):$val[$keys[$i]];
		
		$out .= "[$key] = [$value]".(($i==(count($keys)-1))?"":", ");
	}
	return $out . "}";
}
function setupNotifications()
{
	jslib("notify.js");
	
}
function isActive()
{
	return streq(file_get_contents("/active"), "true");
}
function getLastMember($array)
{
	$el = end($array);
	reset($array);
	return $el;
}
function arraydup($ar)
{
	return unserialize(serialize($ar));
}
function getSessionInfo($ip=null)
{
	$sql = beginSQL("server");
	$res = mysql_query_return_assoc("SELECT * FROM sessionInfo ".($ip!=null?"WHERE `ip` = '$ip' ":"")."LIMIT 0, 1");
	$ret=null;
	if($res!==false)
	{
		$ret = $res;
	}
	@mysql_free_result_array($res);
	endSQL($sql);
	return $ret;
}
function defaultNotify()
{
	notifyBar("__user_message");
	notifyBar("__temp_message");
	notifyBar("__get_message");
	notifyBar("__server_message");
	
	if(isset($_REQUEST["msg"]))
		js("setNotifyBar('#__get_message', '".$_REQUEST["msg"]."', 2000);");
	js("defnot_set_load_user_message(\"".getip()."\");
		defnot_set_load_server_message();");
}
function startsWith($haystack, $needle) {
    // search backwards starting from haystack length characters from the end
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}
function endsWith($haystack, $needle) {
    // search forward starting from end minus needle length characters
    return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE);
}
function checkTempNotify()
{
	if(tempNotifyExists())
	{
		$vl = readTempNotify();
		js("setNotifyBar('#__temp_message', '".addslashes($vl)."', 3000);");
	}
	
}
function notifyBar($id)
{
	echo("<div class='none' style='font-family: Consolas; font-size: 20px; text-align: center' id='$id'></div>");
}
function getifexists($ar, $vl)
{
	if(isset($ar[$vl])) return $ar[$vl];
	else return null;
}
function jserialise($ar) {return jsserialise($ar);}
function jsserialise($ar)
{
	$keys = array_keys($ar);
	$values = array_values($ar);
	$out = "";
	for($i=0;$i<count($values);$i++)
	{
		
		$key = (is_array($keys[$i])?"array_".base64_encode(jsserialise($keys[$i])):base64_encode($keys[$i]));
		$value = (is_array($values[$i])?"array_".base64_encode(jsserialise($values[$i])):base64_encode($values[$i]));
		
		$out .= "$key-$value\r\n";
	}
	return $out;
}
function setForced($vl)
{
	file_put_contents("/force", $vl?"true":"false");
}
function isForced()
{
	return streq(file_get_contents("/force"), "true");
}
function readUntil($str, $c)
{

	$pos = strpos($str, $c);
	if($pos!==false&&$pos>0)
	{
		return substr($str, 0, $pos-1);
	}
	else return $str;
}
function junserialise($ar) {return jsunserialise($ar);}
function jsunserialise($ar)
{
	$ars= array();
	foreach(explode("\r\n", $ar) as $line)
	{
		if($line!="") {
			$ur = explode("-", $line);
			
			$key = startsWith($ur[0], "array_")?junserialise(base64_decode(substr($ur[0], 6))):base64_decode($ur[0]);
			$value = startsWith($ur[1], "array_")?junserialise(base64_decode(substr($ur[1], 6))):base64_decode($ur[1]);
		
			$ars[$key] = $value;
		}
	}
	return $ars;
}
function formatDateTime($dt)
{
	if($dt<TIME_MINUTE)
		return $dt." seconds ago";
	elseif($dt<TIME_HOUR)
		return round($dt/TIME_MINUTE)." minutes ago";
	elseif($dt<TIME_DAY)
		return round($dt/TIME_HOUR)." hours ago";
	elseif($dt<TIME_WEEK)
		return round($dt/TIME_DAY)." days ago";
	elseif($dt<TIME_MONTH)
		return round($dt/TIME_WEEK)." weeks ago";
	elseif($dt<TIME_YEAR)
		return round($dt/TIME_MONTH)." months ago";
	else
		return (round(($dt/TIME_YEAR)*100.00)/100.00)." years ago";
}
function jss($script)
{
	echo ("<script src='$script'></script>");
}
function jslib($name)
{
	jss("/jslib/$name");
}
function isBanned($ip)
{
	$sql = beginSQL("server");
	$res = mysql_query_return_assoc("SELECT banned FROM sessionInfo WHERE `ip`='$ip'");
	$ret = $res[0]["banned"];
	@mysql_free_result_array($res);
	endSQL($sql);
	return $ret;
}
function redirect($page,$wtime=0)
{
	echo '<meta http-equiv="REFRESH" content="'.$wtime.';url='.$page.'"></HEAD>';
}
function getAdminLevel($ip)
{
	$sql = beginSQL("server");
	$res = mysql_query_return_assoc("SELECT `level` FROM admins WHERE `ip`='$ip'");
	$ret=false;
	if($res != array())
	{
		$ret = $res[0]["level"];
	}
	@mysql_free_result_array($res);
	endSQL($sql);
	return $ret;
}
function banUser($ip)
{
	$sql = beginSQL("server");
	mysql_query("UPDATE sessionInfo SET
			`banned`=1
		WHERE `ip`='$ip'");
	endSQL($sql);
}
function unbanUser($ip)
{
	$sql = beginSQL("server");
	mysql_query("UPDATE sessionInfo SET
			`banned`=0
		WHERE `ip`='$ip'");
	endSQL($sql);
}
function jquery()
{
	jslib("jquery-1.8.2.js");
	jslib("jquery.base64.js");
}
function js($str)
{
	echo("<script>$str</script>");
}
function issetmultiple($ar, $vls)
{
	$val = true;
	foreach($vls as $r) $val = $val && isset($ar[$r]);
	return $val;
}
function pageinit_n($sql=null)
{
	pageinit($sql);
	jquery();
	jslib("notify.js");
	enableBanCheck();
	doActiveCheck();
}
function pathfix($str)
{
	return str_replace("\\", "/", $str);
}
function sqldate($stamp=null)
{
	return date("y.m.d H.i.s", $stamp==null?time():$stamp);
}
function enableBanCheck()
{
	jslib("check.js");
	js("banCheck();");
	if(isBanned(getip())) doBan();
}
function activeNotifyBar($id, $val)
{
	echo("<div class='notify' style='font-family: Consolas; font-size: 20px; text-align: center' id='$id'>$val</div>");
}
function doActiveCheck()
{
	if(!isActive()) {
		if(getAdminLevel(getip())!==false)
		{
			echo("<div class='notify' style='font-family: Consolas; font-size: 20px; text-align: center' id='__active_n'>WEBSITE OFFLINE</div>");
		}
		else
			die("website offline");
	}
}
function doBan()
{
	redirect("/banned.php");
	die();
}
function pageinit($vsql=null)
{
	$sql = $vsql==null?beginSQL("server"):$vsql;
	if($vsql!=null)
	{
		mysql_select_db("server",$sql);
	}
	$res = mysql_query_return_assoc("SELECT * FROM `sessionInfo` WHERE `ip`='".getip()."'");
	echo(mysql_error());
	if($res==array())
	{
		mysql_query("INSERT INTO sessionInfo (
			ip, url, sessionid, last
		) VALUES (
			'".getip()."',
			'".geturl()."',
			".(sessionid()==null||streq(sessionid(),"")?"NULL":"'".$_REQUEST["PHPSESSID"]."'").",
			'".date("y.m.d H:i:s")."'
		)");
		echo(mysql_error());
	}
	else
	{
		mysql_query("UPDATE sessionInfo SET 
			url='".geturl()."',
			sessionid=".(sessionid()==null||streq(sessionid(),"")?"NULL":"'".$_REQUEST["PHPSESSID"]."'").",
			
			last='".date("y.m.d H:i:s")."',
			views=views+1
		 WHERE 
			`ip`='".getip()."'
		");
		
		echo(mysql_error());
	}
	@mysql_free_result_array($res);
	doLogger();
	
	if($vsql==null) endSQL($sql);
}
function doLoggerOnce()
{
	$sql = beginSQL("server");
	doLogger();
	endSQL($sql);
}
function setLogAll($l)
{
	file_put_contents("/logall", $l?"true":"false");
}
function isLogAll()
{
	return streq(file_get_contents("/logall"), "true")?true:false;
}
function js_onKeyPress($id, $func, $key)
{
js('$(document).ready(function()
	{
		$("'.$id.'").keypress(function (e){
			if(e.keyCode=='.$key.')
				'.$func.';
		});
	});');
}
function js_onEnterPress($id, $func)
{
	js_onKeyPress($id, $func, 13);
}
function doLogger()
{
	$r = mysql_query_return_assoc("SELECT * FROM logInfo WHERE `ip`='".getip()."'");
	if(($r!=array())||isLogAll())
	{
		mysql_query("INSERT INTO logs (
			ip, url, session, time
		) VALUES (
			'".getip()."',
			'".geturl()."',
			".(sessionid()==null||streq(sessionid(),"")?"NULL":"'".$_REQUEST["PHPSESSID"]."'").",
			'".sqldate()."'
		)");
	}
	else @mysql_free_result_array($r);
}
function writeAllText($fn, $txt)
{
	$p = fopen($fn, "w");
	fwrite($p, $txt);
	fclose($p);
}
function sessionid()
{
	return $_REQUEST["PHPSESSID"];
}
function geturl() {
	$actual_link = "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
	return $actual_link;
}
function getmsg()
{
	$txt = @readalltext("\message");
	if(streq($txt,"")) return NULL;
	return $txt;
}
function button($value, $onclick=null,$other="")
{
	echo("<input type='button' value='$value' ".($onclick==null?"":"onclick='$onclick' ")." $other />");
}
function sessionActive()
{
	return sessionid() !== '';
}
function setTempNotify($msg)
{
	$_SESSION["msg"]=$msg;
}
function tempNotifyExists()
{
	return isset($_SESSION["msg"]);
}
function readTempNotify()
{
	$msg=null;
	if(isset($_SESSION["msg"])) {
		$msg = $_SESSION["msg"];
		unset($_SESSION["msg"]);
	}
	return $msg;
}
function index($ar, $i)
{
	return $ar[$i];
}
function mysql_query_return_assoc($q)
{
	$res = (mysql_query($q));
	$ret=array();
	$i=0;
	
	if(!$res) echo(mysql_error());
	else
		while($cur = mysql_fetch_assoc($res))
		{
			$ret[$i++] = $cur;
		}
	//mysql_free_result($q);
	return $ret;
	
}
function readAllText($fn)
{
	$fp = fopen($fn,"r");
	$data = fread($fp, filesize($fn));
	fclose($fp);
	return $data;
}
function beginSQL($db)
{
	$con = mysql_connect(SQL_DEFAULT_HOST_NAME, SQL_DEFAULT_USER, SQL_DEFAULT_PASSWORD);
	mysql_select_db($db, $con);
	return $con;
}
function endSQL($con)
{
	mysql_close($con);
}
function css($css)
{
	echo '<LINK href="'.$css.'" rel="stylesheet" type="text/css">';
}
function css_main($dir="/")
{
	echo '<LINK href="'.$dir.'css/main.css" rel="stylesheet" type="text/css">';
}
function title($title, $others="",$id=null)
{
	echo "<p id='center' $others class='title' ".($id==null?"":"id='".$id."'").">$title</p>\n";
	echo "<title>$title</title>";
}
function mysql_free_result_array($res)
{
	foreach($res as $re)
		 mysql_free_result($re);
}
function lb()
{
	echo("<br />");
}
function para()
{
	echo("<p />");
}
function validip($ip)
{
	return preg_match("~([0-9]{1,3}[.]){3,3}[0-9]{1,3}~",$ip);
}
function getip() 
{
	if (validip($_SERVER["HTTP_CLIENT_IP"])) {
		return $_SERVER["HTTP_CLIENT_IP"];
	}
	foreach (explode(",",$_SERVER["HTTP_X_FORWARDED_FOR"]) as $ip) {
		if (validip(trim($ip))) {
			return $ip;
		}
	}
	if (validip($_SERVER["HTTP_X_FORWARDED"])) {
		return $_SERVER["HTTP_X_FORWARDED"];
	} elseif (validip($_SERVER["HTTP_FORWARDED_FOR"])) {
		return $_SERVER["HTTP_FORWARDED_FOR"];
	} elseif (validip($_SERVER["HTTP_FORWARDED"])) {
		return $_SERVER["HTTP_FORWARDED"];
	} elseif (validip($_SERVER["HTTP_X_FORWARDED"])) {
		return $_SERVER["HTTP_X_FORWARDED"];
	} else {
		return $_SERVER["REMOTE_ADDR"];
	}
}
function link_tab($res, $txt, $other="")
{
	link($res, $txt, "target='_black' ".$other);
}
function link($res, $txt, $other="")
{
	echo("<a $other href='$res'>$txt</a>");
}
function streq($str,$str2)
{
	return strcmp($str,$str2)==0;
}
function echoline($ln)
{
	echo($ln); lb();
}
function echopara($pa)
{
	echo($pa); para();
}
class Session {
    public static function unserialize($session_data) {
        $method = ini_get("session.serialize_handler");
        switch ($method) {
            case "php":
                return self::unserialize_php($session_data);
                break;
            case "php_binary":
                return self::unserialize_phpbinary($session_data);
                break;
            default:
                throw new Exception("Unsupported session.serialize_handler: " . $method . ". Supported: php, php_binary");
        }
    }

    private static function unserialize_php($session_data) {
        $return_data = array();
        $offset = 0;
        while ($offset < strlen($session_data)) {
            if (!strstr(substr($session_data, $offset), "|")) {
                throw new Exception("invalid data, remaining: " . substr($session_data, $offset));
            }
            $pos = strpos($session_data, "|", $offset);
            $num = $pos - $offset;
            $varname = substr($session_data, $offset, $num);
            $offset += $num + 1;
            $data = unserialize(substr($session_data, $offset));
            $return_data[$varname] = $data;
            $offset += strlen(serialize($data));
        }
        return $return_data;
    }

    private static function unserialize_phpbinary($session_data) {
        $return_data = array();
        $offset = 0;
        while ($offset < strlen($session_data)) {
            $num = ord($session_data[$offset]);
            $offset += 1;
            $varname = substr($session_data, $offset, $num);
            $offset += $num;
            $data = unserialize(substr($session_data, $offset));
            $return_data[$varname] = $data;
            $offset += strlen(serialize($data));
        }
        return $return_data;
    }
	public static function serialize( $array, $safe = true ) {
    
    // the session is passed as refernece, even if you dont want it to
    if( $safe )
        $array = unserialize(serialize( $array )) ;

    //var_dump($array);
    $raw = '' ;
    $line = 0 ;
    $keys = array_keys( $array ) ;
    foreach( $keys as $key ) {
        $value = $array[ $key ] ;
        $line ++ ;
        
        $raw .= $key .'|' ;
        
        if( is_array( $value ) && isset( $value['huge_recursion_blocker_we_hope'] )) {
            $raw .= 'R:'. $value['huge_recursion_blocker_we_hope'] . ';' ;
        } else {
            $raw .= serialize( $value ) ;
        }
        $array[$key] = Array( 'huge_recursion_blocker_we_hope' => $line ) ;
    }
    
    return $raw ;
    
	}
}
?>