<?php
/**
 * 定义模板相关函数
 */
load('extend');
load('ydLib');

//特效
function get_slide($selector, $autoPage, $titCell, $mainCell, $autoPlay, $interTime, $delayTime, $defaultIndex, 
		$trigger, $scroll, $vis, $prevCell, $nextCell, $titOnClassName, $effect){
	$defaultIndex =   !empty($defaultIndex) ?  "defaultIndex:".$defaultIndex."," : '';
	$data = "<script type='text/javascript'>
		$(document).ready(function(){
			$('$selector').slide({
				$autoPage $titCell $mainCell $autoPlay $interTime $delayTime $defaultIndex $trigger $scroll $vis $prevCell $nextCell $titOnClassName $effect
			});
		})
	</script>";
	return $data;
}

//获取顶层菜单
//$menuOwner:  0：会员，1:管理员
//$groupid: 0:表示不受分组权限的限制
function get_menu_top($menuOwner = 0){
	$m = D('Admin/MenuTop');
	$data = $m->getMenuTop( array('MenuOwner'=>$menuOwner) );
	return $data;
}

function get_menu_group($MenuTopID = 0){
	$m = D('Admin/MenuGroup');
	$data = $m->getMenuGroup( $MenuTopID, 1);
	return $data;
}

function get_menu($menuGroupID = 0){
	$m = D('Admin/Menu');
	$data = $m->getMenu( $menuGroupID, 1);
	return $data;
}

function get_menu_operation(){
	$m = D('Admin/MenuOperation');
	$data = $m->getMenuOperationPath( ACTION_NAME, MODULE_NAME, GROUP_NAME);
	return $data;
}

//频道信息
function get_channel($parentID = 0, $depth=1, $prefix='', $idlist=false){
	$channel = D('Admin/Channel');
	$data = $channel->getChannelList($parentID, $depth, $prefix, $idlist);
	$count = count( $data );
	if( empty($data) ) return false;  //当$data为false时，count($data)返回1，因此必选先判断$data是否为空
	//找出ChannelDepth最大值
	$maxDepth = -9999;
	for($j = 0; $j < $count; $j++){
		if( $data[$j]['ChannelDepth'] > $maxDepth ) {
			$maxDepth = $data[$j]['ChannelDepth'];
		}
	}
	
	for($i = 0; $i < $count; $i++){
		if( 33 == $data[$i]['ChannelModelID'] && trim($data[$i]['LinkUrl']) != '' ){ //33:转向链接
			if( GROUP_NAME == 'Wap' && 'http' != strtolower( substr($data[$i]['LinkUrl'], 0, 4))){
				//站内链接手机站，如：1.html ,自动加上全路径
				$data[$i]['ChannelUrl'] = WapHomeUrl().'/'.ltrim($data[$i]['LinkUrl'],'/');
			}else{
				$data[$i]['ChannelUrl'] = $data[$i]['LinkUrl'];
			}
		}else{
			$data[$i]['ChannelUrl'] = ChannelUrl($data[$i]['ChannelID'], $data[$i]['Html'], '');
		}
		$data[$i]['ChannelDepth'] = ($maxDepth - $data[$i]['ChannelDepth'] + 1);
		$data[$i]['Count'] = $count;
		//$data[$i]['HasChild'] = $channel->hasChildChannel($data[$i]['ChannelID']) ? 1 : 0;
	}
	return $data;
}

//专题信息
function get_special($ChannelID = 0, $idlist=-1){
	$m = D('Admin/Special');
	$data = $m->getSpecial($ChannelID, 1, $idlist);
	if( empty($data) ) return false; 
	return $data;
}

//频道信息
function get_navigation($parentID = 0, $depth=1, $idlist=-1, $isshow=1){
	if( !is_numeric($parentID) ) return false;
	$channel = D('Admin/Channel');
	$data = $channel->getNavigation($parentID, $depth, $idlist, $isshow);
	if( empty($data) ) return false;  //当$data为false时，count($data)返回1，因此必选先判断$data是否为空
	$count = count( $data );
	
	//找出ChannelDepth最大值，归一化ChannelDepth，从0开始
	$maxDepth = -9999;
	for($j = 0; $j < $count; $j++){
		if( $data[$j]['ChannelDepth'] > $maxDepth ) {
			$maxDepth = $data[$j]['ChannelDepth'];
		}
	}

	for($i = 0; $i < $count; $i++){
		if( 33 == $data[$i]['ChannelModelID'] && trim($data[$i]['LinkUrl']) != ''){ //33:转向链接
			if( GROUP_NAME == 'Wap' && 'http' != strtolower( substr($data[$i]['LinkUrl'], 0, 4))){
				//站内链接手机站，如：1.html ,自动加上全路径
				$data[$i]['ChannelUrl'] = WapHomeUrl().'/'.ltrim($data[$i]['LinkUrl'],'/');
			}else{
				$data[$i]['ChannelUrl'] = $data[$i]['LinkUrl'];
			}
		}else{
			$data[$i]['ChannelUrl'] = ChannelUrl($data[$i]['ChannelID'], $data[$i]['Html'], '');
		}
		$data[$i]['ChannelDepth'] = ($maxDepth - $data[$i]['ChannelDepth'] + 1);
		//$data[$i]['HasChild'] = $channel->hasChildChannel($data[$i]['ChannelID']) ? 1 : 0;
		$data[$i]['Count'] = $count;
	}
	return $data;
}

//微信应用列表
function get_wx_app(){
	$m = D('Admin/WxApp');
	$App = $m->getApp(-1, -1, -1, '', 1);
	$n = count($App);
	
	for($i=0; $i < $n; $i++){
		switch($App[$i]['AppTypeID']){
			case 1: //微活动
				$type = substr($App[$i]['AppParameter'], 0, 1);
				$App[$i]['Keyword'] = ($type==0) ? '大转盘' : '刮刮卡';
				break;
			case 2:  //微投票
				$App[$i]['Keyword'] = '投票';
				break;
			case 5:  //微调查
				$App[$i]['Keyword'] = '调查';
				break;
			default:
				break;
		}
	}
	
	$wa= D('Admin/WxApptype');
	$type = $wa->getAppType(1);
	foreach($type as $k=>$v){
		$t[ $v['AppTypeID'] ] = $v['AppTypeName'];
	}
	
	$applist = include CONF_PATH.'wxapp.php';  //加载微信配置文件
	foreach ($applist as $k=>$v){
		$App[] = array(
				"AppID"=>$k, 
				'AppName'=>$v['name'], 
				'Keyword'=>$k, 
				'Description'=>$v['description'],
				'AppTypeName'=>$t[ $v['type'] ],
		);
	}
	return $App;
}

//网站地图
function get_sitemap($ChannelID = 0, $depth=-1, $prefix='&nbsp;&nbsp;'){
	return get_navigation($ChannelID, $depth);
}

//友情链接
function get_link($linkClassID = 0, $top = 10){
	$m = D('Admin/Link');
	$data = $m->getLink(0, $top, $linkClassID, 1);
	return $data;
}

//有利于自定义表单
function get_banner_list($BannerGroupID = -1){
	$m = D('Admin/Banner');
	$data = $m->getBanner(1, $BannerGroupID);
	return $data;
}

function get_bannergroup(){
	$m = D('Admin/BannerGroup');
	$data = $m->getBannerGroup();
	return $data;
}

//人才招聘
function get_job($top = 10, $nowPage = 0){
	$m = D('Admin/Job');
	if( $nowPage != 0 ){//分页, $labelID和$top无效, 获取指定分页数据
		$t = array('cn'=>8, 'en'=>4);
		$PageSize = PageSize( $t[LANG_SET] ); //页面大小
		$PageSize = ($PageSize > 0) ? $PageSize : 20;
		$nowPage = ( $nowPage - 1 > 0 ) ? ( $nowPage - 1 ) : 0;
		$offset = $nowPage * $PageSize;
		$data = $m->getJob($offset, $PageSize, 1);
	}else{ //不分页
		$data = $m->getJob(0, $top, 1);
	}
	return $data;
}

//广告
function get_ad($adid, $id, $width, $height, $delay=10, $step=1, $left='8px', $right='8px', $top='260px'){
	$m = D('Admin/Ad');
	$data = $m->where("IsEnable=1 and AdID=$adid")->find();
	
	$AdTypeID = $data['AdTypeID'];
	$des = $data['AdName']."[".$data['AdTime']."]&#13".$data['AdDescription'];
	$adUrl = $data['AdUrl'];
	$adContent = $data['AdContent'];
	$adName = $data['AdName'];
	
	$parseStr = "";
	switch($AdTypeID){
		case 1:   //图片广告
			$parseStr = "<!--图片广告start-->";
			if(empty($adUrl)){
				$parseStr .= "<img $width $height  src='$adContent' border='0' alt='$des' title='$des' />";
			}else{
				$parseStr .= "<a id='$id' href='$adUrl' target='_blank'><img $width $height  src='$adContent' border='0' alt='$des' title='$des' /></a>";
			}
			$parseStr .= "<!--图片广告end-->";
			break;
		case 2:   //Flash广告
			$parseStr .=  "<!--Flash广告start-->\n";
			$parseStr .= "<embed $width $height src=\"".$data['AdContent']."\" ";
			$parseStr .= " quality=\"high\" type=\"application/x-shockwave-flash\" wmode=\"transparent\"  ";
			$parseStr .= " pluginspage=\"http://www.macromedia.com/go/getflashplayer\" allowScriptAccess=\"always\">";
			$parseStr .= "</embed>";
			$parseStr .=  "\n<!--Flash广告start-->";
			break;
		case 3:   //漂浮广告
			$width    = !empty($width)   ? "'imgHeight':".$width."," : '';
			$height   = !empty($height) ? "'imgWidth':".$height."," : '';
			$closefloatad = __ROOT__."/Public/Images/closefloatad.png";
			$parseStr .= "
			<!--漂浮广告start-->
			<script type='text/javascript'>
				$(function(){
					$.floatingAd({
						delay: $delay,
						isLinkClosed: false,
						ad:	[{
							headFilter: 0.1,
							'img': '$adContent',
							$width
							$height
							'linkUrl': '$adUrl',
							'z-index': 100,
							'title': '$adName',
							'closed-icon': '$closefloatad'
						}]
					});
				});
			</script>
			<!--漂浮广告end-->";
			break;
		case 4:   //代码广告
			$parseStr = "<!--代码广告start-->\n".$data['AdContent']."\n<!--代码广告end-->";
			break;
		case 5: //对联广告
			$top1 = str_ireplace('px', '', $top);
			
			$duilianImg = $data['AdContent'];
			$duilianImg = str_replace(array("\r\n","\r"), "\n", $duilianImg);
			$duilianImg = (array)explode ("\n", $duilianImg);
			
			$duilianImg1 = $duilianImg[0];
			$duilianImg2 = !empty($duilianImg[1]) ? $duilianImg[1] : $duilianImg[0];

			$duilianUrl = (array)explode(',', $data['AdUrl']);
			$duilianUrl1 = $duilianUrl[0];
			$duilianUrl2 = !empty($duilianUrl[1]) ? $duilianUrl[1] : $duilianUrl[0];

			$adclose = __ROOT__."/Public/Images/adclose.gif";
			$parseStr = "<!--对联广告start-->
			<style>
			.duilian$id{top:$top; position:absolute; display:none;}
			.duilianclose$id{ cursor:pointer; }
			</style>
			<div class='duilian$id' style='left:$left;'>
			<div><a href='$duilianUrl1' target='_blank'><img src='$duilianImg1' $width $height  alt='$des' title='$des'></a></div>
			<img  class='duilianclose$id' src='$adclose' $width  height='14px'>
			</div>
			<div class='duilian$id'  style='right:$right;'>
			<div><a  href='$duilianUrl2'  target='_blank'><img src='$duilianImg2' $width $height  alt='$des' title='$des'></a></div>
			<img class='duilianclose$id' src='$adclose' $width  height='14px'>
			</div>
			<script type='text/javascript'>
			$(document).ready(function(){
				var duilian = $('div.duilian$id');
				var window_w = $(window).width();
				if( window_w > 1000 ){ duilian.show(); }
				$(window).scroll(function(){
				var scrollTop = $(window).scrollTop();
				duilian.stop().animate({top:scrollTop+$top1}, 800);
			});
			$('img.duilianclose$id').click(function(){
				$(this).parent().hide();
				return false;
			});
			});
			</script>
			<!--对联广告end-->";
			break;
		}
		return $parseStr;
}

function AdCount($adGroupID){
	$m = D('Admin/Ad');
	$n = $m->getAdCount($adGroupID);
	return $n;
}

function get_ad_list($groupID = -1){
	$m = D('Admin/Ad');
	$p['IsEnable'] = 1;
	if( $groupID != -1){
		$p['AdGroupID'] = $groupID;
	}
	$data = $m->getAd(-1, -1, $p);
	return $data;
}

function get_adgroup(){
	$m = D('Admin/AdGroup');
	$p['IsEnable'] = 1;
	$data = $m->getAdGroup($p);
	return $data;
}

//在线客服列表
function get_support($qqstyle){
	$m = D('Admin/Support');
	$data = $m->getSupport(1);
	$n = count($data);
	for($i = 0; $i < $n; $i++){
		switch( $data[$i]['SupportTypeID']){
			case 2://淘宝旺旺
				$data[$i]['SupportFace'] = yd_taobao_face($data[$i]['SupportNumber']);
				break;
			case 3://阿里旺旺
				$data[$i]['SupportFace'] = yd_ali_face($data[$i] ['SupportNumber'] );
				break;
			case 4 : // 微软MSN
				$data [$i] ['SupportFace'] = yd_msn_face ( $data [$i] ['SupportNumber'] );
				break;
			case 5 : // Skype
				$data [$i] ['SupportFace'] = yd_skype_face ( $data [$i] ['SupportNumber'] );
				break;
			case 6://国际版阿里旺旺
				$data[$i]['SupportFace'] = yd_interali_face($data[$i] ['SupportNumber'] );
				break;
			case 7: //自定义
				$data[$i]['SupportFace'] = $data[$i]['SupportNumber'];
				break;
			case 1 : // qq
			default :
				$data [$i] ['SupportFace'] = yd_qq_face ( $data [$i] ['SupportNumber'], $qqstyle );
				break;
		}
	}
	return $data;
}

//获取标签数据
function get_label($channelmodelid){
	$m = D('Admin/Label');
	$data = $m->getLabel($channelmodelid,-1,1);
	return $data;
}

//获取表单字段列表
function get_form($channelmodelid){
	$m = D('Admin/Attribute');
	$group = $m->getGroup($channelmodelid);
	$Attribute = $m->getAttribute($channelmodelid);
	foreach($group as $g){
		foreach ($Attribute as $a){
			if( $a['GroupID'] == $g['AttributeID'] ){
				$data[] = $a;
			}
		}
	}
	unset($group, $Attribute);
	return $data;
}

//主要用于前台模型调用，获取模型字段列表
function get_model($channelmodelid, $idlist=-1){
	$index = array('en'=>1, 'cn'=>0);
	$id = $index[ get_language_mark() ];
	$m = D('Admin/Attribute');
	$group = $m->getGroup($channelmodelid);
	$Attribute = $m->getAttribute($channelmodelid, false, 1, -1, $idlist);
	$n = 0;
	foreach($group as $g){
		foreach ($Attribute as $a){
			if( $a['GroupID'] == $g['AttributeID'] ){
				$DisplayName = explode(',', $a['DisplayName']);
				$a['DisplayName'] = isset($DisplayName[$id]) ? $DisplayName[$id] : $DisplayName[0];
				$data[$n] = $a;
				
				if( stripos($a['DisplayType'], 'radio') !== false ){
					$Selected = "checked='checked'";
				}else if(stripos($a['DisplayType'], 'checkbox') !== false ){
					$Selected = "checked='checked'";
				}else if(stripos($a['DisplayType'], 'select') !== false ){
					$Selected = "selected='selected'";
				}
				//获取具体项目
				if(stripos($a['DisplayType'], 'radio') !== false 
						|| stripos($a['DisplayType'], 'checkbox') !== false 
						||  stripos($a['DisplayType'], 'select') !== false){
					$defaultValue = str_replace(array("\r\n","\r"), "\n", $a['DisplayValue']);
					$item = explode("\n", $defaultValue);
					for($j = 0; $j < count($item); $j++){
						$itemString = explode(',', $item[$j]);
						$itemString = isset($itemString[$id]) ? $itemString[$id] : $itemString[0];
						$t = explode ('|', $itemString ); //value|item|是否是默认
						$sel=empty($t[2]) ? '' : $Selected;
						$data[$n]['Item'][$j] = array('Value'=> $t[0], 'Text'=>$t[1], 'Selected'=>$sel);
					}
				}
				$n++;
			}
		}
	}
	unset($group, $Attribute);
	return $data;
}

//获取订阅邮件分类
function get_mail_class(){
	$m = D('Admin/MailClass');
	$data = $m->getMailClass(1);
	return $data;
}

//获取友情链接分类
function get_link_class(){
	$m = D('Admin/LinkClass');
	$data = $m->getLinkClass();
	return $data;
}

function get_videopalyer($data){
	import("@.Common.YdVideoPlayer");
	$v = new YdVideoPlayer( $data );
	$html = $v->render();
	return $html;
}

//banner
function get_banner($width, $height, $time, $showtext, $textcolor, $textbgcolor,$textbgalpha,$bartextcolor,$barovercolor,$baroutcolor,$channelid,$groupid=-1,$top=-1,$labelid=-1){
	$files = '';  $links = ''; $texts = '';
	if(empty($channelid) ){
		$m = D('Admin/Banner');
		$data = $m->getBanner(1 , $groupid);
		$count = count($data);
		if( $count <= 0 ) return '';
		if( $count == 1 ) return get_one_banner($data [0]['BannerImage'], $data [0]['BannerUrl'] ,$data [0]['BannerName'], $width, $height);
		for($i = 0; $i < $count; $i++){
			$files .= '|'.$data[$i]['BannerImage'];
			$links .= '|'.$data[$i]['BannerUrl'];
			$texts .= '|'.$data[$i]['BannerName'];
		}
	}else{
		$m = D('Admin/Info');
		$data = $m->getInfoImage($channelid, $top, $labelid);
		$count = count($data);
		if( $count <= 0 ) return '';
		if( $count == 1 ) return get_one_banner($data[0]['InfoPicture'], InfoUrl( $data [0]['InfoID'] ),$data [0]['InfoTitle'], $width, $height);
		for($i = 0; $i < $count; $i++){
			$files .= '|'.$data[$i]['InfoPicture'];
			$links .= '|'.InfoUrl($data[$i]['InfoID']);
			$texts .= '|'. $data[$i]['InfoTitle'];
		}
	}
	
	$files = substr($files, 1);
	$links = substr($links, 1);
	$texts = ($showtext==1) ? substr($texts, 1) : ''; //控制是否显示标题
	
	$effectFile = __ROOT__.'/Public/effect/normal.swf';
	
	//-- config:参数 自动播放时间(秒)|文字颜色|文字背景色|文字背景透明度|按键数字颜色|当前按键颜色|普
	$parseStr = "<script type=\"text/javascript\">
	var swf_width = '$width';
	var swf_height = '$height';
	var config = '$time|$textcolor|$textbgcolor|$textbgalpha|$bartextcolor|$barovercolor|$baroutcolor';
	var files = '$files';
	var links = '$links';
	var texts = '$texts';
	
	document.write('<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0\" width=\"'+ swf_width +'\" height=\"'+ swf_height +'\">');
	document.write('<param name=\"movie\" value=\"$effectFile\" />');
	document.write('<param name=\"quality\" value=\"high\" />');
	document.write('<param name=\"menu\" value=\"false\" />');
	document.write('<param name=wmode value=\"opaque\" />');
	document.write('<param name=\"FlashVars\" value=\"config='+config+'&bcastr_flie='+files+'&bcastr_link='+links+'&bcastr_title='+texts+'\" />');
	document.write('<embed src=\"$effectFile\" wmode=\"opaque\" FlashVars=\"config='+config+'&bcastr_flie='+files+'&bcastr_link='+links+'&bcastr_title='+texts+'& menu=\"false\" quality=\"high\" width=\"'+ swf_width +'\" height=\"'+ swf_height +'\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />');
	document.write('</object>');
	</script>";
	return $parseStr;
}

//输出banner1，存在Bug，如仅支持jpg，偶尔图片显示空白
function get_banner1($width, $height, $time, $showtext, $channelid,$groupid=-1,$top=-1,$labelid=-1) {
	$files = $links = $texts = '';
	if (empty ( $channelid )) {
		$m = D ( 'Admin/Banner' );
		$data = $m->getBanner ( 1 , $groupid);
		$count = count ( $data );
		if( $count <= 0 ) return '';
		if( $count == 1 ) return get_one_banner($data [0]['BannerImage'], $data [0]['BannerUrl'] ,$data [0]['BannerName'],$width, $height);
		for($i = 0; $i < $count; $i ++) {
			$files .= '|' . $data [$i]['BannerImage'];
			$links .= '|' . $data [$i]['BannerUrl'];
			$texts .= '|' . $data [$i]['BannerName'];
		}
	} else { // 取频道图片
		$m = D ( 'Admin/Info' );
		$data = $m->getInfoImage ( $channelid , $top, $labelid);
		$count = count ( $data );
		if( $count <= 0 ) return '';
		if( $count == 1 ) return get_one_banner($data[0]['InfoPicture'], InfoUrl( $data [0]['InfoID'] ),$data [0]['InfoTitle'],$width, $height);
		for($i = 0; $i < $count; $i ++) {
			$files .= '|' . $data [$i] ['InfoPicture'];
			$links .= '|' . InfoUrl ( $data [$i] ['InfoID'] );
			$texts .= '|' . $data [$i] ['InfoTitle'];
		}
	}
	
	$files = substr ( $files, 1 );
	$links = substr ( $links, 1 );
	$texts = substr ( $texts, 1 );
	$effectFile = __ROOT__ . '/Public/effect/slide.swf';
	
	// -- config:参数 自动播放时间(秒)|文字颜色|文字背景色|文字背景透明度|按键数字颜色|当前按键颜色|普
	$parseStr = "<script type='text/javascript'>
	var interval_time=$time;
	var focus_width='$width';
	var focus_height='$height';
	var text_height = $showtext;
	var text_align= 'center';
	var swf_height = parseInt(focus_height)+parseInt(text_height);
	
	var pics= '$files'
	var links='$links'
	var texts='$texts'
		
	document.write('<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\" width=\"'+ focus_width +'\" height=\"'+ swf_height +'\">');
	document.write('<param name=\"movie\" value=\"$effectFile\"><param name=\"quality\" value=\"high\"><param name=\"bgcolor\" value=\"#ffffff\">');
	document.write('<param name=\"menu\" value=\"false\"><param name=wmode value=\"transparent\">');
	document.write('<param name=\"FlashVars\" value=\"pics='+pics+'&links='+links+'&texts='+texts+'&borderwidth='+focus_width+'&borderheight='+focus_height+'&textheight='+text_height+'&text_align='+text_align+'&interval_time='+interval_time+'\">');
	document.write('<embed src=\"$effectFile\" wmode=\"opaque\" FlashVars=\"pics='+pics+'&links='+links+'&texts='+texts+'&borderwidth='+focus_width+'&borderheight='+focus_height+'&textheight='+text_height+'&text_align='+text_align+'&interval_time='+interval_time+'\" menu=\"false\" bgcolor=\"#ffffff\"  quality=\"high\" width=\"'+ focus_width +'\" height=\"'+ swf_height +'\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />');
	document.write('</object>');
	</script>";
	return $parseStr;
}
// banner2
function get_banner2($width, $height, $time, $showtext, $channelid,$groupid=-1,$top=-1,$labelid=-1) {
	return get_banner1 ( $width, $height, $time, $showtext, $channelid  , $groupid, $top, $labelid);
}
// banner3
function get_banner3($width, $height, $time, $showtext, $channelid,$groupid=-1,$top=-1,$labelid=-1) {
	// symbol: linear（直线）和circular（圆形，译注：类似倒计时，顺时针）。
	$xml = "<?xml version='1.0' encoding='utf-8' ?>
	<cu3er>
	<settings>
	<auto_play>
	<defaults symbol='circular' time='$time' /><!--倒计时按钮的位置-->
	<tweenIn width='30' height='30' tint='0xFF0000' alpha='0.5'/>
	<tweenOver alpha='1'/>
	</auto_play>
	<prev_button>
	<defaults round_corners='5,5,5,5'/>
	<tweenOver tint='0xFFFFFF' scaleX='1.1' scaleY='1.1'/>
	<tweenOut tint='0x000000' />
	</prev_button>
	<prev_symbol>
	<tweenOver tint='0x000000' />
	</prev_symbol>
	<next_button>
	<defaults round_corners='5,5,5,5'/>
	<tweenOver tint='0xFFFFFF'  scaleX='1.1' scaleY='1.1'/>
	<tweenOut tint='0x000000' />
	</next_button>
	<next_symbol>
	<tweenOver tint='0x000000' />
	</next_symbol>
	</settings>
	<slides>";
	
	//num – 每次变换包含的切片数 slicing – 立方体切片方向：水平horizontal或垂直vertical
	// direction - 变换方向 / 立方体旋转方向：上up、下、左、右
	//shader – transition shading type – none, flat, phong
	//<transition num="4" direction="right" shader="flat" />
	//$transition[] = "<transition num='4' slicing='vertical' direction='down' />";
	$transition = array(0=>'<transition num="3" slicing="vertical" direction="down"/>',
	    1=>'<transition num="4" direction="right" shader="flat" />',
	    2=>'<transition num="6" slicing="vertical" direction="up" shader="phong" delay="0.05" z_multiplier="4" />',
	    3=>'',
	);
	$n = count($transition)-1;
	if(empty($channelid) ){
		$m = D('Admin/Banner');
		$data = $m->getBanner(1 , $groupid);
		$count = count($data);
		if( $count <= 0 ) return '';
		if( $count == 1 ) return get_one_banner($data [0]['BannerImage'], $data [0]['BannerUrl'] ,$data [0]['BannerName'], $width, $height);
		for($i = 0; $i < $count; $i++){
			$title = trim($data[$i]['BannerName']);
			$img = $data[$i]['BannerImage'];
			$url = $data[$i]['BannerUrl'];
			$xml .= "\n<slide><url>$img</url>";
			if( $showtext && $title !='' ){
			    $xml .= "\n<description>\n<link target='_blank'>$url</link>\n<heading>$title</heading>\n<paragraph></paragraph>\n</description>";
			}else{
			    $xml .= "\n<link target='_blank'>$url</link>";
			}
			$tr = ($i != $count - 1) ? $transition[$i % $n] : '';
			$xml .= "\n</slide>\n$tr";
		}
	}else{ //取频道图片
			$m = D('Admin/Info');
			$data = $m->getInfoImage($channelid, $top, $labelid);
			$count = count($data);
			if( $count <= 0 ) return '';
			if( $count == 1 ) return get_one_banner($data[0]['InfoPicture'], InfoUrl( $data [0]['InfoID'] ),$data [0]['InfoTitle'], $width, $height);
			for($i = 0; $i < $count; $i++){
				$title = $data[$i]['InfoTitle'];
				$para = $data[$i]['InfoSContent'];
				$img = $data[$i]['InfoPicture'];
				$url = InfoUrl($data[$i]['InfoID']);
				$xml .= "\n<slide><url>$img</url>";
				if( $showtext && $title !='' ){
				$xml .= "\n<description>\n<link target='_blank'>$url</link>\n<heading>$title</heading>\n<paragraph>$para</paragraph>\n</description>";
				}else{
				$xml .= "\n<link target='_blank'>$url</link>";
				}
				$tr = ($i != $count - 1) ? $transition[$i % $n] : '';
				$xml .= "\n</slide>\n$tr";
		  }
	}
	$xml .= "\n</slides>\n</cu3er>";
	$fileName = RUNTIME_PATH.'data/banner3.xml';
	$b = file_put_contents($fileName, $xml);
	if( !b ) return false;
	$effectFile = __ROOT__.'/Public/effect/cu3er.swf';
	
	$parseStr = "<script type='text/javascript'>
	var swf_width='$width';
	var swf_height = '$height';
	var xml = '$fileName';
	document.write('<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\" width=\"'+ swf_width +'\" height=\"'+ swf_height +'\">');
	document.write('<param name=\"movie\" value=\"$effectFile\"><param name=\"quality\" value=\"high\"><param name=\"bgcolor\" value=\"#ffffff\">');
	document.write('<param name=\"menu\" value=\"false\"><param name=wmode value=\"transparent\">');
	document.write('<param name=\"FlashVars\" value=\"xml='+xml+'\">');
	document.write('<embed src=\"$effectFile\" wmode=\"opaque\" FlashVars=\"xml='+xml+'\" menu=\"false\" bgcolor=\"#ffffff\"  quality=\"high\" width=\"'+ swf_width +'\" height=\"'+ swf_height +'\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />');
	document.write('</object>');
	</script>";
	return $parseStr;
}
//输出单个媒体文件支持：图像，swf
//$url仅对图像格式文件有效
function get_one_banner($image, $url, $title, $width, $height){
	$ext = strtolower( yd_file_ext($image) );
	$str = '';
	if( empty($ext) ) return $str;
	if($ext == 'swf'){ //flash动画
		$str = "
		<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\" width=\"$width\" height=\"$height\">
		<param name=\"movie\" value=\"$image\">
		<param name=\"quality\" value=\"high\">
		<param name=\"bgcolor\" value=\"#ffffff\">
		<param name=\"menu\" value=\"false\">
		<param name=wmode value=\"transparent\">
		<embed src=\"$image\" wmode=\"opaque\"  menu=\"false\" bgcolor=\"#ffffff\"  quality=\"high\" width=\"$width\" height=\"$height\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />
		</object>";
	}else{ //图像
		//$width .= 'px'; $height .= 'px';  //必须加上px image的宽度或高度才生效
		//经测试不加px，正常
		if( is_numeric($width) ) $width .= 'px';
		if( is_numeric($height) ) $height .= 'px';
		if( empty($url) ){
			$str = "<img src='$image' alt='$title'  style=\"width:$width;height:$height\"  />";
		}else {
			$str = "<a href='$url' target='_blank'><img src='$image' alt='$title'    style='width:$width;height:$height;border:0px'  /></a>";
		}
	}
	return $str;
}

//客户留言
function get_guestbook($top = 10, $nowPage = 0){
	$m = D('Admin/Guestbook');
	if( $nowPage != 0 ){//分页, $labelID和$top无效, 获取指定分页数据
		$t = array('cn'=>9, 'en'=>5);
		$PageSize = PageSize( $t[LANG_SET] ); //页面大小
		$PageSize = ($PageSize > 0) ? $PageSize : 20;
		$nowPage = ( $nowPage - 1 > 0 ) ? ( $nowPage - 1 ) : 0;
		$offset = $nowPage * $PageSize;
		$data = $m->getMessage($offset, $PageSize, 1);
	}else{ //不分页
		$data = $m->getMessage(0, $top, 1);
	}
	return $data;
}

//获取评论信息
function get_comment($infoid, $nowPage = 0){
	$m = D('Admin/Comment');
	if( $nowPage != 0 ){
		$c = YdCache::readComment();
		$PageSize = $c['COMMENT_PAGE_SIZE']; //页面大小
		$PageSize = ($PageSize > 0) ? $PageSize : 20;
		$nowPage = ( $nowPage - 1 > 0 ) ? ( $nowPage - 1 ) : 0;
		$offset = $nowPage * $PageSize;
		$data = $m->getComment($offset, $PageSize, -1, $infoid, 1);  //-1:所有人的评论，1: 审核通过的
	}else{ //不分页
		$data = $m->getComment(-1, -1, -1, $infoid, 1);
	}
	return $data;
}

//投票调查
function get_vote_list($id){
	$m = D('Admin/WxApp');
	$data = $m->findTagVote($id);
	return $data;
}

function get_infoalbum($infoid){
	$m = D('Admin/Info');
	$data = $m->getInfoAlbum( $infoid );
	return $data;
}

function get_inforelation($infoid){
	$m = D('Admin/Info');
	$data = $m->getInfoRelation($infoid);
	if( empty($data) ) return false;
	$Total = count($data);
	for($i = 0; $i < $Total; $i++){
		$data[$i]['InfoSTitle'] = $data[$i]['InfoTitle'];
		$data[$i]['InfoUrl'] = InfoUrl($data[$i]['InfoID'], $data[$i]['Html'], $data[$i]['LinkUrl'], false, $data[$i]['ChannelID']);
		$data[$i]['ChannelUrl'] = ChannelUrl($data[$i]['ChannelID'], $data[$i]['ChannelHtml'], $data[$i]['ChannelLinkUrl']);
		$data[$i]['Count'] = $Total;
	}
	return $data;
}

function get_tag($infoid){
	$m = D('Admin/Info');
	$str = $m->getTag($infoid);
	if( empty($str) ) return false;
	$data = explode(',', $str);
	$n = count($data);
	$tag = false;
	for($i = 0; $i < $n; $i++){
		$name = trim($data[$i]);
		$url = InfoSearchAction();
		$url .= (strpos($url, '?') === false ) ? '?' : '&';
		$url .= 'Keywords='.urlencode($name);
		$tag[$i]['TagName'] = $name;
		$tag[$i]['TagUrl'] = $url;
	}
	return $tag;
}

//获取信息
function get_info($channelID = 0, $specialID = 0, $top = 10, $timeFormat='Y-m-d', $titleLen = 0, $suffix='...', $labelID='', $nowPage=0, $keywords='', $orderby=false){
	$m = D('Admin/Info');
	$options = array('Time'=>1);
	if( $nowPage != 0 ){//分页, $labelID和$top无效, 获取指定分页数据
		$Total = $m->getCount($channelID, 1, 1, $keywords, -1, $specialID, $labelID, 1, -1, $options); //获取总记录数$page
		$PageSize = D('Admin/Channel')->where("ChannelID=$channelID")->getField('PageSize'); //页面大小
		$PageSize = ($PageSize > 0) ? $PageSize : 20;
		$nowPage = ( $nowPage - 1 > 0 ) ? ( $nowPage - 1 ) : 0;
		$offset = $nowPage * $PageSize;
		$data = $m->getInfo($offset, $PageSize, $channelID, 1, 1, $labelID, $keywords, -1, $specialID, 1, $orderby, -1, $options);
	}else{ //不分页
		$data = $m->getInfo(0, $top, $channelID, 1, 1, $labelID, $keywords, -1, $specialID, 1, $orderby, -1, $options);
		$Total = count($data);
	}
	if( empty($data) ) return false;  //当$data为false时，count($data)返回1，因此必选先判断$data是否为空
	$count = count( $data );
	//$html = C('HTML_CACHE_ON');
	for($i = 0; $i < $count; $i++){
		//当$titleLen＝0时这样写会浪费CPU资源。$len = mb_strlen( $data[$i]['InfoTitle'] , 'utf-8'); //1个汉字算1个长度
		if( $titleLen > 0 &&  mb_strlen( $data[$i]['InfoTitle'] , 'utf-8') > $titleLen ){ //截取字符串
			$data[$i]['InfoSTitle'] = msubstr( $data[$i]['InfoTitle'], 0, $titleLen, 'utf-8', $suffix);
		}else{
			$data[$i]['InfoSTitle'] = $data[$i]['InfoTitle'];
		}
		//if($html){
		//	$data[$i]['InfoHit'] = "<script src='".__GROUP__."/public/getInfoHit?infoid={$data[$i]['InfoID']}'></script>";
		//}	
		$data[$i]['InfoTime'] = date($timeFormat, strtotime( $data[$i]['InfoTime'] ) );  //格式化时间
		$data[$i]['InfoUrl'] = InfoUrl($data[$i]['InfoID'], $data[$i]['Html'], $data[$i]['LinkUrl'],  false, $data[$i]['ChannelID']);
		$data[$i]['ChannelUrl'] = ChannelUrl($data[$i]['ChannelID'], $data[$i]['ChannelHtml'], $data[$i]['ChannelLinkUrl']);
		$data[$i]['Count'] = $Total;
	}
	return $data;
}

/**
 * 执行sql返回数据
 * @param string $sql   //sql不能包含< > 引号等特殊字符,<用&lt;替代，>用&gt;替代, 单引号用^替代
 * @param int $page 小于等于0表示不分页
 */
function get_data($sql){
	//sql合法性检验
	$prefix = strtolower(substr($sql, 0, 6));
	if( $prefix != 'select' ) return false;
	$chars = array(
			'&lt;'=>'<', '&gt;'=>'>', '^^'=>'"', '^'=>"'",
			' nheq '=>' !== ',' heq '=>' === ',' neq '=>' != ',' eq '=>' == ',' egt '=>' >= ',' gt '=>' > ',' elt '=>' <= ',' lt '=>' < '
	);
	$sql = str_replace(array_keys($chars), array_values($chars), $sql);
	$banTable = array('admin','admin_group','member','member_group','config');
	$tablePrefix = C('DB_PREFIX');
	foreach($banTable as $v){
		if( stripos($sql, $tablePrefix.$v) ){
			return false;
		}
	}
	$m = new Model();
	$data = $m->query($sql);
	return $data;
}

/**
 * 返回json数组
 * @param string $url
 */
function get_json($url){
	$content = file_get_contents($url);
	$data[0] = json_decode($content, true); //返回二维数组，便于voilist遍历
	return $data;
}

//根据主键获取表中字段值, $tableName:不带前缀
function get_single_value($id, $tableName, $FieldName){
	if(!is_numeric($id)) return false;
	switch ( strtolower($tableName) ){
		case 'info': //信息
			$m = D('Admin/Info');
			$result = $m->where("InfoID=$id and IsEnable=1 and IsCheck=1")->getField($FieldName);
			return $result;
		case 'channel': //频道
			$m = D('Admin/Channel');
			$where = "ChannelID=$id and IsEnable=1 ";
			if( $FieldName == 'LinkUrl' ){ //必须为链接模型才返回LinkUrl
					$where .= ' and ChannelModelID = 33';
			}
			$result = $m->where($where)->getField($FieldName);
			return $result;
		case 'channel_model':
			$m = D('Admin/ChannelModel');
			$result = $m->where("ChannelModelID=$id")->getField($FieldName);
			return $result;
		case 'banner': //幻灯
			$m = D('Admin/Banner');
			$result = $m->where("BannerID=$id and IsEnable=1")->getField($FieldName);
			return $result;
		case 'bannergroup': //幻灯片分组
			$m = D('Admin/BannerGroup');
			$result = $m->where("BannerGroupID=$id")->getField($FieldName);
			return $result;
		case 'link': //友情链接
			$m = D('Admin/Link');
			$result = $m->where("LinkID=$id and IsEnable=1")->getField($FieldName);
			return $result;
		case 'linkclass': //友情链接分类
			$m = D('Admin/LinkClass');
			$result = $m->where("LinkClassID=$id")->getField($FieldName);
			return $result;
		case 'ad': //广告
			$m = D('Admin/Ad');
			$result = $m->where("AdID=$id and IsEnable=1")->getField($FieldName);
			return $result;
		case 'adgroup': //广告分组
			$m = D('Admin/AdGroup');
			$result = $m->where("AdGroupID=$id and IsEnable=1")->getField($FieldName);
			return $result;
		case 'job': //职位
			$m = D('Admin/Job');
			$result = $m->where("JobID=$id and IsEnable=1")->getField($FieldName);
			return $result;
		case 'tag': //自定义标签
			$m = D('Admin/Tag');
			$result = $m->where("TagID=$id and IsEnable=1")->getField($FieldName);
			return $result;
		case 'special': //专题
			$m = D('Admin/Special');
			$result = $m->where("SpecialID=$id and IsEnable=1")->getField($FieldName);
			return $result;
		case 'guestbook': //留言
			$m = D('Admin/Guestbook');
			$result = $m->where("MessageID=$id")->getField($FieldName);
			return $result;
		case 'label': //频道属性标记
			$m = D('Admin/Label');
			$result = $m->where("LabelID=$id")->getField($FieldName);
			return $result;
		default:
			return false;
	}
}

//频道单字段 Start===============================================
function HasChild($id){
	$HasChild = get_single_value($id, 'Channel', 'HasChild');
	return $HasChild;
}

//当前频道顶层频道是否有子频道
function TopHasChild($id){
	$result = HasChild($id);
	if($result==1) return 1;
	
	$result = HasParent($id);
	if($result==1) return 1;
	
	return 0;
}

function HasParent($id){
	$result = get_single_value($id, 'Channel', 'Parent');
	return $result > 0 ? 1: 0;
}
//指定频道的最顶层频道ID
function TopChannelID($id){
	$m = D('Admin/Channel');
	$topChannelID = $m->getTopChannel($id);
	return $topChannelID;
}
function ChannelName($id){
	$ChannelName = get_single_value($id, 'Channel', 'ChannelName'); 
	return $ChannelName;
}
function ChannelModelName($id){	return  get_single_value($id, 'Channel_Model', 'ChannelModelName');}
function ChannelModelID($id){	return  get_single_value($id, 'Channel', 'ChannelModelID');}
function ChannelTarget($id){	return  get_single_value($id, 'Channel', 'ChannelTarget');}
function ChannelOrder($id){	return  get_single_value($id, 'Channel', 'ChannelOrder');}

function ChannelUrl($id, $html=false, $linkurl=false, $langmark = false){
	static $_cache = array();
	if (isset($_cache[$id])){
		return $_cache[$id];
	}
	
	if($langmark === false){
		$prefix = LANG_PREFIX;
	}else{ //显式传入$langmark
		$prefix = $langmark != C('DEFAULT_LANG') ? '/'.$langmark : '';
	}
	
	//如果存在欢迎页=================================================
	if($id == 1 || $id== 2) {
		$HasWelcome = file_exists( THEME_PATH.'channel/welcome.html' );
		if( $HasWelcome == false){
			$url =  (strtolower(GROUP_NAME) != 'wap') ? __APP__ : __GROUP__;
			//存在bug，没有电脑站并默认为Wap时，英文版首页地址为：/index.php/en,会调到home分组
			//解决方案：将配置文件config路由默认home删除即可
			$url .= $prefix;  
			if( $url == '' ) $url = '/';  //当在public/login时，若__APP__为空，则首页为/public地址
			$url = AppendWxUrlPara($url);
			$_cache[$id] = $url;
			return $url;
		}
	}
	//===========================================================
	
	//转向链接======================================================
	if( false === $linkurl ){ //无显式参数传入
		$linkurl = ChannelLinkUrl($id);
		if( !empty( $linkurl ) ) return AppendWxUrlPara($linkurl);
	}else if( !empty($linkurl) ){ //有参数插入，并且不为空
		return AppendWxUrlPara($linkurl);
	}
	//============================================================
	
	//非转向链接的情况==============================
	if( false === $html){  //无显式参数传入
		$html = ChannelHtml($id);
	}
	//=========================================
	
	if(C('URL_ROUTER_ON')){//支持路由
		$url = (strtolower(GROUP_NAME) != 'wap') ? U($prefix."/$html") : U('/wap'.$prefix.'/'.$html);
	}else{
		$url = (strtolower(GROUP_NAME) != 'wap') ? U('channel/index', "id=$html") : U('wap/channel/index', "id=$html");
	}
	$url = AppendWxUrlPara($url);
	$_cache[$id] = $url;
	return $url;
}

function ChannelLinkUrl($id){
	$linkurl = get_single_value($id, 'Channel', 'LinkUrl');
	return $linkurl;
}
function ChannelSName($id){
	return get_single_value($id, 'Channel', 'ChannelSName'); 
}
function ChannelContent($id, $count = 0, $suffix='...'){
	$content = get_single_value($id, 'Channel', 'ChannelContent');
	if( $count > 0 ){
		$len = mb_strlen( $content , 'utf-8');  //获取实际内容的长度
		if( $len > $count ){ //截取字符串
			$content = msubstr( $content, 0, $count, 'utf-8', $suffix);
		}
	}
	$content = ParseTag($content);
	return $content;
}
function ChannelSContent($id, $count = 0, $suffix='...'){
	$content = get_single_value($id, 'Channel', 'ChannelSContent');
	if( $count <= 0 ) return $content;
	$len = mb_strlen( $content , 'utf-8');  //获取实际内容的长度
	if( $len > $count ){ //截取字符串
		$content = msubstr( $content, 0, $count, 'utf-8', $suffix);
	}
	return $content;
}
function ChannelPicture($id){
	return get_single_value($id, 'Channel', 'ChannelPicture');
}
function ChannelReadTemplate($id){
	return get_single_value($id, 'Channel', 'ReadTemplate');
}
function ChannelIndexTemplate($id){
	return get_single_value($id, 'Channel', 'IndexTemplate');
}
function ChannelReadLevel($id){	return get_single_value($id, 'Channel', 'ReadLevel');}
function PageSize($id){	return get_single_value($id, 'Channel', 'PageSize');}
function ChannelParent($id){
	return get_single_value($id, 'Channel', 'Parent');
}
function ChannelIcon($id){
	return get_single_value($id, 'Channel', 'ChannelIcon');
}
function ChannelStyle($id){return get_single_value($id, 'Channel', 'ChannelStyle');}
function ChannelF1($id){
	return get_single_value($id, 'Channel', 'f1');
}
function ChannelF2($id){
	return get_single_value($id, 'Channel', 'f2');
}
function ChannelF3($id){
	return get_single_value($id, 'Channel', 'f3');
}

function ChannelHtml($id){	return get_single_value($id, 'Channel', 'Html');}
function ChannelTitle($id){	return  get_single_value($id, 'Channel', 'Title');}
function ChannelKeywords($id){	return  get_single_value($id, 'Channel', 'Keywords');}
function ChannelDescription($id){	return  get_single_value($id, 'Channel', 'Description');}
function ChannelIsShow($id){	return  get_single_value($id, 'Channel', 'IsShow');}
//频道单字段 End================================================

//频道属性标记 Start==============================================
function LabelName($id){
	$name = get_single_value($id, 'Label', 'LabelName');
	return $name;
}
//频道属性标记 End===============================================

//友情链接 start===============================================
//友情链接 Start==============================================
function LinkClassName($id){
	return get_single_value($id, 'LinkClass', 'LinkClassName');
}
function LinkName($id){
	return get_single_value($id, 'Link', 'LinkName');
}
function LinkClassID($id){
	return get_single_value($id, 'Link', 'LinkClassID');
}
function LinkType($id){
	return get_single_value($id, 'Link', 'LinkType');
}
function LinkLogo($id){
	return get_single_value($id, 'Link', 'LinkLogo');
}
function LinkUrl($id){
	return get_single_value($id, 'Link', 'LinkUrl');
}
function LinkDescription($id){
	return get_single_value($id, 'Link', 'LinkDescription');
}
//友情链接 End===============================================

//幻灯片 start===============================================
function BannerGroupName($id){
	return get_single_value($id, 'BannerGroup', 'BannerGroupName');
}
function BannerName($id){
	return get_single_value($id, 'Banner', 'BannerName');
}
function BannerGroupID($id){
	return get_single_value($id, 'Banner', 'BannerGroupID');
}
function BannerImage($id){
	return get_single_value($id, 'Banner', 'BannerImage');
}
function BannerThumbnail($id){
	return get_single_value($id, 'Banner', 'BannerThumbnail');
}
function BannerUrl($id){
	return get_single_value($id, 'Banner', 'BannerUrl');
}
function BannerDescription($id){
	return get_single_value($id, 'Banner', 'BannerDescription');
}
//幻灯片 End===============================================

//专题 start===============================================
function SpecialName($id){
	return get_single_value($id, 'Special', 'SpecialName');
}
function SpecialDescription($id){
	return get_single_value($id, 'Special', 'SpecialDescription');
}
//专题 End===============================================

//自定义标签 start===============================================
function TagName($id){
	return get_single_value($id, 'Tag', 'TagName');
}
function TagContent($id){
	return get_single_value($id, 'Tag', 'TagContent');
}
function TagDescription($id){
	return get_single_value($id, 'Tag', 'TagDescription');
}
//自定义标签 End===============================================

//广告标签 start===============================================
function AdName($id){
	return get_single_value($id, 'Ad', 'AdName');
}
function AdContent($id){
	return get_single_value($id, 'Ad', 'AdContent');
}
function AdUrl($id){
	return get_single_value($id, 'Ad', 'AdUrl');
}
function AdDescription($id){
	return get_single_value($id, 'Ad', 'AdDescription');
}
function AdTime($id){
	return get_single_value($id, 'Ad', 'AdTime');
}
function AdGroupID($id){
	return get_single_value($id, 'Ad', 'AdGroupID');
}
function AdGroupName($id){
	return get_single_value($id, 'AdGroup', 'AdGroupName');
}
function AdGroupDescription($id){
	return get_single_value($id, 'AdGroup', 'AdGroupDescription');
}
//广告标签 End===============================================

//信息单字段 Start===============================================
function ChannelID($id){return get_single_value($id, 'Info', 'ChannelID');}
function InfoTitle($id){return get_single_value($id, 'Info', 'InfoTitle');}
function InfoTime($id){return get_single_value($id, 'Info', 'InfoTime');}
function InfoF1($id){ return get_single_value($id, 'Info', 'f1');}
function InfoF2($id){return get_single_value($id, 'Info', 'f2');}
function InfoF3($id){return get_single_value($id, 'Info', 'f3');}
function InfoF4($id){return get_single_value($id, 'Info', 'f4');}
function InfoF5($id){return get_single_value($id, 'Info', 'f5');}

function InfoSContent($id, $count = 0, $suffix='...'){
	$content = get_single_value($id, 'Info', 'InfoSContent');
	if( $count <= 0 ) return $content;
	$len = mb_strlen( $content , 'utf-8');  //获取实际内容的长度
	if( $len > $count ){ //截取字符串
		$content = msubstr( $content, 0, $count, 'utf-8', $suffix);
	}
	return $content;
}
function InfoContent($id, $count = 0, $suffix='...'){
	$content = get_single_value($id, 'Info', 'InfoContent');
	if( $count > 0 ){
		$len = mb_strlen( $content , 'utf-8');  //获取实际内容的长度
		if( $len > $count ){ //截取字符串
			$content = msubstr( $content, 0, $count, 'utf-8', $suffix);
		}
	}
	$content = ParseTag($content);
	return $content;
}
function InfoPicture($id){
	return get_single_value($id, 'Info', 'InfoPicture');
}
function InfoAttachment($id){
	return get_single_value($id, 'Info', 'InfoAttachment');
}
function InfoHtml($id){
	return get_single_value($id, 'Info', 'Html');
}
function InfoLinkUrl($id){
	return get_single_value($id, 'Info', 'LinkUrl');
}

function InfoUrl($id, $html=false, $linkurl=false, $langmark = false, $channelid=false){
	//转向链接======================================================
	if( false === $linkurl ){ //无显式参数传入
		$linkurl = InfoLinkUrl($id);
		if( !empty( $linkurl ) ) return AppendWxUrlPara($linkurl);
	}else if( !empty($linkurl) ){ //有参数插入，并且不为空
		return AppendWxUrlPara($linkurl);
	}
	//============================================================
	
	if($langmark === false){
		$prefix = LANG_PREFIX;
	}else{ //显式传入$langmark
		$prefix = $langmark != C('DEFAULT_LANG') ? '/'.$langmark : '';
	}
	
	if($channelid !== false){
		$dir = YdCache::readChannel($channelid);
	}else{
		$channelid = ChannelID($id);
		$dir = YdCache::readChannel($channelid);
	}
	if( empty($dir) ) $dir = 'info';
	
	//非转向链接的情况
	if( false === $html){  //无显式参数传入
		$html = InfoHtml($id);
		if( !empty($html) ) $id = $html;
	}else if( !empty($html) ){ //显式传参
		$id = $html;
	}
	
	if(C('URL_ROUTER_ON')){
		$url =  (strtolower(GROUP_NAME) != 'wap') ? U("{$prefix}/{$dir}/{$id}") : U("/wap{$prefix}/{$dir}/{$id}");  //支持路由
	}else{
		$url =  (strtolower(GROUP_NAME) != 'wap') ? U("{$dir}/read", "id={$id}") : U("wap/{$dir}/read", "id={$id}");
	}
	return AppendWxUrlPara($url);
}
function InfoCount($id){
	$m = D('Admin/Info');
	$n = $m->getInfoCount($id);
	return $n;
}

function InfoOrder($id){return get_single_value($id, 'Info', 'InfoOrder');}
function InfoHit($id){return get_single_value($id, 'Info', 'InfoHit');}
function InfoFrom($id){return get_single_value($id, 'Info', 'InfoFrom');}

function LabelID($id){
	return get_single_value($id, 'Info', 'LabelID');
}
function InfoAlbum($id){
	return get_single_value($id, 'Info', 'InfoAlbum');
}
function InfoRelation($id){
	return get_single_value($id, 'Info', 'InfoRelation');
}

function InfoReadLevel($id){return get_single_value($id, 'Info', 'ReadLevel');}
function SpecialID($id){return get_single_value($id, 'Info', 'SpecialID'); }
function InfoKeywords($id){	return get_single_value($id, 'Info', 'Keywords'); }
function InfoDescription($id){ return get_single_value($id, 'Info', 'Description'); }
//信息单字段 End===============================================

//常见页面Url=================================================
//信息检索
function InfoSearchAction( $ChannelID = 0 ){
	//$url = __APP__.'/'.GROUP_NAME.'/channel/search';
	$url = __GROUP__.'/channel/search';
	if( $ChannelID != 0 ){
		$url .= '/id/'.$ChannelID;
	}
	$url .= '/l/'.LANG_SET;
	return AppendWxUrlPara($url);
}

function InfoSearchUrl( $ChannelID = 0 ){
	return InfoSearchAction( $ChannelID );
}

//邮件订阅Url
function SubscibeUrl($MailClassID = false){
	$url = __GROUP__.'/channel/subscibe';
	if( $MailClassID ){
		$url .= '/id/'.$MailClassID;
	}
	$url .= '/l/'.LANG_SET;
	return $url;
}

//用户注册
function MemberRegAction(){
	$url = __GROUP__.'/public/savereg/l/'.LANG_SET;
	return AppendWxUrlPara($url);
}

function MemberSaveRegUrl(){
	return MemberRegAction();
}

//留言板地址
function GuestbookAddAction(){
	$url = __GROUP__.'/channel/guestbookadd/l/'.LANG_SET;
	return $url;
}

function GuestbookAddUrl(){
	return GuestbookAddAction();
}

function CommentAddAction(){
	$url = __GROUP__.'/channel/commentadd/l/'.LANG_SET;
	return $url;
}

function OrderAddAction(){
	$url = __GROUP__.'/channel/orderAdd/l/'.LANG_SET;
	return $url;
}

function ShopUrl($InfoID){
	$url = __APP__.'/wap/public/addCart/l/'.LANG_SET.'?infoid='.$InfoID;
	return $url;
}

//网站首页地址
function HomeUrl(){
	$t = array('en'=>2, 'cn'=>1);
	$id = $t[ get_language_mark() ];
	if(stripos($_SERVER['HTTP_USER_AGENT'],"MicroMessenger") === false) {
		return ChannelUrl($id);
	}else{
		return WxChannelUrl($id);
	}
}

//手机站首页网址
function WapHomeUrl($langmark=false){
	if($langmark === false){
		$prefix = LANG_PREFIX;
	}else{ //显式传入$langmark
		$prefix = $langmark != C('DEFAULT_LANG') ? '/'.$langmark : '';
	}
	$url =  __APP__.'/wap'.$prefix;
	$domainRules = C('APP_SUB_DOMAIN_RULES');
	if(!empty($domainRules)){
		$data = array_keys( $domainRules );
		if( isset($data[0]) ){
			if( 2 == C('URL_MODEL') ){
				$url =  'http://'.$data[0].$prefix;
			}else{
				$url =  'http://'.$data[0].'/index.php'.$prefix;
			}
		}
	}
	$url = AppendWxUrlPara($url);
	return $url;
}

//人才招聘地址
function JobUrl(){
	$t = array('en'=>3, 'cn'=>8);
	$id = $t[ get_language_mark() ];
	return ChannelUrl($id);
}

//语言切换地址
function LanguageUrl($mark = 'cn'){
	//如果不存在欢迎页==============================================
	$HasWelcome = file_exists( THEME_PATH.'channel/welcome.html' );
	if( $HasWelcome == false){ //如果不存在欢迎页
		$url =  (strtolower(GROUP_NAME) != 'wap') ? __APP__ : __GROUP__;
		if( $url == '' ) $url = '/';
		$url .= '?l='.$mark;
		return AppendWxUrlPara($url);
	}
	//==========================================================
	
	$t = array('en'=>2, 'cn'=>1);
	$id = $t[$mark];
	$html = ChannelHtml($id);
	if(C('URL_ROUTER_ON')){ //支持路由
		$url = (strtolower(GROUP_NAME) != 'wap') ? U("/$html") : U("/wap/$html");
	}else{
		$url = (strtolower(GROUP_NAME) != 'wap') ? U('channel/index', "id=$html") : U('wap/channel/index', "id=$html");
	}
	$url .= '?l='.$mark;
	return AppendWxUrlPara($url);
}

//网站地图地址
function SitemapUrl(){
	$t = array('en'=>14, 'cn'=>3);
	$id = $t[ get_language_mark() ];
	$url = ChannelUrl($id);
	return $url;
}

//在线订购地址
function OrderUrl($InfoID=false){
	$t = array('en'=>7, 'cn'=>6);
	$id = $t[ get_language_mark() ];
	$html = ChannelHtml($id);	
	if(C('URL_ROUTER_ON')){
		$url = (strtolower(GROUP_NAME) != 'wap') ? U(LANG_PREFIX."/$html$InfoID") : U("/wap".LANG_PREFIX."/d$InfoID");  //支持路由
	}else{
		$url =  (strtolower(GROUP_NAME) != 'wap') ? U('channel/index', array('id'=>$html,'infoid'=>$InfoID)) : U('/wap/channel/index', array('id'=>$html,'infoid'=>$InfoID));
	}
	return AppendWxUrlPara($url);
}


//投递简历地址
function ResumeUrl($JobID=false){
	$t = array('en'=>11, 'cn'=>10);
	$id = $t[ get_language_mark() ];
	$html = ChannelHtml($id);
	if(C('URL_ROUTER_ON')){
		$url = (strtolower(GROUP_NAME) != 'wap') ? U(LANG_PREFIX."/$html$JobID") : U("/wap".LANG_PREFIX."/r$JobID");  //支持路由
	}else{
		$url =  (strtolower(GROUP_NAME) != 'wap') ? U('channel/index', array('id'=>$html,'jobid'=>$JobID)) : U('/wap/channel/index', array('id'=>$html,'jobid'=>$JobID));
	}
	return AppendWxUrlPara($url);
}

//用户登录
function MemberLoginUrl(){
	$url = __GROUP__.'/public/login/l/'.LANG_SET;
	return AppendWxUrlPara($url);
}

//用户注册
function MemberRegUrl(){
	$url = __GROUP__.'/public/reg/l/'.LANG_SET;
	return AppendWxUrlPara($url);
}

//忘记密码
function MemberForgetUrl(){
	$url = __GROUP__.'/public/forget/l/'.LANG_SET;
	return AppendWxUrlPara($url);
}

//登陆验证
function CheckMemberUrl(){
	$url = __GROUP__.'/public/checkLogin';
	return $url;
}
//用户后台首页
function MemberUrl(){
	$url = __APP__.'/member/public/index';
	return $url;
}

function MemberLogoutUrl(){
	$url = __APP__.'/member/public/logout';
	return $url;
}

//反馈表单提交
function FeedbackUrl(){
	$url =  __GROUP__.'/Channel/feedbackAdd/l/'.LANG_SET;
	return $url;
}

//邮件发送
function MailUrl($isverify = 1){
	$url =  __GROUP__.'/public/sendMail?isverify='.$isverify;
	return $url;
}




/**
 * 生成验证码
 * @param string $verifyName 验证码session名称
 * @param int $width 宽度
 * @param int $height 高度
 * @param int $length 验证码个数
 * @param int $mode 模式 0:字母, 1:数字, 2:大写字母, 3:小写字母, 4:中文, 5:混合
 * @param string $type 验证码图片格式
 */
function CodeUrl($verifyName='verify',$width = 22, $height = 22, $length = 4, $mode = 1, $type = 'png'){
	$get = "?verify=$verifyName&width=$width&height=$height&length=$length&mode=$mode&type=$type";
	return __GROUP__."/public/verifyCode".$get;
}
//表单Action end==================================================


//微信实用函数start==============================================
//微信API接口地址
function WxApiUrl(){
	$v = C('URL_MODEL');
	$url = get_web_url();
	if($v == 1){
		$url .= '/index.php';
	}
	$url .= '/public/wxapi/';
	return $url;
}

//附加微信参数，修复不能拨号的bug，$iswx＝true表示确定是微信
function AppendWxUrlPara($url, $iswx=false){
	if( $iswx || stripos($_SERVER['HTTP_USER_AGENT'],"MicroMessenger") ) {
		//判断url中是否存在?参数
		$append = (strpos($url, '?') === false ) ? '?' : '&';
		$url .= $append.C('WX_URL_APPEND');
	}
	return $url;
}

function WxLotteryUrl($appID){
	$url = get_wx_url()."/app/lottery?appid=$appID";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//投票Url
function WxVoteUrl($appID){
	$url = get_wx_url()."/app/vote?appid=$appID";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//调查Url
function WxResearchUrl($appID){
	$url = get_wx_url()."/app/research?appid=$appID";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//提交投票
function WxVoteAddUrl($appID){
	$url =  __GROUP__.'/channel/voteAdd?appid='.$appID;
	return $url;
}

//会员卡首页地址
function WxCardUrl(){
	$url = get_wx_url()."/app/card";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

function WxCardStoreUrl(){
	$url = get_wx_url()."/app/cardStore";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//会员卡说明地址
function WxCardInfoUrl(){
	$url = get_wx_url()."/app/cardInfo";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//会员卡通知管理
function WxCardNotifyUrl(){
	$url = get_wx_url()."/app/cardNotify";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//我的消费记录
function WxCardMyConsumeUrl(){
	$url = get_wx_url()."/app/cardMyConsume";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//我的积分记录
function WxCardMyScoreUrl(){
	$url = get_wx_url()."/app/cardMyScore";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//我的兑换记录
function WxCardMyExchangeUrl(){
	$url = get_wx_url()."/app/cardMyExchange";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//会员资料
function WxCardMemberUrl(){
	$url = get_wx_url()."/app/cardMember";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//会员特权地址
function WxCardPrivilegeUrl(){
	$url = get_wx_url()."/app/cardprivilege";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//会员卡优惠卷地址
function WxCouponUrl(){
	$url = get_wx_url()."/app/cardCoupon";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//会员卡兑换
function WxExchangeUrl(){
	$url = get_wx_url()."/app/cardExchange";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//会员卡签到
function WxCardScoreUrl(){
	$url = get_wx_url()."/app/cardScore";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//微应用Url地址
function WxAppUrl($AppID, $AppTypeID=false){
	$AppTypeID = (false === $AppTypeID) ? WxAppTypeID($AppID) : $AppTypeID;
	switch($AppTypeID){
		case 1: //微活动
			$url = WxLotteryUrl($AppID);
			break;
		case 2: //微投票
			$url = WxVoteUrl($AppID);
			break;
		case 5: //微调查
			$url = WxResearchUrl($AppID);
			break;
		case 6: //微会员卡
			$url = WxCardUrl();
			break;
		default:
			$url = "";
	}
	return $url;
}

//生成微信Token唯一字符串
function WxToken(){
	$name = explode('.', get_web_url());
	if( !empty( $name[1] ) ){
		$prefix = strtoupper( trim( $name[1] ) ) ;
		$prefix = str_replace('-', '', $prefix);
	}else{
		$prefix = 'YOUDIANCMS';
	}
	$token = $prefix.date('YmdHis');
	//$token必须为英文或数字，长度为3－32字符
	if( strlen($token) > 32 ){
		$token = substr($token, 0, 32);
	}
	return $token;
}

function WxAppName($appID){
	$m = D('Admin/WxApp');
	$AppName = $m->where("AppID=$appID")->getField('AppName');
	return $AppName;
}

function WxAppTypeID($appID){
	$m = D('Admin/WxApp');
	$AppTypeID = $m->where("AppID=$appID")->getField('AppTypeID');
	return $AppTypeID;
}

//微信频道Url，带wx=1后缀
function WxChannelUrl($id, $html=false, $linkurl=false, $langmark = false){
	static $_cache = array();
	if (isset($_cache[$id])){
		return $_cache[$id];
	}

	if($langmark === false){
		$prefix = LANG_PREFIX;
	}else{ //显式传入$langmark
		$prefix = $langmark != C('DEFAULT_LANG') ? '/'.$langmark : '';
	}

	$url = get_wx_url();  //返回微信绝对地址
	//如果存在欢迎页=================================================
	if($id == 1 || $id== 2) {
		$HasWelcome = file_exists( THEME_PATH.'channel/welcome.html' );
		if( $HasWelcome == false){
			$url .= $prefix;
			$url = AppendWxUrlPara($url, true);
			$_cache[$id] = $url;
			return $url;
		}
	}
	//===========================================================

	//转向链接======================================================
	if( false === $linkurl ){ //无显式参数传入
		$linkurl = ChannelLinkUrl($id);
		if( !empty( $linkurl ) ) {
			$linkurl = WxAbsoulteUrl( $linkurl );
			return AppendWxUrlPara($linkurl, true);
		}
	}else if( !empty($linkurl) ){ //有参数插入，并且不为空
		$linkurl = WxAbsoulteUrl( $linkurl );
		return AppendWxUrlPara($linkurl, true);
	}
	//============================================================

	//非转向链接的情况==============================
	if( false === $html){  //无显式参数传入
		$html = ChannelHtml($id);
	}
	//=========================================
	$url .= $prefix.'/'.$html;
	$url = AppendWxUrlPara($url, true);
	$_cache[$id] = $url;
	return $url;
}

//转化为微信绝对地址
function WxAbsoulteUrl($url){
	$resourceUrl = '';
	if(!empty($url)){
		if( strtolower( substr($url, 0, 7) ) == 'http://' || strtolower( substr($url, 0, 8) ) == 'https://'
				|| strtolower( substr($url, 0, 6) ) == 'ftp://' ){
			$resourceUrl = $url;
		}else{
			$resourceUrl = get_wx_url().$url; //必须是绝对地址
		}
	}
	return $resourceUrl;
}

//微信信息Url地址
function WxInfoUrl($id, $html=false, $linkurl=false, $langmark = false, $channelid=false){
	//转向链接======================================================
	if( false === $linkurl ){ //无显式参数传入
		$linkurl = InfoLinkUrl($id);
		if( !empty( $linkurl ) ) {
			$linkurl = WxAbsoulteUrl( $linkurl );
			return AppendWxUrlPara($linkurl, true);
		}
	}else if( !empty($linkurl) ){ //有参数插入，并且不为空
		$linkurl = WxAbsoulteUrl( $linkurl );
		return AppendWxUrlPara($linkurl, true);
	}
	//============================================================

	if($channelid !== false){
		$dir = YdCache::readChannel($channelid);
	}else{
		$channelid = ChannelID($id);
		$dir = YdCache::readChannel($channelid);
	}
	if( empty($dir) ) $dir = 'info';
	
	if($langmark === false){
		$prefix = LANG_PREFIX;
	}else{ //显式传入$langmark
		$prefix = $langmark != C('DEFAULT_LANG') ? '/'.$langmark : '';
	}
	$url = get_wx_url();  //返回微信绝对地址
	//非转向链接的情况
	if( false === $html){  //无显式参数传入
		$html = InfoHtml($id);
		if( !empty($html) ) $id = $html;
	}else if( !empty($html) ){ //显式传参
		$id = $html;
	}
	$url .= "{$prefix}/{$dir}/{$id}";
	$url = AppendWxUrlPara($url, true);
	return $url;
}

//菜单颜色
function WxMenuTypeColor($MenuID){
	$color = array(
			1=>'#000000',  2=>'#90F',  3=>'blue',  4=>'green',  5=>'#630',
			6=>'red',  7=>'#960',
	);
	if( isset($color[$MenuID]) ){
		return $color[$MenuID];
	}else{
		return '#000000'; //默认为黑色
	}
}

//判断微信用户的ID是否有效
function wxUserExist($fromUser){
	$m = D('Admin/Member');
	$b = $m->wxUserExist($fromUser);
	return $b;
}

//微信实用函数end==============================================

//模板实用函数start==============================================
function Left($str, $len = 0, $suffix='...'){
	if( $len <= 0 ) return $str;
	if( LANG_SET == 'en'){
		$len *= 2;  //英文长度自动加倍
	}
	$n = mb_strlen( $str , 'utf-8');  //获取实际内容的长度
	if( $n > $len ){ //截取字符串
		$str = msubstr( $str, 0, $len, 'utf-8', $suffix);
	}
	$str = yd_close_tags($str);//补齐Html标签
	return $str;
}

//返回默认图片url
function DefaultPicture($url, $default='1'){
	if( strlen(trim($url)) <= 0 ){
		$k = get_language_mark();
		$nopic = APP_TMPL_PATH."Public/Images/nopic$k.jpg";
		$nopic_p = get_web_root().$nopic;
		if( !file_exists( $nopic_p ) ){
			$nopic = __ROOT__.'/Public/Images/nopic/'.$default.$k.'.jpg';
		}
		return $nopic;
	}
	return $url;
}

//获取手机网站频道图标
function WapChannelIcon($ChannelID, $default='default.jpg'){
	$icon = APP_TMPL_PATH."Public/images/icon/$ChannelID.jpg";
	$icon_p = get_web_root().$icon;
	if( !file_exists( $icon_p ) ){
		$icon = APP_TMPL_PATH."Public/images/icon/$default";
	}
	return $icon;
}

function WapChannelIconPng($ChannelID, $default='default.png'){
	$icon = APP_TMPL_PATH."Public/images/icon/$ChannelID.png";
	$icon_p = get_web_root().$icon;
	if( !file_exists( $icon_p ) ){
		$icon = APP_TMPL_PATH."Public/images/icon/$default";
	}
	return $icon;
}

//返回对应频道模型ID对应的颜色
function ChannelModelColor($ChannelModelID){
	//30文章,31图片,32单页,33链接,34视频,35下载,36产品
	$color = array(
			30=>'#000000',  31=>'#90F',  32=>'blue',  33=>'red',  34=>'#630',
			35=>'#666',  36=>'green', 37=>'#960', 38=>'#000000',    39=>'#000000',
	);
	if( isset($color[$ChannelModelID]) ){
		return $color[$ChannelModelID];
	}else if($ChannelModelID < 30){
		return '#999';
	}else{
		return '#000000'; //默认为黑色
	}
}
//实用函数End==================================================

//判断是否需要缓存，仅用于ReadHtmlCacheBehavior
function requireCache(){
	$m = strtolower( MODULE_NAME );
	$a = strtolower( ACTION_NAME );
	//首页========================================
	if( $m == 'index' && $a == 'index'){
		$ChannelID = LANG_ID;
		$IsHtml = get_single_value($ChannelID, 'Channel', 'IsHtml');
		return ($IsHtml == 1) ? true : false;
	}
	//===========================================
	
	//频道主页======================================
	if( $m == 'channel' && $a == 'index'){
		$m = D('Admin/Channel');
		$IsHtml = $m->IsHtmlByHtml( $_GET['id'] );
		return ($IsHtml == 1) ? true : false;
	}
	//===========================================
	
	//信息主页======================================
	if( $m == 'info' && $a == 'read'){
		$m = D('Admin/Info');
		$IsHtml = $m->getIsHtml( $_GET['id']  );
		return ($IsHtml == 1) ? true : false;
	}
	//============================================
}

//百度翻译
function baiduTranslate($content, $from='zh', $to = 'en'){
	if( empty($content) || is_numeric($content)){
		$data["Status"] = 1;
		$data["Content"] = $content;
		return $data;
	}
	
	//在翻译img标签是回出现异常，百度翻译标签可能会删除里面的空格
	$content = strip_tags($content, "<img><br>");
	//翻译预处理 alt="" 会导致图片异常
	$search = array('alt=""', '"');
	$replace = array('',"'");
	$content = str_ireplace($search, $replace, $content);
	if( empty($content) || is_numeric($content)){
		$data["Status"] = 1;
		$data["Content"] = $content;
		return $data;
	}
	
	
	//{"from":"en","to":"zh","trans_result":[{"src":"today","dst":"\u4eca\u5929"},{"src":"tomorrow","dst":"\u660e\u5929"}]}
	//  dst:译文，src:原文 只有发生错误时，返回的JSON中才包含error_code和error_msg字段，成功返回的结果中不会包含这两个字段。
	//分段：待翻译内容中的换行符’\n’经urlencode后变为%0A）
	//当API服务发生错误时，返回数据格式如下
	//{"error_code": "52001","error_msg": "TIMEOUT","from": "auto",    "to": "auto",    "query": "he's"}
	//①TIMEOUT：超时（52001）【请调整文本字符长度】
	//②SYSTEM ERROR：翻译系统错误（52002）
	//③UNAUTHORIZED USER：未授权的用户（52003）【请检查是否将api key输入错误】
	$api = "http://openapi.baidu.com/public/2.0/bmt/translate";
	$apikey = YdCache::readOther('BAIDU_TRANSLATE_APIKEY');
	
	$totalBytes = strlen($content);
	$maxBytes = 4800; //GET方式最大支持5k字符的请求，POST方式最大支持3k字符的请求
	$delimiter = "<br />";
	if( $totalBytes > $maxBytes){
		if( stripos($content, $delimiter) !== false){
			$text = explode($delimiter, $content);
		}else{
			$data["Status"] = 0;
			$data["ErrorMessage"] = "内容超过5K字符，请用在内容插入换行{$delimiter}分段翻译";
			return $data;
		}
	}else{
		$text[] = $content;
	}
	
	$nSize = count($text);
	$data = array();
	for($j=0; $j < $nSize; $j++){
		$myText = trim($text[$j]);
		if( strlen($myText) == 0 ) continue;
		$p = array('client_id'=>$apikey,'q'=>$myText, 'from'=>$from, 'to'=>$to);
		$result = yd_curl_get($api, $p);
		$result = json_decode($result, true);
		if(empty($result)){
			$data["Status"] = 0;
			$data["ErrorMessage"] = "翻译结果为空，可能是内容有乱码";
			return $data;
		}
		
		if( !isset($result['error_code']) ){
			$data["Status"] = 1;
			$n = count($result['trans_result']);
			for($i=0;$i<$n;$i++){
				$data['Content'] .= $result['trans_result'][$i]['dst'];
				if($i != $n-1 ){  //段落之间必须加上回车
					$data['Content'] .= "\n";
				}
			}
			if($j != $nSize-1 ){
				$data['Content'] .= $delimiter;
			}
		}else{
			$data["Status"] = 0;
			switch($result['error_code']){
				case '52001':
					$data["ErrorMessage"] = "超时，请调整文本字符长度";
					break;
				case '52002':
					$data["ErrorMessage"] = "翻译系统错误";
					break;
				case '52003':
					$data["ErrorMessage"] = "未授权的用户，请检查api key是否正确";
					break;
				default:
					$data["ErrorMessage"] = "翻译异常";
			}
			return $data;
		}
	} //for end
	return $data;
}

//to 收件人帐号,多个帐号以逗号,分开
function sendwebmail($to, $title, $body){
	if( empty($to) || empty($title) || empty($body)) return false;
	$data = YdCache::readBasic();
	$from = $data['EMAIL_ACCOUNT'];  //发件人账号
	$fromname = $data['EMAIL_SENDER'];  //发件人姓名
	$smtp = $data['EMAIL_SMTP'];
	$pwd = $data['EMAIL_PASSWORD'];
	$b = sendmail($from, $fromname, $to, $title, $body, $from, $pwd, $smtp);
	return $b;
}

/**
 * 
 * @param string 发件人账号
 * @param string 发件人姓名
 * @param mix to 收件人帐号,多个帐号以逗号,分开
 * @param string $title 邮件标题
 * @param string $body 内容
 * @param string $usename  邮箱账号
 * @param string $usepassword  邮箱密码
 * @param string $smtp  smtp服务器
 * @param string $repto
 * @param string $repname
 * @return boolean
 */
function sendmail($from, $fromname, $to, $title, $body, $usename, $usepassword, $smtp, $repto=false, $repname=false, $port=25, $way='tls'){
	ini_set("max_execution_time", "30000");
	include_once('./App/Lib/Common/class.phpmailer.php');
	$mail             = new PHPMailer();
	//$mail->SMTPDebug  = true;
	$mail->CharSet    = "UTF-8"; // charset
	$mail->Encoding   = "base64";

	$mail->IsSMTP(); // telling the class to use SMTP

	//system
	$mail->Port       = $port;
	if(stripos($smtp,'.gmail.com')===false){
		$mail->SMTPSecure = ($way=='tls') ? '' : "ssl";
		$mail->Host       = $smtp; // SMTP server
	}else{
		$mail->Host       = $smtp; // SMTP server
		$mail->SMTPSecure = "ssl";
		//$mail->Host       = 'ssl://'.$smtp; // SMTP server
	}

	$mail->SMTPAuth   = true;
	$mail->Username   = $usename; // SMTP account username
	$mail->Password   = $usepassword;        // SMTP account password

	$mail->From       = $from;//send email
	$mail->FromName   = $fromname; //name of send

	//repet
	if($repto!=""){
		$name = isset($repname)?$repname:$repto;
		$mail->AddReplyTo($repto, $name);
	}
	$mail->WordWrap   = 50; // line

	//title
	$mail->Subject		= (isset($title)) ? $title : '';//title


	//$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; //

	//body
	$body  = eregi_replace("[\]",'',$body);
	$mail->MsgHTML($body);

	//to
	if($to){
		$address = explode(",",$to);
		foreach($address AS $key => $val){
			if( yd_is_email($val) ){  //邮件有效才添加
				$mail->AddAddress($val, "");
			}
		}
	}
	//send attech
	//if(isset($data['attach']))
	//{
	//$attach = explode("|",$data['attach']);
	//foreach($attach AS $key => $val)
	//{
	//$mail->AddAttachment($val,"");             // attech
	//}
	//}
	if(!@$mail->Send()) {
		$mail->SmtpClose();
		//return "Mailer Error: " . $mail->ErrorInfo;
		return false;
	} else {
		$mail->SmtpClose();
		//return "Message sent!";
		return true;
	}
}

//判断now是否位于[start,end]
//$start:开始时间，$end:结束时间, $now:未指定则为当前时间
function isTimeRange($start, $end, $now=false){
	$flag = 0;
	$s = strtotime($start);
	$e = strtotime($end);
	$n = ($now === false) ? time() : strtotime($now);
	if($n < $s){
		$flag = -1;
	}else if($n>$e){
		$flag = 1;
	}else{
		$flag = 0; //位于范围内
	}
	return $flag;
}

//根据模型，获取所有数据
function getAllInfo(&$data, $ChannelModelID=6){
	$m = D('Admin/Attribute');
	$Attribute = $m->getAttribute( $ChannelModelID );
	$f = array();
	foreach($Attribute as $a){
		if( $a['FieldName'] != 'GuestName'){
			$name = explode(',', $a['DisplayName']);
			$f[] = array( 'FieldName'=>$a['FieldName'], 'DisplayName'=>$name[0] );
		}
	}
	unset($Attribute);
	$n = count($data);
	for($i = 0; $i<$n; $i++){
		foreach($f as $v){
			if(!empty($data[$i][$v['FieldName']])){
				$data[$i]['AllInfo'] .= "<b class='displayname'>".$v['DisplayName'].'：</b>'.$data[$i][$v['FieldName']].'<br/>';
			}
		}
	}
}

//解析微信应用参数开始========
//$out:传入数组，用于输出
function parseAppParameter($parameter, $type, &$out){
	$p = explode('@@@', $parameter);
	switch($type){
		case 1:  //微活动
			$out['LotteryType'] = $p[0];
			$out['LotteryIntroduction'] = $p[1];
			$out['LotteryDescription'] = $p[2];
			$out['LotteryStartTime'] = $p[3];
			$out['LotteryEndTime'] = $p[4];
			
			$out['LotteryRepeatTip'] = $p[5];
			$out['LotteryStartPicture'] = $p[6];
			$out['LotteryEndPicture'] = $p[7];
			$out['LotteryEndTitle'] = $p[8];
			$out['LotteryEndDescription'] = $p[9];
				
			$out['LotteryAward1'] = $p[10];
			$out['LotteryAward1Num'] = $p[11];
			$out['LotteryAward1Probability'] = $p[12];
			
			$out['LotteryAward2'] = $p[13];
			$out['LotteryAward2Num'] = $p[14];
			$out['LotteryAward2Probability'] = $p[15];
			
			$out['LotteryAward3'] = $p[16];
			$out['LotteryAward3Num'] = $p[17];
			$out['LotteryAward3Probability'] = $p[18];
			
			$out['LotteryMax'] = $p[19];
			$out['LotteryPassword'] = $p[20];
			
			$out['LotteryDayMax'] = $p[21];
			$out['LotteryTip'] = $p[22];
		case 5:  //微调查
			//0图片封面@@@1开始说明@@@2开始说明@@@3开始时间@@@4结束时间@@@5转向链接@@@6图文描述@@@7是否匿名
			$out['ResearchPicture'] = $p[0];
			$out['StartDescription'] = $p[1];
			$out['EndDescription'] = $p[2];
			$out['StartTime'] = $p[3];
			$out['EndTime'] = $p[4];
			$out['LinkUrl'] = $p[5];
			$out['ResearchDescription'] = $p[6];
			$out['IsAnonymous'] = $p[7];
			break;
		case 6: //微会员卡
			//0名称@@@1图标@@@2背景@@@3封面图片@@@4封面消息@@@5卡号文字颜色@@@6名称文字颜色
			//@@@7使用说明@@@8积分规则说明@@@9签到奖励@@@10消费奖励
			//@@@11商家名称@@@12商家简介@@@13联系方式@@@14商家地址@@@15经度@@@16纬度@@@17商家确认消费密码
			//@@@分店列表(StoreID###StoreName###StoreTelephone###StoreAddress$$$)
			//@@@业务关联LinkName###LinkType###LinkUrl$$$
			$out['CardName'] = $p[0];
			$out['CardIcon'] = $p[1];
			$out['CardBackground'] = $p[2];
			$out['CardPicture'] = $p[3];
			$out['CardTip'] = $p[4];
			
			$out['CardNumberColor'] = $p[5];
			$out['CardNameColor'] = $p[6];
			$out['CardDescription'] = $p[7];
			$out['ScoreDescription'] = $p[8];
			$out['SignAward'] = $p[9];
			
			$out['ConsumeAward'] = $p[10];
			$out['MerchantName'] = $p[11];
			$out['MerchantDescription'] = $p[12];
			$out['MerchantTelephone'] = $p[13];
			$out['MerchantAddress'] = $p[14];
			
			$out['Longitude'] = $p[15];
			$out['Latitude'] = $p[16];
			$out['CardPassword'] = $p[17];
			
			if( !empty($p[18]) ){
				$store = (array)explode('$$$', $p[18]);
				foreach($store as $it){
					$t = (array)explode('###', $it);
					$out['Store'][]=array(
							'StoreID'=>$t[0], 
							'StoreName'=>$t[1], 
							'StoreTelephone'=>$t[2], 
							'StoreAddress'=>$t[3]
					);
				}
			}
			
			if( !empty($p[19]) ){
				$link = (array)explode('$$$', $p[19]);
				foreach($link as $it){
					$t = (array)explode('###', $it);
					$out['Link'][]=array(
							'LinkName'=>$t[0],
							'LinkType'=>$t[1],
							'LinkUrl'=>$t[2]
					);
				}
			}
			
		case 2:  //微调查
			//是否多选@@@开始时间@@@结束时间@@@选项@@@图片@@@结果显示
			$out['IsMultiple'] = $p[0];
			$out['StartTime'] = $p[1];
			$out['EndTime'] = $p[2];
			$out['VotePicture'] = $p[4];
			$out['ShowResult'] = $p[5];
			$temp = (array)explode('$$$', $p[3]);
			foreach ($temp as $it){
				$tt = (array)explode('###', $it);
				$out['Item'][] = array('ItemID'=>$tt[0],'ItemName'=>$tt[1]);
			}
			break;
	}
}
//解析微信应用参数结束========

/**
 * 用于解析内容中的标签，仅支持及少数标签
 * 目前支持的标签右：videoplayer
 * @param string $content
 */
function ParseTag($content){
	$start = stripos($content, '<videoplayer');
	if( $start !== false ){
		$posEnd = stripos($content, '/>', $start);
		$length = $posEnd - $start + 2;
		$tag = substr($content, $start, $length);
		$xml = simplexml_load_string($tag);
		if($xml) {
			$attr = (array)($xml->attributes());
			$attr= array_change_key_case($attr['@attributes']);
			import("@.Common.YdVideoPlayer");
			$v = new YdVideoPlayer( $attr );
			$html = $v->render();
			$content = substr_replace($content, $html, $start, $length);
		}
	}
	return $content;
}
?>