<?php

class Util {

 	
	function __construct(){
		

	}
	static function stripslashesGPC(){
	 
			if	( 	(function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc() )
            		|| 
					(ini_get('magic_quotes_sybase') && ( strtolower(ini_get('magic_quotes_sybase')) != "off" ))
           		){
            foreach($_GET as $k => $v) $_GET[$k] = stripslashes($v);
            foreach($_POST as $k => $v) $_POST[$k] = stripslashes($v);
            foreach($_COOKIE as $k => $v) $_COOKIE[$k] = stripslashes($v);
        }
	}
        
	static function getArrayItemValueByItemPropertyValue($sourceArray, $propertyName, $propertyValue){
		
		for($i=0; $i<count($sourceArray); $i++){
			if($sourceArray[$i][$propertyName]==$propertyValue)
				return $sourceArray[$i];
		}
		
		return null;

	}
	
	static function getArrayItemIndexByItemPropertyValue($sourceArray, $propertyName, $propertyValue){
		
		for($i=0; $i<count($sourceArray); $i++){
			if($sourceArray[$i][$propertyName]==$propertyValue)
				return $i;
		}
		
		return -1;

	}
	// FILES FUNCTIONS
	static function moveFile($fromFile, $toFile){
	 
		$ud = new UD();
		
		if($ud->move($fromFile, $toFile, $force=true)===true)
			return true;
		else
			return false;
		
	}
	static function copyFile($fromFile, $toFile){
	 
		$ud = new UD();
		
		if($ud->copy($fromFile, $toFile, $force=true)===true)
			return true;
		else
			return false;
		
	}	

	static function copyDir( $source, $target ){
        if ( is_dir( $source ) )
        {
        	if ( !is_dir( $target ) ){
          	  @mkdir( $target );
          	}
           
            $d = dir( $source );
           
            while ( FALSE !== ( $entry = $d->read() ) )
            {
                if ( $entry == '.' || $entry == '..' )
                {
                    continue;
                }
               
                $Entry2 = $source . '/' . $entry;           
                if ( is_dir( $Entry2 ) )
                {
                    Util::copyDir( $Entry2, $target . '/' . $entry );
                    continue;
                }
                copy( $Entry2, $target . '/' . $entry );
            }
           
            $d->close();
        }else
        {
            copy( $source, $target );
        }
    }



	static function deleteFile($pathToFile){
	
		if(!is_file($pathToFile)){
			return false; 
		} 
			
		if(@unlink($pathToFile)===false){
			return false;
		}
		
		return true;
		
	}


	static function writeFile($filename,$content){
	 
		GLOBAL $config;
		
		if (!$handle = @fopen($filename, 'w')) { 
	        return false; 
		} 
	
		if (!@fwrite($handle, $content)) { 
			fclose($handle); 
		  	return false; 
		} 
		 
		fclose($handle); 
		
	//??	chmod($filename, Config::get("chmod_file"));
		
		return true;
		 
	}

	static function readXmlFile($filename){
	
		$fileArr = file($filename);
		if (!$fileArr) { 
	        return false; 
		} 
		
		$content = "";
		for($i=0; $i<count($fileArr); $i++){
			$line = trim($fileArr[$i]);
			if($line!="" && substr($line, 0, 2)!="//"){
			 	$content.=$line;
			}
		}

		return $content;
	}
	static function readFile($filename){
	
		if (!$handle = @fopen($filename, 'r')) { 
	        return false; 
		} 
		
		$content="";
		if(filesize($filename)>0)
			$content = @fread($handle, filesize($filename));
			
		if ($content===false) { 
			fclose($handle); 
		  	return false; 
		} 

		fclose($handle);

		return $content;
	}
	
	static function readFileArray($filename){

		if (!$retArray = file($filename)) { 
	        return false; 
		} 

		return $retArray;
		
	}
 	
 	static function createDirectoryIfNotExist($dirPath){
 	 
 	 	global $config;
 	 	
 		if(is_dir($dirPath)) return true;
 		
		$ret = mkdir($dirPath);
 		
 		if($ret!=false)
		 	chmod($dirPath, Config::get("chmod_dir"));
 		
 		return $ret;
		
		 
 	}
 	
 	static function writeLineToFileBeginning($filename, $content, $max_filesize=0){

		$fcontent = "";
		if (file_exists($filename)) {
			$fh = fopen($filename, "r");
			$size = filesize($filename);
			if($size==0){
				$fcontent="";
			}else {
				$fcontent = fread($fh, $size);
				$fcontent  ="\n".$fcontent;
			}
			
			if($size>$max_filesize && $max_filesize!=0){
				$fcontent=substr($fcontent,0,$max_filesize);
			}
		}
		
		$towrite = $content.$fcontent;
		$fh2 = fopen($filename, 'w+');
		fwrite($fh2, $towrite);
		
		if($fh)fclose($fh);
		fclose($fh2);
 	}
 	 
 	static function getDateForFile(){
 	 
 	 	GLOBAL $config;
 		return date(Config::get("file_date")); 
 		
 	}
 	static function getTimeForFile(){
 	 
 	 	GLOBAL $config;
 		return date(Config::get("file_time")); 
 		
 	}
 	function getDateTimeForFile(){
 	 
 	 	GLOBAL $config;
 		return date(Config::get("file_datetime")); 
 		
 	}
 	static function getArrayFromObjectArray($arr, $name){
 	 
	 	reset($arr);
	 	foreach ($arr as $value){
	 	 
	 		$retArr[] = $value[$name];
	 	}
		
		return $retArr;
 	}
 	static function randString($n=10){
 		return substr(md5(microtime()),0,$n);
 	}
 	static function getDriveFromPath($path){
 	  	$pos = strpos($path, ":");
 		if($pos===false) return false;
 		return substr($path, 0, $pos);
 	}
	static function getRelativePathFromPath($path){
 		$pos = strpos($path, ":");
 		if($pos===false) return "";
 		return substr($path, $pos+1);
 	}
	static function cloneObject($object) {
	  if (version_compare(phpversion(), '5.0') < 0) {
	   return $object;
	  } else {
	   return @clone($object);
	  }
	 }
	 
	static function getFileNameFromPath($filePath){
	  	$pos = strrpos($filePath, "/");
 		if($pos===false) return "";
 		return substr($filePath, $pos+1);
	}
	
	static function	 _getExtensionCS($file){

		$pos = strrpos($file, "."); 
		if ($pos === false) { 
			return "";	
		} 	
		
		$extension = substr($file, $pos+1);
		
		return $extension;
		
	} 
	static function	 _getExtension($file){

		$file = self::_getExtensionCS($file);
		
		$extension = strtolower($file);
		
		return $extension;
		
	}

	static function  getExtension($file){	
		return self::_getExtension($file);
	}
	
	static function httpSocketConnection($url, $method="GET", $data="")
    {
     
       	$url_parsed = parse_url($url);
   		$host = $url_parsed["host"];
  	 	$path = $url_parsed["path"];
   
   
        $method = strtoupper($method);       
       
        if ($method == "GET")
        {
            $path.= '?'.$data;
        }   
       
        $filePointer = fsockopen($host, 80, $errorNumber, $errorString);
       
        if (!$filePointer)
        {
            //logEvent('debug', 'Failed opening http socket connection: '.$errorString.' ('.$errorNumber.')<br/>\n');
            return false;
        }

        $requestHeader = $method." ".$path."  HTTP/1.1\r\n";
        $requestHeader.= "Host: ".$host."\r\n";
        $requestHeader.= "User-Agent:      Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0\r\n";
        $requestHeader.= "Content-Type: application/x-www-form-urlencoded\r\n";

        if ($method == "POST")
        {
            $requestHeader.= "Content-Length: ".strlen($data)."\r\n";
        }
       
        $requestHeader.= "Connection: close\r\n\r\n";
       
        if ($method == "POST")
        {
            $requestHeader.= $data;
        }           

        fwrite($filePointer, $requestHeader);
       
        $responseHeader = '';
        $responseContent = '';

        do
        {
            $responseHeader.= fread($filePointer, 1);
        }
        while (!preg_match('/\\r\\n\\r\\n$/', $responseHeader));
       
       
        if (!strstr($responseHeader, "Transfer-Encoding: chunked"))
        {
            while (!feof($filePointer))
            {
                $responseContent.= fgets($filePointer, 128);
            }
        }
        else
        {

            while ($chunk_length = hexdec(fgets($filePointer)))
            {
                $responseContentChunk = '';
           
                //logEventToTextFile('debug', $chunk_length);
                $read_length = 0;
               
                while ($read_length < $chunk_length)
                {
                    $responseContentChunk .= fread($filePointer, $chunk_length - $read_length);
                    $read_length = strlen($responseContentChunk);
                }

                $responseContent.= $responseContentChunk;
               
                fgets($filePointer);
               
            }
           
        }

        //logEventToTextFile('debug', $responseContent);
       
       	//echo $responseContent;
        return chop($responseContent);
    }
	
	static function deleteDirectoryAndAllItsContent($directory, $notBehindDirectory){ // $notBehindDirectory is for security reasons
		
		if(empty($notBehindDirectory)){
		 	return -5;
		}
		
		if(substr($directory,0,strlen($notBehindDirectory))!=$notBehindDirectory){
		 	return -4;
		}
		
		if(!is_dir($directory))
			return -1;
		
		if(!is_readable($directory))
			return -2;
	

		$handle = opendir($directory);
		while (false !== ($item = readdir($handle))){
			if($item != '.' && $item != '..'){
				$path = $directory.'/'.$item;
				if(is_dir($path)) {
					self::deleteDirectoryAndAllItsContent($path,$path);
				}
				else{
					self::deleteFile($path);
				}
			}
		}
		closedir($handle);
		
		if (count(glob("$directory/*")) !== 0)
		 	return -3;
	
		if( @rmdir($directory)===false)
			return -3;
		
		return true;
		
	}
	 
	 
	public static function selfURL() { 
	 
		$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
		$protocol = self::strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
		$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]); 
		return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
		   
	} 
	    
	public static function selfDirURL() { 
	 
		$url = self::selfURL();
		return self::strrleft($url, "/");
	 
	} 
	
	public static function  strleft($s1, $s2) {
		return substr($s1, 0, strpos($s1, $s2)); 
	}
	public static function  strrleft($s1, $s2) {
		return substr($s1, 0, strrpos($s1, $s2)); 
	}
	
}