<?php
function SCpesan(){
	if(isset($_SESSION['pesan'])){
		$ssp = explode('|',$_SESSION['pesan']);
		echo "<script>pesan('$ssp[0]','$ssp[1]','$ssp[2]');</script>";
		unset($_SESSION['pesan']);
	}
}

function notif($pesan,$type='info'){
	$str = '<div class="alert alert-'.$type.'">'.$pesan.'</div>';
	echo "<script>$(document).ready(function(e){
				$('".$str."').appendTo('body').insertBefore('.login-box');
			});
		  </script>";
}
function genColorCodeFromText($text,$min_brightness=100,$spec=10)
{
	// Check inputs
	if(!is_int($min_brightness)) throw new Exception("$min_brightness is not an integer");
	if(!is_int($spec)) throw new Exception("$spec is not an integer");
	if($spec < 2 or $spec > 10) throw new Exception("$spec is out of range");
	if($min_brightness < 0 or $min_brightness > 255) throw new Exception("$min_brightness is out of range");
	
	
	$hash = sha256($text);  //Gen hash of text
	$colors = array();
	for($i=0;$i<3;$i++)
		$colors[$i] = max(array(round(((hexdec(substr($hash,$spec*$i,$spec)))/hexdec(str_pad('',$spec,'F')))*255),$min_brightness)); //convert hash into 3 decimal values between 0 and 255
		
	if($min_brightness > 0)  //only check brightness requirements if min_brightness is about 100
		while( array_sum($colors)/3 < $min_brightness )  //loop until brightness is above or equal to min_brightness
			for($i=0;$i<3;$i++)
				$colors[$i] += 10;	//increase each color by 10
				
	$output = '';
	
	for($i=0;$i<3;$i++)
		$output .= str_pad(dechex($colors[$i]),2,0,STR_PAD_LEFT);  //convert each color to hex and append to output
	
	return '#'.$output;
}
function hex_color(){
	$c = '';
	while(strlen($c)<5){
		$c .= sprintf("%02X", mt_rand(0, 255));
	}
	return '#'.$c;
}
function rgb_color(){
	$color = 'rgb('.rand(0,255).','.rand(0,255).','.rand(0, 255).')';
	return $color;
}
function encryptString($pure_string, $encryption_key) {
    $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, utf8_encode($pure_string), MCRYPT_MODE_ECB, $iv);
    return base64_encode($encrypted_string);
}

function decryptString($encrypted_string, $encryption_key) {
    $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $encryption_key, base64_decode($encrypted_string), MCRYPT_MODE_ECB, $iv);
    $string = iconv("UTF-8","ISO-8859-1//IGNORE",$decrypted_string);
	$string_dec = iconv("ISO-8859-1","UTF-8",$string);
	return trim($string_dec);
}
function setAuth($connect, $id,$auth,$update=false){
	if($update){
		mysqli_query($connect, "UPDATE `user_login` set `auth`='$auth', `time`='".date('Y-m-d H:i:s')."' WHERE ID='$update'") or die(mysqli_error($connect));
	}else{
		$cauth = mysqli_query($connect, "SELECT * FROM `user_login` WHERE `user_agent`='".$_SERVER['HTTP_USER_AGENT']."' AND `ID_user`='$id'") or die(mysqli_error($connect));
		if(mysqli_num_rows($cauth)){
			mysqli_query($connect, "UPDATE `user_login` set `time`='".date('Y-m-d H:i:s')."',`ip`='".getRealIP()."',`auth`='$auth' WHERE `ID_user`='$id' AND `user_agent`='".$_SERVER['HTTP_USER_AGENT']."'") or die(mysqli_error($connect));
		}else{
			mysqli_query($connect, "INSERT INTO `user_login` (`ID_user`, `auth`, `ip`, `user_agent`, `time`)
									       VALUES ('$id', '$auth', '".getRealIP()."', '".$_SERVER['HTTP_USER_AGENT']."', '".date('Y-m-d H:i:s')."');") or die(mysqli_error($connect));
		}
	}
	
}
function removeAuth($connect, $auth){
	mysqli_query($connect, "DELETE FROM `user_login` where `auth`='$auth'") or die(mysqli_error($connect));
}
function cekAuth($connect, $auth){
	if($auth){
		$dec = json_decode(decryptString($auth,ENCRYPTION_KEY));
		if($_SERVER['HTTP_USER_AGENT']==$dec->ua){
			//if($dec->timeout-time()>0){
				$q=mysqli_query($connect, "select b.*,a.ID as a_id from user_login a, users b where a.ID_user=b.ID and b.user_email='".$dec->email."' and a.auth='".$auth."'") or die(mysqli_error($connect));
				if(mysqli_num_rows($q)){
					$b=mysqli_fetch_assoc($q);
					if($b['user_status']==1){
						//$timeout=time()+1800;
						//$auth_data = array('email'=>$b['email'],'origin'=>getConfig($connect, 'base_url'),'timeout'=>$timeout);
						//$auth = encryptString(json_encode($auth_data),ENCRYPTION_KEY);
						//setAuth($b['id_user'],$auth,$b['a_id']);
						$b['l']=1;
						$data = array('status'=>1,'user'=>$b,'new_auth'=>$auth);
					}else{
						$data = array('status'=>0,'code'=>403,'msg'=>'403 Forbidden');
					}
				}else{
					$q=mysqli_query($connect, "select b.*,a.ID as a_id from user_login a, karyawan b where a.ID_user=b.ID and b.email='".$dec->email."' and a.auth='".$auth."'") or die(mysqli_error($connect));
					if(mysqli_num_rows($q)){
						$b=mysqli_fetch_assoc($q);
						if($b['status']==1){
							//$timeout=time()+1800;
							//$auth_data = array('email'=>$b['email'],'origin'=>getConfig($connect, 'base_url'),'timeout'=>$timeout);
							//$auth = encryptString(json_encode($auth_data),ENCRYPTION_KEY);
							//setAuth($b['id_user'],$auth,$b['a_id']);
							$b['l']=2;
							$data = array('status'=>1,'user'=>$b,'new_auth'=>$auth);
						}else{
							$data = array('status'=>0,'code'=>403,'msg'=>'403 Forbidden');
						}
					}else{
						$data = array('status'=>0,'code'=>401,'msg'=>'401 User Unauthorized');
					}
				}
			/*}else{
				$data = array('status'=>0,'code'=>408,'msg'=>'408 Authentication Timeout');
			}*/
		}else{
			$data = array('status'=>0,'code'=>502,'msg'=>'502 Bad Request');
		}
	}else{
		$data = array('status'=>0,'code'=>401,'msg'=>'401 Unauthorized');
	}
	return json_encode($data);
}
function create_slug($string){
   $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
   return $slug;
}

function getRealIP(){
    if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
              $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
              $_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
    }
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];
    if(filter_var($client, FILTER_VALIDATE_IP)){
        $ip = $client;
    }elseif(filter_var($forward, FILTER_VALIDATE_IP)){
        $ip = $forward;
    }else{
        $ip = $remote;
    }
    return $ip;
}
function getUrl(){
  return sprintf(
    "%s://%s%s",
    isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
    $_SERVER['SERVER_NAME'],
    $_SERVER['REQUEST_URI']
  );
}
function isJson($string) {
	 return (json_decode($string)==NULL)?false:true;
}
function toJson($string){
	iconv("windows-1251", "UTF-8", $string);
	parse_str(urldecode($string), $result);
	return json_encode($result, JSON_UNESCAPED_UNICODE);
}
function reArrayFiles(&$file_post) {
    $file_ary = array();
    $file_count = count($file_post['name']);
    $file_keys = array_keys($file_post);
    for ($i=0; $i<$file_count; $i++) {
        foreach ($file_keys as $key) {
            $file_ary[$i][$key] = $file_post[$key][$i];
        }
    }
    return $file_ary;
}
function getUploadError($uploadName){
	switch ($_FILES[$uploadName]['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_NO_FILE:
            return ('No file sent.');
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            return ('Exceeded filesize limit.');
        default:
            return ('Unknown errors.');
    }
}
function simpanGambar($data,$lokasi,$percent=75){
	$image = explode(';',$data);
	$imgdata = explode('base64,',$image[1]);
	$gambar = base64_decode($imgdata[1]);
	$type = explode(':',$image[0]);
	$imgtype = $type[1];
	$im = imagecreatefromstring($gambar);
	if($im!==false){
		$lebar       = imagesx($im);
		$tinggi      = imagesy($im);
		$tmb_lebar   = $lebar*($percent/100);
		$tmb_tinggi  = $tinggi*($percent/100);
		$image_tmb   = imagecreatetruecolor($tmb_lebar,$tmb_tinggi);
		imagealphablending($image_tmb, false);
		imagesavealpha($image_tmb, true);
		imagecopyresampled($image_tmb,$im,0,0,0,0,$tmb_lebar,$tmb_tinggi,$lebar,$tinggi);
		$filename = sha256(time().mt_rand());
		if($imgtype=='image/jpeg'){
			imagejpeg($image_tmb,$lokasi.$filename.'.jpg');
			imagedestroy($im);
			imagedestroy($image_tmb);
			return $filename.'.jpg';
		}elseif($imgtype=='image/png'){
			imagepng($image_tmb,$lokasi.$filename.'.png');
			imagedestroy($im);
			imagedestroy($image_tmb);
			return $filename.'.png';
		}
	}else{
		return false;
	}
}
function saveImg($data,$lokasi,$percent=75){
	$gambar = base64_decode($data);
	$im = imagecreatefromstring($gambar);
	if($im!==false){
		$lebar       = imagesx($im);
		$tinggi      = imagesy($im);
		$tmb_lebar   = $lebar*($percent/100);
		$tmb_tinggi  = $tinggi*($percent/100);
		$image_tmb   = imagecreatetruecolor($tmb_lebar,$tmb_tinggi);
		imagecopyresampled($image_tmb,$im,0,0,0,0,$tmb_lebar,$tmb_tinggi,$lebar,$tinggi);
		$filename = sha256(time().mt_rand());
		imagepng($image_tmb,$lokasi.$filename.'.png');
		imagedestroy($im);
		imagedestroy($image_tmb);
		return $filename.'.png';
	}else{
		return NULL;
	}
}
function ob_html_compress($buf){
    return trim(preg_replace(['/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s','/<!--(.|\s)*?-->/'],['>','<','\\1'],trim(preg_replace('/\s\s+/', '', $buf))));
}

function anti_injection($connect, $data){
  $filter = mysqli_real_escape_string($connect, stripslashes(strip_tags(htmlspecialchars($data,ENT_QUOTES))));
  return $filter;
}
function getTitle($page){
	if($_GET['edit']){
		return 'Edit '.ucwords(str_replace("-"," ",$page));
	}elseif($_GET['lihat']){
		return 'Lihat '.ucwords(str_replace("-"," ",$page));
	}elseif($_GET['add']){
		return 'Tambah '.ucwords(str_replace("-"," ",$page));
	}elseif($_GET['ket']){
		return 'Keterangan '.ucwords(str_replace("-"," ",$page));
	}else{
		if(!$page || $page=='home'){
			return 'Dashboard';
		}else{
			return ucwords(str_replace("-"," ",$page));
		}
	}
}
function humanFileSize($bytes, $decimals = 2){
	$size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB');
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) .' '.@$size[$factor];
}
function ceklevel($level,$needle){
	if($level!=-1){
		return strpos($level, $needle) !== false;
	}else{
		return true;
	}
}
function zipBanyak($src,$zipname, $with_src) {
	$zip = new ZipArchive;
	$zip->open($zipname);
    $dir = opendir($src); 
    while( false !== ($file = readdir($dir))){ 
        if( $file != '.' && $file != '..' ) { 
            if(is_dir($src.'/'.$file)){ 
                zipBanyak($src.'/'.$file,$zipname, $with_src); 
            } else { 
				if ($with_src==true){
              		$zip->addFile($src.'/'.$file,$src.'/'.$file);
				}else{
					$zip->addFile($file,$file);
				}
			} 
        } 
    } 
    closedir($dir);
	$zip->close();
}
function timeago($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'tahun',
        'm' => 'bulan',
        'w' => 'minggu',
        'd' => 'hari',
        'h' => 'jam',
        'i' => 'menit',
        's' => 'detik',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
			if($v=='detik'){
				$v='beberapa detik';
			}else{
					$v = ($diff->$k > 1 ? 'Sekitar ' : '').$diff->$k . ' ' . $v;
			}
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' yg lalu' : 'baru saja';
}

function getConfig($connect, $key){
	$qsettings=mysqli_query($connect, "select config_value from config where config_key='$key'") or die(mysqli_error($connect));
	$bsettings=mysqli_fetch_array($qsettings);
	return $bsettings[0];
}

function setConfig($connect, $key,$val){
	$qsettings=mysqli_query($connect, "update config set config_value ='$val' where config_key='$key'") or die(mysqli_error($connect));
}

function hapusTempCart($connect){
	$qtemp=mysqli_query($connect, "select * from cart_temp where order_id='0'") or die(mysqli_error($connect));
	while($btemp=mysqli_fetch_array($qtemp)){
		$hitung = ceil((time()-$btemp['waktu'])/60/60);
		if($hitung>=48){
			$qdel=mysqli_query($connect, "delete from temp_pengiriman where ID_session='$btemp[ID_session]' and order_id='0';") or die(mysqli_error($connect));
			$qdel=mysqli_query($connect, "delete from cart_temp where ID_session='$btemp[ID_session]' and order_id='0';") or die(mysqli_error($connect));	
		}
	} 
}

function filterPost($connect){
	foreach($_POST as $key => $val){
		if(!is_array($val)){
			$string = iconv("UTF-8","ISO-8859-1//IGNORE",$val);
			$string_ = iconv("ISO-8859-1","UTF-8",$string);
			$_POST[$key] = mysqli_real_escape_string($connect, trim($string_));
		}else{
			foreach($val as $i => $vv){
				if(!is_array($vv)){
					$string = iconv("UTF-8","ISO-8859-1//IGNORE",$vv);
					$string_ = iconv("ISO-8859-1","UTF-8",$string);
					$_POST[$key][$i] = mysqli_real_escape_string($connect, trim($string_));
				}else{
					foreach($vv as $a => $b){
						if(!is_array($b)){
							$string = iconv("UTF-8","ISO-8859-1//IGNORE",$b);
							$string_ = iconv("ISO-8859-1","UTF-8",$string);
							$_POST[$i][$a] = mysqli_real_escape_string($connect, trim($string_));
						}else{
							foreach($b as $c => $d){
								if(!is_array($d)){
									$string = iconv("UTF-8","ISO-8859-1//IGNORE",$d);
									$string_ = iconv("ISO-8859-1","UTF-8",$string);
									$_POST[$a][$c] = mysqli_real_escape_string($connect, trim($string_));
								}else{
									foreach($d as $e => $f){
										$string = iconv("UTF-8","ISO-8859-1//IGNORE",$f);
										$string_ = iconv("ISO-8859-1","UTF-8",$string);
										$_POST[$c][$e] = mysqli_real_escape_string($connect, trim($string_));
									}	
								}
							}
						}
					}
				}
			}
		}
	}
}

function filterGet($connect){
	foreach($_GET as $key => $val){
		$_GET[$key] = mysqli_real_escape_string($connect, trim($val));
	}	
}

function Random($len=5){
	return strtoupper(substr(sha256(time().mt_rand()),mt_rand(0,25),$len));
}

function Password($password){
	return hash('sha256',$password.'7F2991158C2899256E1A347ED2E39646');
}

function getDataURI($image, $mime = '') {
	return 'data: '.(function_exists('mime_content_type') ? mime_content_type($image) : $mime).';base64,'.base64_encode(file_get_contents($image));
}

function getToken(){
	$token = sha256(rand().microtime());
	$token_count=count($_SESSION['token']);
	$_SESSION['token'][$token_count] = $token;
	return $token;
}

function cekToken($sToken){
	if(in_array($sToken,$_SESSION['token'])){
		unset($_SESSION['token']);
		return true;
	}else{
		unset($_SESSION['token']);
		return false;
	}
}

function importSQL($connect, $SQLfile){
	$query = '';
	$sqlScript = file($SQLfile);
	foreach ($sqlScript as $line)	{
		$startWith = substr(trim($line), 0 ,2);
		$endWith = substr(trim($line), -1 ,1);
		if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') {
			continue;
		}
		$query = $query . $line;
		if ($endWith == ';') {
			mysqli_query($connect, $query) or die('<div class="error-response sql-import-response">Problem in executing the SQL query <b>' . $query. '</b></div>');
			$query= '';		
		}
	}
}
function masaKerja($tgl_masuk){
	$masuk = strtotime($tgl_masuk);
	$sekarang = strtotime(date('Y-m-d'));
	$bulan = ($sekarang-$masuk)/(3600*24)/30;
	return ceil($bulan);
}
function umur($tgl_lahir){
	$t = date('d/m/Y',strtotime($tgl_lahir));
    $tgl=explode("/",$t);
    $cek_jmlhr1=cal_days_in_month(CAL_GREGORIAN,$tgl['1'],$tgl['2']);
    $cek_jmlhr2=cal_days_in_month(CAL_GREGORIAN,date('m'),date('Y'));
    $sshari=$cek_jmlhr1-$tgl['0'];
    $ssbln=12-$tgl['1']-1;
    $hari=0;
    $bulan=0;
    $tahun=0;
    if($sshari+date('d')>=$cek_jmlhr2){
        $bulan=1;
        $hari=$sshari+date('d')-$cek_jmlhr2;
    }else{
        $hari=$sshari+date('d');
    }
    if($ssbln+date('m')+$bulan>=12){
        $bulan=($ssbln+date('m')+$bulan)-12;
        $tahun=date('Y')-$tgl['2'];
    }else{
        $bulan=($ssbln+date('m')+$bulan);
        $tahun=(date('Y')-$tgl['2'])-1;
    }

      $selisih=$tahun." Thn ".$bulan." Bln ";
    return $selisih;
}




