<?php
error_reporting(0);
$prot = "http";
$port = "";
if ($_SERVER["HTTPS"] == "on")$prot .= "s";
if ($_SERVER["SERVER_PORT"] != "80")$port=":".$_SERVER["SERVER_PORT"];
define("_ROOT_",$prot."://".$_SERVER['SERVER_NAME'].$port."/");
define("_CURURL_",_ROOT_.ltrim($_SERVER["REQUEST_URI"],"/"));
class RphpFunctions extends StrFunctions{//php redifined functions
	
	 //redirect to another page(static)
 public static function redirect($locationPath){
    header("Location: " . $locationPath);
	exit;	
 }

// Help to confirm the page currently loaded(static)
 public static function CheckPage($Page){
	$path = $_SERVER['PHP_SELF'];
	$len = strlen($path);
	$Lpage = substr($path,-($len - (strrpos($path,'/') + 1)));
	$Lpage2 = substr($path,-($len - (strrpos($path,'\\') + 1)));
	if ($Lpage ==   $Page || $Lpage2 == $Page){
		return true;
	}else{
		return false;
	}
	
	
	
	
	//SQL save string
}

public function UrlPrep($url){
	 //http://live/epdevelop/cportal/#Examsanc
	 $root = "root://";
	$url = trim($url);
	
	if(substr($url,0,strlen($root)) == $root){
		$curfile = __FILE__;
		$curfilearr = explode("epconfig",$curfile);
		if(count($curfilearr) > 1){
			$url = $curfilearr[0].substr($url,strlen($root));
		}
	}
	return $url;
}



//check if item(s) are sent trough url (GET)
function CheckGet($arrPost){
	$ck = true;
	//$arr = array();
	if (is_array($arrPost)){
		foreach($arrPost as $post){
		    if (!isset($_GET[$post]) || (empty($_GET[$post]) && $_GET[$post] != '0')){
				//if(!isset($_FILES[$post])){
					return false;	
				//}
				
			}
	    }
	}elseif(is_string($arrPost)){
		if(!isset($_GET[$arrPost]) || (empty($_GET[$arrPost]) && $_GET[$post] != '0')){
			return false;	
		}
	}
return $ck;	
}

//Help handle multiple parameter for methods (all parameters will be loaded into $arrval as array)
public function __call($name, $arrval){
	if($name == 'CheckPost_r'){
		return $this -> CheckPost($arrval);
		
	}elseif($name == 'CheckGet_r'){
		return $this -> CheckGet($arrval);
	}
}



//check if item(s) are posted
 function CheckPost($arrPost){
	$ck = true;
	//$arr = array();
	//print_r($arrPost);
	//$adad = '';
	if (is_array($arrPost)){
		foreach($arrPost as $post){
			
		    if (!isset($_POST[$post]) || (empty($_POST[$post]) && $_POST[$post] != '0')){
				if(!isset($_FILES[$post]) || empty($_FILES[$post])){
					return false;	
				}
				
			}
	    }
	}elseif(is_string($arrPost)){
		if(!isset($_POST[$arrPost]) || empty($_POST[$arrPost])){
			return false;	
		}
	}
return $ck;	
}

//function to form array from a string with format "key=value"

//destroy session
public function Destroy_Session(){
	$_SESSION = array();
	
	if (isset($_COOKIE[session_name()])) {
      setcookie(session_name(), '', time()-42000, '/');
	}
	
	session_destroy();
}

	
}


class StrFunctions{//String manipulation functions all are static
	//form a javascript code
public static function Script($JavascriptCode){
$scripthead = "<script type=\"text/javascript\">";
$scriptClose = "</script>";
echo $scripthead . $JavascriptCode . $scriptClose;	
}

//Escape for string
public static function esc4str($str){
	$str = str_replace("'","\'",$str);
	$str = str_replace('"','\"',$str);
	return $str;
}

function GenerateString($minlen,$maxlen,$exclude=""){
	//$rand = mt_rand()
	$charset = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','!','@','#','$','%','&','*','(',')','-','_','=','+','[','{',']','}','\\','|',';',':',"'",'"','<',',','>',".","?","/",' ',"^",'`');
	$ac = "";
	$s=1;
	$chars = mt_rand($minlen,$maxlen);
	while($s <= $chars){
	  $rand = mt_rand(0,82);
	  $indchar = $charset[$rand];
	  if($exclude != "" && strpos($exclude,$indchar) > -1)continue;
	  $ac .= $indchar;
	   $s++;	
	}
	return $ac;
}
 function _($txt){
	 $decr="";
	 if(trim($txt) != ""){
		 $brd = explode("~",$txt);
		 if(count($brd) >= 3){
			 $pos = $brd[1];
			 $encarr = [];
           for($K=2;$K<count($brd);$K++){
			$encarr[] = $brd[$K];
		   }
			 $enc = implode("~",$encarr);
			 $posvals = explode(" ",$pos);
			 for($f=0;$f<count($posvals);$f++){
				 $curpos = (int)$posvals[$f];
				 $char = substr($enc,$curpos,1);
				 $decr .= $char;	
				}
			}
		}
		return $decr;
	}
function _d($txt,$min=300,$max=500,$ex=""){
	//return "aaa";
	$posstr = "";
	$encr = "";
	if(trim($txt) != ""){
		$totchar = strlen($txt);
		$pick = true;
		for($d=0;$d<$totchar;$d++){
			//if($pick){
				$txtpic = substr($txt,$d,1);
				//$txtpic = strlen($txtpic) == 1?$txtpic."`":$txtpic;
				//$txtpic = substr($txtpic,1,1).substr($txtpic,0,1);
				$GC = $this->GenerateString($min,$max,$ex);
				$GCLen = strlen($encr)+strlen($GC);
				$encr .= $GC.$txtpic;
				$posstr .= $GCLen." ";
				
				
				//$pick = false;
			//}else{
				//$pick = true;
			//}
		}
		$posstr = trim($posstr);
		$encr = $this -> GenerateString($min,$max,$ex)."~".$posstr."~".$encr;
		
		return $encr;
		}
}
function __($txt,$min=300,$max=500,$ex='"\'<>&%'){ //encrypt
	//return $this -> _d($txt,$min,$max,$ex);
	$encr = "";
  do{
    $encr = $this -> _d($txt,$min,$max,$ex);
	$dencr = $this -> _($encr) ;
  }while($dencr !== $txt);
	
	return $encr;
}
public static function truncstr($str,$NumChar){
	 $topicdis = '';
	  if(strlen($str) > $NumChar){
		  $i = 0;
		  while($i < $NumChar){
			   $topicdis .= $str[$i];
			 if(ctype_upper($str[$i])){
				 $i++;
			 }
			 $i++;
		  }
		$topicdis .= " ..."; 
	  }else{
		 $topicdis = $str;
	  }
	  return $topicdis;
}


private function multiformer($keyarr,$value){

}
//function to convert url string to array
public static function DataArray($str,$elemstr = "&",$keyItem = "=",$multiSep = ""){
	$str = trim($str);
	$rst = array();
	if($str != ""){
		$strarr = explode($elemstr,$str);
		for($a=0; $a<count($strarr) ; $a++){
			$strv = $strarr[$a];
			$stratrvallarr = explode($keyItem,$strv);
			if(count($stratrvallarr) >= 2){
				$key = $stratrvallarr[0];
				array_shift($stratrvallarr);
				$aval = urldecode(implode("=",$stratrvallarr));
				if(trim($multiSep) != ""){
					//split keys
					$multikeys = explode($multiSep,$key);
					if(count($multikeys) > 1){ //if  multi dimentional
                       //form the code
					   $cd = "\$rst[";
					   foreach($multikeys as $indkeys){
						   $cd .="'".$indkeys."'][";
					   }
					   $cd = rtrim($cd,"[");
					   $cd = $cd."='';\$rstpos=&".$cd.";";
					   eval($cd);
                       $rstpos = $aval;
					}else{
						$rst[trim($key)] = $aval;
					}
				}else{
					$rst[trim($key)] = $aval;
				}
				
				
			}elseif(count($stratrvallarr) == 1){
				$rst[] = urldecode($stratrvallarr[0]);
			}
			
		}
		
	}
	return $rst;
	
}

//function to convert array to url string
public static function DataString($arr,$safe=true,$recursiveKey=""){
	$str = "";
	$recursiveKey = trim($recursiveKey) != ""?$recursiveKey."_":"";
	if(is_array($arr)){
	  foreach($arr as $key => $val){
		  $key = $recursiveKey.$key; //form the new key in case of multdimentional array
		  if(is_array($val)){ //multi dimentional arrau
			   $str .= self::DataString($val,$safe,$key) ."&";
		  }else{
			if($safe){
			$str .= $key."=".rawurlencode($val)."&";
			}else{
				$str .= $key."=".$val."&";  
			}
		  }
	  }
	}
	return rtrim($str,"&");
}

public function ImageToDataURI($image, $mime = '') {
	return file_exists($image)?('data: '.(function_exists('mime_content_type') ? mime_content_type($image) : $mime).';base64,'.base64_encode(file_get_contents($image))):"";
}
	
}


class DbFunctions extends RphpFunctions{//deals with database work and file system
	public static $con = NULL;
	public static $hostName = NULL;
	public static $dbName = NULL;
	public static $userName = NULL;
	public static $txt = 'constant value';
	var $Connected = false;
	var $ConnectedDB = false;
	var $ConnectStatus = "";
	var $ConnectStatusID = 0;
	var $Connection = NULL;
	 var $FileDir = "image/";
	//var $ff = 'll';
	 public static function Staticf($a){
		
	}
	
	function QRImage($param,$proot){
	return $proot."TaquaLB/Ajax/CGI/PHP/phpqrcode/qrinline.php?id=".urlencode($param);
	}
	function QRImage2($param,$proot){
	return $proot."Admin/qrcoderedirect.php?id=".urlencode($param);
	}
	//contructor
	function __construct($host = "",$user = "",$password = "",$db = ""){
		if($host != "" && $user != ""){
			
			 $this -> Connectdb($host,$user,$db,$password);
		}	
	}
	//private $x = array(1,2,3);
	 public function __call($name, $values)
    {
        if($name == "Select4rmdbtbFirstRw_r"){//alternative if the query is sent to get the first row of a database select rst
			$rst_info1 = $this -> RunQuery($values[0]);
		 return $this -> FirstRw($rst_info1);
		}
		
    }

	
	
	//function to select database
	function Selectdb($db){
		return mysql_select_db($db);
		//return mysqli::select_db($db);
	}

	function SqlSave($str){
	//if($con != null){
       $str = mysqli_real_escape_string($this->Connection,$str);
	//}else{
		//$str = $dbo->SqlSafe($str);
	//}
	//$str = str_replace('"','\"',$str);
	return $str;
}
function SqlSafe($str){
	$str = mysqli_real_escape_string($this->Connection,$str);
	//$str = str_replace('"','\"',$str);
	return $str;
}
	
	//function to start transaction
	function Begin(){
		return $this->Connection->query("START TRANSACTION");
	}
	
		//function to comit transaction
	function Commit(){
		return $this->Connection->query("COMMIT");
	}
	
		//function to rollback transaction
	function Rollback(){
		return $this->Connection->query("ROLLBACK");
	}
	
	//Conect to db
	function Connectdb($host,$user,$db,$password = ""){
		
		//$convar = mysql_connect($host, $user, $password);
		$convar = new mysqli($host, $user, $password,$db);
		//exit($convar->connect_errno);
		/*if (!$convar) {
		//echo( "Cannot connect to server" );
		//$this->Connected = false;
		//exit();
		$convar = "Cannot connect to server; host:{$host} , user:{$user}, db:{$db} , pw:******************** ";
		}else if ($db != "") {
			if (!$this->Selectdb($db)) {
				$convar = "Cannot connect to db";
				$this -> ConnectStatusID = 1;
			}
		}*/
		
		if($convar->connect_errno > 0){
            $convar = "Cannot connect to server; host:{$host} , user:{$user}, db:{$db} , pw:******************** ";
		}else{

		}
		
		self::$con = $convar;
		self::$hostName = $host;
		self::$dbName = $db;
		self::$userName = $user;
		
		if(!is_string($convar)){
		$this->Connected = true;
		$this->ConnectedDB = true;
		$this->Connection = $convar;
		}else{
			$this -> ConnectStatus = $convar;
			
		}
		return $convar;
	}
	
	//function to load select element options
	function LoadOptions($tb,$valField,$DisField,$cond = ""){
		$rstl = $this->Select4rmdbtb($tb,$valField.",".$DisField,$cond);
		if(is_array($rstl)){
			if($rstl[1] > 0){
				$rstlobj = $rstl[0];
			  while($rst_arr = $rstlobj -> fetch_array()){
				echo "<option value=\"{$rst_arr[0]}\">{$rst_arr[1]}</option>";  
			  }
			}else{
				echo "";
			}
		}else{
			echo "";
		}
	}

	//function to form record xml fron a query resource object
function toXML($rst){
	$xml = "<resultSet>";
	//form the total record field
	$xml .= "<_total>{$rst[1]}</_total>";
	
	if($rst[1] > 0){
		$rstobj = $rst[0];
		while($rstval = $rstobj->fetch_array()){
			//return reportError(implode(",",mysql_fetch_array($rst[0])));
			$xml .= "<row>";
			foreach  ($rstval as $key => $val){
				$val = htmlentities($val);
				if(is_string($key)){
				$xml .= "<{$key}>{$val}</{$key}>";
				}
			}
			$xml .= "</row>";
		}
	}
	$xml .= "</resultSet>";
	
	return $xml;
	
}
//Insert object that returns the inserted ID 
function InsertID($tb,$fieldVal){
	$rst = $this->Insert($tb,$fieldVal);
	if($rst == "#"){
		return $this->Connection->insert_id;
	}else{
		return -1;
	}
}

function InsertID2($tb,$fieldVal){
	$rst = $this->Insert($tb,$fieldVal);
	if($rst == "#"){
		return $this->Connection->insert_id;
	}else{
		return $rst;
	}
}
	//short hand for Insert2DbTb
	function Insert($tb,$fieldVal){
		return $this->Insert2DbTb($fieldVal,$tb);
	}
	//insert value into database
  function Insert2DbTb($fields,$tb){
	  $sql = "INSERT INTO ". $tb ." SET ";
		  foreach($fields as $key => $val){
			  if(is_string($val) || empty($val)){
				  $val = "'" . $this->SqlSafe($val) . "'";
			  }else if(!is_numeric($val)){
				 $val = "'" . $this->SqlSafe($val) . "'"; 
			  }
				  $sql .= "`".$key."`" . "=" . $val . ", ";
		  }
		  $sql = trim($sql,', ');
		 
		  //return $sql.";";
			/* "JokeText='$joketext', " .
			 "JokeDate=CURDATE()";*/
			// return $this->Connection->query($sql);
	  if ($this->Connection->query($sql)) {
		return '#';
	  } else {
	  return $this->Connection->error; 
	  }
  }
  
  //upload file
  function UploadFile($file,$size,$UseFileName = false,$replace = false,$extr=""){
	  $error = "";
	$message = "";
	    $target_file = "";
		$val = "";
		$base_name = basename($_FILES[$file]['name']);
		
		//$target_file = $target_file . $base_name;
	if (empty($_FILES[$file]['name']) || !isset($_FILES[$file]['name'])){
		$error = "1";
		$message = "No file found";
	}else{
		//analyse file name
		$ipinfo = pathinfo($_FILES[$file]['name']);// get the file break down
				$idir = $ipinfo['dirname'];
                $ibaseNme = $ipinfo['basename'];
                $iext =  $ipinfo['extension'];
                $ifileN = $ipinfo['filename'];
				if($extr != ""){
					$iext = $extr; 
				}
		if($UseFileName === false){
				$val = mt_rand();
		    $target_file = $this -> FileDir . "pic_".$val . "." . $iext;
		}else{
			if(is_string($UseFileName)){
				$target_file = $this -> FileDir . $UseFileName . "." . $iext;
			}else{
			$target_file = $this -> FileDir . $base_name;
			}
		}
	    //make dir if directary not exits
		if(!file_exists($this -> FileDir)){	
			mkdir($this -> FileDir);
		}
		
		//if not to overide when exist
		if($replace == false){
		while(file_exists($target_file)){
			if($UseFileName == false){
			  $val = mt_rand();
			  $target_file = $this -> FileDir . $val . "." . $iext;
			}else{
				//process the filename to form another file name (e.g filename_2)
				$pinfo = pathinfo($target_file);// get the file break down
				$dir = $pinfo['dirname'];
                $baseNme = $pinfo['basename'];
                $ext =  $pinfo['extension'];
                $fileN = $pinfo['filename'];
				$pos = strrpos($fileN,"_"); //seacrh for _ at the end of the filename
				if($pos === false){// if not found add _2 to defferentiate the new file
					$fileN = $fileN ."_2";
				}else{
					$cntNo = substr($fileN,$pos + 1); //get the string after the Underscore(_)
					if(is_numeric($cntNo)){// if it is a number add one to it to deferentiate it from the first
						$fileN = rtrim($fileN,$cntNo);
						$cntNo =(int)$cntNo + 1;
						$fileN .= $cntNo;
					}else{//if not number just add _2 to the file name
						$fileN = $fileN ."_2";
					}
				}
				$target_file = $dir . "/" . $fileN . "." .$ext; //reform file path
			}
		}
		}
		
		//check if filename is important check only size else check type(image) and size
		if($UseFileName === true){
			$conds = ($_FILES[$file]['size'] < ($size+0) );
		}else{
			$conds = (($_FILES[$file]['type'] == "image/gif") || ($_FILES[$file]['type'] == "image/jpeg") || ($_FILES[$file]['type'] == "image/jpg") || ($_FILES[$file]['type'] == "image/pjpeg")) && ($_FILES[$file]['size'] < (int)$size );
		}
		
			if ($conds){//start check img type
			      if ($_FILES[$file]['error'] > 0){// start check if error
				    $error = "3";
					if($_FILES[$file]['error'] == 1){
						$message = "File exceeds the maximum upload size ";
					}else{
				    $message = "Error :".$_FILES[$file]['error'];
					}
				  }else{
					/* if(strlen($base_name) > 50){
						$error[] = "Passport";
				//$message .= "Name of picture must not be more than 50 characters; edit the name. <br />"; 
				     }else{*/
					  
					             if (move_uploaded_file($_FILES[$file]['tmp_name'],$target_file)){	
										return array('Success' => true, 'Error' => $error, 'ErrorText' => $message, 'Filename' => $target_file);
									}else{
									$error = 4;
									$message = "Cannot upload file-".$target_file;	
									} 
				 
				}
			
			}else{
				$error = "5";
			$message .= "Invalid image file type or <br/> Image size too big(must not be more than ".($size/1000) . "KB)";
				
			}
			
		
	}
	return array('Success' => false, 'Error' => $error, 'ErrorText' => $message, 'Filename' => '');
  }// upload function ends
  
  //authenticate
  function Authenticate($valus,$tb){
	  if (is_array($valus) && isset($tb)){ 
		 $query = "SELECT * FROM {$tb} WHERE ";
		 foreach($valus as $field => $value){
			$q = (is_string($value))?"'":""; 
			
			 $query .= $field . "=" . $q . $this->SqlSafe($value) . $q . " AND ";
		 }
		 $query = trim($query," AND ") . " LIMIT 1";
	  
	  $rst = $this->Connection->query($query);
	  if($rst){
		  if($rst->num_rows == 1){
			 $rst_set = $rst->fetch_array();
			 return array(true,$rst_set); 
		  }else{
			 return array(false,NULL); 
		  }
	  }else{
		 return array(false,$this->Connection->error);
	  }
	 }else{
		return array(false,'Invalid Input value parameter; Function takes array and string table name'); 
	 }
  }
function Exist($tb,$fieldVal){
	return $this->CheckDbValue($fieldVal,$tb);
}
  //Check existence in database
  function CheckDbValue($values,$tb){
	 $rst =  $this -> Authenticate($values,$tb); //check if exist
	 if( $rst[0] == true){//if exist
		 return true;
	 }else{
		 if($rst[1] == NULL){//if not exist
			return false; 
		 }else{// if error
			return $rst[1]; 
		 }
	 }
	  
	}
	
	function SelectAsArray($tbs,$fields = "",$cond = "",$type=MYSQLI_ASSOC){
		$rtn = $this->Select($tbs,$fields,$cond);
		if(is_array($rtn)){
			//$res = $rtn[0]->store_result(MYSQLI_STORE_RESULT_COPY_DATA);
			//$rtt = $rtn[0]->fetch_all($type);
			$rtt = $this->FetchAll($rtn[0],$type);
			$rtn[0]->free();
			return $rtt;
		}
    return $rtn;
	}

  //shorthand 
  function Select($tbs,$fields = "",$cond = ""){
	 return $this -> Select4rmdbtb($tbs,$fields,$cond); 
  }
  
  //Select from database table
  function Select4rmdbtb($tbs,$fields = "",$cond = "",$type=MYSQLI_BOTH){
	  if(isset($tbs)){
		  $query = "SELECT ";
		  //process fileds
		  $filds = "";
		  if(is_array($fields)){// fileds are morthen 1
			  foreach($fields as $f){
				 $filds .= $f . ", "; 
			  }
			  $filds = trim($filds, ", ");
		  }elseif(is_string($fields) && $fields != ""){
			  $filds = $fields;
		  }else{
			  $filds = "*";
		  }
		  $query .= $filds . " FROM ";
		  
		  
		  //process tables
		  $tbstr = "";
		  if(is_array($tbs)){// fileds are morthen 1
			  foreach($tbs as $t){
				 $tbstr .= $t . ", "; 
			  }
			  $tbstr = trim($tbstr, ", ");
		  }else{
			  $tbstr = $tbs;
		  }
		  
		  $query .= $tbstr;
		  
		  //process conditions
		  if($cond != ""){
			$query .= " WHERE " . $cond;  
		  }
		 return $this -> RunQuery($query);
	  }
  }

  //short hand for update operation
  function Update($tb,$fieldval,$cond=""){
	  return $this->Updatedbtb($tb,$fieldval,$cond);
  }

  //short hand for delete operation
  function Delete($tb,$cond){
	  return $this->RunQuery("DELETE FROM $tb WHERE $cond");
  }
  //update table records
 function Updatedbtb($tb,$fieldsValeus,$cond = ""){
	 if(isset($tb) && isset($fieldsValeus)){
		 $qy = "UPDATE {$tb} SET ";
		 if(is_array($fieldsValeus)){
			 foreach($fieldsValeus as $field => $value){
				 $sep = (is_string($value)  || empty($val) )?"'":"";
				$qy .= "`".$field ."` = ". $sep . $this->SqlSafe($value) . $sep . ", "; 
			 }
			 $qy = trim($qy,", ");
			 if($cond != ""){
				$qy .= " WHERE ". $cond ; 
			 }
			 //echo $qy;
			 return $rst = $this -> RunQuery($qy,"Update");
		 }
		 
		 
	 }
 }
  //run query
  
  function RunQuery($query,$type = ""){
	  $rst = $this->Connection->query($query);
	  $query = trim($query);
	  $comd = substr($query,0,6);
	  if(strtolower($comd) != "select"){
		  $type == "dd";
	  }
	  if($rst){
		  if($type == ""){
			 return array($rst,$rst->num_rows);  
		  }else{
			 return array($rst,$this->Connection->affected_rows);
			  //return array($rst, $query);
		  }
		
	  }else{
		 return $this->Connection->error.$query; 
	  }
  }
  
  //Get the total number of rows
  function Select4rmdbtbNumRw($tbs,$fields = "",$cond = ""){
	   $rst_info1 = $this -> Select4rmdbtb($tbs,$fields,$cond);
		   if(is_array($rst_info1)){
			   return  $rst_info1[1];
		   }else{
			   return "";
		   }
  }
  
  //select frum database with function
    function SelectRun($tbs,$func,$fields = "",$cond = ""){
		//$func must contain one parameter which is the select resource
		$rst_info1 = $this -> Select4rmdbtb($tbs,$fileds ,$cond);
		$func($rst_info1);
	}
	
	function SelectRunForEach($tbs,$func,$fields = "",$cond = ""){
		$rst_info1 = $this -> Select4rmdbtb($tbs,$fileds ,$cond);
			 if(is_array($rst_info1)){
				if($rst_info1[1] > 0){
					$rstobjs = $rst_info1[0];
					while($rws = $rstobjs->fetch_array()){
						$rst = $func($rws);
					}
					return $rst;
				}
			  
			 }
	}
  
  //get the a key-value record from database
  function SelectToArr($tb, $KeyCol = "", $ValCol = "", $cond = ""){
	  $keyset = ""; //hold value to determine keyvalue sent
	  $fileds = "";
	  if($KeyCol != ""){
		  if($ValCol != ""){
			$fileds = $KeyCol ."," .  $ValCol; 
			 $keyset = "kv";
		  }else{
			 $keyset = "k"; 
		  }
		 
	  }
	  $rst_info1 = $this -> Select4rmdbtb($tb,$fileds ,$cond);
		 if(is_array($rst_info1)){
				$news = array();
			  if($rst_info1[1] > 0){
				  $rstob = $rst_info1[0];
				  while($rws = $rstob->fetch_array($type)){
					  if($keyset == "k"){ //if only key
					  $news[$rws[$KeyCol]] = $rws; //item id is converted to index
					  }else if($keyset == "kv"){
						$news[$rws[$KeyCol]] = $rws[1]; //item id is converted to index  
					  }else{
						$news[$rws[$KeyCol]] = $rws; //item id is converted to index  
					  }
				  }
			  //$news = array('Headlines','Latest News','Local News','World News','Sport News');
			  }
			  return $news;
		   }else{
			  return $rst_info1;   
			  
		   }
	  
  }
  //shorthand
  function SelectFirstRow($tbs,$fields = "",$cond = "",$type=MYSQLI_BOTH){
	  
	  return $this->Select4rmdbtbFirstRw($tbs,$fields,$cond,$type);
  }
  //get and return the first rowset of a select result
  function Select4rmdbtbFirstRw($tbs,$fields = "",$cond = "",$type=MYSQLI_BOTH){
	   $rst_info1 = $this -> Select4rmdbtb($tbs,$fields,$cond,$type);
		 return $this -> FirstRw($rst_info1,$type);
  }
  
  private function FirstRw($queryRst,$type=MYSQLI_BOTH){
	  if(is_array($queryRst)){
			   if($queryRst[1] > 0){
				   $rrst = $queryRst[0];
				 return $rrst->fetch_array($type);  
			   }else{
				 return NULL;  
			   }
		   }else{
			   return $queryRst;
		   }
  }

  //selectAll - workaround for mysqli fetch_all (some cases where the server memory does not allow fetch all)
  public function SelectAll($tb,$fields,$cond = "",$type=MYSQLI_BOTH){
		$rst = $this -> Select4rmdbtb($tbs,$fields,$cond,$type);
		if(!is_array($rst)) return $rst;
		if($rst[1] < 1)return [];
		$rtn = [];
		while($rw = $rst[0]->fetch_array($type)){
			$rtn[] = $rw;	
		}
		return $rtn;
  }

  public function FetchAll($mysqlobj,$type=MYSQLI_BOTH){
	$rtn = [];
	while($rw = $mysqlobj->fetch_array($type)){
		$rtn[] = $rw;	
	}
	return $rtn;
  }
 
 //check existence of cookie value in the database and redirect to another page if not exist
 function CheckCookie($tb,$field,$cookieName,$redirectto){
	 if(isset($_COOKIE[$cookieName])){
		$id = $_COOKIE[$cookieName];
		$sepr = (is_string($id))?"'":""; 
		$rst_set = $this -> Select4rmdbtb($tb,"","$field = $sepr{$id}$sepr");
		  if(is_array($rst_set)){
			  $recob = $rst_set[0];
			  $rst_row = $recob -> fetch_array();
			  return array('id' => $id,'rowset' => $rst_row);
		  }else{
			 parent::redirect($redirectto."?errordb"); 
		  }	
		}else{
			parent::redirect($redirectto."?errorcookie"); 
		}
 }
   //function to hash for password
 function Hash($password,$salt=""){
	 if(strlen($password) > 4 ){
		 if($salt == ""){
	      $salt = $this -> getToken(20);
		 }
	$newpassw = $password.$salt;
	$hashpw = md5($newpassw);
	 return array($hashpw,$salt);
	 }else{
		 return false;
	 }
 }

 //function to generate random string from stackoverflow - requires enabling php_openssl.dll locally
 function crypto_rand_secure($min, $max)
{
	
    $range = $max - $min;
    if ($range < 1) return $min; // not so random...
    $log = ceil(log($range, 2));
    $bytes = (int) ($log / 8) + 1; // length in bytes
    $bits = (int) $log + 1; // length in bits
    $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
	//return bin2hex(openssl_random_pseudo_bytes($bytes));
    do {
        $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
        $rnd = $rnd & $filter; // discard irrelevant bits
    } while ($rnd > $range);
	//return $rnd;
    return $min + $rnd;
}

function getToken($length)
{
    $token = "";
    $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
    $codeAlphabet.= "0123456789";
    $max = strlen($codeAlphabet); // edited
	//return $this -> crypto_rand_secure(0, $max-1);
//return $codeAlphabet;
    for ($i=0; $i < $length; $i++) {
        $token .= $codeAlphabet[$this -> crypto_rand_secure(0, $max-1)];
    }

    return $token;
}

//function to send post request
function Post($url,$fields){
	$fields_string = "";
	//url-ify the data for the POST
	foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
	$fields_string=rtrim($fields_string, '&');
	
	
	//open connection
	$ch = curl_init();
	//echo $ch;
	//print_r($ch);
	//set the url, number of POST vars, POST data
	curl_setopt($ch,CURLOPT_URL, $url);
	curl_setopt($ch,CURLOPT_POST, count($fields));
	curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	//curl_setopt_array($ch, array(CURLOPT_RETURNTRANSFER => 1));
	
	//execute post
	$rst = curl_exec($ch);
	//return ["aa"=>$url];
	if (curl_error($ch)) {
			$error_msg = curl_error($ch);
			exit($error_msg);
	}
	
	//exit($rst);
	$rst = rtrim($rst,"</html>");
	$rst = trim($rst);
	curl_close($ch);
 
	$etr = urldecode($rst);
	$data = json_decode($etr,true); 
	return is_null($data)?["Message"=>$etr]:$data;
}

public function API($param = []){

	$param = !is_array($param)?["RequestID"=>$param]:$param;
	$ServerRoot = isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:$_SERVER['SERVER_NAME'];
//$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';
$protocol = !empty($_SERVER['HTTPS'])?'https://' : 'http://';

//get the current setup details
$setupdet = $this->SelectFirstRow("setup_tb","","Inuse=1 LIMIT 1");

if(is_array($setupdet)){
	$Versionstr = $setupdet['Version'];
	
	
	// return ["Error"=>["Code"=>0,"Message"=>$protocol.$ServerRoot."/".$Versionstr."/api/engine/request.php"]];
	return $this->Post($protocol.$ServerRoot."/".$Versionstr."/api/engine/request.php",$param);
}
return ["Error"=>["Code"=>0,"Message"=>"API Error: Reading eduporta Installed Version Failed"]];
}

public function EpMarkup($str = "",$search = array('<#','#>','<[',']>','<%','=>','%>'),$repl = array('<img src="','" />','<span class="appcolor">','</span>','<a target="_new" href="','">','</a>')){
	 
	 return str_replace($search,$repl,$str);
}

//function to convert url string to array
public function UrlToArray($str){
	$str = trim($str);
	$rst = array();
	if($str != ""){
		$strarr = explode("&",$str);
		for($a=0; $a<count($strarr) ; $a++){
			$strv = $strarr[$a];
			$stratrvallarr = explode("=",$strv);
			if(count($stratrvallarr) == 2){
				$rst[$stratrvallarr[0]] = $stratrvallarr[1];
				
			}
			
		}
		
	}
	return $rst;
	
}
  
}
?>