<?

/* General purpose functions library */


/* ************************************************************************************* */
/* Encoding / decoding */


//Function encodes parse value
function encoder($value){
	return base64_encode(base64_encode(base64_encode($value)));
	//return $value;
}

//Function decodes parse value
function decoder($value){
	return base64_decode(base64_decode(base64_decode($value)));
	//return $value;
}

function unescape($value){
	$result=str_replace("\'","'",$value);
	$result=str_replace('\"','"',$result);
	return $result;
}

function ununescape($value){
	$result=str_replace("'","\'",$value);
	# myapit - issue no 3
	# $result=str_replace('"','\"',$result);
	return $result;
}

function escape($value){
	$result=str_replace('\"','"',$value);
	$result=str_replace('"','&quot;',$result);
	return $result;
}

/* ************************************************************************************* */
/* Javascript redirections */


//Function pops up a message and redirects to the given url..
function msg_n_goto($where,$msg){
	return "<script>alert('$msg'); document.location='$where';</script>";
}

//Function pops up a message and redirects (TOP) to the given url..
function msg_n_topgoto($where,$msg){
	return "<script>alert('$msg'); top.location='$where';</script>";
}

//Function just pops up a message..
function msg($msg){
	return "<script>alert('$msg');</script>";
}

//Function pops up a message and then closes window..
function msg_n_closewindow($msg){
	return "<script>alert('$msg'); window.close();</script>";
}

//Function just redirects to the given url..
function goto($where){

	return "<script>document.location='$where';</script>";
}

//Function just redirects (TOP) to the given url
function topgoto($where){
	return "<script>top.location='$where';</script>";
}

//Function pops up error message and then returns user to a previous page
function error_n_goto($history_level,$msg){
	return "<script>alert('$msg'); history.go($history_level);</script>";
}


/* ************************************************************************************* */
/* Dates, times, and conversions */


// firus 10/1/2008 - returns full timestamp..
function gettimestamp(){
	return mktime(date('H'),date('i'),date('s'),date('m'),date('d'),date('Y'));
}

// firus 14/1/2008 - returns only date stamp..
function getdatestamp(){
	return mktime(0,0,0,date('m'),date('d'),date('Y'));
}

//Function converts date dd-mm-yyyy to unix time (29-10-1981 becomes 373132800)
//must use PHP5.0>
function converttounix($date_val){
	if ($date_val!=NULL){
		if (strpos($date_val,"-")>-1) {
			$cut_date=explode("-",$date_val);
		} else if (strpos($date_val,"/")>-1) {
			$cut_date=explode("/",$date_val);
		}
		return mktime(0,0,0,$cut_date[1],$cut_date[0],$cut_date[2]);
	} else {
		return NULL;
	}
}

// firus may 2008 - converts up to minutes (seconds=0)..
function converttounixmost($date_val){
	if ($date_val!=NULL){
		$cut_all=explode(" ",$date_val);
		$cut_date=explode("-",$cut_all[0]);
		$cut_time=explode(":",$cut_all[1]);
		return mktime(intval($cut_time[0]),intval($cut_time[1]),0,$cut_date[1],$cut_date[0],$cut_date[2]);
	} else {
		return NULL;
	}
}

// firus sept 2009 - converts full datetime up to seconds..
function converttounixfull($date_val){
	if ($date_val!=NULL){
		$cut_all=explode(" ",$date_val);
		if (strpos($cut_all[0],"-")>-1) {
			$cut_date=explode("-",$cut_all[0]);
		} else if (strpos($cut_all[0],"/")>-1) {
			$cut_date=explode("/",$cut_all[0]);
		}
		$cut_time=explode(":",$cut_all[1]);
		return mktime(intval($cut_time[0]),intval($cut_time[1]),intval($cut_time[2]),$cut_date[1],$cut_date[0],$cut_date[2]);
	} else {
		return NULL;
	}
}

//Function converts date dd-mm-yyyy to unix time as the 1st day of month (29-10-1981 to 01-10-1981)
//must use PHP5.0>
function converttounix_firstdayofmonth($date_val){
	if ($date_val!=NULL){
		$cut_date=explode("-",$date_val);
		return mktime(0,0,0,$cut_date[1],1,$cut_date[2]);			
	} else {
		return NULL;
	}
}

//Function converts date dd-mm-yyyy to unix time as the last day of month (29-10-1981 to 31-10-1981)
//must use PHP5.0>
function converttounix_lastdayofmonth($date_val){
	if ($date_val!=NULL){
		$cut_date=explode("-",$date_val);
			
		$lastday=date('t',converttounix("01-".$cut_date[1]."-".$cut_date[2])); //last day for month
		$dateend_original=converttounix($lastday."-".$cut_date[1]."-".$cut_date[2]);
		$dateend=mktime(23,59,59,date("m",$dateend_original),date("d",$dateend_original),date("Y",$dateend_original));

		return $dateend;
	} else {
		return NULL;
	}
}

//Function reverses unix date time conversion to dd-mm-yyyy
//must use PHP5.0>
function unconverttounix($undate_val){
	if ($undate_val!=NULL){
		return date('d-m-Y',$undate_val);
	} else {
		return NULL;
	}
}

//Function reverses unix date time conversion to dd-mm-yyyy (/ instead of -)
//must use PHP5.0>
function unconverttounixslash($undate_val){
	if ($undate_val!=NULL){
		return date('d/m/Y',$undate_val);
	} else {
		return NULL;
	}
}

//Function reverses unix date time to normal date time..
//must use PHP5.0>
function unconverttounixfull($undate_val){
	if ($undate_val!=NULL){
		return date('d-m-Y - H:i:s',$undate_val);
	} else {
		return NULL;
	}
}

//Function reverses unix date time to normal date time..
//must use PHP5.0>
function unconverttounixfullslash($undate_val){
	if ($undate_val!=NULL){
		return date('d/m/Y - H:i:s',$undate_val);
	} else {
		return NULL;
	}
}

//Function reverses unix date time up to minutes..
function unconverttounixmost($undate_val){
	if ($undate_val!=NULL){
		return date('d-m-Y - H:i',$undate_val);
	} else {
		return NULL;
	}
}

//Function reverses unix date time to time only..
function unconverttounixtime($undate_val){
	if ($undate_val!=NULL){
       return date('H:i:s',$undate_val);
	} else {
		return NULL;
	}
}

//Function reverses unix date time to hour and minutes only..
function unconverttounixhhmm($undate_val) {
	if ($undate_val!=NULL) {
		return date('H:i',$undate_val);
	} else {
		return NULL;
	}
}

//This function is to convert unix timestamp to Full Date & Time	
function unix2fullnormal($unix){
	$normal=date('h:i:sA d-m-Y',$unix);
	return $normal;
}

//13/3/2009 - Calculate elapsed time between two times in days, hours, mins and seconds..
function getelapsedtime($undate_val){
	$now = mktime();
	$diff = $now-$undate_val;
	$daysDiff = floor($diff/60/60/24);
	$diff -= $daysDiff*60*60*24;
	$hrsDiff = floor($diff/60/60);
	$diff -= $hrsDiff*60*60;
	$minsDiff = floor($diff/60);
	$diff -= $minsDiff*60;
	$secsDiff = $diff;
	return $daysDiff.' Days, '.$hrsDiff.' Hrs, '.$minsDiff.' Mins and '.$secsDiff.' Secs';
}

//Function reverses unix date time to normal date time in [] format..
//must use PHP5.0>
function unixtodatetime($undate_val){
	if ($undate_val!=NULL){
       return date('[d-m-Y] & [H:i:s]',$undate_val);
	} else {
		return NULL;
	}
}

//Function converts date dd-mm-yyyy to unix time (29-10-1981 becomes 373132800)
//must use PHP5.0>
function getdayfromunix($unix_date){
	return date('l',$unix_date);
}


/* ************************************************************************************* */
/* Data access functions (deprecated as per Sept 2009) */
/* Deprecated meaning we now use the ones in the baseModel class */


//Function returns the data value as requested from the database
function get_data($tbl,$column,$condition){

	global $db_pms;

	$sql="select $column from $tbl $condition"; 

	//echo $sql;
	//return;

	$result =& $db_pms->query($sql);
	$data=$result->fetchRow();
	$result->free();
	return $data;
}

// Firus new!! (Aug 2009)
function get_list($tbl,$column,$condition,$sorting){

	global $db_pms;
        $listdata=array();
	$dcount=0;

	$sql="select $column from $tbl $condition order by $sorting"; 

	//echo $sql;
	//exit;

	$result =& $db_pms->query($sql);
        while($data=$result->fetchRow()) {
                $listdata[$dcount]=$data;
                $listdata[$dcount]['recordno']=$dcount+1;
		$dcount++;
	}
	$result->free();
	return $listdata;
}

//Function add the data into the specified database/table
function add_data($module,$tbl,$column,$data){

	global $db_pms;
	
	$sql="insert into $tbl ($column) values ($data)";
	//echo $sql;
	//return;

	//Audit trail
	$sql_audit = "Insert into $tbl";
	$insert_audit = new auditTrail();
	$insert_audit->audittrail_add($module,$sql_audit,$sql);
	if ($result =& $db_pms->query($sql)){
		return TRUE;
	} else {
		return FALSE;
	}
}

function add_data_noaudit($tbl,$column,$data){

	global $db_pms;

	$sql="insert into $tbl ($column) values ($data)";

	if ($result =& $db_pms->query($sql)){
		return TRUE;
	} else {
		return FALSE;
	}
}

//Function updates the data value according to the condition given
function update_data($module,$tbl,$column,$condition){

	global $db_pms;
	
 	$sql="update $tbl set $column $condition"; 
	//echo $sql;

	//Audit trail
	$sql_audit = "Update $tbl";
	$insert_audit = new auditTrail();
	$insert_audit->audittrail_add($module,$sql_audit,$sql);
	if ($result =& $db_pms->query($sql)){
		return TRUE;
	} else {
		return FALSE;
	}
}

function update_data_noaudit($tbl,$column,$condition){

	global $db_pms;
	
 	$sql="update $tbl set $column $condition"; 

	if ($result =& $db_pms->query($sql)){
		return TRUE;
	} else {
		return FALSE;
	}
}

//Function delete's the data value according to the condition given
function delete_data($module,$tbl,$condition){

	global $db_pms;
	
 	$sql="delete from $tbl $condition"; 
	//echo msg($sql);

	//Audit trail
	$sql_audit = "Delete from $tbl";
	$insert_audit = new auditTrail();
	$insert_audit->audittrail_add($module,$sql_audit,$sql);
	if ($result =& $db_pms->query($sql)){
		return TRUE;
	} else {
		return FALSE;
	}
}

function delete_data_noaudit($tbl,$condition){

	global $db_pms;
	
 	$sql="delete from $tbl $condition"; 

	if ($result =& $db_pms->query($sql)){
		return TRUE;
	} else {
		return FALSE;
	}
}


/* ************************************************************************************* */
/* Misc */


function idstr($myid) {
	if ($myid>999) {
		return "SP".$myid;
	} else if ($myid>99) {
		return "SP".$myid;
	} else if ($myid>9) {
		return "SP".$myid;
	} else if ($myid<=9) {
		return "SP0".$myid;
	} else {
		return "";
	}
}

function mroidstr($myid,$myrevno="0") {
	if ($myrevno!="0") { $myrevno=" (".$myrevno.")"; } else { $myrevno=""; }
	if ($myid>999) {
		return "MRO".$myid.$myrevno;
	} else if ($myid>99) {
		return "MRO0".$myid.$myrevno;
	} else if ($myid>9) {
		return "MRO00".$myid.$myrevno;
	} else if ($myid<=9) {
		return "MRO000".$myid.$myrevno;
	} else {
		return "";
	}
}

function itqidstr($myid,$myrevno="0") {
	if ($myrevno!="0") { $myrevno=" (".$myrevno.")"; } else { $myrevno=""; }
	if ($myid>999) {
		return "RFQ".$myid.$myrevno;
	} else if ($myid>99) {
		return "RFQ0".$myid.$myrevno;
	} else if ($myid>9) {
		return "RFQ00".$myid.$myrevno;
	} else if ($myid<=9) {
		return "RFQ000".$myid.$myrevno;
	} else {
		return "";
	}
}

function poidstr($myid,$myrevno="0") {
	if ($myrevno!="0") { $myrevno=" (".$myrevno.")"; } else { $myrevno=""; }
	if ($myid>999) {
		return "PO".$myid.$myrevno;
	} else if ($myid>99) {
		return "PO0".$myid.$myrevno;
	} else if ($myid>9) {
		return "PO00".$myid.$myrevno;
	//Kai: Fix this or will have po000 returned everytime.
	} else if ($myid<=9 && $myid > 0) {
		return "PO000".$myid.$myrevno;
	} else {
		return "";
	}
}

function dottedstr($mystring,$maxlength) {
	if (strlen($mystring)<=$maxlength) {
		return $mystring;
	} else {
		return substr($mystring,0,$maxlength)."..";
	}
}


/** 
*  Function:   convert_number 
*
*  Description: 
*  Converts a given integer (in range [0..1T-1], inclusive) into 
*  alphabetical format ("one", "two", etc.)
*
*  @int
*
*  @return string
*
*/ 
function number_to_words($number) 
{ 
    if (($number < 0) || ($number > 999999999)) 
    { 
    throw new Exception("Number is out of range");
    } 

    $Gn = floor($number / 1000000);  /* Millions (giga) */ 
    $number -= $Gn * 1000000; 
    $kn = floor($number / 1000);     /* Thousands (kilo) */ 
    $number -= $kn * 1000; 
    $Hn = floor($number / 100);      /* Hundreds (hecto) */ 
    $number -= $Hn * 100; 
    $Dn = floor($number / 10);       /* Tens (deca) */ 
    $n = $number % 10;               /* Ones */ 

    $res = ""; 

    if ($Gn) 
    { 
        $res .= number_to_words($Gn) . " Million"; 
    } 

    if ($kn) 
    { 
        $res .= (empty($res) ? "" : " ") . 
            number_to_words($kn) . " Thousand"; 
    } 

    if ($Hn) 
    { 
        $res .= (empty($res) ? "" : " ") . 
            number_to_words($Hn) . " Hundred"; 
    } 

    $ones = array("", "One", "Two", "Three", "Four", "Five", "Six", 
        "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", 
        "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen", 
        "Nineteen"); 
    $tens = array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", 
        "Seventy", "Eigthy", "Ninety"); 

    if ($Dn || $n) 
    { 
        if (!empty($res)) 
        { 
            $res .= " and "; 
        } 

        if ($Dn < 2) 
        { 
            $res .= $ones[$Dn * 10 + $n]; 
        } 
        else 
        { 
            $res .= $tens[$Dn]; 

            if ($n) 
            { 
                $res .= "-" . $ones[$n]; 
            } 
        } 
    } 

    if (empty($res)) 
    { 
        $res = "zero"; 
    } 

    return $res; 
} 


//Function get the script name without hard coding it
//Just type get_file_name(); but only for 5 level of array
function get_file_name($file_extension){
	//$file_extension example = .php .htm .html .js
	
	$script_name=explode("/",$_SERVER["SCRIPT_NAME"]);
	if (($sn=preg_match("/$file_extension/",$script_name[0])==1)){
		$sn=$script_name[0];
	} elseif (($sn=preg_match("/$file_extension/",$script_name[1])==1)) {
		$sn=$script_name[1];
	} elseif (($sn=preg_match("/$file_extension/",$script_name[2])==1)) {
		$sn=$script_name[2];
	} elseif (($sn=preg_match("/$file_extension/",$script_name[3])==1)) {
		$sn=$script_name[3];
	} elseif (($sn=preg_match("/$file_extension/",$script_name[4])==1)) {
		$sn=$script_name[4];
	} elseif (($sn=preg_match("/$file_extension/",$script_name[5])==1)) {
		$sn=$script_name[5];
	} else {
		$sn=" Error getting script name!";
	}	
	return $sn;
}

//This function is to get difference of 2 unix timestamp, then convert the unix timestamp to how many days
function numOfDay($start,$stop) {
	/*$getDate1 = getdate($date1);
	$getDate2 = getdate($date2);

	$firstDate = mktime(0,0,0,$getDate1['mon'],$getDate1['mday'],$getDate1['year']);
	$secondDate = mktime(0,0,0,$getDate2['mon'],$getDate2['mday'],$getDate2['year']);
	$total_num_days = Round((($secondDate-$firstDate)/86400),0);
	return $total_num_days;*/ 
 
  	$diff=$stop-$start;
	$day=number_format($diff/86400,0);
	return $day;
}

//This function resets value of months if it exceeds more than 12 month
function reset_month($no_month){
	if ($no_month>12){
		$this_month=date('n');
		$reset=date('n',strtotime($no_month-$this_month ." months"));
	} else {
		$reset=$no_month;
	}
	
	return $reset;
}

//This function resets value of months if it exceeds more than 12 month
function calc_year($no_month,$no_year){
	
	$calc=date('Y',strtotime("+ ".$no_month." months",mktime(0,0,0,0,1,$no_year)));
	return $calc;
}

function get_age($birthDate){
	$bd=$birthDate;
	$td=date('d-m-Y');
	
	$bdx=converttounix($bd);
	$tdx=converttounix($td);
	
	$c=$tdx-$bdx;
	
	$age = ($c / 60 / 60 / 24 / 365.25);
	$age = number_format($age, 2);
	$agex=explode('.',$age);
	return $agex['0'];
}

//Function Upload
//------------------------------------------------------------------------------------------------
// to delete upload file
function delUploadFile($uploaddir,$filename){
	unlink($uploaddir.$filename)or die ("Could not delete file"); 
}
//-----------------------------------------------------------------------------------------------

//to upload file 
function uploadFile($tmpuploadfile,$uploadfile){
	
	if(move_uploaded_file($tmpuploadfile, $uploadfile)){
		return TRUE;
	} else {
		return FALSE;
	}	
}

?>
