<?php
/*******************************************************************
 * 版权协议：2009-2019
 * 版权所有: PHP-北京金南曦网络技术有限公司旗下PHPWMS，PHP商城系统技术支持中心http://www.php188.net，并保留所有权利。 
* PHP商城系统网址: http://www.php188.com
 * PHPWMS系统网址：http://www.phpwms.com
 * 销售电话：010-87875088
 * 销售电话：010-87875188 
*------------------------------------------------------------------
 * 这不是一个完全免费软件！您只能在不用于商业目的的前提下对程序代码进
 * 行修改和使用；不允许对程序代码以任何形式任何目的的再发布。
 *------------------------------------------------------------------
 * 文件名称：phpwms.global.function.php
 * 摘　　要：全局调用函数
 * 适用范围：PHPWMS 1.0
 * 版　　本：1.0
 *------------------------------------------------------------------
 * Script Written By phpwms项目组
 * 最后更新： 2009-09-24 phpwms 由PHP金南曦网络技术有限公司整理发布
 *******************************************************************/
if(!defined('IN_SYS')) {exit('Access Denied');}
require dirname(__FILE__).'/phpwms.common.fun.php'; 

function check_code($string){
	if(!class_exists('CheckCode'))require SYS_ROOT.'include/classes/cls.chk_code.php';
	$check = new CheckCode();
	return $check->check($string); 
}
/**
 * 返回程序执行时间
 *
 * @return unknown
 */
/*
function get_debug_info(){
		global $db;
		$starttime = $GLOBALS['starttime'];
		$endtime = microtime_float();
		$totaltime = abs(number_format(($endtime - $starttime), 6));
		$info= 'Processed in '.$totaltime.' second(s), '.(is_object($db)?$db->getRunInfo():'').', Memory Used '.format_bytes(@memory_get_usage());
		return $info;
}*/
function get_debug_info($echo = false){
	global $db;
	$starttime = $GLOBALS['starttime'];
	$p_endtime = microtime_float();
	$endtime = $GLOBALS['endtime']==''?microtime_float():$GLOBALS['endtime'];
	$totaltime = number_format(($endtime - $starttime), 6);
	$p_total_time = number_format(($p_endtime-$starttime),6);
	$info= 'Page Executioned in '.$p_total_time.' second(s),  Processed in '.$totaltime.' second(s), '.($db?$db->getRunInfo():'').', Memory Used '.format_bytes(@memory_get_usage());
	if($echo)dump($info);
	return $info;
}
function system_debug_info($item = array()){
	global $db;
	$is_show_debug = get_cache(array('siteBase','show_debug'))=='1'?TRUE:FALSE;
	$show_sql_log = $item['show_sql']=='true'?TRUE:FALSE;
	$shows_string = $show_sql_log?dump($db->loadQueryLog(),FALSE):'';
	return $is_show_debug?get_debug_info().$shows_string:$shows_string;
}
/**
 * 发送邮件 根据管理员配置设置发信
 *
 * @param string $name
 * @param array $array
 * @param string $reciver
 * @param string $appendContent
 * @return boolean
 */
function sendSetMail($name,$array,$reciver,$appendContent = ''){
	$tpl = get_mail_tpl(trim($name));
	if(empty($tpl))return FALSE;
	if($tpl['tpl_open']=='1'){
		$content = $tpl['mail_content'];
		$subject = $tpl['mail_tile'];
		foreach ($array as $k=>$v){
			$content = trim(str_replace('<{$'.$k.'}>',$v,$content));
			$subject = trim(str_replace('<{$'.$k.'}>',$v,$subject));
			
		}
			$body = $content.$appendContent;
			return send_mail('','','',array($reciver),$subject,$body);
	}
	return FALSE;
}
/**
 * 递归替换URL地址与还原
 *
 * @param array $array 需要处理的数据
 * @param string $url 需要替换掉的url 可以为空
 * @param string $replace_item 替换后的字符串 可为空
 * @param boolean $decode 是否是替换或反替换 默认为替换url为变量
 * @return mixed
 */
function filter_site_url($array,$url = '',$replace_item = '',$decode = false){
	if(empty($array))return $array;
	$url = empty($url)?get_cache(array('siteBase','sys_url')):$url;
	if(empty($url))return $array;
	$replace_item = empty($replace_item)?'{$phpwms_site_url_tags}':$replace_item;
	$filter = $decode?array($url=>$replace_item):array($replace_item=>$url);
	if(is_array($array)&&!empty($array)){
		$temp = array();
		foreach ($array as $k=>$row)$temp[$k] = filter_site_url($row,$url,$replace_item,$decode);
		return $temp;
	}else{
		return strtr($array,$filter);
	}
}
/**
 * 递归替换URL地址  encode
 *
 * @param string|array $array 
 * @param string $replace_item
 * @param string $replaced_item
 * @return mixed
 */
/*
function filter_site_url_encode($array,$replace_item='',$replaced_item=''){
	return filter_site_url($array,$replace_item,$replaced_item,TRUE);
}*/
/**
 * 递归替换URL地址  encode
 * 去他大爷的编辑器 奶奶的找了半天找不到路径 只有这样折中处理了 
 *
 * @param string|array $array 
 * @param string $replace_item
 * @param string $replaced_item
 * @return mixed
 */
function filter_site_url_encode($array,$replace_item=''){
	if(empty($array))return $array;
	$replace_item = empty($replace_item)?'{$phpwms_site_url_tags}':$replace_item;
	$url = get_cache(array('siteBase','sys_url'));
	if(empty($url))return $array;
	if(is_array($array)){
		$temp = array();
		foreach ($array as $k=>$v){
			$temp[$k] = filter_site_url_encode($v,$replace_item);
		}
		return $temp;
	}else{
		return str_replace(array($url,'../files/','../kindeditor/'),array($replace_item,$replace_item.'files/',$replace_item.'kindeditor/'),$array);
	}
}
/**
 * 同上
 *
 * @param string|array $array 
 * @param string $replace_item
 * @param string $replaced_item
 * @return unknown
 */
function filter_site_url_decode($array,$url= '',$replace_item=''){
	if(empty($array))return $array;
	$cache = get_cache(array('siteBase','sys_url'));
	$cache = empty($cache)?'/':$cache;
	$url = empty($url)&& !empty($cache)?$cache:$url;
	$replace_item = empty($replace_item)?'{$phpwms_site_url_tags}':$replace_item;
	if(is_array($array)){
		$temp = array();
		foreach ($array as $k=>$v){
			$temp[$k] = filter_site_url_decode($v);
		}
		return $temp;
	}else{
		return str_replace($replace_item,$url,$array);
	}
}
/**
 * 获得邮件模板列表
 *
 * @param string $name
 * @return array()
 */
function get_mail_tpl($name = ''){
	global $db;
	$data = php188StaticCache::getInstance()->get('php188_wms_mail_config');
	if(!$data){
		$data = $db->fetch("SELECT * FROM ##__mail_tpl;");
		php188StaticCache::getInstance()->save($data,'php188_wms_mail_config');
	}
	if(!empty($name) && !empty($data)){
		foreach ($data as $item){
			if(trim($item['tpl_name']) == trim($name))return $data;
		}
	}
	return $data;
}
/**
 * 获得缓存
 * get_cache(array('siteBase'));
 * @param string|array $key
 * @return array|string
 */
function get_cache($key=''){
	global $db;
	$file = STATC_CACHE_PATH.'php_cache/global.php';
	if(!file_exists($file)){
		$data = $db->fetch("SELECT * FROM ##__core_setting order by `s_name`;");
		$temp = array();
		if(!empty($data)){
			foreach ($data as &$d)$temp[$d['s_name']] = $d['s_data'];
		}
		$temp = unserialize_deep($temp);
		$file = STATC_CACHE_PATH.'php_cache/global.php';
		$string = "<?php \n if(!defined('IN_SYS'))exit('php188.com');\n".'$GLOBALS[\'PHPWMS_SITE_CACHE\'] = ';
		$string .= var_export($temp,TRUE).";\n";
		$string .= "\n".'?>';
		create_file($string,$file);	
	}
	if(!is_file($file)){
		exit('please check the <b>cache</b> path is can write.');
	}
	require $file;
	$result = array();
	$ary = $GLOBALS['PHPWMS_SITE_CACHE'];
	if(empty($ary))return array();
	if(empty($key)){
		$result = $ary;
	}elseif(!empty($key)&&is_string($key)){
		$result = isset($ary[$key])?$ary[$key]:'';
	}elseif(is_array($key)&&!empty($key)){
		$tag = true;
		foreach ($key as $item) {
			if(is_array($ary) && isset($ary[$item])) $ary = $ary[$item];
			else {$tag = false; break;}
		}
		$result =  $tag?$ary:'';
	}
	return $result;
}
/**
 *全局url 
 */
function get_out_global_url(){
	require SYS_ROOT.'data/self.nav.php';
	return $GLOBALS['self_nav'];
}
/**
 * 提取模型
 * @param $strin $model_id
 * @return array
 */
function get_models($model_id = ''){
	global $db;
	$data = php188StaticCache::getInstance()->get('phpwms_site_models');
	if(!$data){
		$data = $db->fetch("SELECT * FROM ##__model ORDER BY `id` ASC;");
		php188StaticCache::getInstance()->save($data,'phpwms_site_models');
	}
	if(!empty($model_id) && !empty($data)){
		foreach ($data as $item){
			if($item['id']==$model_id){
				return $item;
			}
		}
	}
	return $data;
}
/**
 * 获得用户组
 *
 * @return array
 */
function get_user_group(){
	global $db;
	$data = php188StaticCache::getInstance()->get('phpwms_user_group');
	if(!$data){
		$data = $db->fetch("SELECT name,id,state FROM  ##__user_group;");
		php188StaticCache::getInstance()->save($data,'phpwms_user_group');
	}
	return $data;
}
/**
 * 提取全部频道
 *
 */
function get_channels($model = '',$channel_id = ''){
	global $db;
	$data = php188StaticCache::getInstance()->get('phpwms_site_channels');
	if(!$data){
		$data = $db->fetch("SELECT c.*,m.cn_name,m.en_name FROM ##__channel  as c LEFT JOIN ##__model AS m 
		 ON c.channel_model = m.id ORDER BY c.`channel_id` ASC;");
		php188StaticCache::getInstance()->save($data,'phpwms_site_channels');
	}
	if(!empty($model)&& !empty($data) && empty($channel_id)){
		$datas = array_group_by($data,'channel_model');
		return  isset($datas[$model])?$datas[$model]:array();
	}
	if(empty($model) && !empty($data) && !empty($channel_id)){
		foreach ($data as $d){
			if($d['channel_id']==$channel_id)return $d;
		}
	}
	return $data;
}
/**
 * 通过频道ID获该频道下的所有分类
 *
 * @param int $channel_id
 * @return array
 */
function get_category($model_id = '',$channel_id  = '',$cate_id = '',$cate_sign = ''){
	global $db;
	$data = php188StaticCache::getInstance()->get('phpwms_channel_categorys');
	if(!$data){
		$data = $db->fetch("SELECT * FROM ##__channel AS ch , ##__category AS cat WHERE  ch.`channel_id` = cat.channel_id ;");
		if(!empty($data)){
			foreach ($data as &$d){
				$d['link_cat_data']=array(
					'name'=>$d['category_name'],
					'link'=>building_url('models',get_action($d['channel_id']),array($d['channel_id'],$d['category_id'])),
				);
				$d['link_channel_data']=array(
					'name'=>$d['channel_name'],
					'link'=>building_url('models',get_action($d['channel_id']),array($d['channel_id'])),
				);
			}
		}
		php188StaticCache::getInstance()->save($data,'phpwms_channel_categorys');
	}
	if(!empty($model_id) && !empty($data) && empty($channel_id) && empty($cate_id) && empty($cate_sign)){
		$datas = array_group_by($data,'channel_model');
		return isset($datas[$model_id])?$datas[$model_id]:array();
	}
	if(empty($model_id) && !empty($channel_id) && !empty($data) && empty($cate_id) && empty($cate_sign)){
		$datas = array_group_by($data,'channel_id');
		return isset($datas[$channel_id])?$datas[$channel_id]:array();
	}
	if(!empty($data) && empty($channel_id) && empty($model_id) && !empty($cate_id) && empty($cate_sign)){
		foreach ($data as $d){
			if($d['category_id']==$cate_id)return $d;
		}
	}
	if(!empty($data) && empty($channel_id) && empty($model_id) && empty($cate_id) && !empty($cate_sign)){
		foreach ($data as $d){
			if($d['cate_sign']==$cate_sign)return format_category($d);
		}
	}
	return $data;
}
function is_mulit_array($array){
	if(!is_array($array))return FALSE;
	foreach ($array as $t){
		return is_array($t)?TRUE:FALSE;
	}
	return FALSE;
}
/**
 * 获得分类的子数据
 *
 * @param int $category_id
 * @param array $show_key
 * @param boolean $show_all
 * @param boolean $merge
 * @return array
 */
function get_cate_son($category_id,$merge = true,$show_key = array(),$show_all = true){
	if(!class_exists('WMSTree'))require PUB_CLASS.'phpwms.tree.class.php';
	$trees = get_category();
	$wmstree = new WMSTree();
	$son_tree = $wmstree->get_son($trees,'category_id','parent_id',$category_id,$show_key,$show_all);
	if($merge){
		$datas = array_group_by($trees,'category_id');
		$tree = array_merge($datas[$category_id],$son_tree);
		unset($datas);
		unset($trees);
	}else{
		$tree = $son_tree;
	}
	unset($son_tree);
	return $tree;
}
/**
 * 缓存分类下的总数
 *
 * @param int $category_id
 * @param boolean $all
 * @return string
 */
function get_category_cache_content_index($category_id,$all = true){
	global $db;
	if(empty($category_id) || !is_numeric($category_id))return array();
	$cache_name_string = 'phpwms_category_content_cache_'.$category_id;
	if(!class_exists('WMSTree'))require PUB_CLASS.'phpwms.tree.class.php';
	$data = php188StaticCache::getInstance()->get($cache_name_string);
	$category_data = get_category('','',$category_id);
	if(!$data && $category_data['total']>0){
		$data = $db->fetch("SELECT c_id FROM ##__contents WHERE `category_id` IN ($category_id) AND  
		`is_show` IN(1) AND `is_recycle` in(0)  ORDER BY `c_id` DESC;");
		!empty($data)?php188StaticCache::getInstance()->save($data,$cache_name_string):'';
	}
	if($all){
		$tree = get_cate_son($category_id);
		$a_ids = array();
		if(is_array($tree)&& count($tree)>1){
			foreach ($tree as $t){
				if($t['total']>0){
					$a_ids[] = mulitarray_to_array(get_category_cache_content_index($t['category_id'],FALSE),FALSE);
				}
			}
			$data = is_array($a_ids)?array_pop($a_ids):array();
			unset($a_ids);
		}
	}
	return $data;
}
/**
 * 构造分类树
 *
 * @param int $model_id
 * @return array
 */
function building_tree($model_id){
	if(empty($model_id))return array();
	if(!class_exists('WMSTree'))require SYS_ROOT.'pub/phpwms.tree.class.php';
	$tree = new WMSTree();
	$trees = get_category($model_id);
	return $tree->building_tree($trees,0,'|-',0,'category_id','parent_id');
}
/**
 * 获得扩展属性分组
 *
 * @param int  $type_id
 * @return array
 */
function get_types($type_id = ''){
	global $db;
	$type_id = to_int($type_id);
	$data = php188StaticCache::getInstance()->get('phpwms_extend_types');
	if(!$data){
		$data = $db->fetch("SELECT * FROM ##__extend_type ;");
		php188StaticCache::getInstance()->save($data,'phpwms_extend_types');
	}
	if(!empty($type_id) && !empty($data)){
		foreach ($data as $d){
			if(trim($d['type_id'])==trim($type_id))return $d;
		}
	}
	return $data;
}
/**
 * 导航
 *
 * @return array
 */
function get_navigation(){
	global $db;
	$result = php188StaticCache::getInstance()->get('phpwms_navigation');
	if(empty($result)){
		$sql = "SELECT * FROM ##__navigation WHERE `nav_display` = '1' ORDER BY nav_sort ASC";
		$navs = $db->fetch($sql);
		foreach ($navs as $nav){
			$result[$nav['nav_position']][] = $nav;
		}
		php188StaticCache::getInstance()->save($result, 'phpwms_navigation');
	}
	/*获得频道连接*/
	$channels = get_channels();
	$c_temp = array();
	if($channels){
		foreach ($channels as $c){
			if($c['menu_show']=='1'){
				$model = get_action($c['channel_id']);
				$temps = array(
				  'model'=>empty($model)?'article':$model,
			      'nav_name' => $c['channel_name'],
			      'nav_sort' => '0',
			      'nav_link' => building_url('models',$model,array('id'=>$c['channel_id']),TRUE),
			      'nav_blank' => '_self',
			      'nav_position' => 'center',
			      'nav_display' => '1',
				);
				$c_temp[] = $temps;
			}
		}
	}
	unset($channels);
	//获得分类
	$categorys = get_category();
	if($categorys){
		foreach ($categorys as $c){
			if($c['in_nav'] =='1'){
				$model = get_action($c['channel_id']);
				$temps = array(
				  'model'=>empty($model)?'article':$model,
			      'nav_name' => $c['category_name'],
			      'nav_sort' => '0',
			      'nav_link' => building_url('models',$model,array($c['channel_id'],$c['category_id']),TRUE),
			      'nav_blank' => '_self',
			      'nav_position' => 'center',
			      'nav_display' => '1',
				);
				$c_temp[] = $temps;
			}
		}
	}
	$result['center'] = !is_array($result['center'])?$c_temp:array_merge($c_temp,$result['center']);
	return $result;
}
/**
 * 获得友情链接
 *
 * @return array
 */
function get_link(){
	global $db;
	$result = php188StaticCache::getInstance()->get('phpwms_link');
	if(!$result){
		$sql = "SELECT * FROM ##__link WHERE `state` = '1' ORDER BY order_num ASC";
		$links = $db->fetch($sql);
		foreach($links as $link){
			$link['logo'] = get_self().$link['logo'];
			$result[$link['type']][] = $link;
		}
		php188StaticCache::getInstance()->save($result,'phpwms_link');
	}
	return $result;
}
/**
 * get frinend link for smarty
 * @param array $item
 */
function get_friendlink($item = array()){
	$assign = $item['assign'];
	if(empty($assign))exit('must has a assign tag');
	$GLOBALS['smarty']->assign($assign,get_link());
}
/**
 * 格式化文章数据->列表 文章列表
 *
 * @param array $article_data
 * @param string $action
 * @return array
 */
function format_content($article_data){
	if(!is_array($article_data) || empty($article_data))return $article_data;
	if(is_mulit_array($article_data)){
		foreach ($article_data as &$d){
			$d['title'] = empty($d['short_title'])?$d['long_title']:$d['short_title'];
			$d['content_link'] = empty($d['out_link'])?building_url('content','',$d['c_id']):$d['out_link'];
			if(!empty($d['thumb']))$d['thumb'] = filter_site_url_decode($d['thumb']);
			if(!empty($d['big_pic']))$d['big_pic'] = filter_site_url_decode($d['big_pic']);
			if(!empty($d['category_name']) && !empty($d['channel_id']) && !empty($d['category_id']))$d['category_link'] = building_url('models',get_action($d['channel_id']),array($d['channel_id'],$d['category_id']));
		}
	}else{
			$article_data['title'] = empty($article_data['short_title'])?$article_data['long_title']:$article_data['short_title'];
			$article_data['content_link'] = empty($article_data['out_link'])?building_url('content','',$article_data['c_id']):$article_data['out_link'];
			if(!empty($article_data['thumb']))$article_data['thumb'] = filter_site_url_decode($article_data['thumb']);
			if(!empty($article_data['big_pic']))$article_data['big_pic'] = filter_site_url_decode($article_data['big_pic']);
			if(!empty($article_data['category_name']) && !empty($article_data['channel_id']) && !empty($article_data['category_id']))$article_data['category_link'] = building_url('models',get_action($article_data['channel_id']),array($article_data['channel_id'],$article_data['category_id']));
		
	}
	return $article_data;
}
function format_category($array){
	if(empty($array))return $array;
	if(is_mulit_array($array)){
		foreach ($array as &$c){
			$c['more_link'] = building_url('models',get_action($c['channel_id']),array($c['channel_id'],$c['category_id']));
		}
	}else{
		$array['more_link'] = building_url('models',get_action($array['channel_id']),array($array['channel_id'],$array['category_id']));
	}
	return $array;
}
function get_page($item = array()){
		global $db;
	$id = to_int($item['id']);
	if(empty($id))return array();
	$assign = $item['assign'];
	if(empty($assign))exit('not has the assign tag');
	$cache_string = 'phpwms_one_page_'.$id;
	$cache = trim($assign['cache'])=='true'?true:false;
	if($cache){
		$data = php188StaticCache::getInstance()->get($cache_string);
		if(!$data){
			$data = $db->fetch("select `body` as content,`id`  from ##__single_page where `id` = '$id' limit 0,1",true);
			 php188StaticCache::getInstance()->save($data,$cache_string);
		}
	}else{
		$data = $db->fetch("select `body` as content,`id`  from ##__single_page where `id` = '$id' limit 0,1",true);	
	}
	return $GLOBALS['smarty']->assign($assign,$data);
}
/**
 * 得到广告
 *
 * @param array $params
 * @return string
 */
function get_ads($params = array()){
	$place_name = $params['place_name'];
	$result = php188StaticCache::getInstance()->get('phpwms_ads_place');
	if(!$result){
		global $db;
		$time = time();
		$sql = "SELECT ads.*, place.* FROM ##__ads AS ads LEFT JOIN ##__ads_place AS place ON ads_place_id =place_id WHERE ads_pass = '1' AND ads_endtime > $time AND ads_begintime < $time";
		$result['ads_data'] = $db->fetch($sql);
		//生成广告数据
		if(!empty($result['ads_data'])){
			foreach ($result['ads_data'] as $k=>$place){
				$result['ads_data'][$k]['ads_text'] = unserialize_deep($place['ads_text']);
				$place['ads_text'] = unserialize_deep($place['ads_text']);
				$result['php188_place_ads_'.$place['place_name']] = get_ads_string($place);
			}
		}
		php188StaticCache::getInstance()->save($result, 'phpwms_ads_place');
	}
	return !empty($place_name)?$result['php188_place_ads_'.$place_name]:$result['ads_data'];
}
/**
 * 构造广告
 *
 * @param array $res
 * @return string
 */
function get_ads_string($res){
	$str = '';
	// 得到高度和宽度
	$width = $res['place_width'].'px';
	$height = $res['place_height'].'px';
	// 判断 类型
	switch ($res ['ads_type']) {
		case 'image' :
			$src = filter_site_url_decode($res ['ads_text']['image_src']);
			$linkurl = $res ['ads_text']['image_link'];
			$str = "<img style=\"height:$height; width:$width;overflow:hidden;\"  border=\"0\"  src='$src' />";
			if(!empty($linkurl)){
				$str = "<a target='_blank'  href='$linkurl' >" . $str . "</a>";
			}
			break;
		case 'flash' :
			$src = filter_site_url_decode($res ['ads_text']['flash_scr']);
			$str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'.$width.'" height="'.$height.'" 
			codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" 
			<param name="movie" value="' . $src . '"><param name="quality" value="high"><embed src="' . $src . '"
			 quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" width="'.$width.'" height="'.$height.'" 
			 type="application/x-shockwave-flash"></embed></object>';
			$linkurl = $res ['ads_text']['flash_link'];
			if(!empty($linkurl)){
				$str = "<a target='_blank'  href='$linkurl' >" . $str . "</a>";
			}
			break;
		case 'text' :
			$code = $res ['ads_text']['text_text'];
			$code = str_replace ( "\n", "<br/>", $code );
			$str = "<div style='width:$width; height:$height' class=\"ads_text\" >".$code . '</div>';
			break;
		case 'a' :
			$text = filter_site_url_decode($res ['ads_text']['a_text']);
			$linkurl = $res['ads_text']['a_link'];
			$str = "<a target='_blank' href='$linkurl'>" . $text . '</a>';
			break;
	}
	return  $str;
}
/**
 * 提取公告 formart
 *
 */
function get_notice($item){
	$assign = $item['assign'];
	if(empty($assign))exit('not has the assign tag');
	$result = php188StaticCache::getInstance()->get('phpwms_notice');
	if(empty($result)){
		global $db;
		$sql = "SELECT * FROM ##__notice ORDER BY post_time DESC LIMIT 0, 10";
		$result = $db->fetch($sql);
		foreach ($result as $k=>$v) {
			$result[$k]['content'] = filter_site_url_decode($v['content']);
		}
		php188StaticCache::getInstance()->save($result, 'phpwms_notice');
	}
	$GLOBALS['smarty']->assign($assign,$result);
}
/**
 * 通过频道ID或模型ID获得所属的模型 en_name
 *
 * @param int $channel_id
 */
function get_action($channel_id= '',$model_id=''){
	$models = get_models($model_id);
	if(!empty($model_id) && empty($channel_id)){
		return $models['en_name'];
	}
	if(!empty($channel_id)&&empty($model_id)){
		$channels = get_channels('',$channel_id);	
		return get_action('',$channels['channel_model']);
	}
	return NULL;
}

/**
 * 提取分类for smarty 没构造URL
 * @param int $item
 */
function get_category_for_tpl($item){
	$assign = $item['assign'];
	if(empty($assign))exit('not has assign tag.');
	$channel_id = to_int($item['channel_id']);
	$category_id = to_int($item['category_id']);
	$model = strtolower(trim($item['model']));//所属模型
	$building_tree = $item['building_tree']=='true'?TRUE:FALSE;
	//$building_article = $item['bilding_article'] = 'true'?TRUE:FALSE;
	if(!empty($model)){
		$ary = array_group_by(get_models(),'en_name');
		$keys = array_keys($ary);
		$model_id = in_array($model,$keys)?$ary[$model][0]['id']:1;
	}
	/*构造树*/
	if(!empty($model) && $model_id){
		$datas = get_category($model_id);
	}else{
		$datas = get_category('',$channel_id,$category_id);
	}
	if($building_tree){
		if(!class_exists('WMSTree'))require PUB_CLASS.'phpwms.tree.class.php';
		$trees = new WMSTree();
		$datas = $trees->building_tree($datas);
		unset($trees);
		$datas = array_to_tree($datas,'category_id','parent_id');
	}
	$GLOBALS['smarty']->assign($assign,$datas);	
}
/**
 * 构造URL
 * @param array $items
 */
function building_link_for_smarty($items = array()){
	$model = empty($items['model'])?'goods':$items['model'];
	$action = empty($items['action'])?'php188':$items['action'];
	$parames  = $items['param'];
	$http = $items['http'];
	$http = $http=='false'?false:true;
	$temp = array();
	if(!empty($parames)){
		$tag = array_filter(array_map("trim",explode('&',$parames)));
		if(!empty($tag)){
			foreach ($tag as $t){
				$k = array_filter(array_map("trim",explode('=',$t)));
				$temp[$k[0]] = $k[1];
			}
		}
	}
	return  building_url($model,$action,$temp,array(),false,$http);
}
/**
 * for smarty  提取数据
 *
 * @param array $item
 */
function get_content($item){
	global $db;
	$assign = $item['assign'];
	if(empty($assign))exit('not exis the assign tag');
	$cate_id = to_int($item['category_id']);
	$cate_sign = trim($item['cate_sign']);
	$model = !empty($item['model'])?$item['model']:'article';
	$channel_id = to_int($item['channel_id']);
	$type = !empty($item['type'])?trim($item['type']):'All';
	$show_category_data  = strtolower($item['show_cate_data'])=='true'?TRUE:FALSE; //是否显示分类数据
	$main_cache_string = 'php188_phpwms_all_content_string';
	$cache_string = 'php188_cache_all_'.$model.'_'.$type.'_'.$cate_id.'_'.$channel_id.'_'.$cate_sign;
	$limit = to_int($item['limit']);//提取数据的条数
	$limit = empty($limit)?10:$limit;
	//提取图片文章
	$top_first_pic_article = strtolower($item['picture_article'])=='true'?TRUE:FALSE;
	$top_first_pic_article_num = to_int($item['picture_article_num']);
	$top_first_pic_article_num = empty($top_first_pic_article_num)?1:$top_first_pic_article_num;
	$all_son  = !empty($item['all_content'])?TRUE:FALSE;//是否调用子分类下的数据 默认false
	$cache_data = php188StaticCache::getInstance()->get($main_cache_string);
	$data = $cache_data[$cache_string];
	if(!$data){
		$sql = building_sql($model,$cate_id,$all_son,$channel_id,$cate_sign,$type);
		$data = $cache_data[$cache_string]  = format_content(filter_site_url_decode($db->fetch($sql)));
		php188StaticCache::getInstance()->save($cache_data,$main_cache_string);
		unset($cache_data);
	}
/*
	foreach ($data as &$t){
		$ch = get_channels('',$t['channel_id']);
		$ct = get_category('','',$t['category_id']);
		$j = array_merge($ch,$ct);
		$t = array_merge($t,$j);
	}
	$data = filter_site_url_decode($data);*/
/*	if(!empty($cate_id) || !empty($cate_sign) && empty($channel_id) && $data){
		if(!empty($cate_id)){
			$g  = array_group_by($data,'category_id');
			$data = $g[$cate_id];
			unset($g);
		}
		if(!empty($cate_sign)){
			$cats = get_category('','','',$cate_sign);
			$cate_id = $cats['category_id'];
			$g  = array_group_by($data,'category_id');
			$data = $g[$cate_id];
			unset($g);
		}
	}*/
	//获得这个频道下的分类
/*	if(!empty($channel_id) && !$data){
		$g = array_group_by($data,'channel_id');
		$data = $g[$channel_id];
		unset($g);
		if(!empty($cate_id) && !empty($data)){
			$cat_data = array_group_by($data,'category_id');
			$data = $cat_data[$cate_id];
			unset($cat_data);
		}
		if(!empty($cate_sign) && !empty($data)){
			$cats = get_category('','','',$cate_sign);
			$cate_id = $cats['category_id'];
			$g  = array_group_by($data,'category_id');
			$data = $g[$cate_id];
			unset($g);
		}
	}*/
	/**
	 * 头条新闻
	 */
	$first = array();
	if($top_first_pic_article  && $data){
		foreach ($data as $k=>$t){
			if(!empty($t['thumb'])){
				if($top_first_pic_article_num>1){
					//$first[] = format_content($t);
					unset($data[$k]);	
					if(count($first)==$top_first_pic_article_num)break;
				}else{
					//$first = format_content($t);
					unset($data[$k]);
					break;
				}
			}
		}
	}
	if($limit && isset($data[$limit-1])){
		$t_data = array_slice($data,0,$limit);
		$data = $t_data;
	}
	if($show_category_data && (!empty($cate_id) || !empty($cate_sign))){
		$cate_data = !empty($cate_id)?get_category('','',$cate_id):get_category('','','',$cate_sign);
		$data = array('category_data'=>$cate_data,'article_data'=>$data);
	}
	if($top_first_pic_article){
		$data = array('top_pic_news'=>$first,'data_list'=>array_reverse(array_reverse($data)));
	}
	$GLOBALS['smarty']->assign($assign,$data);
}
/**
 * 删缓存
 *
 * @param booelan $all
 * @param string $model
 * @param string $type
 */
//$all = false,$model = 'article',$type = 'All',$other = array()
function remove_pub_cache(){
	php188StaticCache::getInstance()->remove('php188_phpwms_all_content_string');
}
function select_db_for_smarty($item = array()){
	global $db;
	$assign = $item['assign'];
	if(empty($assign))exit('not exits assign tag');
	$sql = trim($item['sql']);
	$one = $item['one']=='true'?TRUE:FALSE;
	$result = array();
	if(!empty($sql) && preg_match('/^select/iU',strtolower($sql))){
		$result = filter_site_url_encode($db->fetch($sql,$one));
	}else{
		exit('error mysql string parten!');
	}
	return $GLOBALS['smarty']->assign($assign,$result);
}
/**
 * 根据提供的类型提取数据
 * @param string $model
 * @param int|string $cate_id 分类ID
 * @param int $channle_id 频道ID
 * @param string $cate_sign 分类的标志
 * @param string $type 类型
 * @param string $sort 排序
 * @param string $all_son 排序
 * @return string 构造好了的SQL
 */
function building_sql($model = 'article',$cate_id = '',$all_son = true,$channle_id = '',$cate_sign = '',$type = 'ALL',$sort = 'DESC',$limit = '0'){
	$models = get_models();
	$limit  = empty($limit)?50:$limit;
	$en_names = array_group_by($models,'en_name');
	$keys = array_keys($en_names);
	$m = strtolower($model);
	$model_id = !in_array($m,$keys)?1:$en_names[$model][0]['id'];
	$channle_id = to_int($channle_id);
	if(!empty($cate_id) || !empty($cate_sign)){
		$cat_select = ' , CAT.category_name,CAT.cate_sign,CAT.total ';
		$left_cat = ' LEFT JOIN ##__category AS CAT  
				ON C.category_id=CAT.category_id ';
	}
	if(!empty($channle_id)){
		$chanel_selct  = ' , CH.channel_name ';
		$left_channel = '  LEFT JOIN ##__channel AS CH ON C.channel_id = CH.channel_id  ';
	}
	$sql = "SELECT C.c_id,C.short_title,C.long_title,C.is_hot,C.is_show,C.channel_id,C.channel_model,C.category_id,
				C.is_new,C.thumb,C.is_top,C.post_user,C.edit_time,C.post_time,C.hits ,C.product_price 
				$cat_select $chanel_selct
				 FROM 
				##__contents AS C $left_cat $left_channel
		 		WHERE C.channel_model in($model_id) AND C.`is_show` = '1'  AND C.`is_recycle` = '0' 
	"; 		
	switch ($type){
		case 'new'://最新
			$sql .= " AND C.`is_new` = '1' "; 
			break;
		case 'hot'://热门
			$sql .=  " AND C.`is_hot` = '1' ";
			break;
		case 'top'://分类置顶
			$sql .= " AND C.`is_top` = '1'"; 
			break;
		case 'top_all'://全局置顶
			$sql .=  " AND C.is_top = '2'";
			break;
		case 'pic'://图片
			$sql .= " AND C.`is_pic` = '1' AND C.`thumb` <> ''"; 
			break;
		case 'slide'://首页幻灯
			$sql .=  " AND C.`is_index_slide` = '1' ";
			break;
		default: $sql .= " "; 
	}
	if(!empty($cate_id) && empty($cate_sign)){
		if($all_son && is_numeric($cate_id)){
			$cate_id = join(',',get_cate_son($cate_id,TRUE,array('category_id')));
		}else{
			$e = array_filter(explode(',',$cate_id));
			foreach ($e as &$v)$v = to_int($v);
			$cate_id = array_filter($e);
		}
		if(!empty($cate_id) && is_array($cate_id)){
			$cate_id = join(',',$cate_id);
			$sql .= " AND (C.`category_id` in($cate_id) )";
		}else{
			$sql .= " "; 
		}
	}
	if(empty($cate_id) && !empty($cate_sign)){
			$cate_sign_data = get_category('','','',$cate_sign);
			$c_id = $cate_sign_data['category_id'];
		if($all_son){
			$c_id = join(',',get_cate_son($c_id,TRUE,array('category_id')));
		}
		$c_id = is_array($c_id)&& !empty($c_id)?join(',',$c_id):$c_id;
		if(!empty($c_id)){
			$sql .= " AND C.`category_id` in($c_id) ";
		} 
	}
	if(!empty($channle_id)){
		$sql .= " AND C.`channel_id` in($channle_id) "; 
	}
	//前一50条
	$sql .= "  GROUP BY C.`c_id` ORDER BY  C.`c_id` $sort limit 0,$limit"; 	
	return $sql;
}
/**
* 得到 幻灯片图片
*/
function get_flash($item = array()){
	$assign = $item['assign'];
	if(empty($assign))exit('must has a assign tag');
	$result = get_cache('phpwms_slide');
	$res  = filter_site_url_decode(unserialize_deep($result));
	$GLOBALS['smarty']->assign($assign, $res);
}
/**
 * 根据指定的键值对数组排序
 *
 * @param array $array 要排序的数组
 * @param string $keyname 键值名称
 * @param int $sortDirection 排序方向
 *
 * @return array
 */
function array_column_sort($array, $keyname, $sortDirection = SORT_ASC){
    return array_sortby_multifields($array, array($keyname => $sortDirection));
}

/**
 * 将一个二维数组按照指定列进行排序，类似 SQL 语句中的 ORDER BY 这是一个内部函数 非外部调用
 *
 * @param array $rowset 
 * @param array $args
 */
function array_sortby_multifields($rowset, $args){
    $sortArray = array();
    $sortRule = '';
    foreach ($args as $sortField => $sortDir) {
        foreach ($rowset as $offset => $row) {
            @$sortArray[$sortField][$offset] = $row[$sortField];
        }
        $sortRule .= '$sortArray[\'' . $sortField . '\'], ' . $sortDir . ', ';
    }
    if (empty($sortArray) || empty($sortRule)) { return $rowset; }
    eval('array_multisort(' . $sortRule . '$rowset);');
    return $rowset;
}
function get_poll($poll_id, $title){
	global $db;
	$sql = "SELECT * FROM ##__user_option WHERE option_poll_id = '$poll_id' ORDER BY option_id";
	$result['data'] = $db->fetch($sql);
	$result['title'] = $title;
	$sum = 0;
	foreach($result['data'] as $data){
		$sum += $data['option_ticket'];
	}
	$result['sum'] = $sum;
	$result['count'] = count($result['data']);
	return $result;
}
function get_poll_one($item){
	global $db;
	$assign = $item['assign'];
	$poll_id = $item['id'];
	if(empty($assign) || empty($poll_id))exit('must has a assign tag');
	$sql = "SELECT * FROM ##__user_poll WHERE poll_id = '$poll_id'";
	$result = $db->fetch($sql, true);
	$result['op_sub_name'] = $result ['poll_type'] == 'checkbox' ?  'poll_value[]' : 'poll_value';
	$result['data'] = get_poll($poll_id,$result['title']);
	$GLOBALS['smarty']->assign($assign, $result);
}
function get_user_request($item){
	$assign = $item['assign'];
	$type = $item['type'];
	if(empty($assign) || empty($type))exit('must has a assign tag');
	$result = php188StaticCache::getInstance()->get('phpwms_user_request');
	if(empty($result[$type])){
		global $db;
		$sql = "SELECT  `title`, `post_time` FROM ##__user_request WHERE request_type = '$type' AND state != '0' ORDER BY post_time desc LIMIT 0, 5";
		$result[$type] = $db->fetch($sql);
		php188StaticCache::getInstance()->save($result, 'phpwms_user_request');
	}
	$GLOBALS['smarty']->assign($assign, $result[$type]);
}
function search_highlight_str($str,$rReplace, $sPrefix = '<font color="red">', $sPostfix = '</font>'){
	if(empty($str) || empty($rReplace)){
		return $str;//如果有一个为空 直接返回字符串
	}
	// 得到字符串长度
	$strlength = strlen($str);// 字符串的长度
	$prelength = strlen($sPrefix);// 要添加 前缀的长度
	$postlength = strlen($sPostfix);//要添加 后缀的长度
	$rellength = strlen($rReplace);//要替换字符串的长度
	$relstrlower = strtolower($rReplace);// 将要替换的字符串转化为小写
	if($rellength > $strlength){
		return $str;// 判断 替换的长度大于字符串长度，直接返回原来的字符串
	}
	// 开始遍历
	for ($i = 0; $i <= $strlength- $rellength; ++$i){
		$substr = substr($str, $i, $rellength);
		$substrlower = strtolower($substr);//也转换为小写来判断
		// 判断是否相等
		if($substrlower == $relstrlower){
			// 开始拼凑字符串
			$str = substr($str, 0, $i) . $sPrefix . $substr . $sPostfix . substr($str,$i + $rellength, $strlength);
			//重新 矫正 字符串长度
			$strlength += $prelength + $postlength;//重新计算字符串总长度
			$i += $rellength - 1 + $prelength + $postlength;// 改变 $i 变量的值
		}
	}
	return  $str;
}
?>