<?php
 /*
 * 74cms 共用函数
 * ============================================================================
 * 版权所有: 骑士网络，并保留所有权利。
 * 网站地址: http://www.74cms.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
*/
if(!defined('IN_QISHI')) die('Access Denied!');
function addslashes_deep($value)
{
    if (empty($value))
    {
        return $value;
    }
    else
    {
		if (!get_magic_quotes_gpc())
		{
		$value=is_array($value) ? array_map('addslashes_deep', $value) : mystrip_tags(addslashes($value));
		}
		$value=is_array($value) ? array_map('addslashes_deep', $value) : mystrip_tags($value);
		return $value;
    }
} 
function mystrip_tags($string)
{
	$string = safe_replace($string);
	$string = remove_xss($string);
	return $string;
}
function safe_replace($string) {
	$string = str_replace('%20','',$string);
	$string = str_replace('%27','',$string);
	$string = str_replace('%2527','',$string);
	$string = str_replace('*','',$string);
	$string = str_replace('"','&quot;',$string);
	$string = str_replace("'",'',$string);
	$string = str_replace('"','',$string);
	$string = str_replace(';','',$string);
	$string = str_replace('<','&lt;',$string);
	$string = str_replace('>','&gt;',$string);
	$string = str_replace("{",'',$string);
	$string = str_replace('}','',$string);
	$string = str_replace('\\','',$string);
	return $string;
}
function remove_xss($string) { 
    $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);

    $parm1 = Array('javascript', 'union','vbscript', 'expression', 'applet', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound');

    $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload','style','href','action','location','background','src','poster');
	
	$parm3 = Array('alert','sleep','load_file','confirm','prompt','benchmark','select','insert','delete','alter','drop','truncate','script','eval');

    $parm = array_merge($parm1, $parm2, $parm3); 

	for ($i = 0; $i < sizeof($parm); $i++) { 
		$pattern = '/'; 
		for ($j = 0; $j < strlen($parm[$i]); $j++) { 
			if ($j > 0) { 
				$pattern .= '('; 
				$pattern .= '(&#[x|X]0([9][a][b]);?)?'; 
				$pattern .= '|(&#0([9][10][13]);?)?'; 
				$pattern .= ')?'; 
			}
			$pattern .= $parm[$i][$j]; 
		}
		$pattern .= '/i';
		$string = preg_replace($pattern, '****', $string); 
	}
	return $string;
}
function table($table)
{
 	global $pre;
    return $pre .$table ;
}
function showmsg($msg_detail, $msg_type = 0, $links = array(), $auto_redirect = true,$seconds=3)
{
	global $smarty;
    if (count($links) == 0)
    {
        $links[0]['text'] = '返回上一页';
        $links[0]['href'] = $_SERVER['HTTP_REFERER'];// 获得上一页的地址
    }
   $smarty->assign('ur_here',     '系统提示');
   $smarty->assign('msg_detail',  $msg_detail);
   $smarty->assign('msg_type',    $msg_type);
   $smarty->assign('links',       $links);
   $smarty->assign('default_url', $links[0]['href']);
   $smarty->assign('auto_redirect', $auto_redirect);
   $smarty->assign('seconds', $seconds);
   $smarty->display('showmsg.htm');
	exit;
}
function get_smarty_request($str)
{
//rawurldecode->对已编码的 URL 字符串进行解码
$str=rawurldecode($str);
$strtrim=rtrim($str,']');
	if (substr($strtrim,0,4)=='GET[')
	{
	$getkey=substr($strtrim,4);
	return $_GET[$getkey];
	}
	elseif (substr($strtrim,0,5)=='POST[')
	{
	$getkey=substr($strtrim,5);
	return $_POST[$getkey];
	}
	else
	{
	return $str;
	}
}
function get_cache($cachename)
{
	$cache_file_path =QISHI_ROOT_PATH. "data/cache_".$cachename.".php";
	@include($cache_file_path);
	return $data;
}
function exectime(){ 
	$time = explode(" ", microtime());
	$usec = (double)$time[0]; 
	$sec = (double)$time[1]; 
	return $sec + $usec; 
}
function check_word($noword,$content)
{
	$word=explode('|',$noword);
	if (!empty($word) && !empty($content))
	{
		foreach($word as $str)
		{
			if(!empty($str) && strstr($content,$str))
			{
			return true;
			}

		}
	}
	return false;
}
function getip()
{
	if (getenv('HTTP_CLIENT_IP') and strcasecmp(getenv('HTTP_CLIENT_IP'),'unknown')) {
		$onlineip=getenv('HTTP_CLIENT_IP');
	}elseif (getenv('HTTP_X_FORWARDED_FOR') and strcasecmp(getenv('HTTP_X_FORWARDED_FOR'),'unknown')) {
		$onlineip=getenv('HTTP_X_FORWARDED_FOR');
	}elseif (getenv('REMOTE_ADDR') and strcasecmp(getenv('REMOTE_ADDR'),'unknown')) {
		$onlineip=getenv('REMOTE_ADDR');
	}elseif (isset($_SERVER['REMOTE_ADDR']) and $_SERVER['REMOTE_ADDR'] and strcasecmp($_SERVER['REMOTE_ADDR'],'unknown')) {
		$onlineip=$_SERVER['REMOTE_ADDR'];
	}
	preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/",$onlineip,$match);
	return $onlineip = $match[0] ? $match[0] : 'unknown';
}
function convertip($ip) {
	require_once(QISHI_ROOT_PATH."include/IP.class.php");
	$ip_obj= new Ip();
	$arr=$ip_obj->find($ip);
	return $arr[1].$arr[2];
}
function inserttable($tablename, $insertsqlarr, $returnid=0, $replace = false, $silent=0) {
	global $db;
	$insertkeysql = $insertvaluesql = $comma = '';
	foreach ($insertsqlarr as $insert_key => $insert_value) {
		$insertkeysql .= $comma.'`'.$insert_key.'`';
		$insertvaluesql .= $comma.'\''.$insert_value.'\'';
		$comma = ', ';
	}
	$method = $replace?'REPLACE':'INSERT';
	
	$state = $db->query($method." INTO $tablename ($insertkeysql) VALUES ($insertvaluesql)", $silent?'SILENT':'');
	if($returnid && !$replace) {
		return $db->insert_id();
	}else {
	    return $state;
	} 
}
function updatetable($tablename, $setsqlarr, $wheresqlarr, $silent=0) {
	global $db;
	$setsql = $comma = '';
	foreach ($setsqlarr as $set_key => $set_value) {
		if(is_array($set_value)) {
			$setsql .= $comma.'`'.$set_key.'`'.'='.$set_value[0];
		} else {
			$setsql .= $comma.'`'.$set_key.'`'.'=\''.$set_value.'\'';
		}
		$comma = ', ';
	}
	$where = $comma = '';
	if(empty($wheresqlarr)) {
		$where = '1';
	} elseif(is_array($wheresqlarr)) {
		foreach ($wheresqlarr as $key => $value) {
			$where .= $comma.'`'.$key.'`'.'=\''.$value.'\'';
			$comma = ' AND ';
		}
	} else {
		$where = $wheresqlarr;
	}
	$sql = "UPDATE ".($tablename)." SET ".$setsql." WHERE ".$where; 
	return $db->query($sql, $silent?"SILENT":"");
}
function wheresql($wherearr='')
{
	$wheresql="";
	if (is_array($wherearr))
		{
		$where_set=' WHERE ';
			foreach ($wherearr as $key => $value)
			{
			$wheresql .=$where_set. $comma.$key.'="'.$value.'"';
			$comma = ' AND ';
			$where_set=' ';
			}
		}
	return $wheresql;
}
function convert_datefm ($date,$format,$separator="-")
{
	 if ($format=="1")
	 {
	 return date("Y-m-d", $date);
	 }
	 else
	 {
		if (!preg_match("/^[0-9]{4}(\\".$separator.")[0-9]{1,2}(\\1)[0-9]{1,2}(|\s+[0-9]{1,2}(|:[0-9]{1,2}(|:[0-9]{1,2})))$/",$date))  return false;
		$date=explode($separator,$date);
		return mktime(0,0,0,$date[1],$date[2],$date[0]);
	 }
}
function sub_day($endday,$staday,$range='')
{
	$value = $endday - $staday;
	if($value < 0)
	{
		return '';
	}
	elseif($value >= 0 && $value < 59)
	{
		return ($value+1)."秒";
	}
	elseif($value >= 60 && $value < 3600)
	{
		$min = intval($value / 60);
		return $min."分钟";
	}
	elseif($value >=3600 && $value < 86400)
	{
		$h = intval($value / 3600);
		return $h."小时";
	}
	elseif($value >= 86400 && $value < 86400*30)
	{
		$d = intval($value / 86400);
		return intval($d)."天";
	}
	elseif($value >= 86400*30 && $value < 86400*30*12)
	{
		$mon  = intval($value / (86400*30));
		return $mon."月";
	}
	else{	
		$y = intval($value / (86400*30*12));
		return $y."年";
	}
}
function daterange($endday,$staday,$format='Y-m-d',$color='',$range=3)
{
	$value = $endday - $staday;
	if($value < 0)
	{
		return '';
	}
	elseif($value >= 0 && $value < 59)
	{
		$return=($value+1)."秒前";
	}
	elseif($value >= 60 && $value < 3600)
	{
		$min = intval($value / 60);
		$return=$min."分钟前";
	}
	elseif($value >=3600 && $value < 86400)
	{
		$h = intval($value / 3600);
		$return=$h."小时前";
	}
	elseif($value >= 86400)
	{
		$d = intval($value / 86400);
		if ($d>$range)
		{
		return date($format,$staday);
		}
		else
		{
		$return=$d."天前";
		}
	}
	if ($color)
	{
	$return="<span style=\"color:{$color}\">".$return."</span>";
	}
	return $return;	 
}
//计算 文件大小（换算成不同单位）
function filesizerange($filesize)
{
	$filesize = intval($filesize);
	if($filesize < 0)
	{
		return '';
	}
	elseif($filesize > 0 && $filesize < 1024*1024)
	{
		$return=round($filesize/1024,2)."KB";
	}
	elseif($filesize >= 1024*1024 && $filesize < 1024*1024*1024)
	{
		$return=round($filesize/(1024*1024),2)."MB";
	}
	return $return;	 
}
function cut_str($string, $length, $start=0,$dot='') 
{
		if(mb_strlen($string,QISHI_CHARSET) <= $length) {
			return $string;
		}else{
			$strcut = mb_substr($string,$start,$length,QISHI_CHARSET);
			return $strcut.$dot;
		}
		// $length=$length*3;
		// if(strlen($string) <= $length) {
		// 	return $string;
		// }
		// $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
		// $strcut = '';	 
		// 	for($i = 0; $i < $length; $i++) {
		// 		$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		// 	}
		// $strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
		// return $strcut.$dot;
}
function smtp_mail($sendto_email,$subject,$body,$From='',$FromName='')
{	
	global $_CFG;
	$mailconfig=get_cache('mailconfig');
	require_once(QISHI_ROOT_PATH.'phpmailer/class.phpmailer.php');
	$mail = new PHPMailer();
	$From=$From?$From:$mailconfig['smtpfrom'];
	$FromName=$FromName?$FromName:$_CFG['site_name'];
	if ($mailconfig['method']=="1")
	{
		if (empty($mailconfig['smtpservers']) || empty($mailconfig['smtpusername']) || empty($mailconfig['smtppassword']) || empty($mailconfig['smtpfrom']))
		{
		write_syslog(2,'MAIL',"邮件配置信息不完整");
		return false;
		}
	$mail->IsSMTP();
	$mail->Host = $mailconfig['smtpservers'];
	$mail->SMTPDebug= 0; 
	$mail->SMTPAuth = true;
	$mail->Username = $mailconfig['smtpusername']; 
	$mail->Password = $mailconfig['smtppassword']; 
	$mail->Port =$mailconfig['smtpport'];
	$mail->From =$mailconfig['smtpfrom']; 
	$mail->FromName =$FromName;
	}
	elseif($mailconfig['method']=="2")
	{
	$mail->IsSendmail();
	}
	elseif($mailconfig['method']=="3")
	{
	$mail->IsMail();
	}
	$mail->CharSet = QISHI_CHARSET;
	$mail->Encoding = "base64";
	$mail->AddReplyTo($From,$FromName);
	$mail->AddAddress($sendto_email,"");
	$mail->IsHTML(true);
	$mail->Subject = $subject;
	$mail->Body =$body;
	$mail->AltBody ="text/html";
	if($mail->Send())  
	{
	return true;
	}
	else
	{
	write_syslog(2,'MAIL',$mail->ErrorInfo);
	return false;
	}
}
function dfopen($url,$limit = 0, $post = '', $cookie = '', $bysocket = FALSE	, $ip = '', $timeout = 15, $block = TRUE, $encodetype  = 'URLENCOD')
{
		$return = '';
		$matches = parse_url($url);
		$host = $matches['host'];
		$path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
		$port = !empty($matches['port']) ? $matches['port'] : 80;

		if($post) {
			$out = "POST $path HTTP/1.0\r\n";
			$out .= "Accept: */*\r\n";
			//$out .= "Referer: $boardurl\r\n";
			$out .= "Accept-Language: zh-cn\r\n";
			$boundary = $encodetype == 'URLENCODE' ? '' : ';'.substr($post, 0, trim(strpos($post, "\n")));
			$out .= $encodetype == 'URLENCODE' ? "Content-Type: application/x-www-form-urlencoded\r\n" : "Content-Type: multipart/form-data$boundary\r\n";
			$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
			$out .= "Host: $host:$port\r\n";
			$out .= 'Content-Length: '.strlen($post)."\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Cache-Control: no-cache\r\n";
			$out .= "Cookie: $cookie\r\n\r\n";
			$out .= $post;
		} else {
			$out = "GET $path HTTP/1.0\r\n";
			$out .= "Accept: */*\r\n";
			//$out .= "Referer: $boardurl\r\n";
			$out .= "Accept-Language: zh-cn\r\n";
			$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
			$out .= "Host: $host:$port\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Cookie: $cookie\r\n\r\n";
		}

		if(function_exists('fsockopen')) {
			$fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
		} elseif (function_exists('pfsockopen')) {
			$fp = @pfsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
		} else {
			$fp = false;
		}

		if(!$fp) {
			return '';
		} else {
			stream_set_blocking($fp, $block);
			stream_set_timeout($fp, $timeout);
			@fwrite($fp, $out);
			$status = stream_get_meta_data($fp);
			if(!$status['timed_out']) {
				while (!feof($fp)) {
					if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {
						break;
					}
				}

				$stop = false;
				while(!feof($fp) && !$stop) {
					$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
					$return .= $data;
					if($limit) {
						$limit -= strlen($data);
						$stop = $limit <= 0;
					}
				}
			}
			@fclose($fp);
			return $return;
		}
}
function send_sms($mobile,$content)
{
	global $db;
	$content=iconv("utf-8","gbk",$content);
	$sms=get_cache('sms_config');
	if ($sms['open']!="1" || empty($sms['sms_name']) || empty($sms['sms_key']) || empty($mobile) || empty($content))
	{
	return false;
	}
	else
	{
	return dfopen("http://www.74cms.com/SMSsend.php?sms_name={$sms['sms_name']}&sms_key={$sms['sms_key']}&mobile={$mobile}&content={$content}");
	}	
}
function execution_crons()
{
	global $db;
	$crons=$db->getone("select * from ".table('crons')." WHERE (nextrun<".time()." OR nextrun=0) AND available=1 LIMIT 1  ");
	if (!empty($crons))
	{
		require_once(QISHI_ROOT_PATH."include/crons/".$crons['filename']);
	}
}

function get_tpl($type,$id)
{
	global $db,$_CFG,$smarty;
	$id=intval($id);
	$tarr=array("jobs","company_profile","resume",'hunter_profile','hunterjobs','list');
	if (!in_array($type,$tarr)) exit();
	if($type=="hunterjobs")
	{
		$utpl=$db->getone("SELECT h.tpl FROM ".table('jobs')."  AS j LEFT JOIN ".table('hunter_profile')."  AS h ON j.company_id=h.id WHERE j.id='{$id}' limit 1");
	}
	else
	{
		$utpl=$db->getone("SELECT tpl FROM ".table($type)." WHERE id='{$id}' limit 1");
	}
	$thistpl=$utpl['tpl'];
	if (empty($thistpl))
	{
		if ($type=='resume')
		{
		$thistpl="../tpl_resume/{$_CFG['tpl_personal']}/";
		$smarty->assign('user_tpl',$_CFG['site_dir']."templates/tpl_resume/{$_CFG['tpl_personal']}/");
		return $thistpl;
		}
		elseif($type=='hunter_profile')
		{
		$thistpl="../tpl_hunter/default/";
		$smarty->assign('user_tpl',$_CFG['site_dir']."templates/tpl_hunter/{$thistpl}/");
		return $thistpl;
		}
		elseif($type=='hunterjobs')
		{
		$thistpl="../tpl_hunter/default/";
		$smarty->assign('user_tpl',$_CFG['site_dir']."templates/tpl_hunter/{$thistpl}/");
		return $thistpl;
		}
		elseif($type=='list')
		{
		$thistpl="../tpl_hunter/default/";
		$smarty->assign('user_tpl',$_CFG['site_dir']."templates/tpl_hunter/{$thistpl}/");
		return $thistpl;
		}
		else
		{
		$thistpl="../tpl_company/{$_CFG['tpl_company']}/";
		$smarty->assign('user_tpl',$_CFG['site_dir']."templates/tpl_company/{$_CFG['tpl_company']}/");
		return $thistpl;
		}
	}
	else
	{
		if ($type=='resume')
		{
		$smarty->assign('user_tpl',$_CFG['site_dir']."templates/tpl_resume/{$thistpl}/");
		return "../tpl_resume/{$thistpl}/";
		}
		else
		{
		$smarty->assign('user_tpl',$_CFG['site_dir']."templates/tpl_company/{$thistpl}/");
		return "../tpl_company/{$thistpl}/";
		}		
	}	
 
}
function url_rewrite($alias=NULL,$get=NULL,$rewrite=true)
{
	global $_CFG,$_PAGE;
	$url ='';
	if ($_PAGE[$alias]['url']=='0' || $rewrite==false)//原始链接
	{
			if (!empty($get))
			{
				foreach($get as $k=>$v)
				{
				$url .="{$k}={$v}&";
				}
			}
			$url=!empty($url)?"?".rtrim($url,'&'):'';
			return $_CFG['site_domain'].$_CFG['site_dir'].$_PAGE[$alias]['file'].$url;
	}
	else 
	{
			$url =$_CFG['site_domain'].$_CFG['site_dir'].$_PAGE[$alias]['rewrite'];
			if ($_PAGE[$alias]['pagetpye']=='2' && empty($get['page']))
			{
			$get['page']=1;
			}
			foreach($get as $k=>$v)
			{
			$url=str_replace('($'.$k.')',$v,$url);
			}
			
			$url=preg_replace('/\(\$(.+?)\)/','',$url);
			if(substr($url,-5)=='?key=')
			{
			$url=rtrim($url,'?key=');
			}
			return $url;
	}
}
function get_member_url($type,$dirname=false)
{
	global $_CFG;
	$type=intval($type);
	if ($type===0) 
	{
	return "";
	}
	elseif ($type===1)
	{
	$return=$_CFG['site_dir']."user/company/company_index.php";
	}
	elseif ($type===2) 
	{
	$return=$_CFG['site_dir']."user/personal/personal_index.php";
	}
	elseif ($type===3)
	{
	$return=$_CFG['site_dir']."user/hunter/hunter_index.php";
	}
	if ($dirname)
	{
	return dirname($return).'/';
	}
	else
	{
	return $return;
	}
}
function fulltextpad($str)
{
	if (empty($str))
	{
	return '';
	}
	$leng=strlen($str);
	if ($leng>=8)
		{
		return $str;
	}
	else
	{
		$l=4-($leng/2);
		return str_pad($str,$leng+$l,'0');
	}
}
function asyn_userkey($uid)
{
	global $db;
	$sql = "select * from ".table('members')." where uid = '".intval($uid)."' LIMIT 1";
	$user=$db->getone($sql);
	return md5($user['username'].$user['pwd_hash'].$user['password']);
}
function write_syslog($type,$type_name,$str)
{
 	global $db,$online_ip;
	$l_page = addslashes(request_url());
	$str = addslashes($str);
 	$sql = "INSERT INTO ".table('syslog')." (l_type, l_type_name, l_time,l_ip,l_page,l_str) VALUES ('{$type}', '{$type_name}', '".time()."','{$online_ip}','{$l_page}','{$str}')"; 
	return $db->query($sql);
}
/*记录日志
* @param $str  	  积分和套餐说明(比如 积分+10,套餐剩余:5 , 若此字段没有值给赋个 '/' )
* @param $parentuid     企业会员记录日志时相应的parentuid存入值,个人和猎头设置为0就行.
* @param $note  	  操作说明 (比如登录,注册, 发布职位,修改职位等等)
* @param $mode 	  筛选字段(0->不筛选  1->筛选)
* @return true/false        插入结果
*/
function write_memberslog($uid,$utype,$type,$username,$str,$parentuid,$note,$mode=0)
{
 	global $db,$online_ip,$ip_address;
 	$sql = "INSERT INTO ".table('members_log')." (log_parentuid,log_uid,log_username,log_utype,log_type,log_addtime,log_ip,log_address,log_value,log_note,log_mode) VALUES ( '{$parentuid}', '{$uid}','{$username}','{$utype}','{$type}', '".time()."','{$online_ip}','{$ip_address}','{$str}','{$note}','{$mode}')";
	return $db->query($sql);
}
/*站内信*/
// 添加消息
function add_pms($uid,$entrust_id,$message)
{
	global $db;
	$insertarr['uid']=intval($uid);
	$insertarr['entrust_id']=intval($entrust_id);
	$insertarr['message']=trim($message);
	$insertarr['addtime']=time();
	return inserttable(table("pms"),$insertarr);
}
// 获取消息 //$uid,$is_apply,$entrust_type="",$is_look="" 
function get_pms_list($offset,$perpage,$getsql)
{
	global $db;
	$limit=" LIMIT ".intval($offset).','.intval($perpage);
	$sql="select p.* from ".table("pms_sys")." as p ".$getsql." order by p.dateline desc ".$limit;
	$list=$db->getall($sql);
	return $list;
}
// 获取 单条消息的详细信息 调用此方法该消息设置为已看,is_look=2;
function get_pms_one($id,$uid)
{
	global $db;
	$id=intval($id);
	$uid=intval($uid);
	$sql="select * from ".table('pms_sys')." where spmid=$id ";
	$row=$db->getone($sql);
	// 设为已看
	$db->query("update ".table('pms_sys')." set is_look=2 where spmid=$id and uid=$uid ");
	return $row;
}
// 删除消息
function pms_del($del_id,$uid)
{
	global $db;
	$return=0;
	$uidsql=" AND uid=".intval($uid)."";
	if (!is_array($del_id)) $del_id=array($del_id);
	$sqlin=implode(",",$del_id);
	if (preg_match("/^(\d{1,10},)*(\d{1,10})$/",$sqlin))
	{
	if (!$db->query("Delete from ".table('pms_sys')." WHERE spmid IN ({$sqlin}) {$uidsql}")) return false;
	$return=$return+$db->affected_rows();
	}
	return $return;
}
// 将消息设为已看
function pms_set_look($id,$uid)
{
	global $db;
	$return=0;
	$uidsql=" AND uid=".intval($uid)."";
	if (!is_array($id)) $id=array($id);
	$sqlin=implode(",",$id);
	if (preg_match("/^(\d{1,10},)*(\d{1,10})$/",$sqlin))
	{
	if (!$db->query("update ".table('pms_sys')." set is_look=2 WHERE spmid IN ({$sqlin}) {$uidsql} ")) return false;
	$return=$return+$db->affected_rows();
	}
	return $return;
}
//获取站内信信息
function get_pms_sys($offset,$perpage,$get_sql= '')
{
	global $db;
	if(isset($offset)&&!empty($perpage))
	{
	$limit=" LIMIT {$offset},{$perpage}";
	}
	$result = $db->query($get_sql.$limit);
	while($row = $db->fetch_array($result))
	{
		$row_arr[] = $row;
	}
	return $row_arr;
}
/*系统信息
* @param $spms_usertype            接收会员(全部会员->0  仅企业会员->1    仅个人会员->2   仅猎头会员->3)
* @return  $result		    返回统计数目
*/
function count_pms_sys($spms_usertype)
{
	global $db;
	$spms_usertype = intval($spms_usertype);
	if($spms_usertype>0){
		$result = $db->get_total("SELECT COUNT(*) AS num FROM ".table('pms_sys')." WHERE  spms_usertype=0  OR   spms_usertype={$spms_usertype}");
	}else{
		$result = $db->get_total("SELECT COUNT(*) AS num FROM ".table('pms_sys')." WHERE  spms_usertype=0 ");
	}
	return $result;
}
function request_url()
{     
  	if (isset($_SERVER['REQUEST_URI']))     
    {        
   	 $url = $_SERVER['REQUEST_URI'];    
    }
	else
	{    
		  if (isset($_SERVER['argv']))        
			{           
			$url = $_SERVER['PHP_SELF'] .'?'. $_SERVER['argv'][0];      
			}         
		  else        
			{          
			$url = $_SERVER['PHP_SELF'] .'?'.$_SERVER['QUERY_STRING'];
			}  
    }    
    return urlencode($url); 
}
function label_replace($templates)
{
	global $_CFG;
	$templates=str_replace('{sitename}',$_CFG['site_name'],$templates);
	$templates=str_replace('{sitedomain}',$_CFG['site_domain'].$_CFG['site_dir'],$templates);
	$templates=str_replace('{username}',$_GET['sendusername'],$templates);
	$templates=str_replace('{password}',$_GET['sendpassword'],$templates);
	$templates=str_replace('{newpassword}',$_GET['newpassword'],$templates);
	$templates=str_replace('{personalfullname}',$_GET['personal_fullname'],$templates);
	$templates=str_replace('{jobsname}',$_GET['jobs_name'],$templates);
	$templates=str_replace('{companyname}',$_GET['companyname'],$templates);
	$templates=str_replace('{paymenttpye}',$_GET['paymenttpye'],$templates);
	$templates=str_replace('{amount}',$_GET['amount'],$templates);
	$templates=str_replace('{oid}',$_GET['oid'],$templates);
	return $templates;
}
function make_dir($path)
{ 
	//检查文件或目录是否存在
	if(!file_exists($path))
	{
	//dirname返回路径中的目录部分
	make_dir(dirname($path));
	//mkdir新建目录
	@mkdir($path,0777); 	//权限 
	//chmod改变文件模式,建立完目录后使用chmod重新更改权限。
	@chmod($path,0777);
	}
}
//查看会员的刷新日志,得到最后最晚刷新的记录
function get_last_refresh_date($uid,$type)
{
	global $db;
	$sql = "select max(addtime) from ".table('refresh_log')." where uid=".intval($uid).' and ' . "`type`='".$type."'";
	return $db->getone($sql);
}
//查看会员的刷新日志,得到当天的刷新次数
function get_today_refresh_times($uid,$type)
{
	global $db;
	$today = strtotime(date('Y-m-d'));
	$tomorrow = $today+3600*24;
	$sql = "select count(*) as num from ".table('refresh_log')." where uid=".intval($uid).' and ' . "`type`='".$type."' and addtime>".$today." and addtime<".$tomorrow;
	$arr=$db->getone($sql);
	return $arr['num'];
}
function write_refresh_log($uid,$type){
	$setsqlarr['uid'] = $uid;
	$setsqlarr['type'] = $type;
	$setsqlarr['addtime'] = time();
	inserttable(table('refresh_log'),$setsqlarr);
}
function create_excel($top_str,$data){
	header("Content-Type: application/vnd.ms-execl");
	header("Content-Disposition: attachment; filename=myExcel.xls");
	header("Pragma: no-cache");
	header("Expires: 0");
	echo $top_str;
	foreach ($data as $k => $v) {
		foreach ($v as $k1 => $v1) {
			echo $v1;
			echo ($k1+1)<count($v)?"\t":"";
		}
		echo "\t\n";
	}
}
// 导出简历
function export_resume($yid){
	global $db;
	if(is_array($yid) && !empty($yid))
	{
		$yid_str = implode(",", $yid);
	}
	else
	{
		$yid_str=$yid;
	}
	$oederbysql=" order BY refreshtime desc ";
	$wheresql = empty($wheresql)?" id in ({$yid_str}) ":" and id in ({$yid_str}) ";
	if (!empty($wheresql))
	{
	$wheresql=" WHERE ".ltrim(ltrim($wheresql),'AND');
	}
	$data = $db->getall("select * from ".table('resume').$wheresql);
	
	if(!empty($data)){
		$result = $data;
	}
	if(!empty($result)){
		foreach ($result as $key => $value) {
			$arr[$key]['id'] = $value['id'];
			$arr[$key]['title'] = $value['title'];
			$arr[$key]['fullname'] = $value['fullname'];
			$arr[$key]['sex_cn'] = $value['sex_cn'];
			$arr[$key]['birthdate'] = $value['birthdate'];
			$arr[$key]['residence_cn'] = $value['residence_cn'];
			$arr[$key]['marriage_cn'] = $value['marriage_cn'];
			$arr[$key]['experience_cn'] = $value['experience_cn'];
			$arr[$key]['education_cn'] = $value['education_cn'];
			$arr[$key]['trade_cn'] = $value['trade_cn'];
			$arr[$key]['district_cn'] = $value['district_cn'];
			$arr[$key]['wage_hope'] = round($value['wage_hope']/10000,2).'万';
			$arr[$key]['wage_current'] = round($value['wage_current']/10000,2).'万';
			$arr[$key]['school'] = "";
			$school = $db->getall("select * from ".table('resume_education')." where pid=".$value['id']." order by id desc");
			if(!empty($school)){
				foreach ($school as $key1 => $value1) {
					$arr[$key]['school'] .= date("Y-m",$value1['starttime'])."-".date("Y-m",$value1['endtime'])."就读于".$value1['school'].",所学专业：".$value1['speciality'].",学历：".$value1['education_cn'].";&nbsp;";
				}
			}
			$arr[$key]['work'] = "";
			$work = $db->getall("select * from ".table('resume_work')." where pid=".$value['id']." order by id desc");
			if(!empty($work)){
				foreach ($work as $key1 => $value1) {
					$arr[$key]['work'] .= date("Y-m",$value1['starttime'])."-".date("Y-m",$value1['endtime'])."就职于".$value1['companyname'].",任职：".$value1['jobs'].";&nbsp;";
				}
			}

			$arr[$key]['telephone'] = $value['telephone'];
			$arr[$key]['email'] = $value['email'];
			$arr[$key]['currentjobs'] = $value['currentjobs'];
			$arr[$key]['intention_jobs_cn'] = $value['intention_jobs_cn'];
			// $arr[$key]['specialty'] = str_replace("\n","",str_replace("\r", "", $value['specialty']));
			$arr[$key]['addtime'] = date("Y-m-d",$value['addtime']);
			$arr[$key]['refreshtime'] = date("Y-m-d",$value['refreshtime']);
			$arr[$key]['talent'] = $value['talent']==1?"普通":"高级";
			$arr[$key]['complete_percent'] = $value['complete_percent'];
		}
		$top_str = "简历编号\t简历名称\t姓名\t性别\t出生年月\t目前居住地\t婚姻状况\t工作经验\t学历\t意向行业\t意向工作地区\t期望薪资\t目前薪资\t教育培训\t工作经历\t手机\t邮箱\t最近从事工作\t意向职位\t添加时间\t刷新时间\t简历等级\t完整度\t\n";
		create_excel($top_str,$arr);
		return true;
	}else{
		return false;
	}
	
}
?>