<?php
/*
 *  Copyright (C) 2012
 *     Ed Rackham (http://github.com/a1phanumeric/PHP-MySQL-Class)
 *  Changes to Version 0.8.1 copyright (C) 2013
 *	Christopher Harms (http://github.com/neurotroph)
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

// MySQL Class v0.8.1

include_once "class.conn.php";
class MySQL {

	// Base variables
	var $lastError;					// Holds the last error
	var $lastQuery;					// Holds the last query
	var $result;						// Holds the MySQL query result
	var $records;						// Holds the total number of records returned
	var $affected;					// Holds the total number of records affected
	var $rawResults;				// Holds raw 'arrayed' results
	var $arrayedResult;			// Holds an array of the result

	var $hostname;	// MySQL Hostname
	var $username;	// MySQL Username
	var $password;	// MySQL Password
	var $database;	// MySQL Database

	var $databaseLink;		// Database Connection Link
        


	/* *******************
	 * Class Constructor *
	 * *******************/

	function MySQL(){
		$this->database = DB_NAME;
		$this->username = DB_USER;
		$this->password = DB_PASSWORD;
		$this->hostname = DB_HOST;

		$this->Connect();
	}



	/* *******************
	 * Private Functions *
	 * *******************/

	// Connects class to database
	// $persistant (boolean) - Use persistant connection?
	private function Connect($persistant = false){
		$this->CloseConnection();

		if($persistant){
			$this->databaseLink = mysql_pconnect($this->hostname, $this->username, $this->password);
		}else{
			$this->databaseLink = mysql_connect($this->hostname, $this->username, $this->password);
		}

		if(!$this->databaseLink){
   		$this->lastError = 'Could not connect to server: ' . mysql_error($this->databaseLink);
			return false;
		}

		if(!$this->UseDB()){
			$this->lastError = 'Could not connect to database: ' . mysql_error($this->databaseLink);
			return false;
		}
		$this->setTimeZone();

		return true;
	}

	function setTimeZone(){
		$settings = $this->Select("settings");
		$timezone  = $settings['timezone'];
		date_default_timezone_set($timezone);
	}

	// Select database to use
	private function UseDB(){
		if(!mysql_select_db($this->database, $this->databaseLink)){
			$this->lastError = 'Cannot select database: ' . mysql_error($this->databaseLink);
			return false;
		}else{
			return true;
		}
	}


	// Performs a 'mysql_real_escape_string' on the entire array/string
	private function SecureData($data){
		if(is_array($data)){
			foreach($data as $key=>$val){
				if(!is_array($data[$key])){
					$data[$key] = mysql_real_escape_string($data[$key], $this->databaseLink);
				}
			}
		}else{
			$data = mysql_real_escape_string($data, $this->databaseLink);
		}
		return $data;
	}



	/* ******************
	 * Public Functions *
	 * ******************/

        
	// Executes MySQL query
	function ExecuteSQL($query){

		$this->lastQuery 	= $query;
		if($this->result 	= mysql_query($query, $this->databaseLink)){
			$this->records 	= @mysql_num_rows($this->result);
			$this->affected	= @mysql_affected_rows($this->databaseLink);

			if($this->records > 0){
				$this->ArrayResults();
				return $this->arrayedResult;
			}else{
				return true;
			}

		}else{
			$this->lastError = mysql_error($this->databaseLink);
			return false;
		}
	}
          
		  
		function fetchQuery($query){
		    $a=0;
			$results = mysql_query($query)or dir(mysql_error());

			while ($rows = mysql_fetch_assoc($results))
      		$result[$a++]=$rows;
			
			 return $result;
		}  
		  
		    
        function fetchAll($from, $where='', $orderBy='', $limit='', $like=false, $operand='AND',$cols='*'){
            
            if(trim($from) == ''){
			return false;
		}

		$query = "SELECT {$cols} FROM `{$from}` WHERE ";

		if(is_array($where) && $where != ''){
			// Prepare Variables
			$where = $this->SecureData($where);

			foreach($where as $key=>$value){
				if($like){
					//$query .= '`' . $key . '` LIKE "%' . $value . '%" ' . $operand . ' ';
					$query .= "`{$key}` LIKE '%{$value}%' {$operand} ";
				}else{
					//$query .= '`' . $key . '` = "' . $value . '" ' . $operand . ' ';
					$query .= "`{$key}` = '{$value}' {$operand} ";
				}
			}

			$query = substr($query, 0, -(strlen($operand)+2));

		}else{
			$query = substr($query, 0, -7);
		}

		if($orderBy != ''){
			$query .= ' ORDER BY ' . $orderBy;
		}

		if($limit != ''){
			$query .= ' LIMIT ' . $limit;
		}
		//echo $query;

               //print_r($new);
                $results= mysql_query($query);
                
                $a=0;
			$result=array();
				
              while ($rows = mysql_fetch_array($results))
                   $result[$a++]=$rows;
				   
              return $result;
              // }
                
		//return $this->ExecuteSQL($query);
        
        }
		
		
		

		
		
	  function fetchAlljoineachrow($from , $where='', $orderBy='', $limit='',  $cols='*' ,$asc='',$join='',$start=0)
	  {
				  $query = "SELECT {$cols} FROM {$from} WHERE 1 "; 
				  if($join!='')
				  {
					 $query .=' and '.$join;
					 if($orderBy != '')
					 {
						$query .= ' ORDER BY ' . $orderBy;
					}
				   if($asc != '')
				   {
						$query .= $asc;
					}
					if($limit!='')
					$query .= ' LIMIT '.$limit;
				  } //echo $query;echo '<br>';
				   $results= mysql_query($query);
                $a=0;
			$result=array();
				
              while ($rows = mysql_fetch_array($results))
                   $result[$a++]=$rows;
				   
              return $result;
	  }
function fetchAlljoineachrows($from , $where, $orderBy='',$group, $limit='',  $cols='*' ,$asc='',$join='',$start=0)
	  {    echo 'subha';
				  $query = "SELECT {$cols} FROM {$from} WHERE {$where}"; 
				  if($join!='')
				  {
					 $query .=' and '.$join;
					 if($orderBy != '')
					 {
						$query .= ' ORDER BY ' . $orderBy;
					}
					if($group!='')
		{
			$query .= ' GROUP BY ' . $group;
		}
				   if($asc != '')
				   {
						$query .= $asc;
					}
					
		if($limit!='')
		{
					$query .= ' LIMIT ' . $start.','.$limit;
					}
				  }	
				echo 	$query;
				   $results= mysql_query($query);
                $a=0;
			$result=array();
				
              while ($rows = mysql_fetch_array($results))
                   $result[$a++]=$rows;
				   
              return $result;
	  }
	  function fetchAlljoin($from , $where='', $orderBy='', $limit='', $like=false, $operand='AND',$cols='*' ,$asc='',$join='',$start=0){
            if(trim($from) == ''){
			return false;
		}

		$query = "SELECT {$cols} FROM {$from} WHERE 1 "; 
		if($join!=''){
         $query .=' and '.$join;
      }
		if(is_array($where) && $where != ''){
			// Prepare Variables
			$where = $this->SecureData($where);

			foreach($where as $key=>$value){
				if($like){
					//$query .= '`' . $key . '` LIKE "%' . $value . '%" ' . $operand . ' ';
					$query .= "`{$key}` LIKE '%{$value}%' {$operand} ";
				}else{
					//$query .= '`' . $key . '` = "' . $value . '" ' . $operand . ' ';
					$query .= "`{$key}` = '{$value}' {$operand} ";
				}
			}
       
			$query = substr($query, 0, -(strlen($operand)+2));

		}else{
		if($join!=''){
	//	$query = substr($query, 0, -(strlen($operand)+2));
		}else
			$query = substr($query, 0, -7);
		}

		if($orderBy != ''){
			$query .= ' ORDER BY ' . $orderBy;
		}
       if($asc != ''){
			$query .= $asc;
		}
		
		//if($start!='')
		//{
		if($limit!='')
		$query .= ' LIMIT ' . $start.','.$limit;
		//}
		//echo $query;
           //print_r($new);
		//   echo $query;echo '<br>';
		//echo $query;
                $results= mysql_query($query);
                $a=0;
			$result=array();
				
              while ($rows = mysql_fetch_array($results))
                   $result[$a++]=$rows;
				   
              return $result;
              // }
                
		//return $this->ExecuteSQL($query);
        
        }
		 function fetchAlljoinGrp($from , $where='', $orderBy='', $limit='', $like=false, $operand='AND',$cols='*' ,$asc='',$join='',$start,$group=''){
            if(trim($from) == ''){
			return false;
		}

		$query = "SELECT {$cols} FROM {$from} WHERE 1 "; 
		if($join!=''){
         $query .=' and '.$join;
      }
		if(is_array($where) && $where != ''){
			// Prepare Variables
			$where = $this->SecureData($where);

			foreach($where as $key=>$value){
				if($like){
					//$query .= '`' . $key . '` LIKE "%' . $value . '%" ' . $operand . ' ';
					$query .= "`{$key}` LIKE '%{$value}%' {$operand} ";
				}else{
					//$query .= '`' . $key . '` = "' . $value . '" ' . $operand . ' ';
					$query .= "`{$key}` = '{$value}' {$operand} ";
				}
			}
       
			$query = substr($query, 0, -(strlen($operand)+2));

		}else{
		if($join!=''){
	//	$query = substr($query, 0, -(strlen($operand)+2));
		}else
			$query = substr($query, 0, -7);
		}
		if($group!='')
		{
			$query .= ' GROUP BY ' . $group;
		}
		if($orderBy != ''){
			$query .= ' ORDER BY ' . $orderBy;
		}
       if($asc != ''){
			$query .= $asc;
		}
		
		//if($start!='')
		//{
		$query .= ' LIMIT ' . $start.','.$limit;//echo $query ;
		//}
           //print_r($new);
                $results= mysql_query($query);
                $a=0;
			$result=array();
				
              while ($rows = mysql_fetch_array($results))
                   $result[$a++]=$rows;
				   
              return $result;
        }
		 function fetchAlljoinGrpquery($from , $where='', $orderBy='', $limit='', $like=false, $operand='AND',$cols='*' ,$asc='',$join='',$start,$group=''){
            if(trim($from) == ''){
			return false;
		}

		$query = "SELECT {$cols} FROM {$from} WHERE 1 "; 
		if($join!=''){
         $query .=' and '.$join;
      }
		if(is_array($where) && $where != ''){
			// Prepare Variables
			$where = $this->SecureData($where);

			foreach($where as $key=>$value){
				if($like){
					//$query .= '`' . $key . '` LIKE "%' . $value . '%" ' . $operand . ' ';
					$query .= "`{$key}` LIKE '%{$value}%' {$operand} ";
				}else{
					//$query .= '`' . $key . '` = "' . $value . '" ' . $operand . ' ';
					$query .= "`{$key}` = '{$value}' {$operand} ";
				}
			}
       
			$query = substr($query, 0, -(strlen($operand)+2));

		}else{
		if($join!=''){
	//	$query = substr($query, 0, -(strlen($operand)+2));
		}else
			$query = substr($query, 0, -7);
		}
		if($group!='')
		{
			$query .= ' GROUP BY ' . $group;
		}
		if($orderBy != ''){
			$query .= ' ORDER BY ' . $orderBy;
		}
       if($asc != ''){
			$query .= $asc;
		}
		
		if($limit!='')
		{
		$query .= ' LIMIT ' . $start.','.$limit;//echo $query ;
		}
	//	echo $query;
           //print_r($new);
                $results= mysql_query($query);
                $a=0;
			$result=array();
				
              while ($rows = mysql_fetch_array($results))
                   $result[$a++]=$rows;
				   
              return $result;
        }
  function fetchAlljoinrowise($from , $where='', $orderBy='', $limit='', $like=false, $operand='AND',$cols='*' ,$asc='',$join='',$start=0){
            if(trim($from) == ''){
			return false;
		}

		$query = "SELECT {$cols} FROM {$from} WHERE 1 "; 
		if($join!=''){
         $query .=' and '.$join;
      }
		if(is_array($where) && $where != ''){
			// Prepare Variables
			$where = $this->SecureData($where);

			foreach($where as $key=>$value){
				if($like){
					//$query .= '`' . $key . '` LIKE "%' . $value . '%" ' . $operand . ' ';
					$query .= "`{$key}` LIKE '%{$value}%' {$operand} ";
				}else{
					//$query .= '`' . $key . '` = "' . $value . '" ' . $operand . ' ';
					$query .= "`{$key}` = '{$value}' {$operand} ";
				}
			}
       

		}
                $results= mysql_query($query);
                $a=0;
			$result=array();
				
              while ($rows = mysql_fetch_array($results))
                   $result[$a++]=$rows;
				   
              return $result;
        }

	// Adds a record to the database based on the array key names
	function Insert($vars, $table, $exclude = ''){

		// Catch Exclusions
		if($exclude == ''){
			$exclude = array();
		}

		array_push($exclude, 'MAX_FILE_SIZE'); // Automatically exclude this one

		// Prepare Variables
		$vars = $this->SecureData($vars);

		$query = "INSERT INTO `{$table}` SET ";
		foreach($vars as $key=>$value){
			if(in_array($key, $exclude)){
				continue;
			}
			//$query .= '`' . $key . '` = "' . $value . '", ';
			$query .= "`{$key}` = '{$value}', ";
		}

		$query = substr($query, 0, -2);
         //echo $query;
		return $this->ExecuteSQL($query);
	}

	// Deletes a record from the database
	function Delete($table, $where='', $limit='', $like=false){
		$query = "DELETE FROM `{$table}` WHERE ";
		if(is_array($where) && $where != ''){
			// Prepare Variables
			$where = $this->SecureData($where);

			foreach($where as $key=>$value){
				if($like){
					//$query .= '`' . $key . '` LIKE "%' . $value . '%" AND ';
					$query .= "`{$key}` LIKE '%{$value}%' AND ";
				}else{
					//$query .= '`' . $key . '` = "' . $value . '" AND ';
					$query .= "`{$key}` = '{$value}' AND ";
				}
			}

			$query = substr($query, 0, -5);
		}

		if($limit != ''){
			$query .= ' LIMIT ' . $limit;
                       // echo ($query);
                        
		}

		return $this->ExecuteSQL($query);
	}


	// Gets a single row from $from where $where is true
	function Select($from, $where='', $orderBy='', $limit='', $like=false, $operand='AND',$cols='*'){
		// Catch Exceptions
		if(trim($from) == ''){
			return false;
		}

		$query = "SELECT {$cols} FROM `{$from}` WHERE ";

		if(is_array($where) && $where != ''){
			// Prepare Variables
			$where = $this->SecureData($where);

			foreach($where as $key=>$value){
				if($like){
					//$query .= '`' . $key . '` LIKE "%' . $value . '%" ' . $operand . ' ';
					$query .= "`{$key}` LIKE '%{$value}%' {$operand} ";
				}else{
					//$query .= '`' . $key . '` = "' . $value . '" ' . $operand . ' ';
					$query .= "`{$key}` = '{$value}' {$operand} ";
				}
			}

			$query = substr($query, 0, -(strlen($operand)+2));

		}else{
			$query = substr($query, 0, -7);
		}

		if($orderBy != ''){
			$query .= ' ORDER BY ' . $orderBy;
		}

		if($limit != ''){
			$query .= ' LIMIT ' . $limit;
		}
	//echo $query;
		return $this->ExecuteSQL($query);

	}

	// Updates a record in the database based on WHERE
	function Update($table, $set, $where, $exclude = ''){
		// Catch Exceptions

		if(trim($table) == '' || !is_array($set) || !is_array($where)){
			return false;
		}
		if($exclude == ''){
			$exclude = array();
		}

		array_push($exclude, 'MAX_FILE_SIZE'); // Automatically exclude this one

		$set 		= $this->SecureData($set);
		$where 	= $this->SecureData($where);

		// SET

		$query = "UPDATE `{$table}` SET ";

		foreach($set as $key=>$value){
			if(in_array($key, $exclude)){
				continue;
			}
			$query .= "`{$key}` = '{$value}', ";
		}

		$query = substr($query, 0, -2);

		// WHERE

		$query .= ' WHERE ';

		foreach($where as $key=>$value){
			$query .= "`{$key}` = '{$value}' AND ";
		}

		$query = substr($query, 0, -5);
               
       //echo $query;
			 
		return $this->ExecuteSQL($query);
	}
	function UpdateQuery($table, $set, $where, $exclude = ''){
		// Catch Exceptions

		if(trim($table) == '' || !is_array($set) || !is_array($where)){
			return false;
		}
		if($exclude == ''){
			$exclude = array();
		}

		array_push($exclude, 'MAX_FILE_SIZE'); // Automatically exclude this one

		$set 		= $this->SecureData($set);
		$where 	= $this->SecureData($where);

		// SET

		$query = "UPDATE `{$table}` SET ";

		foreach($set as $key=>$value){
			if(in_array($key, $exclude)){
				continue;
			}
			$query .= "`{$key}` = '{$value}', ";
		}

		$query = substr($query, 0, -2);

		// WHERE

		$query .= ' WHERE ';

		foreach($where as $key=>$value){
			$query .= "`{$key}` = '{$value}' AND ";
		}

		$query = substr($query, 0, -5);

		return $query;
	}


	// 'Arrays' a single result
	function ArrayResult(){
		$this->arrayedResult = mysql_fetch_assoc($this->result) or die (mysql_error($this->databaseLink));
		return $this->arrayedResult;
	}

	// 'Arrays' multiple result
	function ArrayResults(){

		if($this->records == 1){
			return $this->ArrayResult();
		}

		$this->arrayedResult = array();
		while ($data = mysql_fetch_assoc($this->result)){
			$this->arrayedResult[] = $data;
		}
		return $this->arrayedResult;
	}

	// 'Arrays' multiple results with a key
	function ArrayResultsWithKey($key='id'){
		if(isset($this->arrayedResult)){
			unset($this->arrayedResult);
		}
		$this->arrayedResult = array();
		while($row = mysql_fetch_assoc($this->result)){
			foreach($row as $theKey => $theValue){
				$this->arrayedResult[$row[$key]][$theKey] = $theValue;
			}
		}
		return $this->arrayedResult;
	}

	// Returns last insert ID
	function LastInsertID(){
		return mysql_insert_id();
	}

	// Return number of rows
	function CountRows($from, $where=''){
		$result = $this->Select($from, $where, '', '', false, 'AND','count(*)');
                
		return $result["count(*)"];
	}
	
	function getWorkingDays($startDate,$endDate,$holidays){
    // do strtotime calculations just once
    $endDate = strtotime($endDate);
    $startDate = strtotime($startDate);


		//The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
		//We add one to inlude both dates in the interval.
		$days = ($endDate - $startDate) / 86400 + 1;
	
		$no_full_weeks = floor($days / 7);
		$no_remaining_days = fmod($days, 7);
	
		//It will return 1 if it's Monday,.. ,7 for Sunday
		$the_first_day_of_week = date("N", $startDate);
		$the_last_day_of_week = date("N", $endDate);
	
		//---->The two can be equal in leap years when february has 29 days, the equal sign is added here
		//In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
		if ($the_first_day_of_week <= $the_last_day_of_week) {
			//if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
			if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
		}
		else {
			// (edit by Tokes to fix an edge case where the start day was a Sunday
			// and the end day was NOT a Saturday)
	
			// the day of the week for start is later than the day of the week for end
			if ($the_first_day_of_week == 7) {
				// if the start date is a Sunday, then we definitely subtract 1 day
				$no_remaining_days--;

			}
			else {
				// the start date was a Saturday (or earlier), and the end date was (Mon..Fri)
				// so we skip an entire weekend and subtract 2 days
				$no_remaining_days -= 1;
			}
		}
	
		//The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
	//---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
	   $workingDays = $no_full_weeks * 6;
		if ($no_remaining_days > 0 )
		{
		  $workingDays += $no_remaining_days;
		}
	
		//We subtract the holidays
		foreach($holidays as $holiday){
			$time_stamp=strtotime($holiday);
			//If the holiday doesn't fall in weekend
			if ($startDate <= $time_stamp && $time_stamp <= $endDate && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
				$workingDays--;
		}
	
		return $workingDays;
	}

	
	
	
	
        // Return number of rows
	function CountRowsGroup($from, $where='',$group, $like=false, $operand='AND',$cols='count(*)'){
		if(trim($from) == ''){
			return false;
		}

		$query = "SELECT {$cols} FROM `{$from}` WHERE ";

		if(is_array($where) && $where != ''){
			// Prepare Variables
			$where = $this->SecureData($where);

			foreach($where as $key=>$value){
				if($like){
					//$query .= '`' . $key . '` LIKE "%' . $value . '%" ' . $operand . ' ';
					$query .= "`{$key}` LIKE '%{$value}%' {$operand} ";
				}else{
					//$query .= '`' . $key . '` = "' . $value . '" ' . $operand . ' ';
					$query .= "`{$key}` = '{$value}' {$operand} ";
				}
			}

			$query = substr($query, 0, -(strlen($operand)+2));

		}else{
			$query = substr($query, 0, -7);
		}


                if(groupBy != ''){
			$query .= ' GROUP BY ' . $group;
		}
                 
               return $result = $this->ExecuteSQL($query);
		
	}

	// Closes the connections
	function CloseConnection(){
		if($this->databaseLink){
			mysql_close($this->databaseLink);
		}
	}
        
        
  function encrypt_password($plain) {


    $password = "jkd564sdf6s4"; //tep_rand();
 

    $salt 		= substr(md5($password), 0, 2);

    $password 	= md5($salt . $plain) ;

    return $password;
  }
  function genRandomString() {
		/*$length = 10;
		$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$string = '';
	 
		for ($p = 0; $p < $length; $p++) {
			$string .= $characters[mt_rand(0, strlen($characters) -1)];
		}*/
		$string = substr(md5(microtime()), rand(0,17), 15);
	 
    return $string;
	}
	  function genPromo($length) {
		$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$string = '';
	 
		for ($p = 0; $p < $length; $p++) {
			$string .= $characters[mt_rand(0, strlen($characters) -1)];
		}
    return $string;
	}
    
function backup_tables($tables = '*')
{

	
	//get all of the tables
	if($tables == '*')
	{
		$tables = array();
		$result = mysql_query('SHOW TABLES');
		while($row = mysql_fetch_row($result))
		{
			$tables[] = $row[0];
		}
	}
	else
	{
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}
	
	//cycle through
	foreach($tables as $table)
	{
		$result = mysql_query('SELECT * FROM '.$table);
		$num_fields = mysql_num_fields($result);
		
		$return.= 'DROP TABLE '.$table.';';
		$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
		$return.= "\n\n".$row2[1].";\n\n";
		
		for ($i = 0; $i < $num_fields; $i++) 
		{
			while($row = mysql_fetch_row($result))
			{
				$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\n";
	}
	
	//save file
	$handle = fopen('db-backup-'.date('Y-m-d-H-i-s').'-'.(md5(time())).'.sql','w+');
	fwrite($handle,$return);
	fclose($handle);
}	

	
	
	    


//------------------------count-----------------------------------//
 function fetchAllcount($from , $where='', $orderBy='', $limit='', $like=false, $operand='AND',$cols='count(*)' ,$asc='',$join=''){
            if(trim($from) == ''){
			return false;
		}
		$query = "SELECT {$cols} FROM {$from} WHERE 1 "; 
		if($join!=''){
         $query .=' and '.$join;
      }
		if(is_array($where) && $where != ''){
			// Prepare Variables
			$where = $this->SecureData($where);

			foreach($where as $key=>$value){
				if($like){
					//$query .= '`' . $key . '` LIKE "%' . $value . '%" ' . $operand . ' ';
					$query .= "`{$key}` LIKE '%{$value}%' {$operand} ";
				}else{
					//$query .= '`' . $key . '` = "' . $value . '" ' . $operand . ' ';
					$query .= "`{$key}` = '{$value}' {$operand} ";
				}
			}
       
			$query = substr($query, 0, -(strlen($operand)+2));

		}else{
		if($join!=''){
	//	$query = substr($query, 0, -(strlen($operand)+2));
		}else
			$query = substr($query, 0, -7);
		}

		if($orderBy != ''){
			$query .= ' ORDER BY ' . $orderBy;
		}
       if($asc != ''){
			$query .= $asc;
		}
		if($limit != ''){
			$query .= ' LIMIT ' . $limit;
		}
           //print_r($new);
                $results= mysql_query($query);
			    $cnt=mysql_num_rows($results);
                return $cnt;
            
        }  
function pagination($page,$limit,$total_pages)
	{ 
	$adjacents = 3;
	if ($page == 0) $page = 1;					//if no page var is given, default to 1.
	$prev = $page - 1;							//previous page is page - 1
	$next = $page + 1;							//next page is page + 1
	$lastpage = ceil($total_pages/$limit);		//lastpage is = total pages / items per page, rounded up.
	$lpm1 = $lastpage - 1;						//last page minus 1
	
	/* 
		Now we apply our rules and draw the pagination object. 
		We're actually saving the code to a variable in case we want to draw it more than once.
	*/
	$pagination = "";$more="";
	if($lastpage > 1)
	{	
		$pagination .= "<div class=\"pagination\">";
		//previous button
		if ($page > 1) 
			$pagination.= "<a class='nextatag' onclick=\"gonextpage($prev)\">  previous</a>";
		else
			$pagination.= "<span class=\"disabled\"> previous</span>";	
		
		//pages	
		if ($lastpage < 7 + ($adjacents * 2))	//not enough pages to bother breaking it up
		{	
			for ($counter = 1; $counter <= $lastpage; $counter++)
			{
				if ($counter == $page)
					$pagination.= "<span class=\"current\"><a class='current' onclick=\"gonextpage($counter)\">$counter</a></span>";
				else
				//	$pagination.= "<a class='nextatag' onclick=\"gonextpage($counter)\">$counter</a>";				
					$more.= "<a class='nextatag' onclick=\"gonextpage($counter)\">More</a>";					
			}
		}
		elseif($lastpage > 5 + ($adjacents * 2))	//enough pages to hide some
		{
			//close to beginning; only hide later pages
			if($page < 1 + ($adjacents * 2))		
			{
				for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
				{
					if ($counter == $page)
						$pagination.= "<span class=\"current\"><a class='current' onclick=\"gonextpage($counter)\">$counter</a></span>";
					else
						$pagination.= "<a  class='nextatag' onclick=\"gonextpage($counter)\">$counter</a>";	
					//$more.= "<a class='nextatag' onclick=\"gonextpage($counter)\">More</a>";						
				}
				$pagination.= "...";
				$pagination.= "<a  class='nextatag' onclick=\"gonextpage($lpm1)\">$lpm1</a>";
				$pagination.= "<a  class='nextatag' onclick=\"gonextpage($lastpage)\">$lastpage</a>";		
			}
			//in middle; hide some front and some back
			elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
			{
				$pagination.= "<a class='nextatag' onclick=\"gonextpage(1)\">1</a>";
				$pagination.= "<a  class='nextatag' onclick=\"gonextpage(2)\">2</a>";
				$pagination.= "...";
				for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
				{
					if ($counter == $page)
						$pagination.= "<span class=\"current\"><a class='nextatag' onclick=\"gonextpage($counter)\">$counter</a></span>";
					else
					$pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";		
					//	$more.= "<a class='nextatag' onclick=\"gonextpage($counter)\">More</a>";					
				}
				$pagination.= "...";
				$pagination.= "<a  class='nextatag' onclick=\"gonextpage($lpm1)\">$lpm1</a>";
				$pagination.= "<a  class='nextatag' onclick=\"gonextpage($lastpage)\">$lastpage</a>";		
			}
			//close to end; only hide early pages
			else
			{
				$pagination.= "<a class='nextatag' onclick=\"gonextpage(1)\">1</a>";
				$pagination.= "<a class='nextatag' onclick=\"gonextpage(2)\">2</a>";
				$pagination.= "...";
				for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
				{
					if ($counter == $page)
						$pagination.= "<span class=\"current\"><a class='nextatag' onclick=\"gonextpage($counter)\">$counter</a></span>";
					else
						$pagination.= "<a class='nextatag' onclick=\"gonextpage($counter)\">$counter</a>";	
					//$more.= "<a class='nextatag' onclick=\"gonextpage($counter)\">More</a>";						
				}
			}
		}
		
		//next button
		if ($page < $counter - 1) 
			$pagination.= "<a class='nextatag' onclick=\"gonextpage($next)\">next >></a>";
		//$more.= " ";		
		else
			$pagination.= "<span class=\"disabled\"><a class='nextatag' onclick=\"gonextpage($next)\">next >></a> </span>";
		$pagination.= "</div>\n";		
	}
	
       return $pagination;    
	   }  
	   
	function subpagination($page,$limit,$total_pages,$gofunction,$j,$ingredient)
	{ 
	$adjacents = 3;
	if ($page == 0) $page = 1;					//if no page var is given, default to 1.
	$prev = $page - 1;							//previous page is page - 1
	$next = $page + 1;							//next page is page + 1
	$lastpage = ceil($total_pages/$limit);		//lastpage is = total pages / items per page, rounded up.
	$lpm1 = $lastpage - 1;						//last page minus 1
	
	/* 
		Now we apply our rules and draw the pagination object. 
		We're actually saving the code to a variable in case we want to draw it more than once.
	*/
	$pagination = "";$more="";
	if($lastpage > 1)
	{	
		$pagination .= "<div class=\"pagination\">";
		//previous button
		if ($page > 1) 
			$pagination.= "<a class='nextatag' onclick=\"gosubpage($prev,$page,$j,$ingredient)\">  previous</a>";
		else
			$pagination.= "<span class=\"disabled\"> previous</span>";	
		
		//pages	
		if ($lastpage < 7 + ($adjacents * 2))	//not enough pages to bother breaking it up
		{	
			for ($counter = 1; $counter <= $lastpage; $counter++)
			{
				if ($counter == $page)
					$pagination.= "<span class=\"current\"><a class='current' onclick=\"gosubpage($counter,$page,$j,$ingredient)\">$counter</a></span>";
				else
				//	$pagination.= "<a class='nextatag' onclick=\"$gofunction($counter)\">$counter</a>";				
					$more.= "<a class='nextatag' onclick=\"gosubpage($counter,$page,$j,$ingredient)\">More</a>";					
			}
		}
		elseif($lastpage > 5 + ($adjacents * 2))	//enough pages to hide some
		{
			//close to beginning; only hide later pages
			if($page < 1 + ($adjacents * 2))		
			{
				for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
				{
					if ($counter == $page)
						$pagination.= "<span class=\"current\"><a class='current' onclick=\"gosubpage($counter,$page,$j,$ingredient)\">$counter</a></span>";
					else
						$pagination.= "<a  class='nextatag' onclick=\"gosubpage($counter,$page,$j,$ingredient)\">$counter</a>";	
					//$more.= "<a class='nextatag' onclick=\"gosubpage($counter)\">More</a>";						
				}
				$pagination.= "...";
				$pagination.= "<a  class='nextatag' onclick=\"gosubpage($lpm1,$page,$j,$ingredient)\">$lpm1</a>";
				$pagination.= "<a  class='nextatag' onclick=\"gosubpage($lastpage,$page,$j,$ingredient)\">$lastpage</a>";		
			}
			//in middle; hide some front and some back
			elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
			{
				$pagination.= "<a class='nextatag' onclick=\"gosubpage(1,$page,$j,$ingredient)\">1</a>";
				$pagination.= "<a  class='nextatag' onclick=\"gosubpage(2,$page,$j,$ingredient)\">2</a>";
				$pagination.= "...";
				for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
				{
					if ($counter == $page)
						$pagination.= "<span class=\"current\"><a class='nextatag' onclick=\"gosubpage($counter,$page,$j,$ingredient)\">$counter</a></span>";
					else
					$pagination.= "<a onclick=\"gosubpage($counter,$page,$j,$ingredient)\">$counter</a>";		
					//	$more.= "<a class='nextatag' onclick=\"gosubpage($counter)\">More</a>";					
				}
				$pagination.= "...";
				$pagination.= "<a  class='nextatag' onclick=\"gosubpage($lpm1,$page,$j,$ingredient)\">$lpm1</a>";
				$pagination.= "<a  class='nextatag' onclick=\"gosubpage($lastpage,$page,$j,$ingredient)\">$lastpage</a>";		
			}
			//close to end; only hide early pages
			else
			{
				$pagination.= "<a class='nextatag' onclick=\"gosubpage(1,$page,$j,$ingredient)\">1</a>";
				$pagination.= "<a class='nextatag' onclick=\"gosubpage(2,$page,$j,$ingredient)\">2</a>";
				$pagination.= "...";
				for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
				{
					if ($counter == $page)
						$pagination.= "<span class=\"current\"><a class='nextatag' onclick=\"gosubpage($counter,$page,$j,$ingredient)\">$counter</a></span>";
					else
						$pagination.= "<a class='nextatag' onclick=\"gosubpage($counter,$page,$j,$ingredient)\">$counter</a>";	
					//$more.= "<a class='nextatag' onclick=\"gosubpage($counter)\">More</a>";						
				}
			}
		}
		
		//next button
		if ($page < $counter - 1) 
			$pagination.= "<a class='nextatag' onclick=\"gosubpage($next,$page,$j,$ingredient)\">$next >></a>";
		//$more.= " ";		
		else
			$pagination.= "<span class=\"disabled\"><a class='nextatag' onclick=\"gosubpage($next,$page,$j,$ingredient)\">$next >></a> </span>";
		$pagination.= "</div>\n";		
	}
	
       return $pagination;    
	   }  
	      
	   
	     function fetchAlljoinrec($from , $where='', $orderBy='', $limit='', $like=false, $operand='AND',$cols='*' ,$asc='',$join='',$start=0){
            if(trim($from) == ''){
			return false;
		}

		$query = "SELECT {$cols} FROM {$from} WHERE 1 "; 
		if($join!=''){
         $query .=' and '.$join;
      }
		if(is_array($where) && $where != ''){
			// Prepare Variables
			$where = $this->SecureData($where);

			foreach($where as $key=>$value){
				if($like){
					//$query .= '`' . $key . '` LIKE "%' . $value . '%" ' . $operand . ' ';
					$query .= "`{$key}` LIKE '%{$value}%' {$operand} ";
				}else{
					//$query .= '`' . $key . '` = "' . $value . '" ' . $operand . ' ';
					$query .= "`{$key}` = '{$value}' {$operand} ";
				}
			}
       
			$query = substr($query, 0, -(strlen($operand)+2));

		}else{
		if($join!=''){
	//	$query = substr($query, 0, -(strlen($operand)+2));
		}else
			$query = substr($query, 0, -7);
		}

		if($orderBy != ''){
			$query .= ' ORDER BY ' . $orderBy;
		}
       if($asc != ''){
			$query .= $asc;
		}
		
		 if($start!='')
		 {
		$query .= ' LIMIT ' . $start.','.$limit;
	 }
           //print_r($new);
                $results= mysql_query($query);
                $a=0;
			$result=array();
				
              while ($rows = mysql_fetch_array($results))
                   $result[$a++]=$rows;
				   
              return $result;
              // }
                
		//return $this->ExecuteSQL($query);
        
        }
	
			function getindividualdata($from,$cat ){
			$catnames = mysql_query("select category from ". $from." where id='".$cat."'");
			 $rows = mysql_fetch_object($catnames);
              return $rows;
			}
			function getindividualdatagrp($from,$cat ,$field,$group){
			$sql= "select ".$field." from ". $from." where  ".$cat;
			if($group!='')
			$sql.=" group by ".$group;
			//echo $sql;
			$catnames = mysql_query($sql);
			 $rows = mysql_fetch_object($catnames);
              return $rows;
			}
			
			
			function convertToGram($qty,$unit){
				$where['id']	=	$unit;
				$conv = $this->Select('inv_ingredient_units',$where);
				$convertion = $conv['convertion'];
				$quantity =  $convertion*$qty;
                               
				return $quantity;
			}
			
			function convertFromGram($qty,$unit){
				$where['id']	=	$unit;
				$conv = $this->Select('inv_ingredient_units',$where);
				
                                 $convertion = $conv['convertion'];
                                    $quantity =  $qty/$convertion;
				return $quantity;
			}
			
			
		
}
$page_rows = 50; 

?>