<?php
// general functions

	// To print content
	function genFtn_Print($val,$transform='',$strip=true,$html=true,$url=false)
	{
		switch(strtolower($transform))
		{
			case 'caps':
			$val = strtoupper($val);
			break;

			case 'ucfirst':
			$val = ucfirst($val);
			break;
		}

		if($strip)
		$val = stripslashes($val);

		if($html)
		$val = htmlentities($val,  ENT_QUOTES | ENT_IGNORE, 'UTF-8');

		if($url)
		{
			if($url==='s')
			$val = urlencode(str_replace("/", " | ", $val));
			else
			$val = urlencode($val);
		}

		return $val;
	}
	
	//String Limit
	function _strLimit($str,$limit)
	{
		return (strlen($str)>$limit)?(substr($str,0,$limit).'..'):$str;
	}
		
	function _ordinal($number) 
	{
		$ends = array('th','st','nd','rd','th','th','th','th','th','th');
		if ((($number % 100) >= 11) && (($number%100) <= 13))
			return $number. 'th';
		else
			return $number. $ends[$number % 10];
	}

	// To get all $_GETS as urls
	function _allGETS($except=[])
	{
	    $url = '';
		if(!@is_array($except))
			$except=[];
	
		if(sizeof($_GET))
			foreach($_GET as $key=>$val)
			{
				if(!@in_array($key,$except))			
					if(!@in_array($key,array("success","error","warning","info")))
						$url.="&$key=$val";
			}
			
		return $url;
	}

	//Remove querys from URL
	function _exceptQuery($url,$data)
	{
		if(strpos($url,"?")===false)
			return $url;
		else {
			$qry = explode('?',$url);
			parse_str($qry[1], $query);
			
		
			if(sizeof($query)) {
				foreach($query as $key=>$val) {
					if(in_array($key,$data))
						unset($query[$key]);
				}
			}

			return $qry[0].'?'.http_build_query($query);
		}

	}		

	//Append query strings to URL
	function _queryString($url,$data)
	{
		return $url.((strpos($url,"?")===false)?'?':'&').http_build_query($data);
	}	

	// To redirect to specified url
	function _redirect($url,$data=[])
	{
		ob_clean();
		header("location:".((sizeof($data)>0)?_queryString($url,$data):$url));
		exit();
	}	
	
	function _youtubeID($url)
	{
		preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=embed/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", trim($url), $matches);
		return ($matches[0])?$matches[0]:false;
	}	

	// To generate new password
	function _generatePassword()
	{
		$coder = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
		$retVal = "";

		//length of the paswword will be 16
		for($i=0;$i<16;$i++)
		$retVal.= $coder[rand(0,strlen($coder)-1)];
		return $retVal;
	}

	function _countryList(string $seleted=NULL,$default)
	{
		$cty = CMS::tables('country')->fields([ 'name' ])->condition("order by k1")->get();	

		if(sizeof($cty))
		foreach($cty as $item)
		{
			?>
			<option value="<?php echo $item["id"];?>" <?php echo ($seleted==$item["id"] || ($item["id"]==$default && $seleted==''))?'selected="selected"':'';?>>
			<?php echo stripslashes($item["name"]);?>
			</option>
			<?php
		}
	}


	//Currency format with or without sign
	function _currFormat($value,$sign=true)
	{
		global $const_default_country;
		return 
		(
			($sign)?
			(
				$const_default_country['currSign'].
				number_format($value,2)
			):
			(
				$value
			)
		);
	}

	//Get All Days
	function _getallDays()
	{
		$timestamp = strtotime('next Sunday');
		$days = array();
		for ($i = 0; $i < 7; $i++) {
			$days[$i] = strftime('%A', $timestamp);
			$timestamp = strtotime('+1 day', $timestamp);
		}
		return $days;
	}
			
	function _sanitize($val, $type="I",$opts=true)
	{
		if($opts && $type=="T")
		$val = htmlentities($val,  ENT_QUOTES | ENT_IGNORE, 'UTF-8');	
	
		switch($type)
		{
			case 'I'://integer
			$val = (int)($val);
			break;
			
			case 'F'://float
			$val = (float)($val);
			break;			
			
			case 'T'://texts
			$healthy = ["", "", "", "", "", "", "", "", "", "", "", "", ""];
			$spammy   = ["insert", "update", "select", "delete","window","alert","INSERT", "UPDATE", "SELECT", "DELETE","WINDOW","ALERT", " --"];			
			$val = str_replace($healthy, $spammy, preg_replace("/[\s-]+/", " ", preg_replace("/[^a-zA-Z0-9_\s-\.\,\@]/", "", strtolower(trim($val)))));			
			break;				
		}		
        return $val;
	}
	 
	function _sanitizeInt($val)
	{	
		_sanitize($val,"I");
	}
	 
	function _sanitizeFloat($val)
	{	
		_sanitize($val,"F");
	}	
	 
	function _sanitizeText($val,$html=true)
	{	
		_sanitize($val,"T",$html);
	}	

	//get requests
	function _request($field='',$cnt='',$type='')
	{
		if($field==='')
		return $_REQUEST;
	
		$tmpV = ($cnt==='')?@$_REQUEST[$field]:$_REQUEST[$field][$cnt];
		
		switch($type)
		{
			case 'I':
				return (int)$tmpV;
			break;
			
			case 'F':
				return (float)$tmpV;
			break;
			
			case 'E':
				global $ajConn;
				return $ajConn->real_escape_string($tmpV);
			break;			
			
			default:
				return $tmpV;
			break;				
		}
	}
	 
	function _requestInt($field,$cnt='')
	{	
		return _request($field,$cnt,'I');
	}
	 
	function _requestFloat($field,$cnt='')
	{	
		return _request($field,$cnt,'F');
	}	
	 
	function _requestText($field,$cnt='')
	{
		return _request($field,$cnt,'E');		
	}	
	
	//Set request
	function _setRequest($field,$cnt,$val='')
	{
		if($val==='')
		$_REQUEST[$field] = $cnt;
		else
		$_REQUEST[$field][$cnt] = $val;	
	}

	//get session
	function _session($field,$cnt='')
	{
		if($field==='')
		return $_SESSION;
			
		return ($cnt==='')?$_SESSION[$field]:$_SESSION[$field][$cnt];
	}
	
	//Set session
	function _setSession($field,$cnt,$val='')
	{
		if($val==='')
		{
			if(!@is_array($_SESSION[$field]) || (@is_array($cnt) && sizeof($cnt)==0))
				$_SESSION[$field] = $cnt;
			else
				$_SESSION[$field][] = $cnt;
		}
		else
			$_SESSION[$field][$cnt] = $val;	
	}

	//get cookie
	function _cookie($field,$cnt='')
	{
		if($field==='')
		return $_COOKIE;
					
		return ($cnt==='')?$_COOKIE[$field]:$_COOKIE[$field][$cnt];
	}	

	function _phpself()
	{
		return basename($_SERVER['PHP_SELF']);
	}

	// To get SEO urls/Slug
	function _slug($string)
	{
		return preg_replace("/[\s_]/", "-", preg_replace("/[\s-]+/", " ", preg_replace("/[^a-z0-9_\s-]/", "", strtolower(trim($string)))));
	}		
	
	function _fileLog($fname,$mode,$content,$path="")
	{
		if($path!="" && substr($path, -1)!='/')
		$path.= "/";
		$file = fopen($path.$fname.".txt",$mode);
		fwrite($file,$content."\r\n");
		fclose($file);	
	}

	function _randFileName($name, $ext=true)
	{
		return  
		date("YmdHis").
		rand(100,999).
		rand(1000,9999).
		(
			($ext)?
			('.'.strtolower(pathinfo(basename($name), PATHINFO_EXTENSION))):''
		);
	}	
	
	function _fileCheck($filePath)
	{
		$fileCont = file_get_contents($filePath);
		if(
			stripos($fileCont, "<?php") === false && 
			stripos($fileCont, "$_request") === false && 
			stripos($fileCont, "$_get") === false && 
			stripos($fileCont, "$_post") === false && 
			stripos($fileCont, "$_files") === false && 												
			stripos($fileCont, "eval(") === false && 
			stripos($fileCont, "move_upload") === false && 
			strpos($fileCont, "encode") === false && 
			strpos($fileCont, "decode") === false && 
			stripos($fileCont, "base64_") === false && 
			stripos($fileCont, "__FILE__") === false && 							
			stripos($fileCont, "gzinflate(") === false && 			
			stripos($fileCont, "unlink") === false
		)
		return true;
		else
		return false;		
	}	
	
	
	//upload files. create the directory if it doesnt exist, will create the directory. 
	function _manageFiles($path,$file='',$prmsn=0777)
	{
		$stus = false;	
		$path.= (substr($path, -1)!='/')?'/':'';
		if(trim($path)!='')
		{
			if(!is_dir($path)) 
			@mkdir($path, $prmsn);
			@chmod($path, $prmsn);
			if($file!='' || (@is_array($file) && sizeof($file)==2))	
			{
				$tmpFile = (is_array($file))?$_FILES[$file[0]]["tmp_name"][$file[1]]:$_FILES[$file]["tmp_name"];
				$nmeFile = (is_array($file))?$_FILES[$file[0]]["name"][$file[1]]:$_FILES[$file]["name"];
				if(_fileCheck($tmpFile))
				{						
					if(@move_uploaded_file($tmpFile, "$path".$nmeFile))
					$stus = true;
				}
				else
				$stus = false;
			}
			else			
			$stus = true;
		}

		return $stus;
	}
	
	//Content upload 
	function _contentUpload($path,$file='',$root='./',$prmsn=0777)
	{
		global $setting_uploadPath;		
		$splitPath = explode('/',$path);
		
		if($file!='')
		{
			$nmeFile = (is_array($file))?$_FILES[$file[0]]["name"][$file[1]]:$_FILES[$file]["name"];
			
			$fileName = _randFileName($nmeFile);
			
			if(is_array($file))
			$_FILES[$file[0]]["name"][$file[1]] = $fileName;
			else
			$_FILES[$file]["name"] = $fileName;
		}
		
		if(sizeof($splitPath))
		for($i=0; $i<(($file!='')?(sizeof($splitPath)-1):sizeof($splitPath));$i++)
		_manageFiles($root.$setting_uploadPath.'/'.@implode('/', array_slice($splitPath, 0, ($i+1))));
		
		if($file!='')
		{
			if(_manageFiles($root.$setting_uploadPath.'/'.$path,$file,$prmsn))		
			return ["path"=>($root.$setting_uploadPath.'/'.$path.((substr($path, -1)!='/')?'/':'')), "filename"=>_escapeFileName($nmeFile) , "originalFilename"=>$fileName ];
			else
			return false;		
		}
		else
		return true;
	}		
	
	//delete folder and it's sub folders & files
	function _deleteFiles($path)
	{
		if (is_dir($path) === true)
		{
			$files = array_diff(scandir($path), array('.', '..'));
			
			if(sizeof($files))
			{
				foreach ($files as $file)
				_deleteFiles(realpath($path) . '/' . $file);
			}
	
			return rmdir($path);
		}
	
		else if (is_file($path) === true)
		return unlink($path);
	
		return false;
	}
	
	//check whether the folder is empty
	function _isFolderEmpty($path)
	{
		if (is_dir($path) === true)
		{
			$files = array_diff(scandir($path), array('.', '..'));

			if(!sizeof($files))
			return true;
		}
		
		return false;
	}	
			
	// To escape file name
	function _escapeFileName($name)
	{
		return ucfirst(preg_replace("/[^a-z0-9_\s-.]/", "", strtolower(trim($name))));
	}
			
	// File extension
	function _fileExt($name)
	{
		$info = new SplFileInfo($name);
		return strtolower($info->getExtension());
	}	

	// To generate CSV file from data array
	function _toCSV($output, $filename)
	{
		header( 'Content-Type: text/csv' );
		header( 'Content-Disposition: attachment;filename='.$filename);
		$fp = fopen('php://output', 'w');
		
		fputcsv($fp, array_keys($output[0]));
		
		foreach($output as $item) {
			fputcsv($fp, $item);
		}
		
		fclose($fp);
	}
	
	// To read text from .docx file
	function _readDocx($filename)
	{
		$striped_content = '';
		$content = '';

		if(!$filename || !file_exists($filename)) return false;

		$zip = zip_open($filename);
		if (!$zip || is_numeric($zip)) return false;

		while ($zip_entry = zip_read($zip)) {

			if (zip_entry_open($zip, $zip_entry) == FALSE) continue;

			if (zip_entry_name($zip_entry) != "word/document.xml") continue;

			$content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

			zip_entry_close($zip_entry);
		}
		zip_close($zip);      
		$content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
		$content = str_replace('</w:r></w:p>', "\r\n", $content);
		$striped_content = strip_tags($content);

		return $striped_content;
	}		
?>
