<?php
defined('PATH_LIB') or die("Restricted Access");
function redirect($url=NULL)
{
	if(is_null($url)) $url=curPageURL();
	if(headers_sent())
	{
		echo "<script>window.location='".$url."'</script>";
	}
	else
	{
		header("Location:".$url);
	}
	exit;
}
function chkHeader()
{
	if(strpos($_SERVER['HTTP_REFERER'],URL_ROOT)==0) return true;
	return false;
}
/*cart detail for add to card*/
if (!function_exists('POST')) {
    function POST($i, $trim = false)
    {
        if (isset($_REQUEST[$i]))
            $i = $_REQUEST[$i];
        if ($trim)
            $i = trim($i);
        if (!get_magic_quotes_gpc())
            $i = addslashes($i);
        $i = rtrim($i);
        $look = array('&', '#', '<', '>', '"', '\'', '(', ')', '%');
        $safe = array('&amp;', '&#35;', '&lt;', '&gt;', '&quot;', '&#39;', '&#40;', '&#41;', '&#37;');
        $i = str_replace($look, $safe, $i);
        //$i = htmlentities($i);
        return $i;
    }
    function unPOST($i)
    {
        global $db;
        $look = array('&', '#', '<', '>', '"', '\'', '(', ')', '%');
        $safe = array('&amp;', '&#35;', '&lt;', '&gt;', '&quot;', '&#39;', '&#40;', '&#41;', '&#37;');
        $i = str_replace($safe, $look, $i);
        $msg = $i;
        return stripslashes($msg); //.$db->getErMsg();
    }
}
function addtocart($pid,$qty)
{
	if(!isset($_SESSION['cart']))
	{
		$_SESSION['cart'][$pid] = $qty;
	}
	else
	{
			if(array_key_exists($pid,$_SESSION['cart']))
			{
				$_SESSION['cart'][$pid] =$_SESSION['cart'][$pid]+ $qty;
			}
			else
			{
				$_SESSION['cart'][$pid] =$qty;
			}
	}
	
}
function updatecart($pid,$qty)
{
	if($qty ==0 or empty($qty))
	{
		unset($_SESSION['cart'][$pid]);
	}
	else
	{
		$_SESSION['cart'][$pid] = $qty;
	}
}
function getStock($pid){
	global $db;
	$st=$db->getVal("select stock from product where school_id='".$_SESSION["admin"]["school_id"]."' and product_id='".$pid."'");
	return $st;
}
function loc($page)
{
	header("location:$page");
}
function price($pid)
{
	global $db;
	$pquery=$db->getVal("SELECT new_price FROM product WHERE product_id='$pid'");
	return $pquery;	
}
/*end card detail*/
function setMsgPage($mod, $sec, $type, $note)
{
	//possible values for type
	//success
	//information
	//warning
	//error
	if(!isset($_SESSION['msg_er'])) $_SESSION['msg_er']=array();
	if(!isset($_SESSION['msg_er'][$mod])) $_SESSION['msg_er'][$mod]=array();
	if(!isset($_SESSION['msg_er'][$mod][$sec])) $_SESSION['msg_er'][$mod][$sec]=array();
	
	$_SESSION['msg_er'][$mod][$sec]['page']=array(
												  'type'=>$type,
												  'note'=>$note
												  );
}
function getMsgPage($mod, $sec)
{
	$return='';
	if(isset($_SESSION['msg_er'][$mod][$sec]['page']) && is_array($_SESSION['msg_er'][$mod][$sec]['page']) && count($_SESSION['msg_er'][$mod][$sec]['page'])>0)
	{
		$class=$_SESSION['msg_er'][$mod][$sec]['page']['type'];
		$return="<div class=\"notification ".$class."\">";
		$return.=$_SESSION['msg_er'][$mod][$sec]['page']['note'];
		$return.="</div>";
		
		unset($_SESSION['msg_er'][$mod][$sec]['page']);
	}
	
	clearErMsg($mod,$sec);
	
	return $return;
}
function setMsgField($mod, $sec, $field, $type, $note)
{
	//possible values for type
	//success
	//information
	//warning
	//error
	
	if(!isset($_SESSION['msg_er'])) $_SESSION['msg_er']=array();
	
	if(!isset($_SESSION['msg_er'][$mod])) $_SESSION['msg_er'][$mod]=array();
	if(!isset($_SESSION['msg_er'][$mod][$sec])) $_SESSION['msg_er'][$mod][$sec]=array();
	
	if(!isset($_SESSION['msg_er'][$mod][$sec]['field'])) $_SESSION['msg_er'][$mod][$sec]['field']=array();
	
	$_SESSION['msg_er'][$mod][$sec]['field'][$field]=array(
														   'type'=>$type,
														   'note'=>$note
														   );
}
function getMsgField($mod, $sec, $field)
{
	$return='';
	if(isset($_SESSION['msg_er'][$mod][$sec]['field'][$field]) && is_array($_SESSION['msg_er'][$mod][$sec]['field'][$field]) && count($_SESSION['msg_er'][$mod][$sec]['field'][$field])>0)
	{
		$class=$_SESSION['msg_er'][$mod][$sec]['field'][$field]['type'];
		$return="<span class=\"notification ".$class."\">";
		$return.=$_SESSION['msg_er'][$mod][$sec]['field'][$field]['note'];
		$return.="</span>";
		unset($_SESSION['msg_er'][$mod][$sec]['field'][$field]);
	}
	if(isset($_SESSION['msg_er'][$mod][$sec]['field']) && is_array($_SESSION['msg_er'][$mod][$sec]['field']) && count($_SESSION['msg_er'][$mod][$sec]['field'])===0) unset($_SESSION['msg_er'][$mod][$sec]['field']);
	
	clearErMsg($mod,$sec);
	
	return $return;
}
function clearErMsg($mod,$sec)
{
	if(isset($_SESSION['msg_er'][$mod][$sec]) && is_array($_SESSION['msg_er'][$mod][$sec]) && count($_SESSION['msg_er'][$mod][$sec])===0) unset($_SESSION['msg_er'][$mod][$sec]);
	
	if(isset($_SESSION['msg_er'][$mod]) && is_array($_SESSION['msg_er'][$mod]) && count($_SESSION['msg_er'][$mod])===0) unset($_SESSION['msg_er'][$mod]);
	
	if(isset($_SESSION['msg_er']) && is_array($_SESSION['msg_er']) && count($_SESSION['msg_er'])===0) unset($_SESSION['msg_er']);
}
function setSort($mod,$sec,$val)
{
	if(!isset($_SESSION['sort'])) $_SESSION['sort']=array();
	if(!isset($_SESSION['sort'][$mod])) $_SESSION['sort'][$mod]=array();
	
	$_SESSION['sort'][$mod][$sec]=$val;
}
function getSort($mod,$sec)
{
	return $_SESSION['sort'][$mod][$sec];
}
function curPageURL() 
{
	$pageURL = 'https';
 	//if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 	$pageURL .= "://";
 	if ($_SERVER["SERVER_PORT"] != "80") 
	{
  		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 	} 
	else 
	{
  		$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 	}
 	return $pageURL;
}
function getQueryString($aryQueryStr)
{
	$aryMatch=array();
	foreach($aryQueryStr as $opt=>$val) { $aryMatch[]=$opt.'='.urlencode($val); }
	return '?'.implode('&',$aryMatch);
}
function selected($needle,$haystack)
{
	if(is_array($haystack) && in_array($needle,$haystack)) { return 'selected="selected"'; }
	elseif(!is_array($haystack) && $needle===$haystack) { return 'selected="selected"'; }
	else { return ''; }
}
function checked($needle,$haystack)
{
	if(is_array($haystack) && in_array($needle,$haystack)) { return 'checked="checked"'; }
	elseif(!is_array($haystack) && $needle===$haystack) { return 'checked="checked"'; }
	else { return ''; }
}
function isValidDate($val)
{
	if(preg_match(REGX_DATE,$val))
	{
		list($year,$month,$date)=explode("-",$val);
		if(checkdate($month,$date,$year)) return true;
	}
	return false;
}
function isAdmin()
{
	if(isset($_SESSION[LOGIN_ADMIN]) && is_array($_SESSION[LOGIN_ADMIN]) && isset($_SESSION[LOGIN_ADMIN]['id'])) return true;
	return false;
}
function getFileSize($path)
{
	if(is_array($path) && count($path)>0)
	{
		//if(!file_exists($path)) return 0;
		//if(is_file($path)) return filesize($path);
		$ret = 0;
		foreach($path as $file)
			$ret+=getFileSize($file);
		return $ret;
	}
	else
	{
		if(!file_exists($path)) return 0;
		if(is_file($path)) return filesize($path);
	}
}
function getRealIpAddr()
{
    if(!empty($_SERVER['HTTP_CLIENT_IP']))//check ip from share internet
    { 
		$ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))//to check ip is pass from proxy
    { 
		$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    { 
		$ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
function fetchSetting(){
	$aryReturn=array();
	$strSetting='';
	global $db;
	if(SETTING=="setting"){
		$aryReturn=$db->getRow("select * from setting where school_id='".$_SESSION["admin"]["school_id"]."' ");
	}else{
		$arySetData=$db->getRows("select * from settings");
		if(is_array($arySetData) && count($arySetData)>0)
		{
			foreach($arySetData as $iSetData)
			{
				$aryReturn[$iSetData['field']]=$iSetData['value'];
			}
		}
	}
	
	return $aryReturn;
}
function getStatusImg($status)
{
	$aryImg=array(
				  '0'=>"status_inactive.png",
				  '2'=>"status_reject.png",
				  '1'=>"status_active.png"
				  );
	return '<img src="'.URL_ADMIN_IMG.$aryImg[$status].'" title="'.getStatusStr($status).'" />';
}
function getStImg($status)
{
	$aryImg=array(
				  'Pending'=>"status_pending.png",
				  'Cancelled'=>"status_pending.png",
				  'Success'=>"status_active.png",
				  'Shipped'=>"status_pending.png"
				  );
	return '<img src="'.URL_ADMIN_IMG.$aryImg[$status].'" title="'.getStStr($status).'" />';
}
function getPImg($status)
{
	$aryImg=array(
				  'Incomplete'=>"status_pending.png",
				  'Cancelled'=>"status_pending.png",
				  'Completed'=>"status_active.png"
				  );
	return '<img src="'.URL_ADMIN_IMG.$aryImg[$status].'" title="'.getPStr($status).'" />';
}
function getOptionImg($status)
{
	$aryImg=array(
				  '0'=>"cross.png",
				  '1'=>"tick.png"
				  );
	return '<img src="'.URL_ADMIN_IMG."icons/".$aryImg[$status].'" />';
}
function getStatusStr($val)
{
	if($val==0)
	{
		return "Inactive";
	}
	else
	{
		return "Active";
	}
}
function getStStr($val)
{
	if($val=='Pending')
	{
		return "Pending";
	}
	elseif($val=='Cancelled')
	{
		return "Cancelled";
	}
	elseif($val=='Shipped')
	{
		return "Shipped";
	}
	else
	{
		return "Success";
	}
}
function getPStr($val)
{
	if($val=='Incomplete')
	{
		return "Incomplete";
	}
	elseif($val=='Cancelled')
	{
		return "Cancelled";
	}else
	{
		return "Completed";
	}
}
function getOptionStr($val)
{
	if($val==0)
	{
		return "No";
	}
	else
	{
		return "Yes";
	}
}
function delete_directory($dirname)
{
	if (is_dir($dirname))
      $dir_handle = opendir($dirname);
   if (!$dir_handle)
      return false;
   while($file = readdir($dir_handle))
   {
      if ($file != "." && $file != "..")
	  {
         if (!is_dir($dirname.DS.$file))
            @unlink($dirname.DS.$file);
         else
            delete_directory($dirname.DS.$file);    
      }
   }
   closedir($dir_handle);
   @rmdir($dirname);
   return true;
}
function check_login($userType='User')
{
	if($userType=='User' && (!isset($_SESSION[LOGIN_USER]) || count($_SESSION[LOGIN_USER])==0))
		return false;
	elseif($userType=='Admin' && (!isset($_SESSION[LOGIN_ADMIN]) || count($_SESSION[LOGIN_ADMIN])==0))
		return false;
		
	return true;
}
function listDirs($where){
	$directoryarr=array();
    $itemHandler=opendir($where);
    $i=0;
    while(($item=readdir($itemHandler)) !== false){
	if ($item == "." || $item == "..") { }
	else {$directoryarr[]=$item;}
       }
	  return($directoryarr);
}
function recurse_copy($src,$dst) { 
    $dir = opendir($src); 
    @mkdir($dst); 
    while(false !== ( $file = readdir($dir)) ) { 
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) { 
                recurse_copy($src . '/' . $file,$dst . '/' . $file); 
            } 
            else { 
                copy($src . '/' . $file,$dst . '/' . $file); 
            } 
        } 
    } 
    closedir($dir); 
}
function enum_select( $table , $field )
{
	global $db;
	$query = "SHOW COLUMNS FROM `$table` LIKE '$field' ";
	$row = $db->getRow( $query );
	#extract the values
	#the values are enclosed in single quotes
	#and separated by commas
	$regex = "/'(.*?)'/";
	preg_match_all( $regex , $row[1], $enum_array );
	$enum_fields = $enum_array[1];
	return( $enum_fields );
}
function randomFix($length)
{
	$random= "";
	
	srand((double)microtime()*1000000);
	
	$data = "AbcDE123IJKLMN67QRSTUVWXYZ";
	$data .= "aBCdefghijklmn123opq45rs67tuv89wxyz";
	$data .= "0FGH45OP89";
	
	for($i = 0; $i < $length; $i++)
	{
		$random .= substr($data, (rand()%(strlen($data))), 1);
	}
	return $random;
}
function href($page,$param="")
{
	global $db;
	$sef="1";
	if($sef=="1")
	{
		$x = explode("&",$param);
		$var = array();
		foreach($x as $k1 => $v1)
		{
			$x2 = explode("=",$v1);
		
			$var[$x2[0]]=$x2[1];
		}
		switch($page)
		{
		case 'page.php' :
		{
			if(isset($var['page_id']))
			{
			  $name=$db->getVal("SELECT linkname FROM cms WHERE school_id='".$_SESSION["admin"]["school_id"]."' and id='".$var['page_id']."'");
			  //$name=str_replace("-","dash",$name); 			
			  //$pagename=str_replace(" ","-",str_replace("+","~",str_replace("&","and",$name)));
			  //return URL_ROOT.'page.php?page_id='.$var['page_id'].'&page='.$name;
			  return URL_ROOT.'content/'.$var['page_id'].'/'.$name;
			}
			break;
		}
		case 'search.php' :
		{
			if(isset($var['subcat_id']))
			{
			  $name=$db->getVal("SELECT category_name FROM category WHERE school_id='".$_SESSION["admin"]["school_id"]."' and category_id='".$var['subcat_id']."'");
			 // $name=str_replace("-","dash",$name);
			  $pagename=str_replace(" ","-",str_replace("+","~",str_replace("&","and",str_replace("%","",$name))));
			  //return URL_ROOT.'search.php?id='.$var['subcat_id'].'&page='.strtolower($pagename);
			  return URL_ROOT.'product/'.$var['subcat_id'].'/'.strtolower($pagename);
			}
			elseif(isset($var['cat_id']))
			{
			  $name=$db->getVal("SELECT category_name FROM category WHERE school_id='".$_SESSION["admin"]["school_id"]."' and category_id='".$var['cat_id']."'");
			 // $name=str_replace("-","dash",$name);
			  $pagename=str_replace(" ","-",str_replace("+","~",str_replace("&","and",str_replace("%","",$name))));
			  //return URL_ROOT.'search.php?id='.$var['subcat_id'].'&page='.strtolower($pagename);
			  return URL_ROOT.'category/'.$var['cat_id'].'/'.strtolower($pagename);
			}	
			break;
		}
		case 'product_detail.php' :
		{
			if(isset($var['product_id']))
			{
				$name=$db->getVal("SELECT name FROM product WHERE school_id='".$_SESSION["admin"]["school_id"]."' and product_id='".$var['product_id']."'");
			 // $name=str_replace("-","dash",$name);
			  $pagename=str_replace(" ","-",str_replace("+","~",str_replace("&","and",str_replace("%","",$name))));
			  //return URL_ROOT.'search.php?id='.$var['subcat_id'].'&page='.strtolower($pagename);
			  return URL_ROOT.'detail/'.$var['product_id'].'/'.strtolower($pagename);
			}
		}
		case 'address.php' :
		{
			if(isset($var['action']) && $var['action']=="add")
			{
				return URL_ROOT.'add-detail-new';
			}
			if(isset($var['action']) && $var['action']=="edit")
			{
				return URL_ROOT.$var["aid"].'/edit-detail-new';
			}
		}
		case 'confirmaddress.php' :
		{
			if(isset($var['step']) && $var['step']=="1")
			{
				return URL_ROOT.'cart-step-1';
			}
		}
		case 'my-account.php' :
		{
			if(isset($var['action']) && $var['action']=="cart")
			{
				return URL_ROOT.'login-check';
			}
		}
		case "myorder.php":
		{
			if(isset($var['oid']) && isset($var['status']))
			{
				return URL_ROOT.'status-orders/'.$var['oid'].'/'.$var['status'];
			}
			else{
				return URL_ROOT.'my-orders';
			}
		}
		case 'addtocart.php' :
		{
			return URL_ROOT.'my-cart';
		}
		case 'checkout.php' :
		{
			return URL_ROOT.'cart-step-2';
		}
		case 'myhome.php' :
		{
			return URL_ROOT.'dashboard';
		}
		case 'booking.php' :
		{
			return URL_ROOT.'booking';
		}
		case 'customer_service.php' :
		{
			return URL_ROOT.'contact-form';
		}
	default:
			{
				if($param=="")
				{
				  return URL_ROOT.$page;
				}
				else
				{
				  return URL_ROOT.$page.'?'.$param;
				}
			}
		
		}
	
	}
	else
	{ 
		if($param=="")
		{
		  return URL_ROOT.$page;
		}
		else
		{
		  return URL_ROOT.'/'.$page.'?'.$param;
		}
	}	
}
  
	
function UpdateUserPosition($sort_order,$id,$table,$field)
{
	global $db;
	$db->updateAry($table,array($field=>($sort_order + 1)),' WHERE id = '.$id);
}
function addvisit()
{
	global $db;
	$qry='CREATE TABLE IF NOT EXISTS `no_visit` (
	  `id` int(11) NOT NULL AUTO_INCREMENT,
	  `ndate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
	  `ip` varchar(150) NOT NULL,
	  `page` varchar(150) NOT NULL,
	  `no` int(11) NOT NULL,
	  PRIMARY KEY (`id`)
	) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;';
	$db->query($qry);
	$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	$v_id=$db->getVal("select no from no_visit where school_id='".$_SESSION["admin"]["school_id"]."' and ip='".$_SERVER['REMOTE_ADDR']."' and page='".$url."'");
	if($v_id==''){
		$VisitData=array("ip"=>$_SERVER['REMOTE_ADDR'],
					"page"=>$url,
					"no"=>1
		);
		$flgVisi=$db->insertAry("no_visit",$VisitData);
		//print_r($VisitData);
	}else{
		$VisitData=array("no"=>($v_id+1));
		$flgVisi=$db->updateAry("no_visit",$VisitData,"where ip='".$_SERVER['REMOTE_ADDR']."' and page='".$url."'");
	}
}
function countVisits()
{
	global $db;
	$cnt=$db->getRows("select no from no_visit  where school_id='".$_SESSION["admin"]["school_id"]."' ");
	$all=0;
	if(is_array($cnt) && count($cnt)>0){
		foreach($cnt as $ct){
			$all=$all+$ct["no"];
		}
	}
	return $all;
}
function mymail($from,$to,$subject,$body)
{
	//global $db,$LinksDetails;
	//$LinksDetails=fetchSetting(array('mail_sender_email','admin_email'));
	//$msgs=$db->getRow("select * from ".MAILMSG);
	//$arr_tpl_vars=array('[MESSAGE]','[ADMIN]','[LOGIN]','[SITE]', '[DATE]');
	//$arr_tpl_data=array(nl2br($body), "info@savarna.in", 'http://erp.savarna.in/adminlogin.php', URL_ROOT, date('d/m/Y'));
	//$e_msg = str_replace($arr_tpl_vars, $arr_tpl_data, $msgs["msg"]);
	//$body = $e_msg;
	$headers  = 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	$headers .= 'From: savarna.in<info@savarna.in>' . "\r\n";
	
	@mail($to,$subject,nl2br($body),$headers);
	return $body;
}
function gmail($from,$to,$subject,$body)
{
	global $db;
	$msgs=$db->getRow("select * from mailmsg");
	$arr_tpl_vars = array('[MESSAGE]','[ADMIN]','[LOGIN]','[SITE]', '[DATE]');
	$arr_tpl_data = array(nl2br($body), $LinksDetails["admin_email"], 'http://gnahighstreet.com/my-account', URL_ROOT, date('d/m/Y'));
	$e_msg = str_replace($arr_tpl_vars, $arr_tpl_data, $msgs["msg"]);
	//$body = nl2br($e_msg);
	$body = $e_msg;
	$mail = new PHPGMailer();
	$mail->IsHTML(true);
	$mail->Username = GMAIL_USER;
	$mail->Password = GMAIL_PASS;
	$mail->From = $LinksDetails["mail_sender_email"];
	$mail->FromName = $LinksDetails["mail_sender_name"];
	$mail->Subject = $subject;
	$mail->AddAddress($to);
	$mail->Body = $body;
	$mail->Send();
	return $body;
}
function website($url){
  if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return "<a target='_blank' href='$url'>".$url."</a>";
}
function notification($notice,$type,$id,$fid){
	global $db;
	$incData=array("notice"=>$notice,
					"type"=>$type,
					"userid"=>$fid,
					"school_id"=>$_SESSION["admin"]["school_id"],"added_by"=>$_SESSION["admin"]["uid"],
					"link_id"=>$id
	);
	$res=$db->insertAry("notification",$incData);
	return $res;
}
function deposit($amount,$fid,$tid,$tfor,$detail="",$status=1){
	global $db;
	$data = array(	 'rid'=>$fid,
					 'tid'=>$tid,
					 'tfor'=>$tfor,
					 'type'=>"deposit",
					 'amount'=>$amount,
					 'status'=>$status,
					 "school_id"=>$_SESSION["admin"]["school_id"],"added_by"=>$_SESSION["admin"]["uid"],
					 'session'=>$_SESSION["admin"]["session"],
					 'detail'=>$detail);
	$did = $db->insertAry(TRANSECTION,$data);
	//notification($notice,$type,$id,$fid)
	$nid=notification("deposit : ".$amount." - ".$detail,"deposit",$did,$fid);
	$subject="Depost your account on:".URL_ROOT;
	return array("did"=>$did,"nid"=>$nid);
}
function withdraw($amount,$fid,$tid,$tfor,$detail="",$status=1){
	global $db;
	$data = array(	 'rid'=>$fid,
					 'tid'=>$tid,
					 'tfor'=>$tfor,
					 'type'=>"withdraw",
					 'amount'=>$amount,
					 "school_id"=>$_SESSION["admin"]["school_id"],"added_by"=>$_SESSION["admin"]["uid"],
					 'session'=>$_SESSION["admin"]["session"],
					 'status'=>$status,
					 'detail'=>$detail);
	$did = $db->insertAry(TRANSECTION,$data);
	//notification($notice,$type,$id,$fid)
	$nid=notification("deposit : ".$amount." - ".$detail,"deposit",$did,$fid);
	$subject="Depost your account on:".URL_ROOT;
	return array("did"=>$did,"nid"=>$nid);
}
function installment_time($id,$name,$udate=""){
	global $db;
	if($udate=="")$udate=date("Y-m-d h:i:g");
	$data = array(	 'idno'=>$id,
					 'date'=>$udate,
	                  "school_id"=>$_SESSION["admin"]["school_id"],
					  "added_by"=>$_SESSION["admin"]["uid"],
					  "session"=>$_SESSION["admin"]["session"],
					 'ins_name'=>$name);
	$did = $db->insertAry("installment_time",$data);
}
function installment_fine($id,$name,$fine,$reasion,$udate=""){
	global $db;
	if($udate=="")$udate=date("Y-m-d h:i:g");
	$data = array(	 'idno'=>$id,
					 'ins_name'=>$name,
					 'fine'=>$fine,
					 'udate'=>$udate,
					 'school_id'=>$_SESSION["admin"]["school_id"],
					 'added_by'=>$_SESSION["admin"]["uid"],
					 "session"=>$_SESSION["admin"]["session"],
					 'reasion'=>$reasion);
	$check=$db->getVal("select idno from installment_fine where school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$id."' and ins_name='".$name."'");
	if($check==""){	
		$did = $db->insertAry("installment_fine",$data);
		if($db->getErMsg()==""){
			deposit($fine,$id,$did,"fine",$reasion);
			return $did;
		}else{
			echo $db->getErMsg();
		}
	}else{
		echo "Fine already added for this student";
	}
}
function loginLog($uid,$status){
	global $db;
	$login_tym = date('Y-m-d H:i:s');
	$user_detail['user_id']=$uid;
	$user_detail['status']=$status;
	$user_detail['login_time']=$login_tym;
	$user_detail['ip']= getHostByName(getHostName());;
	$db->insertAry("user_detail",$user_detail);
}
function diff($timestamp,$date2=""){
	$now = strtotime(date("Y-m-d"));
    $your_date = strtotime($timestamp);
    $datediff =  - $now + $your_date;
    return floor($datediff/(60*60*24));
}
function checkInstallation(){
	global $db,$LinksDetails;$status=array();
	$days=$LinksDetails["expiredate"];
	$rempDate=diff($days);
	$ipAry=explode(",",$LinksDetails["ip"]);
	$ip=trim($_SERVER["REMOTE_ADDR"]);
	$statusChk=0;$allIP="";
	foreach($ipAry as $ips){
		if(trim($ips)==$ip){$statusChk=1;}
		$allIP.=trim($ips);
	}
	if($LinksDetails["is_install"]==0){
		$status["message"]="1";
	}
	elseif(getenv('COMPUTERNAME')!=$LinksDetails["systemname"]){
		$status["message"]='License Expired Plesae contact to dealer <br /><br />or<br /><br />
		<center><br /><br /><hr /><br /><br /><form method="post" action="'.URL_ROOT.'">
		New licance key <input type="text" name="complicence" /><br /><br />
		<input type="submit" name="save" value="Reniew Now"/>
		</form><br /><br /><hr/></center>
		';
		//"Invalid Computer Name .Your computer name is ".getenv('COMPUTERNAME')." and Software can run only ".$LinksDetails["systemname"]." Name<br />";
	}elseif($statusChk==0){
		$status["message"]="License Expired Plesae contact to dealer";
		//"Invalid server Name. Your server name is ".$ip." and Software can run only ".$allIP.$statusChk." server<br />";
	}elseif($rempDate<=0){
		$data='<center><br /><br /><hr /><br /><br /><form method="post" action="'.URL_ROOT.'">
		Next expire Date <input type="text" name="udate" placeholder="yyyy-mm-dd" /><br />
		New licance key <input type="text" name="licence" /><br /><br />
		<input type="submit" name="save" value="Reniew Now"/>
		</form><br /><br /><hr/></center>
		';
		$status["message"]="Software expire on ".$rempDate." days".$data;
	}
	return $status;
}
function sendSMS_new($m,$msg,$page){
	global $db;global $LinksDetails;
	$ID = trim(SMSID);
	$Pwd = trim(SMSPWD);
	$code = trim($LinksDetails["smscode"]);
	$senderID = trim($LinksDetails["senderID"]);
	$baseurl ="http://mysms.msgclub.net/";
	$PhNo = $m;
	$Text = urlencode($msg);
	//Invoke HTTP Submit url
	//$url = "$baseurl/sms.aspx?Id=$ID&Pwd=$Pwd&PhNo=$PhNo&text=$Text";
	$url=$baseurl."rest/services/sendSMS/sendGroupSms?AUTH_KEY=".$code."&mobileNos=".$PhNo."&message=".urlencode($msg)."&senderId=".$senderID."&routeId=1&smsContentType=Unicode";
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	
	$ret = curl_exec($ch);
	curl_close($ch);
	// do sendmsg call
	//$ret = file_get_contents($url);
	$res=$db->insertAry("sms",array("mobile"=>$m, "school_id"=>$_SESSION["admin"]["school_id"],"added_by"=>$_SESSION["admin"]["uid"],"msg"=>$msg,"status"=>$ret,"session"=>$_SESSION["admin"]["session"],"page"=>$url));
	return $ret;
}
function sendSMS($m,$msg,$page){
	global $db;global $LinksDetails;
	$ID = trim(SMSID);
	$Pwd = trim(SMSPWD);
	$code = trim($LinksDetails["smscode"]);
	$senderID = trim($LinksDetails["senderID"]);
	$baseurl ="http://msg.cyberinformatic.in/";
	$PhNo = $m;
	$Text = urlencode($msg);
	//Invoke HTTP Submit url
	//$url = "$baseurl/sms.aspx?Id=$ID&Pwd=$Pwd&PhNo=$PhNo&text=$Text";
	$url=$baseurl."api/sendhttp.php?authkey=".$code."&mobiles=".$PhNo."&message=".$msg."&sender=".$senderID."&route=1&country=0";
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	
	$ret = curl_exec($ch);
	curl_close($ch);
	// do sendmsg call
	//$ret = file_get_contents($url);
	$res=$db->insertAry("sms",array("mobile"=>$m, "school_id"=>$_SESSION["admin"]["school_id"],"added_by"=>$_SESSION["admin"]["uid"],"msg"=>$msg,"status"=>$ret,"session"=>$_SESSION["admin"]["session"],"page"=>$page));
	return $ret;
}

function sendSMS_back($m,$msg,$TemplateID,$EntityID,$SenderID,$page){
	global $db;
	
	global $LinksDetails;
// 	$senderID = trim($LinksDetails["senderID"]);

    $senderID = $SenderID;
	
	$ID = trim(SMSID);
	$Pwd = trim(SMSPWD);
// 	$baseurl ="https://www.businesssms.co.in";
	$baseurl ="http://sms.uphargroup.com";
	$PhNo = $m;
	$Text = urlencode($msg);
	//Invoke HTTP Submit url
// 	$url = "$baseurl/sms.aspx?Id=$ID&Pwd=$Pwd&PhNo=$PhNo&text=$Text&TemplateID=1007601175517305159";
    // $url = "$baseurl/sms.aspx?Id=$ID&Pwd=$Pwd&PhNo=$PhNo&text=$Text&TemplateID=$TemplateID";
    $url = "http://sms.uphargroup.com/submitsms.jsp?user=$ID&key=$Pwd&mobile=$PhNo&message=$Text&senderid=$senderID&accusage=1&entityid=$EntityID&tempid=$TemplateID";
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	
	$ret = curl_exec($ch);
	curl_close($ch);
	// do sendmsg call
	//$ret = file_get_contents($url);
	$res=$db->insertAry("sms",array("mobile"=>$m, "school_id"=>$_SESSION["admin"]["school_id"],"added_by"=>$_SESSION["admin"]["uid"],"msg"=>$msg,"status"=>$ret,"session"=>$_SESSION["admin"]["session"],"page"=>$page));
	return $ret;
}


// function sendSMS_back($m,$msg,$TemplateID,$page){
// 	global $db;
// 	$ID = trim(SMSID);
// 	$Pwd = trim(SMSPWD);
// 	$baseurl ="https://www.businesssms.co.in";
// 	$PhNo = $m;
// 	$Text = urlencode($msg);
// 	//Invoke HTTP Submit url
// // 	$url = "$baseurl/sms.aspx?Id=$ID&Pwd=$Pwd&PhNo=$PhNo&text=$Text&TemplateID=1007601175517305159";
//     $url = "$baseurl/sms.aspx?Id=$ID&Pwd=$Pwd&PhNo=$PhNo&text=$Text&TemplateID=$TemplateID";
// 	$ch = curl_init();
// 	curl_setopt($ch, CURLOPT_URL, $url);
// 	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	
// 	$ret = curl_exec($ch);
// 	curl_close($ch);
// 	// do sendmsg call
// 	//$ret = file_get_contents($url);
// 	$res=$db->insertAry("sms",array("mobile"=>$m, "school_id"=>$_SESSION["admin"]["school_id"],"added_by"=>$_SESSION["admin"]["uid"],"msg"=>$msg,"status"=>$ret,"session"=>$_SESSION["admin"]["session"],"page"=>$page));
// 	return $ret;
// }
function sms($no,$msg,$type="0",$TemplateID="",$EntityID="",$SenderID="", $page=""){
	$n=$no;
	if($page=="")$page=curPageURL(); global $LinksDetails; 
	global $db;
	$template = $db->getRow("select templateid, entityid, senderid from template ");
	
	if($TemplateID==""){
	    $TemplateID = $template["templateid"];
	}
	if($EntityID==""){
	    $EntityID = $template["entityid"];
	}
	if($SenderID==""){
	    $SenderID = $template["senderid"];
	}
	if(trim(SMSID)!=""){
		$mob=explode(",",$no);
		
		$body = $msg;
		if(myNotificationStatus($type)==1){
			if(is_array($mob) && count($mob)>0){
				foreach($mob as $m){
					if($LinksDetails["activesms"]==2){
						if(strlen($m)==10 && is_numeric($m))
							$status=sendSMS("91".$m,$msg,$page);
						elseif(strlen($m)==12 && is_numeric($m))
							$status=sendSMS($m,$msg,$page);
						else
							$status="invalid mobile no";
					}elseif($LinksDetails["activesms"]==3){
						if(strlen($m)==10 && is_numeric($m))
							$status=sendSMS_new("91".$m,$msg,$page);
						elseif(strlen($m)==12 && is_numeric($m))
							$status=sendSMS_new($m,$msg,$page);
						else
							$status="invalid mobile no";
					}else{
						if(strlen($m)==10 && is_numeric($m))
							$status=sendSMS_back("91".$m,$msg,$TemplateID,$EntityID,$SenderID,$page);
						elseif(strlen($m)==12 && is_numeric($m))
							$status=sendSMS_back($m,$msg,$TemplateID,$EntityID,$SenderID,$page);
						else
							$status="invalid mobile no";
					}
				}
			}
			if($db->getErMsg()=="")
			return $status; 
			else
			return $db->getErMsg();
		}
	}else{
		return "SMS is not activated on your system Please contact to your sealer...Thank You :)";
	}
}
function sendVsms($m,$msg){
	$ID = trim(VSMSID);
	$Pwd = trim(VSMSPWD);
	$Sender = trim(VSMSSND);
	$baseurl ="http://msg.cyberinformatic.in";
	$PhNo = $m;
	$startTime=date("Y-m-d h:i:s", time());
	$endTime=date("Y-m-d h:i:s", time() + 620960);
	$Text = urlencode($msg);
	//Invoke HTTP Submit 
	$url = "$baseurl/send_voice_mail.php?user=$ID&password=$Pwd&sender=$Sender&mobiles=$PhNo&duration=30&url_file_name=$msg&schtimestart=$startTime&schtimeend=$endTime&route=4&campaign=New Folder";
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	
	$ret = curl_exec($ch);
	curl_close($ch);
	//$ch=json_decode($ch);
	// do sendmsg call
	/*$ret = file_get_contents($url);
	$arra=array("601"=>"sender id must be numeric",
			"602"=>"your current route is disable . kindly select onother route",
			"603"=>"this sender id is blacklisted . pls use different sender id",
			"604"=>"please enter atleast one correct number to send sms",
			"606"=>"schedule date cannot be more than thre  week",
			"607"=>"please enter campaign name",
			"608"=>"schedule sms canno be less than current time",
			"609"=>"end time cannot be less han or equal to schedule time",
			"610"=>"duration cannot be set to be zero",
			"614"=>"no voice file found please enter voice file and proceed",
			"615"=>"invalid file type . allow extension are wav,wave,mp3,wma,ra,m4a,arm",
			"001"=>"unable to connect database",
			"002"=>"unable to select database",
			"201"=>"invalid username or password");*/
	return $ret."<br />".$url."<hr/>";
}
function vsms($msg,$no,$type="0",$page=""){
	if($page=="")$page=curPageURL();
	if(trim(VSMSID)!=""){
		$mob=explode(",",$no);
		global $db;
		if(is_array($mob) && count($mob)>0){
			foreach($mob as $m){
				if(strlen($m)==10 && is_numeric($m))
					$status=sendVsms("91".$m,$msg);
				elseif(strlen($m)==12 && is_numeric($m))
					$status=sendVsms($m,$msg);
				else
					$status="invalid mobile no";
			}
		}
		$res=$db->insertAry("sms",array("mobile"=>$no,"msg"=>$msg,"school_id"=>$_SESSION["admin"]["school_id"],"added_by"=>$_SESSION["admin"]["uid"],"status"=>$status,"session"=>$_SESSION["admin"]["session"],"page"=>$page));
		if($db->getErMsg()=="")
		return $status; 
		else
		return $db->getErMsg();
	}else{
		return "SMS is not activated on your system Please contact to your sealer...Thank You :)";
	}
}
function myNotificationStatus($name){
	global $db;
	$to1=$_SESSION["admin"]["uid"];
	$chk=$db->getVal("select status from sms_notification where school_id='".$_SESSION["admin"]["school_id"]."' and name='".$name."' and uid='".$to1."'");
	//echo $db->getLastQuery();
	if($chk=="1")$chk=1;
	return $chk; 		
}
function saveNtice($name,$stat){
	global $db;
	$chk=$db->getVal("select id from sms_notification where school_id='".$_SESSION["admin"]["school_id"]."' and name='".$name."' and uid='".$_SESSION["admin"]["uid"]."'");
	$incData=array("name"=>$name,
					"status"=>$stat,
					"school_id"=>$_SESSION["admin"]["school_id"],"added_by"=>$_SESSION["admin"]["uid"],
					"uid"=>$_SESSION["admin"]["uid"]);
	if($chk==""){
		$db->insertAry("sms_notification",$incData);
	}
	else{
		$db->updateAry("sms_notification",$incData,"where school_id='".$_SESSION["admin"]["school_id"]."' and name='".$name."' and uid='".$_SESSION["admin"]["uid"]."'");
	}
}
function mydetail($what,$id,$type){
	global $db;
	$data=$db->getVal("select $what from $type where school_id='".$_SESSION["admin"]["school_id"]."' and idno=$id");
	//return $db->getLastQuery();
	return $data;
}
function FindGrade($obtain,$total){
	$per=round(($obtain*100)/$total);
	global $db;
	$data=$db->getRows("select * from examgrade  where school_id='".$_SESSION["admin"]["school_id"]."' ");
	if(is_array($data) && count($data)>0){
		foreach($data as $d){
			if($per>=$d["minrange"] && $per<=$d["maxrange"]){
				return $d["grade"]; 
			}
		}
	}
	return $per;
	
}
function FindGrade_junior($obtain,$total){
	$per=round(($obtain*100)/$total);
	global $db;
	$data=$db->getRows("select * from examgrade_junior where school_id='".$_SESSION["admin"]["school_id"]."' ");
	if(is_array($data) && count($data)>0){
		foreach($data as $d){
			if($per>=$d["minrange"] && $per<=$d["maxrange"]){
				return $d["grade"]; 
			}
		}
	}
	return $per;
	
}
function rrmdir($dir) { 
  foreach(glob($dir . '/*') as $file) { 
    if(is_dir($file)) rrmdir($file); else unlink($file); 
  } 
  rmdir($dir); 
}
function checkRecepit($idno,$iip,$type="fee"){
	global $db;
	$pay_receipt="";
	$pay_receipt_array=array();
	$payReceptid=array();
	$pay_receipt_arr=array();
	$pay_receipt_ar=array();
	$inst_detail=$db->getRows("select * from reff_receipt where school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$idno."' and type='$type' and session='".$_SESSION["admin"]["session"]."'");
	if(is_array($inst_detail) && count($inst_detail)>0){
		foreach($inst_detail as $in_detail){
			$payReceptid[]=$in_detail["inst_id"];
			$pay_receipt_ar[]=array( "inst_id"=>$in_detail["inst_id"],
									 "amount"=>$in_detail["amount"],
									 "id"=>$in_detail["id"]
			);
		}
	}
	//if(!isset($_SESSION["recept"][$type]))$_SESSION["recept"][$type]=0;
	if(is_array($pay_receipt_ar) && count($pay_receipt_ar)>0){
		$i=0;
		foreach($pay_receipt_ar as $receipt_ar){$i++;
			//$pay_receipt=implode(",",$payReceptid);
			$pre="";$total="";$ids=explode(",",$receipt_ar['inst_id']);
			$t=substr($type,-1);
			$type1=chop($type,$t);
			foreach($ids as $id){$tot="";
				if($type=="hostelfee"){
					$pre="ip";$tot=$db->getVal("select i".$id." from hostelinstallment where school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$idno."' and session='".$_SESSION["admin"]["session"]."'");}
					
				elseif($type=="busfee"){
					$pre="bp";$tot=$db->getVal("select b".$id." from installment where school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$idno."' and session='".$_SESSION["admin"]["session"]."'");}
				
				elseif($type=="fee"){
					$pre="ip";$tot=$db->getVal("select i".$id." from installment where school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$idno."' and session='".$_SESSION["admin"]["session"]."'");}
				elseif($type1=="extrafee"){
					$tot=$db->getVal("select fee from extrafee where pid = 'p".$id."' and type = ".$t." and school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$idno."' and session='".$_SESSION["admin"]["session"]."'");}
				//$total=$type1;
				$total+=$tot;
			}
			$pay_receipt_array=explode(",",$receipt_ar["inst_id"]);
			$pay_receipt_arra=$pre.(implode(",".$pre,$pay_receipt_array));
			$pay_receipt_arr=explode(",",$pay_receipt_arra);
			//print_r($pay_receipt_arr);echo "<hr>".$iip;			
			if(in_array($iip,$pay_receipt_arr)){
				$_SESSION["recept"][$type][$i]++;
				return array("i"=>$_SESSION["recept"][$type][$i],"tot"=>$total,"amount"=>$receipt_ar["amount"],"rrid"=>$receipt_ar["id"],"inst_id"=>$receipt_ar['inst_id']);
				$i++;
			}
		}
		/*$pay_receipt=implode(",",$payReceptid);
		$pay_receipt_array=explode(",",$pay_receipt);
		$pay_receipt_arra="ip".implode(",ip",$pay_receipt_array);
		$pay_receipt_arr=explode(",",$pay_receipt_arra);*/
	}
	/*if($i==0){
		return true;
	}
	else{
		return false;
	}*/
}
function backup_tables($tables = '*')
{
	global $db;
	$return="-- phpMyAdmin SQL Dump
-- version 3.5.5
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: ".date('M d, Y at H:m A')."
-- Server version: 5.5.27-log
-- PHP Version: 5.4.6
SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";
SET time_zone = \"+00:00\";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `smsplush`
--
-- --------------------------------------------------------
";
	if($tables == '*')
	{
		$tables = array();
		$result = $db->getRows('SHOW TABLES');
		foreach($result as $row)
		{
			$tables[] = $row[0];
		}
	}
	else
	{
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}
	//cycle through
	foreach($tables as $table)
	{
		if($table!="no_visit"){
		$result = $db->getRows('SELECT * FROM '.$table);
		$num_fields = count($result);
		$return.= "\n--
-- Table structure for table `".$table."`
--\n";
		//$return.= "\nDROP TABLE IF EXISTS ".$table.";\n";
		$row2 = $db->getRow('SHOW CREATE TABLE '.$table);
		$return.= "\n".$row2[1].";\n\n";
		$return.="\n--
-- Dumping data for table `".$table."`
--\n\n";
		for ($i = 0; $i < $num_fields; $i++) 
		{
			foreach($result as $row)
			{
				if($table!="notification"){
					$return.= 'INSERT INTO '.$table.' VALUES(';
					for($j=0; $j<$num_fields; $j++) 
					{
						$row[$j] = addslashes($row[$j]);
						$row[$j] = ereg_replace("\n","\\n",$row[$j]);
						if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
						if ($j<($num_fields-1)) { $return.= ','; }
					}
					$return.= ");\n";
				}
			}
		}
		$return.="\n-- --------------------------------------------------------\n";
		}
	}
	//save file
	$return.="\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n";
	$handle = fopen('../backup_database/db-backup-'.date("dMY").'.sql','w+');
	fwrite($handle,$return);
	ob_start();
	fclose($handle);
	return $return;
}
function Add($filename){
	$my_file = $filename;
	$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //implicitly creates file
	return false;
}
function Write($filename,$content){
	$my_file = $filename;
	$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
	$data = $content;
	fwrite($handle, $data);
	return false;
}
function checkPermission($pagename,$roll){
	global $db;
	$cando="none";
	$per=$db->getRow("select * from tbl_privilages where school_id='".$_SESSION["admin"]["school_id"]."' and page_name='$pagename' and roll_id=$roll");
	//if($per["r"]==1)$cando="read";
	//elseif($per["w"]==1)$cando="write";
	if($per["a"]==1)$cando="all";
	//elseif($per["n"]==1)$cando="none";
	return $cando;
}
function checkAdminPermission($pagename,$roll){
	global $db;
	$cando="none";
	$per=$db->getRow("select * from admin_privilages where school_id='".$_SESSION["admin"]["school_id"]."' and page_name='$pagename' and role_id=$roll");
	if($per["a"]==1)$cando="all";
	return $cando;
}
function checkStaffPermission($pagename,$roll){
	global $db;
	$cando="none";
	$per=$db->getRow("select * from staff_privilages where school_id='".$_SESSION["admin"]["school_id"]."' and page_name='$pagename' and role_id=$roll");
	if($per["a"]==1)$cando="all";
	return $cando;
}
if(!function_exists ( 'POST' )){
	function POST($i, $trim = false)
	{ 
		if(isset($_POST[$i]))$i=$_POST[$i];
		if ($trim)
			$i = trim($i);
		if (!get_magic_quotes_gpc())
			$i = addslashes($i);
		$i = rtrim($i);
		$look = array('&', '#', '<', '>', '"', '\'', '(', ')', '%');
		$safe = array('&amp;', '&#35;', '&lt;', '&gt;', '&quot;', '&#39;', '&#40;', '&#41;', '&#37;');
		$i = str_replace($look, $safe, $i);
		//$i = htmlentities($i);
		return $i;
	}
	function unPOST($i)
	{
		$look = array('&', '#', '<', '>', '"', '\'', '(', ')', '%');
		$safe = array('&amp;', '&#35;', '&lt;', '&gt;', '&quot;', '&#39;', '&#40;', '&#41;', '&#37;');
		$i = str_replace($safe, $look, $i);
		return stripslashes($i);
	}
}
function date_range($first, $last, $step = '+1 day', $output_format = 'Y-m-d' ) {
    $dates = array();
    $current = strtotime($first);
    $last = strtotime($last);
    while( $current <= $last ) {
        $dates[] = date($output_format, $current);
        $current = strtotime($step, $current);
    }
    return $dates;
}
function month_range($first, $last) {
    $months = array();
    $current = strtotime($first);
    $last = strtotime($last);
	
	$startM    = date('m',$current);
	$endM      = date('m',$last);
	
	$currentDate = $last;
	
	while ($currentDate >= $current) {
		if(strtotime($first)==$current){
			$months[]= date('Y-m-d',$current);
		}elseif(date("m",strtotime($current))==$endM){
			$months[]= date('Y-m-d',$last);
		}else{
			$months[]= date('Y-m-d',$current);//."===".$current."===".strtotime($first);
		}
		$current = strtotime( date('Y/m/01/',$current).' +1 month');
	}
	return $months;
}
function checkans($qid,$ans)
{
	global $db;
	$qos=$db->getRow(" select * from question where id=".$qid);
	$a=array('A','B','C','D');
	$answer=json_decode($qos['options'],true);
	$i=0;
	foreach($answer as $abc)
	{
		$sy[]=$abc['answer']."||".$qos['answer']."||".$qid;
			if(trim($abc['answer'])==trim($qos['answer'])){
			$result=$a[$i];
		   }$i++;
	}
	if($ans==$result)
	{
		$r=$qid;
	}else{
		$r=0;
	}
 return $r;
}
function papername($pid)
{
global $db;
$r=$db->getVal("select name from papers where id=".$pid);	
return 	$r;
}
function getResult($pid,$uid)
{
	global $db, $objindex;
	$udetail=$objindex->profile($uid);	
	
	//if($udetail['subject']>0);
 	$ppr=$db->getRow("select * from papers where id=".$pid." and class ='".$udetail['class']."'");
//	return $ppr;
	
	
 //       $ppr=$db->getRow("select questions,totalqus,marks,ttime,marking_scheme from ".PAPER." where id=".$pid);
	
	$r['date']=$db->getVal("select date from  result where paper_id=".$pid);
	$r['pid']=$pid;
        $r['classID']=$ppr['class'];
  	$r['subjectID']=$ppr['subject'];
	$r['totalquestions']=$ppr['totalqus'];
	$r['marks']=$ppr['marks'];
	$r['time']=$ppr['ttime'];
	$r['papername']=papername($pid);
	$qlist=json_decode($ppr['questions'],true);
	$r['ques']=array();
	if(is_array($qlist) && count($qlist)>0){
		foreach($qlist as $ql){
			$qno=$ql["question"];
			$r['ques'][$qno]=$ql["marks"];
		}
	}
	if($ppr['marking_scheme']==1)
	{
	 	$ms=0.33;
		$r['marking_scheme']="Negative(1/3)";
	}elseif($ppr['marking_scheme']==2){
		$ms=0.25;
		$r['marking_scheme']="Negative(1/4)";
	}else{
		$ms=0;
		$r['marking_scheme']="Normal";
	}
	//each_question_mark=eqm
	//$eqm=$ppr['marks']/$ppr['totalqus'];
	
	$ttlaq=$db->getRows("select * from examdetails where paper_id=".$pid." and student_id=".$uid);
//return $ttlaq;
	$r['totalattemptques']=count($ttlaq);
	$r['correctq']=0;$r['wrongq']=0;
	foreach($ttlaq as $taq)
	{
		$aquid=$taq['qid'];
		$eqm=$r['ques'][$aquid];
			
		if($taq['ans_status']==1)
		{
			$r['cqm']+=$eqm; 
			$r['correctq']+=1;
		}else{
			$r['wqm']+= $ms * $eqm; 
			$r['wrongq']+=1;
		}
		
		$r['cmarks']=round($r['cqm'],2);
		$r['wmarks']=round($r['wqm'],2);
		$r['finaltotal']=$r['cmarks']-$r['wmarks'];
	}
	return $r;
}
function unread_complain()
{
global $db, $objindex;
	
$user_complain=$db->getVal("select count(*) from complain where is_read=0 and status=1");
//return 	$db->getLastQuery();
return 	$user_complain;
}
?>