<?php
	class Utility {


		/**********************************************************
		/ This function will Add Visitor detail
		**********************************************************/

		public static function AddVisitor() {

			global $db;

			if(isset($_COOKIE['uid'])){
				$data['UniqueID']= $_COOKIE['uid'];
			}else{
				$data['UniqueID']= md5(uniqid(time()));
				$expire=time()+60*60*24*365;
				setcookie("uid", $data['UniqueID'], $expire,'/travel');
			}


			$data['IP']=$_SERVER['REMOTE_ADDR'];
			$data['IP-X-Forward']=@getenv("HTTP_X_FORWARDED_FOR");
			$data['HTTP_USER_AGENT']=$_SERVER['HTTP_USER_AGENT'];
			$data['Page_URL']=$_SERVER['PHP_SELF'];
			$data['OrderID']=$_COOKIE['tempid'];
			$data['VisitTimeStamp']=time();
			$data['lastupdated']='now()';

			$db->query_insert(TABLE_VISITORS, $data);

				if($db->affected_rows > 0){

							return true;
					}else{

							return false;
					}

		}//AddVisitor


		/**********************************************************
		/ This function will return   city list
		**********************************************************/

		public static function GetCityList($filter="") {

			global $db;
			$query = "SELECT * from city ". $filter;
			//print($query);exit;
			$rows = $db->fetch_all_array($query);

				if($db->affected_rows > 0){

							return $rows;
					}else{

							return false;
					}
		}//GetCityList

		/**********************************************************
		/ This function will return   city
		**********************************************************/

		public static function GetCity($city) {

			global $db;
			$query = "SELECT * from city  where id='$city'";
			//print($query);exit;
			$rows = $db->query_first($query);

				if($db->affected_rows > 0){

							return $rows;
					}else{

							return false;
					}
		}//GetCity

		//default constructor. Private doesn't allow to create encryption class object
		private function encryption() {

			//do nothing
		} //default constructor

		public static function RandomCharacter($length) {

			srand(date("s"));
			$possible_charactors = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			$string = "";
			while(strlen($string)<$length) {

				$string .= substr($possible_charactors, (rand()%(strlen($possible_charactors))),1);

			}  //while

		return($string);

		}
		public static function RandomNumber($length) {

			srand(date("s"));
			$possible_charactors = "1234567890";
			$string = "";
			while(strlen($string)<$length) {

				$string .= substr($possible_charactors, (rand()%(strlen($possible_charactors))),1);

			}  //while

		return($string);

		}

		// To Encrypt string
		public static function encrypt() {

			$num_args = func_num_args();

			$param= "";
			for($x=0;$x<$num_args;$x++) {

				$param .= trim(func_get_arg($x))."||";

			}

			$param = substr($param,0,strlen($param)-2);

			$param = base64_encode($param);
			$m=1;
			$str="";

			for($i=0;$i<strlen($param);$i++) {
				$str .=substr($param,$i,1);

				if($m==4) {

					$possible_charactors = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
					$val = substr($possible_charactors, rand(0,strlen($possible_charactors))%(strlen($possible_charactors)-20),1);
					$str .=$val;
					$m=1;
				}

			$m++;
		}

		$str = str_replace("=","TcVY",$str);
		return $str;

		} //function

		// To Decrypt String
		public static function decrypt($str) {

			$arr=array('%','$','/','\\','*','+','-','\'','"','#','@','(',')','^','~','`','&',
					'_',',',':',';','?','<','>','!','{','}','[',']');

			$str=str_replace($arr,'',$str);

			$str = str_replace("TcVY","=",$str);
			$m=1;
			$d_str="";
			for($i=0;$i<strlen($str);$i++) {
				if($m!=5) {
						$d_str .= substr($str,$i,1);
					} else {
						$m=1;
					}
				$m++;
			}

			$d_str = base64_decode($d_str);
			return explode("||",$d_str);

		} //function

		/****************************************************************************
		//	 This function will send HTML base EMAIL.
		****************************************************************************/

		public static function SendMail($to,$from,$subject,$message,$cc='0',$bcc='0') {

			$headers  = "MIME-Version: 1.0\r\n";
			$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
			$headers .= "From:  $from\r\n";

			if(strcmp($cc,'0'))
				$headers .= "Cc: $cc\r\n";
			if(strcmp($bcc,'0'))
				$headers .= "Bcc: $bcc\r\n";

			$headers .= "Reply-To: <$from>\r\n";
			$headers .= "X-Mailer: PHP/" . phpversion();
			mail($to, $subject, $message, $headers);

		} //function

		/**************************************************************************************
						Read html via filing
		***************************************************************************************/

		public static function ReadFile($path) {

			$fp = fopen($path,"r");

			$str = "";

			while(!feof($fp))  {

				$str .= fread($fp,1024);

			}
			fclose($fp);
			return $str;


		}

		/*********************************************************************************************
		//	 This function removing to those character that can inject to database from REQUEST Array
		**********************************************************************************************/

		public static function ClearSqlInjection($arr) {

			$arr = array();

			foreach($_REQUEST as $var => $val) {

				$val = addslashes($val);
				$arr[$var] = $val;

			}

			return $arr;

		}



		/*********************************************************************************************
		//	 This function get Complete URL
		**********************************************************************************************/
		public static function getAddress()  {

			/*** check for https ***/
			$protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';

			/*** return the full address ***/
			return $protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

		}
		/*********************************************************************************************
		//	 This function will return the how much time before
		**********************************************************************************************/

		public static function rel_time($from, $to = null)
		 {
		  $to = (($to === null) ? (time()) : ($to));
		  $to = ((is_int($to)) ? ($to) : (strtotime($to)));
		  $from = ((is_int($from)) ? ($from) : (strtotime($from)));

		  $units = array
		  (
		   "YEAR"   => 29030400, // seconds in a year   (12 months)
		   "MONTH"  => 2419200,  // seconds in a month  (4 weeks)
		   "WEEK"   => 604800,   // seconds in a week   (7 days)
		   "DAY"    => 86400,    // seconds in a day    (24 hours)
		   "HOUR"   => 3600,     // seconds in an hour  (60 minutes)
		   "MINUTE" => 60,       // seconds in a minute (60 seconds)
		   "SECOND" => 1         // 1 second
		  );

		  $diff = abs($from - $to);
		  $suffix = (($from > $to) ? ("FROM NOW") : ("AGO"));

		  foreach($units as $unit => $mult)
		   if($diff >= $mult)
		   {

			$and = (($mult != 1) ? ("") : ("and "));
			$output .= ", ".$and.intval($diff / $mult)." ".$unit.((intval($diff / $mult) == 1) ? ("") : ("S"));

			$diff -= intval($diff / $mult) * $mult;
			if(strcmp($output,"year"))break;
			if(strcmp($output,"month"))break;
			if(strcmp($output,"week"))break;
			if(strcmp($output,"day"))break;
			if(strcmp($output,"minute"))break;
			if(strcmp($output,"second"))break;
		   }
		  $output .= " ".$suffix;
		  $output = substr($output, strlen(", "));

		  return $output;

		 }//rel_time



			public static function getDifference($startDate,$endDate,$format = 6)
			{
				list($date,$time) = explode(' ',$startDate);
				$startdate = explode("-",$date);
				$starttime = explode(":",$time);

				list($date,$time) = explode(' ',$endDate);
				$enddate = explode("-",$date);
				$endtime = explode(":",$time);

				$secondsDifference = mktime($endtime[0],$endtime[1],$endtime[2],
					$enddate[1],$enddate[2],$enddate[0]) - mktime($starttime[0],
						$starttime[1],$starttime[2],$startdate[1],$startdate[2],$startdate[0]);

				//print($startDate." ".$endDate);
				switch($format){
					// Difference in Minutes
					case 1:
						return floor($secondsDifference/60);
					// Difference in Hours
					case 2:
						return floor($secondsDifference/60/60);
					// Difference in Days
					case 3:
						return floor($secondsDifference/60/60/24);
					// Difference in Weeks
					case 4:
						return floor($secondsDifference/60/60/24/7);
					// Difference in Months
					case 5:
						return floor($secondsDifference/60/60/24/7/4);
					// Difference in Years
					default:
						return floor($secondsDifference/365.25/60/60/24);
				}
			} //getDifference

		/**********************************************************
		/ This function will return   coutry list
		**********************************************************/

		public static function GetCoutryList($countrytype) {

			global $db;
			$query = "SELECT * from ".TABLE_COUNTRY." where countrytype='$countrytype' order by countryname ";
			//print($query);exit;
			$rows = $db->fetch_all_array($query);

				if($db->affected_rows > 0){

							return $rows;
					}else{

							return false;
					}
		}//GetCoutryList

		public static function check_email_address($email) {
        // First, we check that there's one @ symbol, and that the lengths are right
        if (!preg_match("/^[^@]{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 (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
                return false;
            }
        }
        if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
            $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 (!preg_match("/^(([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;
    }


	}//utility class



?>