<?php
/**
 * 公用函数
 *
 * @author Wzb
 */
class COM_OftenFunction {
	/**
	 * 打开数据库连接
	 *
	 * @param string $hostname 服务器名称
	 * @param string $user 数据库用户名(不能为空)
	 * @param string $pass 数据库密码
	 * @param string $basename 数据库名称
	 * @return Obj 数据连接对象
	 */
	public static function openConn($hostname, $user, $pass, $basename) {
		global $ADODB_FETCH_MODE;
		$conn = ADONewConnection ( "mysql" );
		$conn->Connect ( $hostname, $user, $pass, $basename );
		// 设置获取数据模式 ADODB_FETCH_ASSOC 关联数组 ADODB_FETCH_NUM 数字数组 ADODB_FETCH_DEFAULT 默认 ADODB_FETCH_BOTH 双模式存取
		$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
		return $conn;
	}
	
	/**
	 * 实例化一个Sarty
	 */
	public static function openSmarty() {
		$tpl = new Smarty ();
		$baseUrl = substr ( dirname ( __FILE__ ), 0, - 10 ); // 路径
		$tpl->template_dir = "$baseUrl/Tpl";
		$tpl->compile_dir = "$baseUrl/Temp/Compile";
		$tpl->config_dir = "$baseUrl/Temp/Config";
		$tpl->cache_dir = "$baseUrl/Temp/Cache";
		$tpl->left_delimiter = '{:';
		$tpl->right_delimiter = ':}';
		$tpl->caching = false;
		$tpl->debugging = false;
		return $tpl;
	}
	
	/**
	 * 替换字符串中的特殊字符为10进制的ascii
	 * # ; ! > < ( ) + ' "
	 *
	 * @param string $string 需要处理的字符串
	 * @param bool $isth=true 当为false时表示还原
	 * @return string 处理后的字符串
	 */
	public static function delSpecialChar($string, $isth = true) {
		if (empty ( $string )) {
			return "";
		}
		if ($isth) {
			// 替换
			$string = str_ireplace ( '#', '&#35;', $string );
			$string = str_ireplace ( ';', '&#59;', $string );
			$string = str_ireplace ( '&#35&#59;', '&#35;', $string );
			$old = array ('!','>','<','(',')','+',"'",'"' );
			$now = array ('&#33;','&#62;','&#60;','&#40;','&#41;','&#43;','&#39;','&#34;' );
			$string = str_ireplace ( $old, $now, $string );
		} else {
			// 还原
			$now = array ('#',';','!','>','<','(',')','+',"'",'"' );
			$old = array ('&#35;','&#59;','&#58;','&#62;','&#60;','&#40;','&#41;','&#43;','&#39;','&#34;' );
			$string = str_ireplace ( $old, $now, $string );
		}
		return $string;
	}
	
	/**
	 * 去除HTML JS CSS
	 *
	 * @param string $string 需要处理的字符串
	 * @return string 纯文本字符串
	 */
	public static function noHtml($string) {
		if (empty ( $string )) {
			return "";
		}
		$search = array ("'<script[^>]*?>.*?</script>'si","'<style[^>]*?>.*?</style>'si","'<[/!]*?[^<>]*?>'si","'<!--[/!]*?[^<>]*?>'si" );
		$replace = array ("","","","" );
		$string = preg_replace ( $search, $replace, $string );
		return str_replace ( array ("　"," ","\r","\n","&nbsp;" ), "", $string );
	}
	
	/**
	 * 数据格式化
	 * 键 ****_int、****_txt、****_time
	 *
	 * @param array $theArray
	 * @param array
	 */
	public static function makeArray($theArray) {
		if (count ( $theArray ) == 0) {
			return array ();
		}
		$newArray = array ();
		foreach ( $theArray as $key => $value ) {
			if (strpos ( $key, "_" ) !== false) {
				$tempArr = explode ( "_", $key );
				switch (strtolower ( $tempArr [1] )) {
					case "int" :
						$newArray [$tempArr [0]] = intval ( $value );
						break;
					case "txt" :
						$newArray [$tempArr [0]] = self::delSpecialChar ( $value );
						break;
					case "time" :
						$newArray [$tempArr [0]] = date ( "Y-m-d H:i:s", strtotime ( $value ) );
						break;
					case "noreplace" :
						$configObj = BLL_WebSet::getOne ( 1, 'editorBase' );
						$value = str_replace ( $configObj ['editorBase'] . "Upload/", "Upload/", $value );
						$newArray [$tempArr [0]] = str_replace ( $configObj ['editorBase'] . "Bianji/", "Bianji/", $value );
						break;
					default :
						break;
				}
			}
		}
		return $newArray;
	}
	
	/**
	 * 编辑器内文件的路径修正
	 *
	 * @param string $content
	 * @return string
	 */
	public static function editorFilesPath($content) {
		$configObj = BLL_WebSet::getOne ( 1, 'editorBase' );
		$content = str_replace ( "Upload/", $configObj ['editorBase'] . "Upload/", $content );
		return str_replace ( "Bianji/", $configObj ['editorBase'] . "Bianji/", $content );
	}
	
	/**
	 * 后台分页辅助函数
	 *
	 * @param array $theArray
	 */
	public static function managerPageInfo($theArray) {
		$value = '';
		if (empty ( $theArray ['frist'] )) {
			$value .= '&lt;&lt;&nbsp;首页';
			$value .= '&nbsp;&nbsp;&nbsp;&nbsp;&lt;&lt;&nbsp;上一页';
		} else {
			$value .= "<a href=\"$theArray[frist]\">&lt;&lt;&nbsp;首页</a>";
			$value .= "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"$theArray[pre]\">&lt;&lt;&nbsp;上一页</a>";
		}
		if (empty ( $theArray ['end'] )) {
			
			$value .= '&nbsp;&nbsp;&nbsp;&nbsp;下一页&nbsp;&gt;&gt;';
			$value .= '&nbsp;&nbsp;&nbsp;&nbsp;尾页&nbsp;&gt;&gt;';
		} else {
			$value .= "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"$theArray[next]\">下一页&nbsp;&gt;&gt;</a>";
			$value .= "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"$theArray[end]\">尾页&nbsp;&gt;&gt;</a>";
		}
		$value .= "&nbsp;&nbsp;&nbsp;&nbsp;总计：$theArray[maxPage]页";
		$value .= "&nbsp;&nbsp;&nbsp;&nbsp;$theArray[recordCount]条记录";
		$value .= '&nbsp;&nbsp;&nbsp;&nbsp;跳转至&nbsp;';
		$value .= '<select onChange="goToTheUrl(this);">';
		foreach ( $theArray ['pageList'] as $one ) {
			$value .= '<option value="' . $one ['url'] . '"';
			if ($one ['isSelected']) {
				$value .= " selected=\"selected\"";
			}
			$value .= ">$one[num]</option>";
		}
		$value .= '</select>&nbsp;页';
		return $value;
	}
	
	/**
	 * 获取编辑器初始化代码
	 *
	 * @param string $theId 编辑器对象的表单ID
	 * @param string $widht=100% 宽度 百分比
	 * @param int $height=0 高度 单位是PX 0表示采用系统设置的高度
	 */
	public static function GetXhEditor($theId, $widht = "100%", $height = 0) {
		$ConfigObj = BLL_WebSet::getOne ( 1, 'editorBase' );
		echo "<script type=\"text/javascript\">\r\n";
		echo 'window.UEDITOR_HOME_URL="' . $ConfigObj ['editorBase'] . 'Bianji/";' . "\r\n";
		echo "</script>\r\n";
		echo "<script type=\"text/javascript\" src=\"../../Bianji/ueditor.config.js\"></script>\r\n";
		echo "<script type=\"text/javascript\" src=\"../../Bianji/ueditor.all.min.js\"></script>\r\n";
		echo "<script type=\"text/javascript\">\r\n";
		echo "UE.getEditor('" . $theId . "',{initialFrameHeight:500});\r\n";
		echo "</script>\r\n";
	}
	
	/**
	 * 设置列表页面的地址
	 *
	 * @param string $sessionName SESSION名称
	 */
	public static function setListPageUrl($sessionName) {
		$_SESSION [$sessionName] = $_SERVER ['REQUEST_URI'];
	}
	
	/**
	 * 输出列表页面的地址
	 *
	 * @param string $sessionName SESSION名称
	 * @param string $url 默认列表页面的地址
	 */
	public static function getListPageUrl($sessionName, $url) {
		if (isset ( $_SESSION ) && array_key_exists ( $sessionName, $_SESSION ) && ! empty ( $_SESSION [$sessionName] )) {
			echo $_SESSION [$sessionName];
		} else {
			echo $url;
		}
	}
	
	/**
	 * 获取移动链接
	 *
	 * @param string $theStr idA-idB-serialNumA-serialNumB
	 * @param string $jt 箭头
	 * @param string $action
	 * @return string
	 */
	public static function getMove($theStr, $jt, $action) {
		$value = "&nbsp;";
		if (! empty ( $theStr )) {
			$temp = explode ( "-", $theStr );
			$value = "<a href=\"TheAction.php?action=$action&idStr=$temp[0]-$temp[1]-$temp[2]-$temp[3]&rnd=" . rand ();
			$value .= "\" onclick='ClickMove(this)' target='hideframe'>$jt</a>";
		}
		return $value;
	}
	
	/**
	 * 获取缩略图
	 *
	 * @param string $srcFile 原始路径
	 * @param string $picSize 尺码 例如：16X16
	 * @return string
	 */
	public static function GetPic($srcFile, $picSize) {
		global $configObj;
		// 文件不存在
		if (! file_exists ( $srcFile )) {
			return '';
		}
		
		// 获取缩略图尺寸
		$theSizeArr = explode ( "X", $picSize );
		if (empty ( $theSizeArr [0] )) {
			$imginfo = getimagesize ( $srcFile );
			$theSizeArr [0] = intval ( intval ( $theSizeArr [1] ) * intval ( $imginfo [0] ) / intval ( $imginfo [1] ) );
			$theSizeArr [0] = $theSizeArr [0] > 0 ? $theSizeArr [0] : 1;
		}
		if (empty ( $theSizeArr [1] )) {
			$imginfo = getimagesize ( $srcFile );
			$theSizeArr [1] = intval ( intval ( $theSizeArr [0] ) * intval ( $imginfo [1] ) / intval ( $imginfo [0] ) );
			$theSizeArr [1] = $theSizeArr [1] > 0 ? $theSizeArr [1] : 1;
		}
		
		// 已关闭缩略图
		if (strpos ( $srcFile, "_AUTO." ) === false || intval ( $configObj ['isSetImg'] ) === 0) {
			return $srcFile;
		}
		
		// 生成路径
		$pathArr = explode ( '/', $srcFile );
		$dir_path = "";
		$filename = $pathArr [count ( $pathArr ) - 1];
		$filenameArr = explode ( '.', $filename );
		for($i = 0; $i < count ( $pathArr ) - 1; $i ++) {
			$dir_path .= $pathArr [$i] . '/';
		}
		
		// 已存在缩略图
		$newfilename = $dir_path . 'T-' . str_replace ( '_AUTO', '', $filenameArr [0] ) . '-' . $theSizeArr [0] . 'X' . $theSizeArr [1] . '.' . $filenameArr [1];
		if (file_exists ( $newfilename )) {
			return $newfilename;
		}
		
		// 生成缩略图
		$theObj = new COM_CreatMiniature ();
		$theObj->SetVar ( $srcFile, "file" );
		$theObj->BackFill ( $newfilename, $theSizeArr [0], $theSizeArr [1] );
		return $newfilename;
	}
	
	/**
	 * 设置网页标题
	 * (方便修改标题)
	 *
	 * @param string $thisName 本次标题
	 */
	public static function setWebName($thisName = '') {
		global $configObj;
		return $thisName . $configObj ['webName'];
	}
	
	/**
	 * 字符串截取
	 *
	 * @param string $sourcestr 是要处理的字符串
	 * @param int $cutlength 为截取的长度(即字数)
	 */
	public static function CutStr($sourcestr, $cutlength) {
		$returnstr = "";
		$i = 0;
		$n = 0;
		$str_length = strlen ( $sourcestr );
		// 字符串的字节数
		while ( ($n < $cutlength) and ($i <= $str_length) ) {
			$temp_str = substr ( $sourcestr, $i, 1 );
			$ascnum = Ord ( $temp_str );
			// 得到字符串中第$i位字符的ascii码
			// 如果ASCII位高与224，
			if ($ascnum >= 224) {
				$returnstr .= substr ( $sourcestr, $i, 3 );
				// 根据UTF-8编码规范，将3个连续的字符计为单个字符
				$i = $i + 3;
				// 实际Byte计为3
				$n ++; // 字串长度计1
					       // 如果ASCII位高与192，
			} elseif ($ascnum >= 192) {
				$returnstr = $returnstr . substr ( $sourcestr, $i, 2 );
				// 根据UTF-8编码规范，将2个连续的字符计为单个字符
				$i = $i + 2;
				// 实际Byte计为2
				$n ++; // 字串长度计1
					       // 如果是大写字母，
			} elseif ($ascnum >= 65 && $ascnum <= 90) {
				$returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
				$i = $i + 1;
				// 实际的Byte数仍计1个
				$n ++; // 但考虑整体美观，大写字母计成一个高位字符
			} else { // 其他情况下，包括小写字母和半角标点符号，
				$returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
				$i = $i + 1;
				// 实际的Byte数计1个
				$n = $n + 0.5; // 小写字母和半角标点等与半个高位字符宽…
			}
		}
		if ($str_length > $i) {
			$returnstr .= "...";
			
			// 超过长度时在尾处加上省略号
		}
		return $returnstr;
	}
	
	/**
	 * 获取客户端ip
	 */
	public function getIp() {
		if (isset ( $_SERVER )) {
			if (isset ( $_SERVER ['HTTP_X_FORWARDED_FOR'] )) {
				$realip = $_SERVER ['HTTP_X_FORWARDED_FOR'];
			} elseif (isset ( $_SERVER ['HTTP_CLIENT_IP'] )) {
				$realip = $_SERVER ['HTTP_CLIENT_IP'];
			} else {
				$realip = $_SERVER ['REMOTE_ADDR'];
			}
		} else {
			if (getenv ( "HTTP_X_FORWARDED_FOR" )) {
				$realip = getenv ( "HTTP_X_FORWARDED_FOR" );
			} elseif (getenv ( "HTTP_CLIENT_IP" )) {
				$realip = getenv ( "HTTP_CLIENT_IP" );
			} else {
				$realip = getenv ( "REMOTE_ADDR" );
			}
		}
		return $realip;
	}
}
?>