<?
function START_TRANSACTION(){
	mysql_query('START TRANSACTION');
}
function COMMIT(){
	mysql_query('COMMIT');
}
function ROLLBACK(){
	mysql_query('ROLLBACK');
}

function stayfocus($form,$objname,$objvalue) {
     print("<SCRIPT LANGUAGE=Javascript>");
     printf("for(i=0;i<document.%s.%s.options.length;i++) {",$form,$objname);
     printf("if(document.%s.%s.options[i].value==\"%s\")",$form,$objname,$objvalue);
     printf("document.%s.%s.options[i].selected=true",$form,$objname);
     print("}");
     print("</SCRIPT>"); 
}
function staymultifocus($form,$objname,$objvalue) {
	for($i=0;$i<count($objvalue);$i++){
     print("<SCRIPT LANGUAGE=Javascript>");
     printf("for(i=0;i<document.%s.%s.options.length;i++) {",$form,$objname);
     printf("if(document.%s.%s.options[i].value=='%s')",$form,$objname,$objvalue[$i]);
     printf("document.%s.%s.options[i].selected=true",$form,$objname);
     print("}");
     print("</SCRIPT>"); 
	} 
}
function email_notification($nm,$lang){
	if($lang=="ENG")$sql="select en_subject as subject,en_message as message from email_notification where en_name='$nm'";
	else $sql="select en_subject as subject,en_chimessage as message from email_notification where en_name='$nm'";

	$result=mysql_query($sql);
	return $myrow=MySQL_fetch_array($result,MYSQL_ASSOC);
}
function system_date($date){
	list($d,$m,$y)=explode("/",$date);
	return $y."-".$m."-".$d;
}

function window_date($date){
	list($y,$m,$d)=explode("-",$date);
	return $d."/".$m."/".$y;
}
function record_valid($f,$t,$w){
	$sql="select $f from $t $w";
	$result=mysql_query($sql);
	$num_rows=mysql_num_rows($result);
	if($num_rows==0){
		return "FALSE";
	}else return "TRUE";
}


function get_data($f,$t,$w){
	$sql="select $f from $t $w";
	$result=mysql_query($sql) or die(mysql_error());
	$row=MySQL_fetch_array($result,MYSQL_ASSOC);
	return $row;
}

function record_num_rows($f,$t,$w){
	$sql="select $f from $t $w";
	$result=mysql_query($sql);
	return mysql_num_rows($result);
}


function nextid($f){
	$result=mysql_query("select $f from nextid");
	while($myrow=MySQL_fetch_array($result))
	     $ret=$myrow[$f];	

	$sql = "update nextid set $f =LAST_INSERT_ID($f+1)";
	if(!@mysql_query($sql))$mysql_error = mysql_error();
		 
	return $ret;

}
function last_insert_id($idtype){
	$sql = "update nextid set $idtype =LAST_INSERT_ID($idtype+1)";
	if(!@mysql_query($sql))$mysql_error = mysql_error();
}

function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message,$user,$cc,$bcc) {

	$message=str_replace("/UserFiles/$user/","http://crm.sepanggoldcoast.com/UserFiles/$user/",$message);
	$message=str_replace('\"','"',$message);

    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $name = basename($file);
//    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header = "From: ".$from_mail."\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    if($cc)$header .= "Cc: ".$cc."\r\n";
    if($bcc)$header .= "Bcc: ".$bcc."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/html; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";
    if (mail($mailto, $subject, "", $header)) {
//        echo "mail send ... OK"; // or use booleans here
    } else {
//        echo  "mail send ... ERROR!";
    }
}
function mail_sent($mailto, $from_mail, $from_name, $replyto, $subject, $message,$user,$cc,$bcc) {

	$message=str_replace("/UserFiles/$user/","crm.sepanggoldcoast.com/UserFiles/$user/",$message);

	$message=str_replace('\"','"',$message);
    $uid = md5(uniqid(time()));
	
//    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header = "From: ".$from_mail."\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    if($cc)$header .= "Cc: ".$cc."\r\n";
    if($bcc)$header .= "Bcc: ".$bcc."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/html; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
	
	if (mail($mailto, $subject, "", $header)) {
   //     echo "mail send ... OK"; // or use booleans here
	} else {
	 //   echo  "mail send ... ERROR!";
	}
	

}
function position_value(){
	$sql="select * from newvalue where nv_type='Position'";
	$result=mysql_query($sql) or die(mysql_error());
	while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
		$ret[$myrow["nv_id"]]=$myrow["nv_name"];

	return $ret;
}

function httpRequest($url){
  $pattern = "/http...([0-9a-zA-Z-.]*).([0-9]*).(.*)/";
    preg_match($pattern,$url,$args);
    $in = "";

	 $args[3]="w".$args[3];

//    $fp = fsockopen("$args[1]", $args[2], $errno, $errstr, 30);
    $fp = fsockopen("$args[1]", 80, $errno, $errstr, 30);
    if (!$fp) {
       return("$errstr ($errno)");
    } else {
        $out = "GET /$args[3] HTTP/1.1\r\n";
        $out .= "Host: $args[1]:$args[2]\r\n";
        $out .= "User-agent: BulkSMS2u PHP client\r\n";
   
        $out .= "Accept: */*\r\n";
        $out .= "Connection: Close\r\n\r\n";

        fwrite($fp, $out);
        while (!feof($fp)) {
          // $in.=fgets($fp, 128);
           $in=fgets($fp, 128);
        }
    }
  
    fclose($fp);
    return($in);

}

function SMSalert_sent($id,$type,$user){

	$debug = false;

	$ret=get_data("nv_id","newvalue","where nv_name='MOBILE'");
	$mobile=$ret["nv_id"];
	
	$stamp=nextid('n_sms');
	last_insert_id('n_sms');
	// search send 
	$sql="select * from sms_alert where smsa_id='$id'";
	$result=mysql_query($sql);	
	while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
	{
		$user=$myrow["smsa_user"];
		$ret= get_data("usergrp","user","where id='$user'");
		$ugrp=split(",",$ret["usergrp"]);
	
		$grp=$myrow["smsa_grp"];
		
		if($myrow["smsa_grp"]=="Y"){
			if($myrow["smsa_race"]>1)$psql_ar[]="p_race='".$myrow["smsa_race"]."'";
			if($myrow["smsa_type"]>1)$psql_ar[]="p_type='".$myrow["smsa_type"]."'";
			if($myrow["smsa_source"]>1)$psql_ar[]="p_source='".$myrow["smsa_source"]."'";
		}else $to=$myrow["smsa_contactno"];
	}	
	
	$n=0;
	unset($grprcp);
	//send person
	if($grp=="Y"){
		if(count($psql_ar)>0)$psql=implode(" and ",$psql_ar);
		else $psql="1";

		$sql="select p_id,p_name,p_phone1,p_phone1_label,p_phone2,p_phone2_label,p_phone3,p_phone3_label from person where 
		 $psql and p_active='Yes' and ((p_phone1<>'' && p_phone1_label='$mobile') or (p_phone2<>'' && p_phone2_label='$mobile') or (p_phone3<>'' && p_phone3_label='$mobile')) and p_user IN ('".implode("','",$ugrp)."')"; 
		$result=mysql_query($sql) or die(mysql_error());
		while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
		{
			unset($phone);
			if($myrow["p_phone1_label"]==$mobile && $myrow["p_phone1"]){
				$phone=$myrow["p_phone1"];
			}
			if($myrow["p_phone2_label"]==$mobile && $myrow["p_phone2"]){
				if($phone)$phone.="#".$myrow["p_phone2"];
				else $phone=$myrow["p_phone2"];
			}
			if($myrow["p_phone3_label"]==$mobile && $myrow["p_phone3"]){
				if($phone)$phone.="#".$myrow["p_phone3"];
				else $phone=$myrow["p_phone3"];
			}

			$grprcp[]=$myrow["p_id"]."|".$myrow["p_name"]."|$phone";
		}		

	}else{
		$contact=explode(",",$to);
		for($i=0;$i<count($contact);$i++)
		{
			$grprcp[]="-|-|".$contact[$i];
		}
	}
	
	if(count($grprcp)>0){
		for($i=0;$i<count($grprcp);$i++)
		{
			list($pid,$pname,$phone)=explode("|",$grprcp[$i]);
			$gphone=explode("#",$phone);

			for($j=0;$j<count($gphone);$j++){
				$phonenum=$gphone[$j];
				if($phonenum){	

					$sql="
						INSERT INTO `sms_outbox` (smso_stamp,
						`smso_alert` ,smso_phone,smso_name,`smso_created` ,smso_status,smso_user)
						VALUES ('$stamp','$id','$phonenum','$pname',CURRENT_TIMESTAMP,'Pending','$user'
						);
						";
					@mysql_query($sql) or die(mysql_error());

					$n++;
				}
			}
		}
	}

		
	if($type=="Now"){
		$sql="
		UPDATE `sms_alert` SET 
		`smsa_senddate` ='0000-00-00'
		 WHERE `smsa_id` ='$id'";
		@mysql_query($sql) or die(mysql_error());
	}		
	return $n;	
	
}

/*
version 1 
function SMSalert_sent($id,$type,$user){

	$debug = false;

	$ret=get_data("nv_id","newvalue","where nv_name='MOBILE'");
	$mobile=$ret["nv_id"];
	
	$stamp=nextid('n_sms');
	last_insert_id('n_sms');
	// search send 
	$sql="select * from sms_alert where smsa_id='$id'";
	$result=mysql_query($sql);	
	while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
	{
		$user=$myrow["smsa_user"];
		$ret= get_data("usergrp","user","where id='$user'");
		$ugrp=split(",",$ret["usergrp"]);
	
		//person
		if($myrow["smsa_pselect"]=="All")$psql="1";
		else if($myrow["smsa_pselect"]=="Individual"){
			if($myrow["smsa_title"]>1)$psql_ar[]="p_title='".$myrow["smsa_title"]."'";
			if($myrow["smsa_role"]>1)$psql_ar[]="p_role='".$myrow["smsa_role"]."'";
			if($myrow["smsa_race"]>1)$psql_ar[]="p_race='".$myrow["smsa_race"]."'";
			if($myrow["smsa_status"]>1)$psql_ar[]="p_status='".$myrow["smsa_status"]."'";
			if($myrow["smsa_gender"]>1)$psql_ar[]="p_gender='".$myrow["smsa_gender"]."'";
			if($myrow["smsa_ageformula"] && $myrow["smsa_age"] > 0){
				$dob=date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")-$myrow["smsa_age"]));
				$psql_ar[]="p_dob ".$myrow["smsa_ageformula"]." '$dob'";
			}
			if($myrow["smsa_type"]>1)$psql_ar[]="p_type='".$myrow["smsa_type"]."'";
			if($myrow["smsa_industry"]>1)$psql_ar[]="p_industry='".$myrow["smsa_industry"]."'";
			if($myrow["smsa_source"]>1)$psql_ar[]="p_source='".$myrow["smsa_source"]."'";
			if($myrow["smsa_classification"]>1)$psql_ar[]="p_classification='".$myrow["smsa_classification"]."'";
			if($myrow["smsa_country"])$psql_ar[]="p_country='".$myrow["smsa_country"]."'";
		}	
		//company
		if($myrow["smsa_cselect"]=="All")$csql="1";
		else if($myrow["smsa_cselect"]=="Individual"){
			if($myrow["smsa_cband"]>1)$csql_ar[]="c_band='".$myrow["smsa_cband"]."'";
			if($myrow["smsa_ctype"]>1)$csql_ar[]="c_type='".$myrow["smsa_ctype"]."'";
			if($myrow["smsa_cindustry"]>1)$csql_ar[]="c_industry='".$myrow["smsa_cindustry"]."'";
			if($myrow["smsa_csource"]>1)$csql_ar[]="c_source='".$myrow["smsa_csource"]."'";
			if($myrow["smsa_cclassification"]>1)$csql_ar[]="c_classification='".$myrow["smsa_cclassification"]."'";
			if($myrow["smsa_ccountry"])$csql_ar[]="c_country='".$myrow["smsa_ccountry"]."'";
		}
//		$p_dear=$myrow["smsa_pdear"];
//		$c_dear=$myrow["smsa_cdear"];
	}	
	
	$n=0;
	//send person
	if(count($psql_ar)>0)$psql=implode(" and ",$psql_ar);
	
	
	if($psql){
		$sql="select p_id,p_name,p_phone1,p_phone1_label,p_phone2,p_phone2_label,p_phone3,p_phone3_label from person where 
		 $psql and p_active='Yes' and ((p_phone1<>'' && p_phone1_label='$mobile') or (p_phone2<>'' && p_phone2_label='$mobile') or (p_phone3<>'' && p_phone3_label='$mobile')) and p_user IN ('".implode("','",$ugrp)."')"; 
//		 $psql and p_active='Yes' and ((p_phone1<>'' && p_phone1_label='$mobile') or (p_phone2<>'' && p_phone2_label='$mobile') or (p_phone3<>'' && p_phone3_label='$mobile')) and p_user='$user'"; 
		$result=mysql_query($sql) or die(mysql_error());
	//	$pnum=mysql_num_rows($result);
		while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
		{
			unset($phone);
			if($myrow["p_phone1_label"]==$mobile && $myrow["p_phone1"]){
				$phone=$myrow["p_phone1"];
			}
			if($myrow["p_phone2_label"]==$mobile && $myrow["p_phone2"]){
				if($phone)$phone.="#".$myrow["p_phone2"];
				else $phone=$myrow["p_phone2"];
			}
			if($myrow["p_phone3_label"]==$mobile && $myrow["p_phone3"]){
				if($phone)$phone.="#".$myrow["p_phone3"];
				else $phone=$myrow["p_phone3"];
			}

			$grprcp[]=$myrow["p_id"]."|".$myrow["p_name"]."|$phone";
			
		}		

		if(count($grprcp)>0){
			for($i=0;$i<count($grprcp);$i++)
			{
				list($pid,$pname,$phone)=explode("|",$grprcp[$i]);
				$gphone=explode("#",$phone);
//				if($p_dear=="name")$disname=$pname;
//				else if($p_dear=="default")$disname="Valued Customer";

				for($j=0;$j<count($gphone);$j++){
					$phonenum=$gphone[$j];
					if($phonenum){	

						$sql="
							INSERT INTO `sms_outbox` (smso_stamp,
							`smso_alert` ,smso_phone,smso_name,`smso_created` ,smso_status,smso_user)
							VALUES ('$stamp','$id','$phonenum','$pname',CURRENT_TIMESTAMP,'Pending','$user'
							);
							";
						@mysql_query($sql) or die(mysql_error());

						$n++;
					}
				}
			}
		}
	}

	// company
	if(count($csql_ar)>0)$csql=implode(" and ",$csql_ar);
	unset($grprcp);
	if($csql){
		$sql="select c_id,c_name,c_phone1,c_phone1_label,c_phone2,c_phone2_label,c_phone3,c_phone3_label from company
		 where $csql and c_active='Yes' and ((c_phone1<>'' && c_phone1_label='$mobile') or (c_phone2<>'' && c_phone2_label='$mobile') or (c_phone3<>'' && c_phone3_label='$mobile')) and  c_user IN ('".implode("','",$ugrp)."')"; 
		$result=mysql_query($sql) or die(mysql_error());
		$cnum=mysql_num_rows($result);
		while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
		{
			unset($phone);		
			if($myrow["c_phone1_label"]==$mobile && $myrow["c_phone1"]){
				$phone=$myrow["c_phone1"];
			}
			if($myrow["c_phone2_label"]==$mobile && $myrow["c_phone2"]){
				if($phone)$phone.="#".$myrow["c_phone2"];
				else $phone=$myrow["c_phone2"];
			}
			if($myrow["c_phone3_label"]==$mobile && $myrow["c_phone3"]){
				if($phone)$phone.="#".$myrow["c_phone3"];
				else $phone=$myrow["c_phone3"];
			}
			
			$dnm=$myrow["c_name"];
//			if($myrow["c_person"])$dnm=$myrow["c_person"];
	//		else $dnm="Valued Customer";
			$grprcp[]=$myrow["c_id"]."|$dnm|$phone";
			
		}		
		if(count($grprcp)>0){
			for($i=0;$i<count($grprcp);$i++)
			{
				list($pid,$pname,$phone)=explode("|",$grprcp[$i]);
				$gphone=explode("#",$phone);
//				if($c_dear=="name")$disname=$pname;
//				else if($c_dear=="default")$disname="Valued Customer";

				for($j=0;$j<count($gphone);$j++){
					$phonenum=$gphone[$j];
					if($phonenum){

						$sql="
							INSERT INTO `sms_outbox` (smso_stamp,
							`smso_alert` ,smso_phone,smso_name,`smso_created` ,smso_status,smso_user)
							VALUES ('$stamp','$id','$phonenum','$pname',CURRENT_TIMESTAMP,'Pending','$user'
							);
							";
						@mysql_query($sql) or die(mysql_error());	
						
						$n++;
					}
				}
			}
		}
		
	}



		
	if($type=="Now"){
		$sql="
		UPDATE `sms_alert` SET 
		`smsa_senddate` ='0000-00-00'
		 WHERE `smsa_id` ='$id'";
		@mysql_query($sql) or die(mysql_error());
	}		
	return $n;	
	
}
*/
function SendSMS($phone, $msg, $debug=false, $sender){
//      global $bulksms2u_user,$bulksms2u_password,$bulksms2u_url;
//echo ">>>>>>>>>>>>".SMS_USER;
	$bulksms2u_user = SMS_USER;
	$bulksms2u_password = SMS_PWD;
	$bulksms2u_url = SMS_API;
	  

      $url = 'username='.$bulksms2u_user;
      $url.= '&password='.$bulksms2u_password;
      $url.= '&sender='.$sender;
      $url.= '&type=1';
      $url.= '&mobile='.urlencode($phone);
      $url.= '&message='.urlencode($msg);

      $urltouse =  $bulksms2u_url.$url;
      if ($debug) { echo "Request: <br>$urltouse<br><br>"; }

      //Open the URL to send the message
      $response = httpRequest($urltouse);
      if ($debug) {
           echo "Response: <br><pre>".
           str_replace(array("<",">"),array("&lt;","&gt;"),$response).
           "</pre><br>"; }

      return($response);
}


function insert_log($user,$desc){
	$sql="insert into log (l_user,l_desc) values ('$user',\"$desc\")";
	@mysql_query($sql) or die(mysql_error());
}


function destroy($dir) {

	$mydir = opendir($dir);
	while(false !== ($file = readdir($mydir))) {
		if($file != "." && $file != "..") {
			chmod($dir.$file, 0777);
			if(is_dir($dir.$file)) {
				chdir('.');
				destroy($dir.$file.'/');
				rmdir($dir.$file) or DIE("couldn't delete $dir$file<br />");
            }else unlink($dir.$file) or DIE("couldn't delete $dir$file<br />");
		}
	 }
	 closedir($mydir);
}
function generatePassword($length=8, $strength=4) {
	$vowels = 'aeuy';
	$consonants = 'bdghjmnpqrstvz';
	if ($strength & 1) {
		$consonants .= 'BDGHJLMNPQRSTVWXZ';
	}
	if ($strength & 2) {
		$vowels .= "AEUY";
	}
	if ($strength & 4) {
		$consonants .= '23456789BDGHJLMNPQRSTVWXZ';
	}
	if ($strength & 8) {
		$consonants .= '@#$%';
	}
 
	$password = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++) {
		if ($alt == 1) {
			$password .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		} else {
			$password .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
		}
	}
	return $password;
}

function get_days($d1,$d2){
	$sql="select to_days('$d2')-to_days('$d1') as a";
	$result=mysql_query($sql) or die(mysql_error());
	while($myrow=MySQL_fetch_array($result))return $myrow["a"];

}
function reserv_num($no,$st,$ye){
	$sql="select sum(irs_confirm_night) as tot from ivc_reservation where irs_status='Y' and irs_memberno='$no' 
	and irs_confirm_date >= '$st' and irs_confirm_date <='$ye'";
	$result=mysql_query($sql) or die(mysql_error());
	while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
	 return $myrow["tot"];
	
	return 0;
}

function vacation_info($no){
	$sql="select ye_expiry,ye_night,ye_start from ivc_yearly_ent where ye_memberno='$no' and ye_expiry >= '".date("Y-m-d")."' order by ye_expiry limit 1";
	$result=mysql_query($sql) or die(mysql_error());
	while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
	{
		$ye=$myrow["ye_expiry"];
		$st=$myrow["ye_start"];
		$entnight=$myrow["ye_night"];
	}


	$tot_night=reserv_num($no,$st,$ye);

	$tot=$entnight - $tot_night;	

	$sql="select ip_code,ip_name,ip_adult,ip_child,im_expired,im_entnight,ir_type,ir_descr,im_scheme,im_freemaint,im_program  
	from ivc_members left join ivc_products on im_scheme=ip_id left join ivc_rooms on ip_room = ir_id where im_formno ='$no'";
	$result=mysql_query($sql) or die(mysql_error());
	if(mysql_num_rows($result)==0)echo "1";	
	else{
		while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
		{

			$ret= $myrow["ip_code"]." - ".$myrow["ip_name"]."|".$myrow["ir_type"]." - ".$myrow["ir_descr"]."|$entnight|".$myrow["im_freemaint"]."|".$myrow["im_expired"]."|$tot|$ye|".$myrow["im_program"]."|".$myrow["ip_adult"]."|".$myrow["ip_child"];
		}
	}
	
	return $ret;
}

function book_adv(){
	return date("Y-m-d",mktime(0,0,0,date("m"),date("d")+14,date("Y")));
}

function yearly_expired($memberno){

	$sql="select ye_expiry from ivc_yearly_ent where ye_memberno='$memberno' and ye_expiry >= '".date("Y-m-d")."' order by ye_expiry limit 1";
	$result=mysql_query($sql) or die(mysql_error());
	while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
	{
		return $myrow["ye_expiry"];
	}
}


?>
