<?
function dump($val){
	echo '<pre>';
	print_r($val);
	echo '</pre>';
}

function xif($a,$b,$c)
{
	if ($a)
	{
		return $b;
	}
	else
	{
		return $c;
	}
}

function base_url($uri = '')
{
	$tmphttp = isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http';
	return $tmphttp . "://" . $_SERVER['HTTP_HOST'] . $uri;
}
		
function checkloginstatus(){
	//判斷是否已登入，或停留過久session值被清空
	if(empty($_SESSION['member']['login'])){
		unset($_SESSION['member']);
		header("Location:".base_url('/root/login.php'),true);
		die();
	}
}

function alert($str) {
	echo "<script language = 'javascript'>";
	echo "alert(\"$str\");";
	echo "history.go(-1);";
	echo "</script>";
	exit;
}

//過濾單引號
function substituir($subs)
{
	$subs = str_replace("\\","\\\\",$subs);
	return str_replace("'","''",$subs);
}

function chinese_str($sqlstr) { 
	 $res_st=""; 
     if(get_magic_quotes_gpc()) // 處理 magic_quotes_gpc 啟動
	  $sqlstr = Stripslashes($sqlstr);
      
	  //處理非中文字中的跳脫字元 \ 
	  $tmp_length = strlen($sqlstr);
      for($tmp_i=0; $tmp_i<$tmp_length; $tmp_i++ ) {
		 $ascii_str_a = substr($sqlstr, $tmp_i,1);
		 $ascii_str_b = substr($sqlstr, $tmp_i+1, 1);
         $ascii_value_a = ord($ascii_str_a);
         $ascii_value_b = ord($ascii_str_b);
		 if($ascii_value_a < 128 ) { //不是中文字
		    if($ascii_value_a == 92){ //加上/
		       $sqlstr = substr($sqlstr, 0, $tmp_i) . "\\"  . substr($sqlstr,$tmp_i);
			   $tmp_i++;
			   $tmp_length++;
			}
		 }else //中文字
		    $tmp_i++;
	  }
	  //處理輸入字串中有'符號
      $res_str = str_replace ("'", "\'",$sqlstr); 
	return $res_str;

}

//---------------------------2019.08.11------------------------------------
//作用:取得使用者IP
//參數:
//-------------------------------------------------------------------------
function get_user_ip(){
	if (!empty($_SERVER['HTTP_CLIENT_IP']))
	{
	  $ip=$_SERVER['HTTP_CLIENT_IP'];
	}
	else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
	{
	  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	}
	else
	{
	  $ip=$_SERVER['REMOTE_ADDR'];
	}
	return $ip;
}

function select_db($datastr){
	global $conn;
	$tmprs = mysqli_query($conn,$datastr);
	$rows = array();
	while($row = mysqli_fetch_assoc($tmprs)){
		
		$rows[] = $row;
	
	}
	return $rows;
}

function select_db_num($datastr){
	global $conn;
	$num = mysqli_num_rows(mysqli_query($conn,$datastr));
	return $num;
}

function select_db_one($datastr){
	global $conn;
	$rows = array();
	$rows = mysqli_fetch_assoc(mysqli_query($conn,$datastr));
	return $rows;
}

function select_db_var($datastr){
	$rows = array();
	$rows = mysql_fetch_array($datastr);
	return $rows[0];
}

function get_max_id($table_name){
	global $CFG;
	$query = mysql_query("select max(id) as max from $table_name");
	$rs = mysql_fetch_array($query);
	$id = $rs["max"] + 1;
	return $id;
}

function get_system_email($id=0) {
	$query = mysql_query("select manage_email from config");
	$rs = mysql_fetch_array($query);
	$id = $rs["manage_email"];
	return $id;
}

//取出會員和店家email
function get_member_email($id=0){
	$query = mysql_query("select email FROM member WHERE id={$id}");
	$rs = mysql_fetch_array($query);
	$email = $rs["email"];
	return $email;
}

//取出會員和店家email
function get_company_email($id=0){
	$query = mysql_query("select email FROM member WHERE id={$id}");
	$rs = mysql_fetch_array($query);
	$email = $rs["email"];
	return $email;
}

function getmoduser($info){

	$info['new_user_name'] = '系統';
	$info['update_user_name'] = '';

	$msg ="" ;
	
	if(isset($info['new_user']) && isset($info['update_user']) ){
		$tmpsql = "select name,id from person where id IN ('{$info['new_user']}','{$info['update_user']}')";
		$user = select_db(mysql_query($tmpsql));
		if(!empty($user)){
			foreach($user as $key => $val){
				if($val['id'] == $info['new_user']) $info['new_user_name'] = $val['name'];
				if($val['id'] == $info['update_user']) $info['update_user_name'] = $val['name'];
			}
		}
	}
	
	if(isset($info['new_time'])){
		$info['new_time'] = date('Y-m-d H:i:s', strtotime($info['new_time']));
		$msg .= "建立資訊：<b>{$info['new_time']}</b> 由 <b>{$info['new_user_name']}</b> 所建立 <br>" ;
	}
	if(isset($info['update_time'])){
		$info['update_time'] = date('Y-m-d H:i:s', strtotime($info['update_time']));
		$msg .= "最後修改：<b>{$info['update_time']}</b> 由 <b>{$info['update_user_name']}</b> 所修改 ";
	}	
	return $msg ;

}

//作用:過濾字串
//參數:POST 或 GET值
//-----------------------------
function trim2($val){		
	if(is_array($val)) 
		return $val;
	$val = htmlentities($val,  ENT_QUOTES, 'UTF-8') ;
	return trim($val);
}

function trim2_post($info=''){
	$list = array();
	//將null設定為有值
	foreach($info as $key => $val){
		$list[$key] = 1;
	}
	foreach($_POST as $key => $val){
		if(isset($list[$key]) && $key != 'back_url') {
			$info[$key] = trim2($val);
		}
	}
	return $info;
}

//---------------------------2013.10.25------------------------------------
//作用：過濾相關GET參數
//輸入：info 陣列預設的值
//-------------------------------------------------------------------------
function trim2_get($info=''){
	$list = array();
	//將null設定為有值
	foreach($info as $key => $val){
		$list[$key] = 1;
	}

	foreach($_GET as $key => $val){
		if(isset($info[$key]) && $key != 'back_url')
			$info[$key] = trim2($val);
	}
	if(isset($_GET['send'])) $info['send'] = trim2($_GET['send']);
	return $info;
}

//----2013.09.18---------------
//作用:過濾字串
//參數:POST 或 GET值
//-----------------------------
function retrim2($val){		
	if(is_array($val)) 
		return $val;
	$val = html_entity_decode($val,  ENT_QUOTES, 'UTF-8') ;
	return $val;
}

//----2011.08.08---------------
//作用:截字
//參數:字串,英文字數,方式	,段行次數
//-----------------------------
function cut_str($str,$num,$type='cut',$brnum=0)
{
	switch($type)
	{
		case "cut"://正常截字
			$txt=mb_strimwidth($str, 0, $num, '...', 'utf8');
			break;
		case "cut2":
			$txt=mb_strimwidth($str, 0, $num, '+', 'utf8');
			break;
		case 'content'://內容截字
			$str=str_replace("\n",' ',$str);
			$str=strip_tags($str);				
			$str=trim($str);
			$txt=mb_strimwidth($str, 0, $num, '...', 'utf8');
			break;
		case 'section'://分段截字-純文字版
			$snum=0;
			$str=str_replace(array('<div>','<br>','<br />'),"\n",$str);
			$str=strip_tags($str);
			for($i=0;$i<=$brnum;$i++)
			{
				$spos=strpos($str,"\n",$snum);
				//找不到斷行
				if($spos==''){
					$nnum=$num;
					break;	
				}
				$stxt=substr($str,$snum,$spos);
				$nnum=mb_strwidth($stxt);
				//字數大於所需要字數
				if($nnum>=$num){
					$nnum=$num;
					break;
				}
				$snum=$spos+1;
			}
			$txt=mb_strimwidth($str, 0, $nnum, '...', 'utf8');
			break;
		case 'sectionimg'://分段截字-首頁專用
			$snum=0;$txt=$str;
			$str=str_replace(array('<div>','<br>','<br />'),"\n",$str);
			$str=str_replace(array('&gt;','&lt;','&amp;','&quot;'),"",$str);
			$str=str_replace(array('&nbsp;','nbsp;')," ",$str);
			$bbcode_search = array(
					'/<object width="384" height="308">(.*?)<\/object>/is',
					'/<img(.*?)>/is'
					);
				$bbcode_replace = array(
								'貼了影片',
								'貼了圖片'
								);
			$str=preg_replace($bbcode_search,$bbcode_replace, $str);
			$str=strip_tags($str);
			for($i=0;$i<=$brnum;$i++)
			{
				$spos=strpos($str,"\n",$snum);
				//找不到斷行
				if($spos==''){
					$nnum=$num;
					break;	
				}
				$stxt=substr($str,$snum,$spos);
				$nnum=mb_strwidth($stxt);
				//字數大於所需要字數
				if($nnum>=$num){
					$nnum=$num;
					break;
				}
				$snum=$spos+1;
			}
			$txt=mb_strimwidth($str, 0, $nnum, '...', 'utf8');
			break;
		default:break;
	}
	return $txt;
}

//---------------------------2012.08.27------------------------------------
//作用:取頁數參數值
//參數:每頁數量,頁數
//-------------------------------------------------------------------------
function get_page_arr($pagenum,$p)
{
	if($p<1 || $p=='') $p=1;
	$start=($p-1)*$pagenum;
	return array($pagenum,$p,$start);
}

//----2011.11.05---------------
//作用:設定cookie
//參數:名稱,值,有效日期	
//----------------------------- 
function set_cookie($key="",$val="",$day=1)
{
	if(empty($key) ) return ;
	
	//setcookie 操作 取消 是時間改為負
	$time = time()+(3600*24*$day) ;
	if($val == ""){
		$val = "-" ;
		$time = time() - (3600*24*1) ;
	}
	
	if($key != "tip_msg"){	//tip_msg 跳頁提示 不加密
		$val = UrlEn($val); 
	}
	
	setcookie($key,$val,$time,"/");
	//setcookie($key,$val,time()+(3600*24*$day),"/",$_SERVER['HTTP_HOST']);
}

//----2011.08.29---------------
//作用:base64解碼
//參數:字串
//----------------------------- 	
function UrlDe($str)
{
	if($str!=''){
		$str=str_replace(array('_','~','-'),array('+','/','='),$str);
		$str=base64_decode($str);		
		return $str;
	}else return false;
}

//----2011.08.29---------------
//作用:base64編碼符合網址
//參數:字串
//----------------------------- 
function UrlEn($str)
{
	if($str!=''){
		$str=base64_encode($str);
		$str=str_replace(array('+','/','='),array('_','~','-'),$str);
		return $str;
	}else{
		return false;
	}	
}

function random_serial( $chars=6 ){
	$initial_text = '';
	for( $i=1;$i<=$chars; $i++ ){
		if( $i==1 ){
			$c=2;
		}else{
			$c=rand(2,3);
		}
		if($c==2){$a=rand(65,90);$b=chr($a);}
		if($c==3){$b=rand(0,9);}
		$initial_text=$initial_text.$b;
	}
	return $initial_text;
}

//後台事件紀錄
function event_log($func='',$class_id=0,$da=array()){
	
	$mod_list=array('add'=>2,'mod'=>3,'del'=>4,'import'=>6);
	if(!isset($mod_list[$func]) || (empty($class_id) && $mod_list[$func] != 6) ){
	   return ; 
	}
	
	$ida = array(
		'type'=>$mod_list[$func],
		'manage_id' =>$_SESSION['iperson']['id'],
		'power_id' => $_SESSION['pid'],
		'class_id'=>$class_id,
		'ip' => IP,
		'new_time' => TODAYTIME,
	);
	
	if(!empty($da['mod_num'])){
		$ida['mod_num'] = $da['mod_num'];
	}
	if(!empty($da['add_num'])){
		$ida['add_num'] = $da['add_num'];
	}
	if(!empty($da['note'])){
		$ida['note'] = $da['note'];
	}	
	
	insert_db("web_log",$ida);
}

/* Convert image size. true color*/ 
//$src 來源檔案 
//$dest 目的檔案 
//$maxWidth 縮圖寬度 
//$maxHeight 縮圖高度 
//$quality JPEG品質 
function ImageCopyResizedTrue($src,$dest,$maxWidth,$maxHeight,$quality=90) { 

	//檢查檔案是否存在 
	if (file_exists($src) && isset($dest)) { 
	
		$destInfo = pathInfo($dest); 
		$srcSize = getImageSize($src); //圖檔大小 
		$srcRatio = $srcSize[0]/$srcSize[1]; // 計算寬/高 
		$destRatio = $maxWidth/$maxHeight; 
		if ($destRatio > $srcRatio) { 
			$destSize[1] = $maxHeight; 
			$destSize[0] = $maxHeight*$srcRatio; 
		} else { 
			$destSize[0] = $maxWidth; 
			$destSize[1] = $maxWidth/$srcRatio; 
		} 
	
		//GIF 檔不支援輸出，因此將GIF轉成JPEG 
		//if ($destInfo['extension'] == "gif") $dest = substr_replace($dest, 'jpg', -3); 
	
		//建立一個 True Color 的影像 
		$destImage = imageCreateTrueColor($destSize[0],$destSize[1]); 
	
		//根據副檔名讀取圖檔 
		switch ($srcSize[2]) { 
			case 1: $srcImage = imageCreateFromGif($src); break; 
			case 2: $srcImage = imageCreateFromJpeg($src); break; 
			case 3: $srcImage = imageCreateFromPng($src); break; 
			default: return false; break; 
		} 
	
		//取樣縮圖 
		ImageCopyResampled($destImage, $srcImage, 0, 0, 0, 0,$destSize[0],$destSize[1], 
		$srcSize[0],$srcSize[1]); 
	
		//輸出圖檔 
		switch ($srcSize[2]) { 
			case 1: case 2: imageJpeg($destImage,$dest,$quality); break; 
			case 3: imagePng($destImage,$dest); break; 
		} 
		
		return true; 
		
	} else { 
	
		return false; 
		
	} 
}


/*  Convert image size. true color*/ 
//$src        來源檔案 
//$dest        目的檔案 
//$maxWidth    縮圖寬度 
//$maxHeight    縮圖高度 
//$quality    JPEG品質 
function ImageCopyResizedTrue2($src,$dest,$maxWidth,$maxHeight,$quality=100) { 

	//檢查檔案是否存在 
	if (file_exists($src)  && isset($dest)) { 
	
		$destInfo  = pathInfo($dest); 
		$srcSize   = getImageSize($src); //圖檔大小 
		$srcRatio  = $srcSize[0]/$srcSize[1]; // 計算寬/高 
		$destRatio = $maxWidth/$maxHeight; 
		if ($destRatio > $srcRatio) { 
			$destSize[1] = $maxHeight; 
			$destSize[0] = $maxHeight*$srcRatio; 
		} 
		else { 
			$destSize[0] = $maxWidth; 
			$destSize[1] = $maxWidth/$srcRatio; 
		} 
	
	
		//GIF 檔不支援輸出，因此將GIF轉成JPEG 
		if ($destInfo['extension'] == "gif") $dest = substr_replace($dest, 'jpg', -3); 
	
		//建立一個 True Color 的影像 
		$destImage = imageCreateTrueColor($destSize[0],$destSize[1]); 
	
		//根據副檔名讀取圖檔 
		switch ($srcSize[2]) { 
			case 1: $srcImage = imageCreateFromGif($src); break; 
			case 2: $srcImage = imageCreateFromJpeg($src); break; 
			case 3: $srcImage = imageCreateFromPng($src); break; 
			default: return false; break; 
		} 
	
		//取樣縮圖 
		ImageCopyResampled($destImage, $srcImage, 0, 0, 0, 0,$destSize[0],$destSize[1], 
							$srcSize[0],$srcSize[1]); 
	
		//輸出圖檔 
		switch ($srcSize[2]) { 
			case 1: case 2: imageJpeg($destImage,$dest,$quality); break; 
			case 3: imagePng($destImage,$dest); break; 
		} 
		return true; 
	} 
	else { 
		return false; 
	} 
	
}

function get_insert_id($tmptbname) { 
	
	global $conn;
    $id = 0;
    $tmprow = mysql_fetch_assoc(mysql_query($conn,"SELECT IDENT_CURRENT('" . $tmptbname . "') as insertid"));
    if (is_array($tmprow)) { 
        $id = $tmprow["insertid"]; 
    } 
    return $id;
}

function data_post_fixsql($column,$default='',$setlen=30){
	$retureValue='';
	$retureValue=FixSQL($_POST[$column],$default,$setlen);
	return $retureValue;
}

function FixSQL($strIn,$default="",$setlen=30)
{
	if(is_array($strIn)){
		foreach($strIn as $k => $v){
			if(!empty($v)){
				$v = trim($v);
				$v = htmlspecialchars($v,ENT_QUOTES);
				$len = (mb_strlen($v,"UTF-8") > $setlen ? $setlen : mb_strlen($v,"UTF-8") );
				$v = mb_substr($v, 0 , $len ,"UTF-8");
			}
			if($v=="" && $default!="") $v = $default;
			$strIn[$k]=$v;
		}
	}else{
		if(!empty($strIn)){
			//去左右空白
			$strIn = trim($strIn);
			//將<、>等符號取代成HTML文字
			$strIn = htmlspecialchars($strIn,ENT_QUOTES);
			//擷取字串長度
			$len = (mb_strlen($strIn,"UTF-8") > $setlen ? $setlen : mb_strlen($strIn,"UTF-8") );
			$strIn = mb_substr($strIn, 0 , $len ,"UTF-8");
		}
		//如果有預設值
		if(($strIn=="" || is_null($strIn)) && $default!=""){$strIn=$default;}
	}
	return $strIn;
}
?>