<?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", $string);
	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", $string);
}

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()) {
	$specs = array('nl'=>'n');
	echo $string;
	if (isset($specs)) {
		if (isset($specs["nl"])) {
			if (strtolower($specs["nl"])=="b") echo "<br />";
			if (strtolower($specs["nl"])=="n") echo "\n";
		}
	}
}
function dateFormat($time=NULL, $format=NULL) {
	if (!isset($time)) $time = time();
	if (!isset($format)) $foramt = 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 adminSubMenu($parUrl, $parType, $parLabel) {
	$spanClass = "main";
	$hrefLabel = "Main";
	switch($parType) {
		case "add": { $spanClass = "add"; break; }
		case "edit": { $spanClass = "edit"; break; }
		case "delete": { $spanClass = "delete"; break; }
		case "image": { $spanClass = "image"; break; }
		case "back": { $spanClass = "back"; break; }
	}
	return '<a class="'.$spanClass.'" href="'.$parUrl.'"><span class="'.$spanClass.'"></span> '.$parLabel.'</a>';
}
function textSeparator($par=0) {
	if ($par==0) {
		return '&nbsp;&nbsp;';
	} else {
		return '&nbsp;|&nbsp;';
	}
}
function tdWidth($width=180, $useStyle=0) {
	if ($useStyle==0) {
		return ' width:'.$width.'px; ';
	} else {
		return ' style="width:'.$width.'px;"';
	}
}
function tRowOddEven(&$count) {
	$count = $count + 1;
	if ($count % 2 == 0) {
		return 'reve';
	} else {
		return 'rodd';
	}
}

function genCustomerName($customerName, $firstName, $lastName) {
	if ($customerName!="") {
		$namacustomer = $customerName;
	} else {
		$namacustomer = '';
		if ($firstName!="" || $lastName!="") {
			$namacustomer .= ($namacustomer!=""?' ':'').($firstName!=""?$firstName:'');
			$namacustomer .= ($namacustomer!=""?' ':'').($lastName!=""?$lastName:'');
		} else {
			$namacustomer = '<em>No Name</em>';
		}
	}
	return trim($namacustomer);
}
function checkDateTime($data, $format) {
	if (date('Y-m-d H:i:s', strtotime($data)) == $data) {
		return true;
	} else {
		return false;
	}
}
function genTransactionNo($type, $time=null) {
	switch ($type) {
		case "pb": { $kode = "PB"; $table="purchases"; $field="nopb"; $fieldtgl="tglpb"; break; }
		case "pj": { $kode = "PJ"; $table="sells"; $field="nopj"; $fieldtgl="tglpj"; break; }
		default: { $kode = "AUTO"; }
	}
	$year = date('Y');
	$month = date('m');
	if (isset($time)) {
		$detime = date('Y-m-d H:i:s', strtotime($time));
		if (checkDateTime($detime, 'Y-m-d H:i:s')) {
			$year = date('Y', strtotime($time));
			$month = date('m', strtotime($time));
		}
	}
	$rsn=array();$qn="SELECT $field FROM $table WHERE MONTH(FROM_UNIXTIME($fieldtgl))=".$month." AND YEAR(FROM_UNIXTIME($fieldtgl))=".$year." ORDER BY $field DESC, $fieldtgl DESC LIMIT 0,1";
	
	callRS($rsn, $qn);
	if (count($rsn)!=0) {
		$test = explode("/", $rsn[0][$field]);
		$newTmpNo = intval($test[count($test)-1])+1;
	} else {
		$newTmpNo = 1;
	}
	$tmpNo = "";
	for ($n=5;$n>strlen($newTmpNo);$n--) {
		$tmpNo .= "0";
	}
	$tmpNo .= $newTmpNo;
	$theNumber = $kode."/".$year."/".$month."/".$tmpNo;
	return $theNumber;
	
}
function browseContents($id, $page, $defaultID="", $defaultValue="") {
	switch ($page) {
		case "purchases": {
			$ajaxURL="/_ajax/purchases.php";
			if ($id=="item_id") {
				$deQS="a=callitem&isactive=1";
			}
			if ($id=="customer_id") {
				$deQS="a=callcustomer&isactive=1";
			}
			
			break;
		}
		case "sells": {
			$ajaxURL="/_ajax/sells.php";
			if ($id=="item_id") {
				$deQS="a=callitem&isactive=1";
			}
			if ($id=="customer_id") {
				$deQS="a=callcustomer&isactive=1";
			}
			
			break;
		}
		case "items": {
			$ajaxURL="/_ajax/items.php";
			if ($id=="category_id") {
				$deQS="a=callcategory&isactive=1";
			}
			
			break;
		}
		case "customerprice": {
			$ajaxURL="/_ajax/customerprice.php";
			if ($id=="customer_id") {
				$deQS="a=callcustomer&isactive=1";
			}
			
			break;
		}
		default: { $ajaxURL=""; }
	}
	$str = '';
	if ($ajaxURL!="") {
		$str.= '<div style="float:left;">';
		$str.= '<input type="hidden" name="i'.$id.'" id="i'.$id.'" value="'.$defaultID.'" />';
		$str.= '<input type="text" name="v'.$id.'" id="v'.$id.'" value="'.$defaultValue.'" />';
		$str.= '</div>';
		$str.= '<div style="float:left;">';
		$str.= '<a class="browse" id="browse'.$id.'" href="#" onclick="browseContents(\''.$id.'\', \''.$page.'\');return false;"><img src="/img/book_icon.png" alt="Browse" /></a>';
		$str.= '<a class="clear" id="clear'.$id.'" href="#" onclick="clearContents(\''.$id.'\', \''.$page.'\');return false;"><img src="/img/edit_clear.png" alt="Clear" /></a>';
		$str.= '</div>';
		$str.= '
		<script type="text/javascript">
			$("#v'.$id.'").autocomplete({
				source: "'.$ajaxURL.'?'.$deQS.'",
				select: function(event, ui){
					$("#i'.$id.'").val(ui.item.id);
					$("#v'.$id.'").val(ui.item.value);
				}
			});
		</script>
		';
	}
	return $str;
}
function temporaryTransactionNumber($parType) {
	switch ($parType) {
		case "nopb": { $ajaxURL="/_ajax/purchases.php"; $deA="gettmpnopb"; $elemID="nopb"; $elemCont="exnopb"; break; }
		case "nopj": { $ajaxURL="/_ajax/sells.php"; $deA="gettmpnopj"; $elemID="nopj"; $elemCont="exnopj"; break; }
		default: { $ajaxURL=""; }
	}
	if ($ajaxURL!="") {
		$str = '';
		$str.= '<span id="'.$elemCont.'">Automatic</span>';
		$str.= '
		<script type="text/javascript">
			$.ajax({
				type: "GET",
				url: "'.$ajaxURL.'",
				data: "a='.$deA.'&flag=" + $("#'.$elemID.'").val(),
				success: function(resp) {
					$("#'.$elemCont.'").html(resp);
				}
			});
		</script>
		';
		return $str;
	}
		
}
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 createDirectory2($sub_dir, $dir_name, $permisi=0777) {
	$thisdir=getcwd()."/";
	$tmp_dir = "";
	if(file_exists($sub_dir."/".$dir_name)) {
		$tmp_dir = $sub_dir."/".$dir_name;
		#return $sub_dir."/".$dir_name;
	} else {
		if(! mkdir($sub_dir."/".$dir_name, $permisi)) {
			die('Failed to create folders...');
		} else {
			$tmp_dir = $sub_dir."/".$dir_name;
			#return $sub_dir."/".$dir_name;
		}
	}
	if ($tmp_dir[strlen($tmp_dir)-1]!="/") $tmp_dir=$tmp_dir."/";
	return $tmp_dir;
}
function deleteDirectory($dir) {
	if(! file_exists($dir))
		return true;
	if(! is_dir($dir) || is_link($dir))
		return unlink($dir);
	foreach(scandir($dir) as $item) {
		if($item=='.' || $item=='..')
			continue;
		if(! deleteDirectory($dir."/".$item)) {
			chmod($dir."/".$item, 0777);
			if(! deleteDirectory($dir."/".$item))
				return false;
		}
		;
	}
	return rmdir($dir);
}
function smart_resize_image($file, $width=0, $height=0, $proportional=false, $output='file', $delete_original=true, $use_linux_commands=false, $posx=0, $posy=0) {
	if($height<=0 && $width<=0)
		return false;
	$info=getimagesize($file);
	$image='';
	$final_width=0;
	$final_height=0;
	list($width_old, $height_old)=$info;
	if($proportional) {
		if($width==0)
			$factor=$height / $height_old;
		elseif($height==0)
			$factor=$width / $width_old;
		else
			$factor=min($width / $width_old, $height / $height_old);
		
		$final_width=round($width_old * $factor);
		$final_height=round($height_old * $factor);
	} else {
		$final_width=($width<=0)?$width_old:$width;
		$final_height=($height<=0)?$height_old:$height;
	}
	
	switch($info[2]) {
		case IMAGETYPE_GIF:
			$image=imagecreatefromgif($file);
			break;
		case IMAGETYPE_JPEG:
			$image=imagecreatefromjpeg($file);
			break;
		case IMAGETYPE_PNG:
			$image=imagecreatefrompng($file);
			break;
		default:
			return false;
	}
	
	$image_resized=imagecreatetruecolor($final_width, $final_height);
	if(($info[2]==IMAGETYPE_GIF) ||($info[2]==IMAGETYPE_PNG)) {
		$trnprt_indx=imagecolortransparent($image);
		if($trnprt_indx>=0) {
			$trnprt_color=imagecolorsforindex($image, $trnprt_indx);
			$trnprt_indx=imagecolorallocate($image_resized, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
			imagefill($image_resized, 0, 0, $trnprt_indx);
			imagecolortransparent($image_resized, $trnprt_indx);
		} elseif($info[2]==IMAGETYPE_PNG) {
			imagealphablending($image_resized, false);
			$color=imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
			imagefill($image_resized, 0, 0, $color);
			imagesavealpha($image_resized, true);
		}
	}
	
	imagecopyresampled($image_resized, $image, 0, 0, $posx, $posy, $final_width, $final_height, $width_old, $height_old);
	//imagecopyresampled($dst_image, $src_image, $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h)
	if($delete_original) {
		if($use_linux_commands)
			exec('rm '.$file);
		else
			@unlink($file);
	}
	
	switch(strtolower($output)) {
		case 'browser':
			$mime=image_type_to_mime_type($info[2]);
			header("Content-type: $mime");
			$output=NULL;
			break;
		case 'file':
			$output=$file;
			break;
		case 'return':
			return $image_resized;
			break;
		default:
			break;
	}
	
	switch($info[2]) {
		case IMAGETYPE_GIF:
			imagegif($image_resized, $output);
			break;
		case IMAGETYPE_JPEG:
			imagejpeg($image_resized, $output, 100);
			break;
		case IMAGETYPE_PNG:
			imagepng($image_resized, $output);
			break;
		default:
			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 convertSecToStr($secs){
	$output = '';
	if($secs >= 86400) {
		$days = floor($secs/86400);
		$secs = $secs%86400;
		$output = $days.' day';
		if($days > 1) $output .= 's';
		if($secs > 0) $output .= ', ';
	}
	if($secs>=3600){
		$hours = floor($secs/3600);
		$secs = $secs%3600;
		$output .= $hours.' hr';
		if($hours > 1) $output .= 's';
		if($secs > 0) $output .= ', ';
	}
	if($secs>=60){
		$minutes = floor($secs/60);
		$secs = $secs%60;
		$output .= $minutes.' min';
		if($minutes > 1) $output .= 's';
		if($secs >= 0) $output .= ', ';
	}
	$output .= $secs.' sec';
	if($secs > 1) $output .= 's'; 
	return $output;
}
function redirect($to,$code=301)
{	$location = null;
	$sn = $_SERVER['SCRIPT_NAME'];
	$cp = dirname($sn);
	if (substr($to,0,4)=='http') $location = $to; // Absolute URL
	else
	{	$schema = $_SERVER['SERVER_PORT']=='443'?'https':'http';
		$host = strlen($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:$_SERVER['SERVER_NAME'];
		if (substr($to,0,1)=='/') $location = "$schema://$host$to";
		elseif (substr($to,0,1)=='.') // Relative Path
		{	$location = "$schema://$host/";
			$pu = parse_url($to);
			$cd = dirname($_SERVER['SCRIPT_FILENAME']).'/';
			$np = realpath($cd.$pu['path']);
			$np = str_replace($_SERVER['DOCUMENT_ROOT'],'',$np);
			$location.= $np;
			if ((isset($pu['query'])) && (strlen($pu['query'])>0)) $location.= '?'.$pu['query'];
		}
	}
	$hs = headers_sent();
	if ($hs==false)
	{	if ($code==301) header("301 Moved Permanently HTTP/1.1"); // Convert to GET
		elseif ($code==302) header("302 Found HTTP/1.1"); // Conform re-POST
		elseif ($code==303) header("303 See Other HTTP/1.1"); // dont cache, always use GET
		elseif ($code==304) header("304 Not Modified HTTP/1.1"); // use cache
		elseif ($code==305) header("305 Use Proxy HTTP/1.1");
		elseif ($code==306) header("306 Not Used HTTP/1.1");
		elseif ($code==307) header("307 Temporary Redirect HTTP/1.1");
		else trigger_error("Unhandled redirect() HTTP Code: $code",E_USER_ERROR);
		header("Location: $location");
		header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
	}
	elseif (($hs==true) || ($code==302) || ($code==303))
	{	// todo: draw some javascript to redirect
		$cover_div_style = 'background-color: #ccc; height: 100%; left: 0px; position: absolute; top: 0px; width: 100%;'; 
		echo "<div style='$cover_div_style'>\n";
		$link_div_style = 'background-color: #fff; border: 2px solid #f00; left: 0px; margin: 5px; padding: 3px; ';
		$link_div_style.= 'position: absolute; text-align: center; top: 0px; width: 95%; z-index: 99;';
		echo "<div style='$link_div_style'>\n";
		echo "<p>Please See: <a href='$to'>".htmlspecialchars($location)."</a></p>\n";
		echo "</div>\n</div>\n";
	}
	exit(0);
	// Do stuff here before sending headers
	//redirect('/')
	//redirect("/my/page")
	//redirect("http://www.foo.bar/page.htm",303)
	//redirect("./index.php",307)

}
function checkAuth($pid, $ids) {
	return true;
	if (in_array($pid, $ids)) {
		return true;
	} else {
		return false;
		#return true;
	}
}
function viewNoAuth() {
	cout('<div style="color:red;"><em>No authorization to access this page!</em></div>');
}
function authorizedModule($module, $kduser) {
	#return true;
	if (trim($module)!="" && trim($kduser)!="") {
		#cara 1
		#$rsmod=array();$qmod="SELECT a.*, mod_name, mod_label FROM _user_auth a
		#	LEFT JOIN _admin_mods b ON b.kdmod=a.kdmod
		#	WHERE mod_name='".trim($module)."' AND kduser='".trim($kduser)."'";
		#callRS($rsmod, $qmod);
		#if (count($rsmod)!=0) {
		#	if (intval($rsmod[0]["isallowed"])==1) {
		#		return true;
		#	} else {
		#		return false;
		#	}
		#} else {
		#	return false;
		#}
		# end cara 1
		
		#cara 2
		$avail_mods = $_SESSION["user_auth"][$kduser];
		if (intval($avail_mods[trim($module)]["isallowed"])==1) {
			return true;
		} else {
			if (trim($kduser)=="0") {
				return true;
			}
			return false;
		}
		# end cara 2
	}
}
function unAuthorizedAccess($module, $tipe=0) {
	#cara 1
	#$rsmod=array();$qmod="SELECT mod_name, mod_label FROM _admin_mods
	#	WHERE mod_name='".trim($module)."'";
	#callRS($rsmod, $qmod);
	#$mod_label = count($rsmod)!=0?': <strong>'.$rsmod[0]["mod_label"].'</strong>.':'.';
	## end cara 1
	
	## cara 2
	$avail_mods = $_SESSION["user_auth"][$_SESSION["user"]["kduser"]];
	$mod_label = ': <strong>'.$avail_mods[$module]["mod_label"].'</strong>';
	# end cara 2
	if ($tipe==0) {
		cout('<div class="alert alert-danger">
			<em>You are <strong>not allowed</strong> to access this module'.$mod_label.'. Please ask your supervisor for more information.</em>
		</div>');
	}
	if ($tipe==1) {
		cout('<div class="alert alert-danger" style="float:left;margin:5px;">
			<em>No Access to'.$mod_label.'</em>
		</div>');
	}
	if ($tipe==2) {
		return ('<div class="alert alert-danger">
			<em>You are <strong>not allowed</strong> to access this module'.$mod_label.'. Please ask your supervisor for more information.</em>
		</div>');
	}
	if ($tipe==3) {
		return ('<div class="alert alert-danger" style="float:left;margin:5px;">
			<em>No '.$mod_label.'</em>
		</div>');
	}
	if ($tipe==4) {
		return ('<span class="alert alert-danger">
			<em>No '.$mod_label.'</em>
		</span>');
	}
}
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 printR($parArr, $tipe=0) {
	if ($tipe!=0) {
		return str_replace(array(",", ", "), ", ", json_encode($parArr));
	}
	echo'<pre>';print_r($parArr);echo'</pre>';
}
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 updateUserActivities($parKet) {
	if (isset($_SESSION["user"])) {
		$session_id = $_SESSION["user"]["session_id"];
		$_SESSION["user"]["last_click"] = time();
		$rscua = array(); $qcua = "SELECT * FROM _user_activities WHERE session_id='$session_id' AND kduser='".$_SESSION["user"]["kduser"]."'";
		callRSL($rscua, $qcua);
		#if (count($rscua)!=0) {
		#	$qua = "UPDATE _user_activities SET ket='$parKet', last_click='".time()."' WHERE session_id='$session_id' AND kduser = '".$_SESSION["user"]["kduser"]."'";
		#	execRS($qua);
		#} else {
			$kdcua = getIDL("_user_activities", "kd");
			$kduser = $_SESSION["user"]["kduser"];
			$username = $_SESSION["user"]["username"];
			$inisial = $_SESSION["user"]["inisial"];
			$login_time = $_SESSION["user"]["login_time"];
			$last_click = $_SESSION["user"]["last_click"];
			$qua = "INSERT INTO _user_activities (kd, kduser, username, inisial, login_time, last_click, session_id, ket) 
				VALUES ('$kdcua', '$kduser', '$username', '$inisial', '$login_time', '$last_click', '$session_id', '$parKet')";
			execRSL($qua);
		#}
	}
}
function XML2Array(SimpleXMLElement $parent) {
	$array = array();
	foreach ($parent as $name => $element) {
		($node = & $array[$name])
			&& (1 === count($node) ? $node = array($node) : 1)
			&& $node = & $node[];
		$node = $element->count() ? XML2Array($element) : trim($element);
	}
	return $array;
}
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;
}
function uploadException($parCode) {
	$code = $parCode;
	switch ($code) { 
		case UPLOAD_ERR_INI_SIZE: 
			$message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
			break;
		case UPLOAD_ERR_FORM_SIZE: 
			$message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
			break;
		case UPLOAD_ERR_PARTIAL: 
			$message = "The uploaded file was only partially uploaded";
			break;
		case UPLOAD_ERR_NO_FILE: 
			$message = "No file was uploaded";
			break;
		case UPLOAD_ERR_NO_TMP_DIR: 
			$message = "Missing a temporary folder";
			break;
		case UPLOAD_ERR_CANT_WRITE: 
			$message = "Failed to write file to disk";
			break;
		case UPLOAD_ERR_EXTENSION: 
			$message = "File upload stopped by extension";
			break;

		default: 
			$message = "Unknown upload error";
		break;
	}
	return $message;
}
?>