<?php
if (!defined("root")) {
	define("root", $_SERVER['DOCUMENT_ROOT']);
}
$timezone = "Asia/Jakarta";
if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);

if (!function_exists("saltEncoding")) {
	function saltEncoding($toencode, $times=8986) {
		#enchsetenev
		$salt='s+(_a*';
		for($zo=0; $zo<$times; $zo=$zo+1) {
			$toencode=hash('sha512', $salt.$toencode);
			$toencode=md5($toencode.$salt);
		}
		return $toencode;
	}
}
function cleanQuery($string) {
	$setup=cvdb();
	$con=mysql_connect($setup["dbs"], $setup["dbu"], $setup["dbp"]);
	if(! $con)
		showMySQLError("Function: CleanQuery");
	if(get_magic_quotes_gpc())
		$string=stripslashes($string);
	$string=(phpversion()>="4.3.0")?mysql_real_escape_string($string):mysql_escape_string($string);
	return $string;
	if(! mysql_close($con))
		showMySQLError("Function: CleanQuery");
}

function cekpost($pstr, $prep) {
	$returnValue=($pstr!="" && isset($pstr))?$pstr:$prep;
	return $returnValue;
}
function numberToRoman($num) {
	$n=intval($num);
	$result='';
	$lookup=array("M" => 1000, "CM" => 900, "D" => 500, "CD" => 400, "C" => 100, "XC" => 90, "L" => 50, "XL" => 40, "X" => 10, "IX" => 9, "V" => 5, "IV" => 4, "I" => 1);
	foreach($lookup as $roman => $value) {
		$matches=intval($n / $value);
		$result .= str_repeat($roman, $matches);
		$n=$n % $value;
	}
	return $result;
}
function cout($string, $specs=array()) {
	if (!isset($specs)) {
		$specs = array('nl'=>'n');
	}
	$isdev = 0;
	if ($isdev==0) {
		if (strpos($string, "<!--") > 0 && strpos($string, "-->") > 0) {
			$str = $string;
			$needle_start = '<!--';
			$needle_end = '-->';
			$replacement = '';
			$pos = strpos($str, $needle_start);
			$start = $pos === false ? 0 : $pos + strlen($needle_start);

			$pos = strpos($str, $needle_end, $start);
			$end = $pos === false ? strlen($str) : $pos;
			#echo $end.'-';
			#echo $start.'-';
			#echo 'loik..';
			$string = substr_replace($str, $replacement,  $start, $end - $start);
			$string = str_replace('<!---->', '', $string);
		}
	}
	echo $string;
	if (isset($specs)) {
		if (isset($specs["nl"])) {
			if (strtolower($specs["nl"])=="b") echo "<br />";
			if (strtolower($specs["nl"])=="n") echo "\n";
			if (strtolower($specs["nl"])=="w") echo "";
		}
	}
}
function dateFormat($time=NULL, $format=NULL) {
	if (!isset($time)) $time = time();
	if (!isset($format)) $format = 0;
	$s = "";
	$year = date('o', $time);
	$week = date('W', $time);
	switch ($format) {
		case 0: { $s='l, jS M Y'; break; }
	}
	return date($s, $time);
}

function cleanURL($string) {
	$url=str_replace("'", '', $string);
	$url=str_replace('%20', ' ', $url);
	$url=preg_replace('~[^\\pL0-9_]+~u', '-', $url); // substitutes anything but letters, numbers and '_' with separator
	$url=trim($url, "-");
	$url=iconv("utf-8", "us-ascii//TRANSLIT", $url);  // you may opt for your own custom character map for encoding.
	$url=strtolower($url);
	$url=preg_replace('~[^-a-z0-9_]+~', '', $url); // keep only letters, numbers, '_' and separator
	return $url;
}
function generateRandomString($length=30, $usevowels=false) {
	$randomString="";
	$possible="346789bcdfhjkmnprtwxyBCDFGHJKLMNPQRTWXY";
	if($usevowels)
		$possible .= "AUEaue";
	$maxlength=strlen($possible);
	if($length > $maxlength)
		$length=$maxlength;
	$i=0;
	while($i<$length) {
		$char=substr($possible, mt_rand(0, $maxlength - 1), 1);
		if(! strstr($randomString, $char)) {
			$randomString .= $char;
			$i++;
		}
	}
	return $randomString;
}

function printR($parArr) {
	echo'<pre>';print_r($parArr);echo'</pre>';
}
function check_email_address($email) {
	// First, we check that there's one @ symbol, 
	// and that the lengths are right. 
	if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
		// Email invalid because wrong number of characters 
		// in one section or wrong number of @ symbols.
		return false;
	}
	// Split it into sections to make life easier
	$email_array = explode("@", $email);
	$local_array = explode(".", $email_array[0]);
	for ($i = 0; $i < sizeof($local_array); $i++) {
		if
		(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
		'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
		$local_array[$i])) {
			return false;
		}
	}
	// Check if domain is IP. If not, 
	// it should be valid domain name
	if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
		$domain_array = explode(".", $email_array[1]);
		if (sizeof($domain_array) < 2) {
			return false; // Not enough parts to domain
		}
		for ($i = 0; $i < sizeof($domain_array); $i++) {
			if
			(!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
			([A-Za-z0-9]+))$",
			$domain_array[$i])) {
				return false;
			}
		}
	}
	return true;
}
function smartCopy($source, $dest, $folderPermission=0755, $filePermission=0644) {
	$result=false;
	if(is_file($source)) {
		if(is_dir($dest)) {
			if($dest[strlen($dest) - 1]!='/')
				$__dest=$dest."/";
			$__dest .= basename($source);
		} else {
			$__dest=$dest;
		}
		$result=copy($source, $__dest);
		chmod($__dest, $filePermission);
	} elseif(is_dir($source)) {
		if(! is_dir($dest)) {
			@mkdir($dest, $folderPermission);
			chmod($dest, $folderPermission);
		}
		if($source[strlen($source) - 1]!='/')
			$source=$source."/";
		if($dest[strlen($dest) - 1]!='/')
			$dest=$dest."/";
		
		$result=true;
		$dirHandle=opendir($source);
		while(($file=readdir($dirHandle))==true) {
			if($file!="." && $file!="..")
				$result=smartCopy($source.$file, $dest.$file, $folderPermission, $filePermission);
		}
		closedir($dirHandle);
	} else {
		$result=false;
	}
	return $result;
}
function ShowFileExtension($filepath) {
	preg_match('/[^?]*/', $filepath, $matches);
	$string=$matches[0];
	$pattern=preg_split('/\./', $string, - 1, PREG_SPLIT_OFFSET_CAPTURE);
	# check if there is any extension
	if(count($pattern)==1) {
		return 'No File Extension Present';
		exit();
	}
	if(count($pattern) > 1) {
		$filenamepart=$pattern[count($pattern) - 1][0];
		preg_match('/[^?]*/', $filenamepart, $matches);
		return $matches[0];
	}
	return false;
}
function get_client_ip() {
	$ipaddress = '';
	if (getenv('HTTP_CLIENT_IP'))
		$ipaddress = getenv('HTTP_CLIENT_IP');
	else if(getenv('HTTP_X_FORWARDED_FOR'))
		$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
	else if(getenv('HTTP_X_FORWARDED'))
		$ipaddress = getenv('HTTP_X_FORWARDED');
	else if(getenv('HTTP_FORWARDED_FOR'))
		$ipaddress = getenv('HTTP_FORWARDED_FOR');
	else if(getenv('HTTP_FORWARDED'))
		$ipaddress = getenv('HTTP_FORWARDED');
	else if(getenv('REMOTE_ADDR'))
		$ipaddress = getenv('REMOTE_ADDR');
	else
		$ipaddress = 'UNKNOWN';
	return $ipaddress; 
}
function get_client_ip2() {
	// check for shared internet/ISP IP
	if (!empty($_SERVER['HTTP_CLIENT_IP']) && validate_ip($_SERVER['HTTP_CLIENT_IP'])) {
		return $_SERVER['HTTP_CLIENT_IP'];
	}

	// check for IPs passing through proxies
	if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		// check if multiple ips exist in var
		if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false) {
			$iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
			foreach ($iplist as $ip) {
				if (validate_ip($ip))
				return $ip;
			}
		} else {
			if (validate_ip($_SERVER['HTTP_X_FORWARDED_FOR']))
			return $_SERVER['HTTP_X_FORWARDED_FOR'];
		}
	}
	if (!empty($_SERVER['HTTP_X_FORWARDED']) && validate_ip($_SERVER['HTTP_X_FORWARDED']))
		return $_SERVER['HTTP_X_FORWARDED'];
	if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
		return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
	if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && validate_ip($_SERVER['HTTP_FORWARDED_FOR']))
		return $_SERVER['HTTP_FORWARDED_FOR'];
	if (!empty($_SERVER['HTTP_FORWARDED']) && validate_ip($_SERVER['HTTP_FORWARDED']))
		return $_SERVER['HTTP_FORWARDED'];
	
	// return unreliable ip since all else failed
	return $_SERVER['REMOTE_ADDR'];
}
function get_client_ip3() {
	//Just get the headers if we can or else use the SERVER global
	if ( function_exists( 'apache_request_headers' ) ) {
		$headers = apache_request_headers();
	} else {
		$headers = $_SERVER;
	}
	//Get the forwarded IP if it exists
	if ( array_key_exists( 'X-Forwarded-For', $headers ) && filter_var( $headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
		$the_ip = $headers['X-Forwarded-For'];
	} elseif ( array_key_exists( 'HTTP_X_FORWARDED_FOR', $headers ) && filter_var( $headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 )) {
		$the_ip = $headers['HTTP_X_FORWARDED_FOR'];
	} else {
		####$the_ip = filter_var( $_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 );
		$the_ip = $_SERVER['REMOTE_ADDR'];
	}
	return $the_ip;
}
function validate_ip($ip) {
    if (strtolower($ip) === 'unknown')
        return false;

    // generate ipv4 network address
    $ip = ip2long($ip);

    // if the ip is set and not equivalent to 255.255.255.255
    if ($ip !== false && $ip !== -1) {
        // make sure to get unsigned long representation of ip
        // due to discrepancies between 32 and 64 bit OSes and
        // signed numbers (ints default to signed in PHP)
        $ip = sprintf('%u', $ip);
        // do private network range checking
        if ($ip >= 0 && $ip <= 50331647) return false;
        if ($ip >= 167772160 && $ip <= 184549375) return false;
        if ($ip >= 2130706432 && $ip <= 2147483647) return false;
        if ($ip >= 2851995648 && $ip <= 2852061183) return false;
        if ($ip >= 2886729728 && $ip <= 2887778303) return false;
        if ($ip >= 3221225984 && $ip <= 3221226239) return false;
        if ($ip >= 3232235520 && $ip <= 3232301055) return false;
        if ($ip >= 4294967040) return false;
    }
    return true;
}
// just the excerpt
function first_n_words($text, $number_of_words) {
   // Where excerpts are concerned, HTML tends to behave
   // like the proverbial ogre in the china shop, so best to strip that
   $text = strip_tags($text);

   // \w[\w'-]* allows for any word character (a-zA-Z0-9_) and also contractions
   // and hyphenated words like 'range-finder' or "it's"
   // the /s flags means that . matches \n, so this can match multiple lines
   $text = preg_replace("/^\W*((\w[\w'-]*\b\W*){1,$number_of_words}).*/ms", '\\1', $text);

   // strip out newline characters from our excerpt
   return str_replace("\n", "", $text);
}

function getBrowser() {
	$u_agent = $_SERVER['HTTP_USER_AGENT'];
	$bname = 'Unknown';
	$platform = 'Unknown';
	$version= "";
	
    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
		$platform = 'linux';
    } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
		$platform = 'mac';
    } elseif (preg_match('/windows|win32/i', $u_agent)) {
		$platform = 'windows';
    }
    // Next get the name of the useragent yes seperately and for good reason
	if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) {
		$bname = 'Internet Explorer';
		$ub = "MSIE";
	} elseif(preg_match('/Firefox/i',$u_agent)) {
		$bname = 'Mozilla Firefox';
		$ub = "Firefox";
	} elseif(preg_match('/Chrome/i',$u_agent)) {
		$bname = 'Google Chrome';
		$ub = "Chrome";
	} elseif(preg_match('/Safari/i',$u_agent)) {
		$bname = 'Apple Safari';
		$ub = "Safari";
	} elseif(preg_match('/Opera/i',$u_agent)) {
		$bname = 'Opera';
		$ub = "Opera";
	} elseif(preg_match('/Netscape/i',$u_agent)) {
		$bname = 'Netscape';
		$ub = "Netscape";
	}
	
	// finally get the correct version number
	$known = array('Version', $ub, 'other');
	$pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
	if (!preg_match_all($pattern, $u_agent, $matches)) {
		// we have no matching number just continue
	}
	// see how many we have
	$i = count($matches['browser']);
	if ($i != 1) {
		//we will have two since we are not using 'other' argument yet
		//see if version is before or after the name
		if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
			$version= $matches['version'][0];
		} else {
			$version= $matches['version'][1];
		}
	} else {
		$version= $matches['version'][0];
	}
	
	// check if we have a number
	if ($version==null || $version=="") {$version="?";}
	return array(
		'userAgent'	=> $u_agent,
		'name'		=> $bname,
		'version'	=> $version,
		'platform'	=> $platform,
		'pattern'	=> $pattern
	);
}
?>