<?php
/**
* @file Str.php
*
* @class Str
*
* @bref 스트링 Utility
*
* @date 2009
*
* @author 권혁준(impactlife@naver.com)
*
* @copyright PLUGSYS.co.kr & Kwon Hyuk-June. All rights reserved.
*
* @section MODIFYINFO
* 	- 2010-03-09/권혁준 : cp949ToUtf8(), Utf8ToCp949() 추가
*
* @section Example
*   - 없음
*/

class Str{

	/**
	* @bref
	*   - 값이 있으면 true
	**/
	public static function isValue($str){
		return !self::isBlank($str);
	}

	/**
	* @bref
	*   - 값이 없으면 true
	**/
	public static function isBlank($str){
		if(trim($str)==='' || !isset($str)){
			return true;
		}else{
			return false;
		}
	}

	/**
	* @bref
	*   - 공백을 '-'으로 바꿈, 리턴값 없음
	**/
	public static function blankToHyphen(&$value){
		if(self::isBlank($value)) $value = '-';
	}

	/**
	* @bref
	*   - 값이 있는것을 이항연산으로 리턴
	**/
	public static function binValue($var1, $var2){
		return !self::isBlank($var1) ? $var1 : $var2;
	}

	/**
	* @bref
	*   - 문자열 자르기
	**/
	public static function strCut($length, $str, $addstring="...", $encoding="utf-8"){
		/*
		if(strlen($str) > $length) {
			$str = substr($str,0,$length);
			//$str = mb_strimwidth($str, 5, 36, $addstring, $encoding);
			if($encoding=="utf-8"){
				//mbstring.dll이 설치가 안되어있어서 직접선언(/Utils/DefineFunction.php)
				//$str = mb_strimwidth($str, 0, 100, $addstring);

				//$str = mb_strimwidth($str, 5, 36, $addstring, $encoding);
			}else{
				$str = preg_replace("/(([\x80-\xFE].)*)[\x80-\xFE]?$/","\\1", $str);
			}

		}
		*/
		//echo mb_strlen($str, $encoding)." : ".$length."<BR>";
		if(mb_strlen($str, $encoding) > $length){
			$str = mb_substr($str, 0, $length, $encoding).$addstring;
		}
		return $str;
	}

	/**
	* @bref
	*   - 배열안의 변수 모두 trim 처리
	**/
	public static function arrayTrim(&$arr){
		if(!is_array($arr)) return;
		foreach($arr as $key=>$value){
			if(is_array($arr[$key])){
				self::arrayTrim($arr[$key]);
			}else{
				$arr[$key] = trim($value);
			}
		}
	}

	/**
	* @bref
	*   - 배열안의 변수 모두 addslashes 처리
	**/
	public static function arrayAddSlashes(&$arr){
		if(!is_array($arr)) return;
		foreach($arr as $key=>$value){
			if(is_array($arr[$key])){
				self::arrayAddSlashes($arr[$key]);
			}else{
				$arr[$key] = addslashes($value);
			}
		}
	}

	/**
	* @bref
	*   - 배열안의 변수 모두 stripslashes 처리
	**/
	public static function arrayStripSlashes(&$arr){
		if(!is_array($arr)) return;
		foreach($arr as $key=>$value){
			if(is_array($arr[$key])){
				self::arrayAddSlashes($arr[$key]);
			}else{
				$arr[$key] = stripcslashes($value);
			}
		}
	}

	/**
	* @bref
	*   - 배열안의 변수에 콜론이 있으면 addslashes 처리
	**/
	public static function arrayColonSlashes(&$arr){
		if(!is_array($arr)) return;
		foreach($arr as $key=>$value){
			if(is_array($arr[$key])){
				self::arrayColonSlashes($arr[$key]);
			}else{
				$arr[$key] = str_replace(";", "\;", $value);
			}
		}
	}

	/**
	* @bref
	*   - 배열안의 변수 모두 strip_tags 처리
	**/
	public static function arrayStripTags(&$arr){
		if(!is_array($arr)) return;
		foreach($arr as $key=>$value){
			if(is_array($arr[$key])){
				self::arrayTrim($arr[$key]);
			}else{
				$arr[$key] = strip_tags($value);
			}
		}
	}
	
	/**
	* @brief 마지막 '/'를 제거한다
	* @param string : 디렉토리 경로
	* @return string : 제거된 디렉토리 경로
	**/
	public static function getStripLastSlashes($path){
		return substr(trim($path), -1, 1) == DS ? substr($ptah, 0, strlen($path)-1) : $path;
	}

	/**
	* @bref
	*   - 문자면 따옴표를 붙인다
	**/
	public static function addQuotes($value){
		if(is_string($value) || is_null($value)){
			$value = "'".$value."'";
		}
		return $value;
	}

	/**
	* @bref
	*   - 배열안의 값이 문자면 모두 따옴표를 붙인다
	**/
	public static function addQuotesAll(&$arr){
		foreach($arr as $key => $val){
			if(is_array($val)){
				self::addQuoteseAll($arr[$key]);
			}else{
				$arr[$key] = self::addQuotes($val);
			}
		}
	}

	/**
	* @bref
	*   - 넘어온값 모두 trim 처리 (returnType : void)
	**/
	public static function paramAllTrim($method){
		self::arrayTrim(${'_'.strtoupper($method)});
	}

	/**
	* @bref
	*   - utf8일때 문자열 자르기
	**/
	public static function strimwidth($str, $len, $checkmb=false, $tail='...') {
		preg_match_all('/[\xEA-\xED][\x80-\xFF]{2}|./', $str, $match);
		$m    = $match[0];
		$slen = strlen($str);  // length of source string
		$tlen = strlen($tail); // length of tail string
		$mlen = count($m);    // length of matched characters

		if ($slen <= $len) return $str;
		if (!$checkmb && $mlen <= $len) return $str;

		$ret  = array();
		$count = 0;

		for ($i=0; $i < $len; $i++) {
			$count += ($checkmb && strlen($m[$i]) > 1)?2:1;
			if ($count + $tlen > $len) break;
			$ret[] = $m[$i];
		}
		return join('', $ret).$tail;
	}

	/**
	* @bref
	*   - CP949 => UTF8
	**/
	public static function cp949ToUtf8($str, $urlencode=true){
		$str = iconv("CP949", "UTF-8", $str);
		if($urlencode) $str = rawurlencode($str);
		return $str;
	}

	/**
	* @bref
	*   - UTF8 => CP949
	**/
	public static function Utf8ToCp949($str, $urldecode=true){
		$str = iconv("UTF-8", "euc-kr", $str);
		if($urldecode) $str = rawurldecode($str);
		return $str;
	}

	/**
	* @bref
	*   - UTF8인지 검사
	**/
	public static function isUTF8($str) {
		// From http://w3.org/International/questions/qa-forms-utf-8.html
		return preg_match(
			'%^(?:
			[\x09\x0A\x0D\x20-\x7E]            # ASCII
			| [\xC2-\xDF][\x80-\xBF]            # non-overlong 2-byte
			|  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
			| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
			|  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
			|  \xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
			| [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
			|  \xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
			)*$%xs',
			$str
		);
	}

	/**
	* @bref
	*   - utf8과 euckr 을 토글 : 지금은 안쓰는 듯..
	**/
	public static function autoCharConvert($str, $current_charset="utf-8"){
		$current_charset = strtolower($current_charset);
		$isutf = self::isUTF8($str);

		if($current_charset=="utf-8"){
			if(!$isutf) $str = self::cp949ToUtf8($str, false);
		}else if($current_charset=="euc-kr"){
			if($isutf) $str = self::Utf8ToCp949($str, false);
		}
		return $str;
	}

	/**
	* @bref
	*   - 특수문자 제거
	**/
	public static function stripSpecialChar($str){
		return preg_replace ("/[ #\&\+\-%@=\/\\\:;,\.'\"\^`~\_|\!\?\*$#<>()\[\]\{\}]/i", "",  $str);
	}

	/**
	* @bref
	*   - 스크립트 태그 제거 - 예 : <script> 를 <s-cript> 로 만든다
	**/
	public static function stripScriptTag($str){
		$pattern = "/(\<\?|\<%|\<s)/i";
		$target = "$1-";
		return preg_replace($pattern, $target, $str);
	}

	/**
	* @bref
	*   - 태그를 html로
	**/
	public static function tagToHtml($str){
		$pattern[] = '/\</';
		$target[] = '&lt;';
		$pattern[] = '/\>/';
		$target[] = '&gt;';
		$pattern[] = "/\'/";
    	$target[] = "&#039;";
    	$pattern[] = '/\n/';
    	$target[] = '<br />';
    	return preg_replace($pattern, $target, $str);
	}

	/**
	* @bref
	*   - 공백을 html태그로
	**/
	public static function blankToHtml($str){
		$pattern = ' ';
		$target = '&nbsp;';
		return str_replace($pattern, $target, $str);
	}

	/**
	* @bref
	*   - 두번째 문자가 있을때 => return 첫번째문짜 + 두번째 문자
	**/
	public static function addHeadString($head, $str){
		if(trim($str)!='') return $head.$str;
		else return;
	}

	/**
	* @bref
	*   - 배열을 히든 박스로 변환
	**/
	public static function arrayToHiddenBox($arr){
		$str = "";
		foreach($arr as $key => $val){
			$str .= self::makeHiddenBox($key, $val);
		}
		return $str;
	}

	/**
	* @bref
	*   - 숫자를 한글로 표현
	**/
	function number2str($number){

		$temp = explode('#', Lang::get()->str_numstr);
		
		$arr = explode('|', $temp[0]);
		$num = array_merge(array(''), $arr);
		
		$arr = explode('|', $temp[1]);
		$unit4 = array_merge(array(''), $arr);
		
		$arr = explode('|', $temp[2]);
		$unit1 = array_merge(array(''), $arr);

		$res = array();
		$number = str_replace(',', '', (string)$number);
		$split4 = str_split(strrev((string)$number),4);

		for($i=0;$i<count($split4);$i++){
			$temp = array();
			$split1 = str_split((string)$split4[$i], 1);
			for($j=0;$j<count($split1);$j++){
				$u = (int)$split1[$j];
				if($u > 0) $temp[] = $num[$u].$unit1[$j];
			}
			if(count($temp) > 0) $res[] = implode('', array_reverse($temp)).$unit4[$i];
		}
		return implode('', array_reverse($res));
	}

	/**
	* @bref
	*   - 히든박스 만들기
	**/
	public static function makeHiddenBox($name, $value, $id="", $attr=""){
		return "<input type='hidden' name='".$name."' id='".$id."' value='".$value."' ".$attr." />\n";
	}

	/**
	* @bref
	*   - 배열을 GET 형식으로 묶음
	**/
	public static function qstrserial($arr = array()){
		$temp = array();
		foreach($arr as $key=>$value){
			if(trim($value)=="") continue;
			array_push($temp, $key."=".$value);
		}
		return @implode("&", $temp);
	}

	/**
	* @bref
	*   - QueryString 을 배열로 만든다
	**/
	public static function qstr2array($query){
		$temp = explode('&', $query);
		$arr = array();
		for($i=0;$i<count($temp);$i++){
			$tmp = explode('=', $temp[$i]);
			$arr[$tmp[0]] = $tmp[1];
		}
		return $arr;
	}
}