<?php
/*--------------------------------------------------------- 
 * File:utility.php
 * Author:Tomix,邱洪榮
 * Description: 
 * Created:2009-6-10
 * -------------------------------------------------------
 * Modified history:
 * -------------------------------------------------------
 * Copyright:
 * -------------------------------------------------------
 */
 
 class utility
 {
 	//應用程序根目錄(返回值末尾沒有加"/")
 	static public function getAppRoot()
 	{
 		require_once dirname(__FILE__)."/../configuration/configFactory.php";
 		$config=configFactory::createConfiguration();
 		$root=trim($config->getConfigValue("appsettings","appRoot"));
 		$appRoot="";
 		if(!isset($root) || $root == "")
 		{
 			$appRoot = "http://".$_SERVER["HTTP_HOST"];
 		}
 		else if(strpos($root,"http://"))
 		{
 			$appRoot = $root;
 		}
 		else
 		{
 			if(strpos($root,"/") === false || strpos($root,"/") != 0)
 				$root="/".$root;
 			$appRoot = "http://".$_SERVER["HTTP_HOST"].$root;
 		}
 		if(strrpos($appRoot,"/") == strlen($appRoot) - 1)
 			$appRoot=substr($appRoot,0,strlen($appRoot) - 1);
 		return $appRoot;
 	}
 	
 	static public function getCurrentUrl()
 	{
 		$url=self::getAppRoot().$_SERVER["SCRIPT_NAME"];
 		$param="";
		foreach ($_GET as $key => $value)
		{     
			if($param!="")
				$param .="&";
			$param .= $key."=".urldecode($value);     
		}
		if(count($_GET)>0)
		$url.="?".$param;
 		return $url;
 	}
 	
 	//去掉路径名的前后反斜杆
 	static public function removeDirSlash($dir)
 	{
 		if(strpos($dir,"/") === 0 && strlen($dir) > 1)
 			$dir=substr($dir,1);
 		if(strrpos($dir,"/") === strlen($dir)-1 && strlen($dir) > 1)
 			$dir=substr($dir,0,strlen($dir)-1);
 		return $dir;
 	}
 	
 /*	//产生40位不可逆加密字串(密码)
 	static public function irrEncrypt($forEncrypt)
 	{
 		$rndStr=strtolower(utility::getRandomString(8));
 		$mixedStr=$rndStr.$forEncrypt;
 		return $rndStr.md5($mixedStr);
 	}
 	
 	//对比字串与加密后的字串是否一致
 	static public function checkEncrypt($checkString,$encryptedString)
 	{
 		if(strlen($encryptedString) != 40)
 			return false;
 		$preString=substr($encryptedString,0,8);
 		$sufString=substr($encryptedString,8);
 		if(md5($preString.$checkString) == $sufString)
 			return true;
 		return false;
 	}
 	*/
 	//產生隨機字符串
 	//參數說明:$length,返回字符串長度;$mode返回模式(0:数字与字母组合;1:纯数字;2纯字母)
 	static public function getRandomString($length,$mode=0)
 	{
		$chars=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"
					,"0","1","2","3","4","5","6","7","8","9");
		if($mode==1)
			$chars=array("0","1","2","3","4","5","6","7","8","9");
		if($mode==2)
			$chars=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");
		shuffle($chars);   
		$max=count($chars);
		$returnValue = ""; 
		while(strlen($returnValue)<$length)
		{
			$randIndex=rand(0,$max);
			$returnValue .= $chars[$randIndex];
		} 
		return $returnValue;  		
 	}
 	
 	//取得上級數據(包括自身)
 	static public function getAncestors($source,$idField,$pidField,$fieldValue)
 	{
 		$returnValue=array();
 		$current=array();
 		foreach($source as $row)
 		{
 			if($row[$idField]==$fieldValue)
 			{
 				$current=$row;
 				$returnValue[]=$current;
 				break;
 			}
 		}
 		while($current[$pidField] > 0)
 		{
 			$current=self::_getAncestors($source,$idField,$current[$pidField]);
 			$returnValue[]=$current;
 		}
 		
 		//echo $returnValue[1][$idField];		
 		return array_reverse($returnValue);
 	}
 	
    //私有方法:	
 	//根據ID取得數據
 	static private function _getAncestors($source,$idField,$fieldValue)
 	{
 		foreach($source as $row)
 		{ 	
 			if($row[$idField] == $fieldValue)
 			{
 				return $row;
 			}
 		} 		
 	}
 	//公開方法:取得下級數據(包括自身)
 	//參數說明:$source,二維陣列類型源數據;$idField,id字段;$pidField,上級ID字段;$fieldValue,當前id字段值
 	static public function getOffSprings($source,$idField,$pidField,$fieldValue)
 	{
 		$tmpValue=self::_getOffSprings($source,$idField,$pidField,$fieldValue);
 		
 		//添加自身
 		foreach($source as $arr)
 		{
 			if($arr[$idField] == $fieldValue)
 			{
 				$tmpValue[]=$arr;
 			}
 		}
 		
 		//使用主鍵值索引
 		$returnValue = array();
 		foreach($tmpValue as $arr)
 		{
 			if(!isset($returnValue[$arr[$idField]]))
 				$returnValue[$arr[$idField]]=$arr;
 		}
 		
 		return $returnValue;
 	}
 
 	//私有方法:取得下級數據(不包括自身)
 	//參數說明:$source,二維陣列類型源數據;$idField,id字段;$pidField,上級ID字段;$fieldValue,當前id字段值
 	static private function _getOffSprings($source,$idField,$pidField,$fieldValue)
 	{
 		$returnValue=array();
 		foreach($source as $arr)
 		{
 			if($arr[$pidField] == $fieldValue)
 			{
 				$returnValue[]=$arr;
 				$index=array_search($arr,$source);
 				if(null!=$index)
 				{
 					unset($source[$index]);
 				}
 			}
 		}
 		$rootArray=$returnValue;
 		foreach($rootArray as $arr)
 		{
 			$temp=self::getOffSprings($source,$idField,$pidField,$arr[$idField]);
 			$returnValue=array_merge_recursive($returnValue,$temp);
 		}
 		return $returnValue;
 	}
 	
   static public function substr_utf8($str, $start, $lenth)
   {
		$len = strlen($str);
		$r = array();
		$n = 0;
		$m = 0;
		for($i = 0; $i < $len; $i++) 
		{
			$x = substr($str, $i, 1);
			$a = base_convert(ord($x), 10, 2);
			$a = substr('00000000'.$a, -8);
			if ($n < $start)
			{
			    if (substr($a, 0, 1) == 0) 
			    {
			     }
				elseif(substr($a, 0, 3) == 110) 
				{
					$i += 1;
				}
				elseif (substr($a, 0, 4) == 1110) 
				{
					$i += 2;
				}
				$n++;
		   }
		   else
		   {
				if (substr($a, 0, 1) == 0) 
				{
				    $r[] = substr($str, $i, 1);
				}
				elseif (substr($a, 0, 3) == 110)
				 {
				    $r[] = substr($str, $i, 2);
				    $i += 1;
				 }
				 elseif (substr($a, 0, 4) == 1110)
				  {
				     $r[] = substr($str, $i, 3);
				     $i += 2;
				  }
				  else
				  {
				      $r[] = '';
				  }
				  if (++$m >= $lenth){
				    break;
			      }
		    }
		 }
		$mystr=implode($r);
		return $mystr;
     } // End subString_UTF8
     
     //按比例縮放圖片大小
     //如果$width=-1,$height>0時,按$height參數進行縮放(不限寬的圖片);反之按$width參數進行縮放(不限高的圖片);$width>0,$height>0時,按比例縮放(限寬,限高圖片)
     static public function resizeImage($oldWidth,$oldHeight,$width=-1,$height=-1)
     {
     	$arr=array();
     	if(!is_numeric($oldWidth)
     		|| !is_numeric($oldHeight)
     		|| $oldWidth == 0
     		|| $oldHeight == 0
     		|| $width ==0
     		||$height == 0)
     	{
     		$arr["width"]=$width;
     		$arr["height"]=$height;
     		return $arr;
     	}
     	
     	if($width < 0 && $height < 0)	//不缩放
     	{
     		$arr["height"]=$oldWidth;
     		$arr["width"]=$oldHeight;
     		return $arr;
     	}    
     	else if($oldWidth/$oldHeight > $width/$height || $height < 0)	//圖片較寬或不限高
     	{
     		$arr["width"]=$width;
     		$arr["height"]=$oldHeight/$oldWidth*$width;
     		return $arr;
     	}
     	else if($oldHeight/$oldWidth > $height/$width || $width < 0) //图片较高或不限宽
     	{
     		$arr["height"]=$height;
     		$arr["width"]=$oldWidth/$oldHeight*$height;
     		return $arr;
     	}
     	else
     	{
     		$arr["width"]=$width;
     		$arr["height"]=$height;
     		return $arr;
     	}
     }
     
         
    //寫入日誌文件
	static public function writeLog($message,$logPrefix="sys",$logType="sys log")
	{
		$msg="\r\n=============================================================================\r\n";
		$msg.="Time:".(string)date("Y-m-d H:i:s")."\r\n";
		$msg.="Type:".$logType."\r\n";
		$msg.="Message:\r\n";
		$msg.=$message;
		
		$path=dirname(__FILE__)."/../../logs/";
		if(!is_dir($path))
			@mkdir($path,0777);
		$fn=$path.$logPrefix."_".(string)date("Ymd").".log";
		$fp=fopen($fn,"ab");
		fwrite($fp,$msg);
		fclose($fp);
	}
     
 }
 
?>
