<?PHP


function popup($text, $url, $w =413, $h=200, $title = null,$cls=null,$attr=null) {

  if ($title == null) {
    $titel = time();
  }
//إضافة رقم عشوائي إلى اسم النافذة لكي يتم عرض نافذة جديدة في كل مرة
  $a = "
<a  class=\"$cls\" $attr style=\"cursor: pointer;\"
onclick=\"window.open('$url','$title','width=$w,height=$h,toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes');\" >$text</a>
 ";
  return $a;
}
function zip_and_download_dir($dir,$zip_file) { 


// Get real path for our folder
$rootPath = realpath($dir);

// Initialize archive object
$zip = new ZipArchive();
$zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();


header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($zip_file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($zip_file));
readfile($zip_file);

			
}

function copy_dir($source,$destination) {
	 if ( is_dir( $source ) ) {
        @mkdir( $destination );
        $directory = dir( $source );
        while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
            if ( $readdirectory == '.' || $readdirectory == '..' ) {
                continue;
            }
            $PathDir = $source . '/' . $readdirectory; 
            if ( is_dir( $PathDir ) ) {
                copy_dir( $PathDir, $destination . '/' . $readdirectory );
                continue;
            }
            copy( $PathDir, $destination . '/' . $readdirectory );
        }

        $directory->close();
    }else {
        copy( $source, $destination );
    }
} 
 function del_dir($dir) { 
   $files = array_diff(scandir($dir), array('.','..')); 
    foreach ($files as $file) { 
      (is_dir("$dir/$file")) ? del_dir("$dir/$file") : unlink("$dir/$file"); 
    } 
    return rmdir($dir); 
  } 
  
function file_stt($key,$file_url){ 
   
$settings=file_get_contents($file_url); 


$lines = explode("\n",trim("$settings")); 

foreach ($lines as $l){ 
            if(strstr($l,"|")){     
                $l=trim($l); 
                $line = explode("|",$l); 
            $li[]=$line; 
            } 
             
}
//    echo var_dump($li)."<hr>"; 
     
    foreach ($li as $lin){ 
        if(trim("$key")==trim($lin[0])){ 
        $ret= trim($lin[1]); 
        } 
    } 
    RETURN @$ret; 
}

function add_log($action=null,$msg=null,$user_id=null,$url=null){
	
	$user_id=is($user_id==null,login('id'),$user_id);
	$url=is($url==null,current_link(),$url);
	

	$data=array(
		'action'=>$action,
		'msg'=>$msg,
		'user_id'=>$user_id,
		'url'=>$url,
		'date'=>date('Y-m-d H:i:s'),
		
	);

	dbIns('user_logs',$data);
}

function soft_image($image_url,$dflt_image){
	if($image_url){
		return files_url($image_url);		
	}else{
		return base_url('assets/images/'.$dflt_image);
	}
}
function files_url($url){
	if(strstr(sett('files_url'),'http')){
		
		return str_replace("..",sett('files_url'),"$url");

	}else{
	
		return str_replace("..",base_url(sett('files_url')),"$url");
	}
		
}

function is_english($str)
{
	if (strlen($str) != strlen(utf8_decode($str))) {
		return false;
	} else {
		return true;
	}
}

function enc($action, $string) {
   $key="1";
	$ci_crype=false;
	
    if( $action == 'enc' ) {
		
		
		
		
		 if (!$key && $key !== false) {
            $key = config_item('encryption_key');
        } elseif ($key === false) {
            $key = '';
        }
        if ($ci_crype) {
            $S1 = &get_instance();
            $S1->load->library('encrypt');
            $encode = $S1->encrypt->encode($string, $key);

            return str_replace(array('/', '+', '='), array('-', '_', '.'), $encode);
        }
        $key = sha1($key);
        $strLen = strlen($string);
        $keyLen = strlen($key);
        $j = 0;
        $hash = '';
        for ($i = 0; $i < $strLen; ++$i) {
            $ordStr = ord(sub_str($string, $i, 1));
            if ($j == $keyLen) {
                $j = 0;
            }
            $ordKey = ord(sub_str($key, $j, 1));
            ++$j;
            $hash .= strrev(base_convert(dechex($ordStr + $ordKey), 16, 36));
        }

        $output= $hash;
		
		
		
		
       
    }
    else if( $action == 'dec' ){
        if (!$key && $key !== false) {
            $key = config_item('encryption_key');
        } elseif ($key === false) {
            $key = '';
        }
        if ($ci_crype) {
            $S1 = &get_instance();
            $S1->load->library('encrypt');
            $string = str_replace(array('-', '_', '.'), array('/', '+', '='), $string);

            return $S1->encrypt->decode($string, $key);
        }
        $key = sha1($key);
        $strLen = strlen($string);
        $keyLen = strlen($key);
        $j = 0;
        $hash = '';
        for ($i = 0; $i < $strLen; $i += 2) {
            $ordStr = hexdec(base_convert(strrev(sub_str($string, $i, 2)), 36, 16));
            if ($j == $keyLen) {
                $j = 0;
            }
            $ordKey = ord(sub_str($key, $j, 1));
            ++$j;
            $hash .= chr($ordStr - $ordKey);
        }

         $output= $hash;
    
    }
    
 
 
 return $output;
}


if (!function_exists('sub_str')) {
    function sub_str($str, $start, $end = null, $ext = false)
    {
        if ($ext) {
            $ext = str_len($str) > $end ? ($ext === true ? '...' : $ext) : '';
        }
        if (function_exists('mb_substr')) {
            return mb_substr($str, $start, $end, 'UTF-8').$ext;
        } else {
            return substr($str, $start, $end).$ext;
        }
    }
}

if (!function_exists('str_len')) {
    function str_len($str)
    {
        if (function_exists('mb_strlen')) {
            return mb_strlen($str, 'UTF-8');
        } else {
            return strlen($str);
        }
    }
}


function startsWith($haystack, $needle) { 
$length = strlen($needle); return (substr($haystack, 0, $length) === $needle); 
}

function endsWith($haystack, $needle) {
	$length = strlen($needle); if ($length == 0) { return true; } return (substr($haystack, -$length) === $needle); }
	
	
function is($vrbl,$text,$false_text=null){
if($vrbl){
$x=$text;
}else{
$x=  $false_text;
}
return $x;
}


function S( $vrbl,$defult=null ){ //set vrbl if not, and set vlue if not
if(isset($vrbl)){
return  $vrbl;
}else{
return $defult;
}
}

function go($uri,$method = 'auto', $code = NULL){ 
	return redirect($uri,$method,$code);
}


function session_login($kay){ 
	if (isset($_SESSION['login']["$kay"])) {
		return $_SESSION['login']["$kay"];
	}else{
		return false;
	}
}



function GET($action,$defult=null){
if(isset($_GET["$action"])){return $action=$_GET["$action"];}else{return $defult;}
}
function POST($action,$defult=null){
if(isset($_POST["$action"])){return $action=$_POST["$action"];}else{return $defult;}
}


function lnks($str){
$lnks =explode(",",$str);
foreach ($lnks as $lnk){
  @$ret.= is(get($lnk),"&$lnk=".get($lnk));
}
	return $ret;
}



function between_time($start_string,$col_name,$start_date=null,$end_date=null){
	if($start_date){
	$start_date_ts=date2ts("d/m/Y",$start_date);
	 $start_sql=" $col_name  >= '$start_date_ts' ";
}else{
	 $start_sql=null;
}

if($end_date){
	 $end_date_ts=date2ts("d/m/Y",$end_date);
	 $end_sql="$col_name <= '$end_date_ts'";
	}else{
	 $end_sql=null;
}

if (!$start_sql==null and !$end_sql==null){
	return "$start_string $start_sql and $end_sql";
}elseif($start_sql){
	return "$start_string $start_sql";
}elseif($end_sql){
	return "$start_string $end_sql";
}
	
}
	
function date2ts($formt,$date){
// e.s : date2ts("d/m/Y","01/12/2015");
$date = date_parse_from_format($formt, $date);
return  mktime(0, 0, 0, $date['month'], $date['day'], $date['year']);
}

function current_link(){
	if (!isset($_ENV)){
	return (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	}else{
	return "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	}
}



function add_time ($add_time,$date,$date_frmt="Y/m/d"){
// add_time ('+1 days',"01/12/2015","d/m/Y");
 $date=  strtotime($add_time, date2ts($date_frmt,$date));
return date($date_frmt, $date);
}

function time_chack($date,$limit){
	
$baqi= a_time(date2ts("Y/m/d",date("Y/m/d")),date2ts("Y/m/d",add_time ("+$limit days","$date","Y/m/d")));
if($baqi<=0 ){
return 0;
}else{
return $baqi;
}
}


function a_time($start,$end = null){
//return date('d-m-Y',$start);
            $end = (is_null($end)) ? time() : $end; 
        	   $time = $end - $start;
			if($start == 0 or $time == ""){
        		return 0;
        	}
        	
        	$days = round($time/86400,0);

				return $days;
        	
	//Using: echo b_time($date,time());  

        }


 function getTotal ($rows,$coll_to_total,$col_to_mlty) {
      $tot = 0;
      foreach ($rows as $r) {
		  if($col_to_mlty){
		  $r[$coll_to_total] = $r[$coll_to_total] * $r[$col_to_mlty];
		  }
        $tot =$tot+ $r[$coll_to_total];
      }
      return $tot;
    }

function col_from_arr($col,$arr,$output='string'){
$rows=$arr;
if(count($rows)==0){
	if($output=='string'){
		$ids="0";
	}else{ //output as array;
		$ids=array(0);
	}
}else{
	
	foreach ($rows as $row){
		$id_str[]=$row["$col"];
	}

	if($output=='string'){
		$ids_=implode(",",$id_str);
		$ids="$ids_";
	}else{ // output array;
		$ids=$id_str;
	}

}
return $ids;
}

function array_to_csv_download($array, $filename = "export.csv", $delimiter=",") {
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="'.$filename.'";');
header('Content-Transfer-Encoding: binary');

echo "\xEF\xBB\xBF"; // Byte Order Mark
   
    $f = fopen('php://output', 'w');

    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
    }
} 


function ranger($str){
// ranger ("1,2,3,6-10,12,13"); // 1,2,3,6,7,8,9,10,12,13
$inputArray = explode(',', $str);
$outputArray = array();

foreach($inputArray as $v) {
    if(strpos($v, '-') === false) {
        $outputArray[] = intval($v);
    } else {
        $minMax = explode('-',$v);

        if($minMax[0]<=$minMax[1]) {
            $outputArray = array_merge($outputArray, range($minMax[0], $minMax[1]));
        }
    }
}
return $outputArray;
} 
