<?php
class ApiAction extends HomeBaseAction {
	//Api初始化
	function _initialize(){
		parent::_initialize();
		error_reporting(0); //API调用关闭所有错误
		define('API_SHOW_TIME', true);
		if(API_SHOW_TIME){
			$GLOBALS['ApiStartTime'] = microtime(TRUE);
			if(MEMORY_LIMIT_ON) {
				$GLOBALS['ApiStartMemory'] = memory_get_usage();
			}
		}
		
		//API通用参数
		$Format = isset($_REQUEST['Format']) ? trim($_REQUEST['Format']) : 'json';
		$Version = isset($_REQUEST['Version']) ? trim($_REQUEST['Version']) : '1.0';
		$LanguageID = isset($_REQUEST['LanguageID']) ? intval($_REQUEST['LanguageID']) : get_language_id();
		$JsonpCallback = isset($_REQUEST['JsonpCallback']) ? trim($_REQUEST['JsonpCallback']) : 'jsonpReturn';
		$HasConfig = isset($_REQUEST['HasConfig']) ? intval($_REQUEST['HasConfig']) : 0;
		$Sign = isset($_REQUEST['Sign']) ? trim($_REQUEST['Sign']) : ''; //签名字符串
		
		//定义常量
		define('API_FORMAT', $Format);
		define('API_VERSION', $Version);
		define('API_LANGUAGE_ID', $LanguageID);
		define('API_JSONP_CALLBACK', $JsonpCallback);
		define('API_HAS_CONFIG', $HasConfig);
		define('API_SIGN', $Sign);
	}
	
	/**
	 * 获取系统配置（不进行签名验证）
	 */
	public function GetConfig(){
		$data['Data'] = $this->GetConfigData();
		$this->ApiReturn($data, '', 1, API_FORMAT);
	}
	
	private function GetConfigData(){
		$config = &$GLOBALS['Config'];
		$domain = get_current_url();
		$AppLogo = app_to_fullurl($config['APP_LOGO'], $domain);
		
		$AppApkUrl = app_to_fullurl($config['APP_APK_URL'], $domain);
		$AppIpaUrl = app_to_fullurl($config['APP_IPA_URL'], $domain);
		$AppApkQrcode = app_to_fullurl($config['APP_APK_QRCODE'], $domain);
		$AppIpaQrcode = app_to_fullurl($config['APP_IPA_QRCODE'], $domain);
		
		$AppAbout = yd_relative_to_absolute($config['APP_ABOUT'], $domain);
		
		$lang = array('cn'=>1, 'en'=>2);
		$LanguageMark = C('DEFAULT_LANG');   //当前默认语言标识名称
		$LanguageID = $lang[$LanguageMark];  //当前默认语言ID
		$EnableMultiLauguage = intval(C('LANG_AUTO_DETECT')); //是否启用多语言
		$data = array(
				'WebName'=>$config['WEB_NAME'],  //网站名称
				'EnableMultiLauguage'=>$EnableMultiLauguage,
				'LanguageMark'=>$LanguageMark,
				'LanguageID'=>$LanguageID,
					
				'AppAbout'=>$AppAbout,
				'AppLogo'=>$AppLogo,
				'AppThemeColor'=>$config['APP_THEME_COLOR'],
				'AppVersion'=>$config['APP_VERSION'],
				'AppVersionDescription'=>nl2br($config['APP_VERSION_DESCRIPTION']),
				
				'AppShareTitle'=>$config['APP_SHARE_TITLE'],
				'AppShareDescription'=>$config['APP_SHARE_DESCRIPTION'],
				'AppApkShareUrl'=>$config['APP_APK_SHARE_URL'],
					
				'AppApkSize'=>$config['APP_APK_SIZE'],
				'AppApkUrl'=>$AppApkUrl,
				'AppApkQrcode'=>$AppApkQrcode,
				'AppIpaUrl'=>$AppIpaUrl,
				'AppIpaQrcode'=>$AppIpaQrcode,
	
				'AppTab2ChannelID'=>$config['APP_TAB2_CHANNELID'],
				'AppTab2Icon'=>$config['APP_TAB2_ICON'],
				'AppTab2Title'=>$config['APP_TAB2_TITLE'],
				'AppTab2IconActive'=>$config['APP_TAB2_ICON_ACTIVE'],
	
				'AppTab3ChannelID'=>$config['APP_TAB3_CHANNELID'],
				'AppTab3Icon'=>$config['APP_TAB3_ICON'],
				'AppTab3Title'=>$config['APP_TAB3_TITLE'],
				'AppTab3IconActive'=>$config['APP_TAB3_ICON_ACTIVE']
				);
				return $data;
	}
	
	/**
	 * 获取频道数据
	 */
	public function GetChannel(){
		$ChannelID = intval($_REQUEST['ChannelID']);
		$Depth = isset($_REQUEST['Depth']) ? intval($_REQUEST['Depth']) : 1;
		$ShowHidden = isset($_REQUEST['ShowHidden']) ? $_REQUEST['ShowHidden'] : 0;
		$IsShow = ($ShowHidden == 0) ? 1 : -1;
		$IDList= isset($_REQUEST['IDList']) ? $_REQUEST['IDList'] : '';
		$ChannelModelID = $_REQUEST['ChannelModelID'];
		$Field = $_REQUEST['Field'];
		$data['Data'] = get_navigation($ChannelID, $Depth, $IDList, $IsShow, $ChannelModelID, API_LANGUAGE_ID, $Field);
		$this->ApiReturn($data, '', 1, API_FORMAT);
	}
	
	/**
	 * 获取信息数据
	 */
	public function GetInfo(){
		$ChannelID = isset($_REQUEST['ChannelID']) ? $_REQUEST['ChannelID'] : 0;
		$SpecialID = isset($_REQUEST['SpecialID']) ? $_REQUEST['SpecialID'] : 0;
		$Top = isset($_REQUEST['Top']) ? $_REQUEST['Top'] : -1;
		$TimeFormat = isset($_REQUEST['TimeFormat']) ? $_REQUEST['TimeFormat'] : 'Y-m-d';
		$TitleLen = isset($_REQUEST['TitleLen']) ? $_REQUEST['TitleLen'] : 0;
		
		$Suffix = isset($_REQUEST['Suffix']) ? $_REQUEST['Suffix'] : '...';
		$LabelID = isset($_REQUEST['LabelID']) ? $_REQUEST['LabelID'] : '';
		$NowPage = isset($_REQUEST['NowPage']) ? $_REQUEST['NowPage'] : 0;
		$PageSize = isset($_REQUEST['PageSize']) ? $_REQUEST['PageSize'] : 0;
		$Keywords = isset($_REQUEST['Keywords']) ? $_REQUEST['Keywords'] : '';
		$OrderBy = isset($_REQUEST['OrderBy']) ? $_REQUEST['OrderBy'] : '';
		
		$MinPrice = isset($_REQUEST['MinPrice']) ? $_REQUEST['MinPrice'] : -1;
		$MaxPrice = isset($_REQUEST['MaxPrice']) ? $_REQUEST['MaxPrice'] : -1;
		$Attr = isset($_REQUEST['Attr']) ? $_REQUEST['Attr'] : '';
		$Field = $_REQUEST['Field'];

		$data['Data'] = get_info($ChannelID, $SpecialID, $Top, $TimeFormat, $TitleLen, $Suffix, $LabelID, $NowPage, $Keywords, 
				$OrderBy, $MinPrice, $MaxPrice, $Attr, API_LANGUAGE_ID, $Field, $PageSize);
		
		//转化为绝对路径
		if( !empty($data['Data']) ){
			$domain = get_current_url();
			$n = count( $data['Data'] );
			for($i=0; $i<$n; $i++){
				$data['Data'][$i]['InfoAttachment'] = app_to_fullurl($data['Data'][$i]['InfoAttachment'], $domain);
				$data['Data'][$i]['InfoPicture'] = app_to_fullurl($data['Data'][$i]['InfoPicture'], $domain);
			}
		}
		
		//分页才运行
		if( !empty($data['Data']) && is_array($data['Data']) && $NowPage > 0){
			$data['Total'] = $data['Data'][0]['Count'];  //信息总条数
			$data['PageSize'] = $PageSize;  //分页大小
			$data['PageCount'] = ceil($data['Total']/$PageSize); //总页数
			$data['NowPage'] = $NowPage;
			$data['HasNextPage'] = ( $NowPage >= $data['PageCount']) ? 0 : 1;
		}else{
			$data['HasNextPage'] = 0;
		}
		$this->ApiReturn($data, '', 1, API_FORMAT);
	}
    
	/**
	 * 查找信息
	 */
	public function FindInfo(){
		$m = D('Admin/Info');
		$data = $m->findinfo($_REQUEST['id']); //可以是id或文件名
		if(empty($data)){
			$this->ApiReturn(false, '', 0, API_FORMAT);
		}
		$id = $data['InfoID'];
		//判断频道是否禁用，频道禁用后，不能查看频道的信息
		$ChannelID = $data['ChannelID'];
		$mc = D('Admin/Channel');
		$channel = $mc->findField($ChannelID,'Parent,HasChild,ReadLevel,ChannelModelID,ChannelName,IsEnable,ChannelSName,Html,LinkUrl,ReadTemplate,Title,Keywords,Description');
		if( $channel['IsEnable'] == 0 ){
			$this->ApiReturn(false, '', 0, API_FORMAT);
		}
		
		//计算特殊字段值start=================================================
		//是否有阅读权限
		if( !empty($data['ReadLevel']) ){
			$ReadLevel = $data['ReadLevel'];
		}else{
			$ReadLevel = ( !empty($channel['ReadLevel']) || $channel['Parent'] == 0) ? $channel['ReadLevel'] : get_read_level( $channel['Parent'] );
		}
		$data['HasReadLevel'] = has_read_level( $ReadLevel ) ? 1 : 0;
		 
		//搜索引擎优化
		if( empty($data['Title']) ) {
			$data['Title'] = !empty($channel['Title']) ? $channel['Title'] : get_title( $channel['Parent'] );
		}
		$data['Title'] = YdInput::checkSeoString($data['Title'] );
		 
		if( empty($data['Keywords']) ) {
			$data['Keywords'] = !empty($channel['Keywords']) ? $channel['Keywords'] : get_keywords( $channel['Parent'] );
		}
		$data['Keywords'] = YdInput::checkSeoString($data['Keywords'] );
		
		if( !empty($data['Description']) ){
			$data['Description'] = YdInput::checkSeoString($data['Description'] );
		}else if( !empty($data['InfoSContent'])  ){
			$data['Description'] = YdInput::checkSeoString($data['InfoSContent']);
		}else if( !empty($data['InfoContent'])  ){
			$data['Description'] = YdInput::checkSeoString($data['InfoContent'] );
			$data['Description'] = Left($data['Description'], 120);
		}
		
		$m->IncHit($id); //文章点击次数加1
		$data['InfoHit'] = $data['InfoHit']+1;
		
		$data['ChannelModelID'] = $channel['ChannelModelID'];
		$data['ChannelName'] = $channel['ChannelName'];
		$data['ChannelUrl'] = ChannelUrl($ChannelID, $channel['Html'], $channel['LinkUrl']);
		$data['ChannelSName'] = $channel['ChannelSName'];
		$data['InfoContent'] = ParseTag( $data['InfoContent'] );
		
		//频道信息
		$wapDomain = get_wx_url();
		$data['InfoUrl'] = InfoUrl($id, $data['Html'], $data['LinkUrl'], false, $data['ChannelID']);
		$data['InfoUrl'] = $wapDomain.$data['InfoUrl'];
		$data['Parent'] = $channel['Parent'];
		$data['HasChild'] = $channel['HasChild'];
		$data['TopChannelID'] = ($channel['Parent']==0) ? $ChannelID : $mc->getTopChannel( $ChannelID );
		$data['TopHasChild'] = ( $channel['HasChild'] == 1 ||  $channel['Parent'] != 0 ) ? 1 : 0;
		$data['DiscountPrice'] = $data['InfoPrice'] * $GLOBALS['DiscountRate'];
		$data['InfoFriendTime'] = yd_friend_date(strtotime( $data['InfoTime'] ));
		
		//内容相对路径转化为绝对路径
		$domain = get_current_url();
		$data['InfoContent'] = yd_relative_to_absolute( $data['InfoContent'] ,$domain);
		$data['f1'] = yd_relative_to_absolute( $data['f1'] ,$domain);
		$data['f2'] = yd_relative_to_absolute( $data['f2'] ,$domain);
		$data['f3'] = yd_relative_to_absolute( $data['f3'] ,$domain);
		$data['f4'] = yd_relative_to_absolute( $data['f4'] ,$domain);
		$data['f5'] = yd_relative_to_absolute( $data['f5'] ,$domain);
		//地址转换
		$data['ChannelUrl'] = app_to_fullurl($data['ChannelUrl'], $domain);
		$data['InfoUrl'] = app_to_fullurl($data['InfoUrl'], $domain);
		$data['InfoPicture'] = app_to_fullurl($data['InfoPicture'], $domain);
		$data['VideoPlayer'] = app_video_player($data['InfoAttachment'], $domain);
		$data['InfoAttachment'] = app_to_fullurl($data['InfoAttachment'], $domain);
		
		//获取是否被收藏
		if( isset($_REQUEST['MemberID']) && $_REQUEST['MemberID']>0 ){
			$mf = D('Admin/Favorite');
			$data['IsFavorite'] = $mf->isAdd($id, $_REQUEST['MemberID']);
		}else{
			$data['IsFavorite'] = 0;
		}
		
		unset($data['MemberID']); //禁止使用MemberID
		$this->ApiReturn(array('Data'=>$data), '', 1, API_FORMAT);
	}
	
	/**
	 * 登陆检查
	 */
	public function Login(){
		$this->checkSign();
		$MemberName = trim($_POST['MemberName']);
		$MemberPassword = trim($_POST['MemberPassword']);
		if($MemberName == ''){
			$this->ApiReturn(null, L('UserNameRequired'), 0, API_FORMAT);
		}
		if($MemberPassword == ''){
			$this->ApiReturn(null, L('PasswordRequired'), 0, API_FORMAT);
		}
		
		$m = D('Admin/Member');
		$LoginFailCount = $m->getLoginFailCount($MemberName);
		if($LoginFailCount > 20){
			$this->ApiReturn(null, L('PasswordErrorMaxCount'), 0, API_FORMAT);
		}
		
		//0: 用户名或密码错误，1：用户被锁定，2:用户组不存在，数组：认证成功
		$result = $m->checkLogin($MemberName, md5($MemberPassword) );
		if( $result == 0 ){
			$this->ApiReturn(null, L('UserNamePasswordError'), 0, API_FORMAT);
		}else if($result == 1){
			$this->ApiReturn(null, L('AccountLock'), 0, API_FORMAT);
		}else if($result == 2){
			$this->ApiReturn(null, L('AdminGroupNotExist'), 0, API_FORMAT);
		}else if($result == 3){
			$this->ApiReturn(null, L('AccountUnchecked'), 0, API_FORMAT);
		}else if( is_array($result) ){ //认证成功
			$m->UpdateLogin($result['MemberID']);
			$data['Data']=array(
					'MemberID'=>$result['MemberID'],
					'MemberName'=>$result['MemberName'],
					'MemberGender'=>$result['MemberGender'],
					'MemberTelephone'=>$result['MemberTelephone'],
					'MemberEmail'=>$result['MemberEmail'],
					'MemberQQ'=>$result['MemberQQ'],
					
					'RegisterTime'=>$result['RegisterTime'],
					'RegisterIP'=>$result['RegisterIP'],
					
					'MemberMobile'=>$result['MemberMobile'],
					'MemberGroupID'=>$result['MemberGroupID'],
					'MemberGroupName'=>$result['MemberGroupName'],
					'MemberAvatar'=>app_to_fullurl($result['MemberAvatar']),
					'DiscountRate'=>$result['DiscountRate'],
			);
			$this->ApiReturn($data, L('LoginSuccess'), 1, API_FORMAT);
		}
	}
	
	/**
	 * 自动登录
	 */
	public function AutoLogin(){
		$this->checkSign();
		$MemberName = trim($_POST['MemberName']);
		$MemberPassword = trim($_POST['MemberPassword']);
		if($MemberName == '' || $MemberPassword == ''){
			$this->ApiReturn(null, '', 0, API_FORMAT);
		}
		$m = D('Admin/Member');
		$LoginFailCount = $m->getLoginFailCount($MemberName);
		$MaxLoginFailCount = 20;
		if($LoginFailCount > $MaxLoginFailCount){
			$this->ApiReturn(null, L('PasswordErrorMaxCount'), 0, API_FORMAT);
		}
		
		//0: 用户名或密码错误，1：用户被锁定，2:用户组不存在，数组：认证成功
		$result = $m->checkLogin($MemberName, md5($MemberPassword) );
		if( is_array($result) ){ //认证成功
			$m->UpdateLogin($result['MemberID']);
			$data['Data']=array(
					'MemberID'=>$result['MemberID'],
					'MemberName'=>$result['MemberName'],
					'MemberGender'=>$result['MemberGender'],
					'MemberTelephone'=>$result['MemberTelephone'],
					'MemberEmail'=>$result['MemberEmail'],
					'MemberQQ'=>$result['MemberQQ'],
					
					'RegisterTime'=>$result['RegisterTime'],
					'RegisterIP'=>$result['RegisterIP'],
						
					'MemberMobile'=>$result['MemberMobile'],
					'MemberGroupID'=>$result['MemberGroupID'],
					'MemberGroupName'=>$result['MemberGroupName'],
					'MemberAvatar'=>app_to_fullurl($result['MemberAvatar']),
					'DiscountRate'=>$result['DiscountRate'],
			);
			$this->ApiReturn($data, '', 1, API_FORMAT);
		}
		$this->ApiReturn(null, '', 0, API_FORMAT);
	}
	
	/**
	 * 注册
	 */
	public function Reg(){
		$this->checkSign();
		$_REQUEST = YdInput::checkReg($_POST, array('MemberPassword','MemberPassword1') ); //防止xss注入
		
		$ip = get_client_ip();
		if(!app_can_reg($ip)){
			$this->ApiReturn(null, L('RegFail'), 0, API_FORMAT);
		}
		
		//手机号码
		$MemberMobile = trim($_POST['MemberMobile']);
		if( $MemberMobile == '' ){
			$this->ApiReturn(null, L('MobileRequired'), 0, API_FORMAT);
		}
		
		//检查手机号码是否已经被注册
		$m = D('Admin/Member');
		if( $m->hasMobile($MemberMobile) ){
			$this->ApiReturn(null, L('MemberMobileExist'), 0, API_FORMAT);
		}
		
		//验证密码=====================================
		$MemberPassword = trim($_POST['MemberPassword']);
		if( $MemberPassword == '' ){
			$this->ApiReturn(null, L('PasswordRequired'), 0, API_FORMAT);
		}
		
		$MemberPassword1 = trim($_POST['MemberPassword1']);
		if( $MemberPassword1 == '' ){
			$this->ApiReturn(null, L('ConfirmPasswordRequired'), 0, API_FORMAT);
		}
		
		if( $MemberPassword != $MemberPassword1 ){
			$this->ApiReturn(null, L('PasswordUnmatch'), 0, API_FORMAT);
		}
		//============================================
		
		$data['MemberMobile'] = $MemberMobile;
		$data['MemberPassword'] = md5($MemberPassword);
		$data['RegisterTime'] = date('Y-m-d H:i:s');
		$data['RegisterIP'] = $ip;
		$data['IsCheck'] = 1;
		$MemberID = $m->add($data);
		if( $MemberID ){
			$result = $m->field("MemberID,MemberName,MemberMobile,MemberGroupID,MemberAvatar")->find($MemberID);
			$mg = D('Admin/MemberGroup');
			$group = $mg->field("MemberGroupName,DiscountRate")->find($result['MemberGroupID']);
			$reg['Data']=array(
					'MemberID'=>$result['MemberID'],
					'MemberName'=>$result['MemberName'],
					'MemberMobile'=>$result['MemberMobile'],
					'MemberGroupID'=>$result['MemberGroupID'],
					'MemberGroupName'=>$group['MemberGroupName'],
					'MemberAvatar'=>app_to_fullurl($result['MemberAvatar']),
					'DiscountRate'=>$group['DiscountRate'],
				);
				$this->ApiReturn($reg, L('RegSuccessNoCheck'), 1, API_FORMAT);
			}else{
				$this->ApiReturn(null, L('RegFail'), 0, API_FORMAT);
			}
	}
	
	/**
	 * 找回密码
	 */
	public function Forget(){
		$this->checkSign();
		header("Content-Type:text/html; charset=utf-8");
		$Step = trim( $_POST['Step'] );  //当前步骤
		if( $Step == 1 ){   //第一步：验证用户是否存在
			$MemberName = trim( $_POST['MemberName'] ); //可以是用户名、电子邮件、手机号码
			if( $MemberName == ''){
				$this->ApiReturn(null, L('UserNameRequired'), 0, API_FORMAT);
			}
		
			$m = D('Admin/Member');
			$data = $m->getFindPwdData($MemberName);
			if( empty($data)){
				$this->ApiReturn(null, L('UserNotExist'), 0, API_FORMAT);
			}else{
				$result['Data']['SmsEnable'] = $GLOBALS['Config']['SMS_ACCOUNT'] ? 1 : 0;
				$result['Data'] = $data;
				$this->ApiReturn($result, 'success', 1, API_FORMAT);
			}
		}else if( $Step == 2 ){   //第二部：密码重置
			//先检查密码
			$MemberPassword = trim($_POST['MemberPassword']);
			if( $MemberPassword == '' ){
				$this->ApiReturn(null, L('PasswordRequired'), 0, API_FORMAT);
			}
			$MemberPassword1 = trim($_POST['MemberPassword1']);
			if( $MemberPassword1 == '' ){
				$this->ApiReturn(null, L('ConfirmPasswordRequired'), 0, API_FORMAT);
			}
			if( $MemberPassword != $MemberPassword1 ){
				$this->ApiReturn(null, L('PasswordUnmatch'), 0, API_FORMAT);
			}
		
			$m = D('Admin/Member');
			$where['MemberID'] = intval( $_POST['MemberID'] );
			if( $_POST['FindPwdWay'] == 2 ){ //1:密码问题，2：手机
				//手机找回密码，暂未实现
				//检查短信验证码是否有效
				/*
				$SmsCode = trim($_REQUEST['SmsCode']);
				if( $SmsCode == '' ){
					$this->ApiReturn(null, L('SmsCodeRequired'), 0, API_FORMAT);
				}
				$SmsCode1 = session('SmsCode');
				if( $SmsCode != $SmsCode1){
					$this->ApiReturn(null, L('SmsCodeError'), 0, API_FORMAT);
				}
				*/
			}else{
				//检查密保答案
				$MemberAnswer = trim( $_POST['MemberAnswer'] );
				if( $MemberAnswer == ''){
					$this->ApiReturn(null, L('AnswerRequired'), 0, API_FORMAT);
				}
				$answer = $m->where($where)->getField('MemberAnswer');
				if( empty($answer) || $MemberAnswer != $answer){
					$this->ApiReturn(null, L('AnswerError'), 0, API_FORMAT);
				}
			}
			$result =  $m->where($where)->setField('MemberPassword', md5($MemberPassword) );
			if( $result === false ){
				$this->ApiReturn(null, L('ResetPwdFail'), 0, API_FORMAT);
			}else{
				$this->ApiReturn(null, L('ResetPwdSuccess'), 1, API_FORMAT);
			}
		}
	}
	
    /**
     * 获取评论数据
     */
    public function GetComment(){
    	//接口参数
    	$params['InfoID'] = intval( $_REQUEST['InfoID'] );  //评论InfoID
    	$params['CommentRank'] = isset($_REQUEST['CommentRank']) ? intval($_REQUEST['CommentRank']) : -1; //-1:表示返回所有评论
    	$params['LanguageID'] = API_LANGUAGE_ID;
    	$params['IsCheck'] = 1;
    	$params['Parent'] = 0; //不获取回复的信息
    	$params['ReplyComments'] = 1; //获取回复数据
    
    	//分页
    	$p = isset($_REQUEST['p']) ? intval($_REQUEST['p']) : 1;  //当前页
    	if( isset($_REQUEST['PageSize']) ){
    		$PageSize = intval($_REQUEST['PageSize']);
    	}else{
    		$PageSize = intval( $GLOBALS['Config']['COMMENT_PAGE_SIZE'] );
    	}
    	if( $PageSize <= 0 ) $PageSize = 20;
    
    	$m = D('Admin/Comment');
    	$TotalItemCount = $m->getCommentCount($params);
    	$data['CurrentPage'] = $p; //当前页码
    	$data['PageSize'] = $PageSize; //分页大小
    	$data['TotalItemCount'] = $TotalItemCount; //单项总条数
    	if($TotalItemCount <= 0){
    		$data['TotalPage'] = 0;
    	}else{
    		$data['TotalPage'] = ceil($TotalItemCount/$PageSize); //总页数
    		$Offset = $PageSize*($p-1);
    		$data['Data'] = $m->getComment($Offset, $PageSize, $params);
    	}
    	$this->ApiReturn($data, '', 1, API_FORMAT);
    }
    
    /**
     * 统计评论数据（本地使用，非APP使用）
     */
    public function StatComment(){
    	//接口参数
    	$InfoID = intval( $_REQUEST['InfoID'] );  //评论ID
    	$m = D('Admin/Comment');
    	//获取评论统计数
    	$stat = $m->statCommenRank($InfoID, -1, API_LANGUAGE_ID);
    	$data['PositiveCount'] = isset($stat[3]) ? $stat[3] : 0;
    	$data['NeutralCount'] = isset($stat[2]) ? $stat[2] : 0;
    	$data['NegativeCount'] = isset($stat[1]) ? $stat[1] : 0;
    	$TotalCount = $data['PositiveCount'] + $data['NeutralCount'] + $data['NegativeCount'];
    	$data['PositiveRate'] = ($TotalCount > 0) ? round($data['PositiveCount']*100/$TotalCount) : 0;
    	$data['NeutralRate'] = ($TotalCount > 0) ? round($data['NeutralCount']*100/$TotalCount) : 0;
    	$data['NegativeRate'] = ($TotalCount > 0) ? round($data['NegativeCount']*100/$TotalCount) : 0;
    	$data['TotalCount'] = $TotalCount;  //评论总数
    	$this->ApiReturn($data, '', 1, API_FORMAT);
    }
    
    /**
     * 浏览历史
     */
    public function GetHistory(){
    	$this->checkSign();
    	//接口参数
    	$params['MemberID'] = intval( $_POST['MemberID'] );
    	$params['LanguageID'] = API_LANGUAGE_ID;
    	$NowPage = isset($_POST['NowPage']) ? $_POST['NowPage'] : 1;
    	$PageSize = isset($_POST['PageSize']) ? $_POST['PageSize'] : 20;
    	 
    	$m = D('Admin/History');
    	$Total = $m->getHistoryCount($params);
    	//初始化结果
    	$result = array('Data' => false, 'PageSize' => $PageSize, 'PageCount' => 0, 'NowPage' => $NowPage, 'HasNextPage' => 0 );
    	if( $Total > 0 ) {
    		$offset = ($NowPage - 1 > 0) ? ($NowPage - 1)*$PageSize : 0;
    		$data = $m->getHistory($offset, $PageSize, $params);
    		if( !empty($data)){
    			$domain = get_current_url();
    			$n = count( $data );
    			for($i=0; $i<$n; $i++){
    				$timestamp = strtotime( $data[$i]['InfoTime'] );
    				$data[$i]['InfoFriendTime'] = yd_friend_date($timestamp);
    				$data[$i]['InfoAttachment'] = app_to_fullurl($data[$i]['InfoAttachment'], $domain);
    				$data[$i]['InfoPicture'] = app_to_fullurl($data[$i]['InfoPicture'], $domain);
    			}
    			$result['Data'] = $data;  //数据
    			$result['Total'] = $Total;  //信息总条数
    			$result['PageSize'] = $PageSize;  //分页大小
    			$result['PageCount'] = ceil($Total/$PageSize); //总页数
    			$result['NowPage'] = $NowPage;
    			$result['HasNextPage'] = ( $NowPage >= $result['PageCount']) ? 0 : 1;
    		}
    	}
    	$this->ApiReturn($result, '', 1, API_FORMAT);
    }
    
    /**
     * 保存浏览器历史
     */
    public function AddHistory(){
    	$this->checkSign();
    	//判断InfoID是否存在
    	$InfoID = intval($_POST['InfoID']);
    	$MemberID = intval($_POST['MemberID']);
    	if( !app_info_exist($InfoID) || !app_member_exist($MemberID) ){
    		$this->ApiReturn(null, '', 0, API_FORMAT);
    	}
    	$m = D('Admin/History');
    	$result = $m->addHistory($InfoID, $MemberID); //做了不能重复添加的控制
    	$this->ApiReturn(null, '', 1, API_FORMAT);
    }
    
    /**
     * 我的收藏
     */
    public function GetFavorite(){
    	$this->checkSign();
    	//接口参数
    	$params['MemberID'] = intval( $_POST['MemberID'] );
    	$params['LanguageID'] = API_LANGUAGE_ID;
    	$NowPage = isset($_POST['NowPage']) ? $_POST['NowPage'] : 1;
    	$PageSize = isset($_POST['PageSize']) ? $_POST['PageSize'] : 20;
    	
    	$m = D('Admin/Favorite');
    	$Total = $m->getFavoriteCount($params);
    	//初始化结果
    	$result = array('Data' => false, 'PageSize' => $PageSize, 'PageCount' => 0, 'NowPage' => $NowPage, 'HasNextPage' => 0 );
    	if( $Total > 0 ) {
    		$offset = ($NowPage - 1 > 0) ? ($NowPage - 1)*$PageSize : 0;
    		$data = $m->getFavorite($offset, $PageSize, $params);
    		if( !empty($data)){
    			$domain = get_current_url();
    			$n = count( $data );
    			for($i=0; $i<$n; $i++){
    				$timestamp = strtotime( $data[$i]['InfoTime'] );
    				$data[$i]['InfoFriendTime'] = yd_friend_date($timestamp);
    				$data[$i]['InfoAttachment'] = app_to_fullurl($data[$i]['InfoAttachment'], $domain);
    				$data[$i]['InfoPicture'] = app_to_fullurl($data[$i]['InfoPicture'], $domain);
    			}
    			
    			$result['Data'] = $data;  //数据
    			$result['Total'] = $Total;  //信息总条数
    			$result['PageSize'] = $PageSize;  //分页大小
    			$result['PageCount'] = ceil($Total/$PageSize); //总页数
    			$result['NowPage'] = $NowPage;
    			$result['HasNextPage'] = ( $NowPage >= $result['PageCount']) ? 0 : 1;
    		}
    	}
    	$this->ApiReturn($result, '', 1, API_FORMAT);
    }
    
    /**
     * 加入收藏
     */
    public function AddFavorite(){
    	$this->checkSign();
    	if( !app_info_exist($_REQUEST['InfoID']) ){
    		$this->ApiReturn(null, L('FavoriteFail'), 0, API_FORMAT);
    	}
    	$m = D('Admin/Favorite');
    	//有写入数据的请求必须是POST提交
    	if( isset( $_POST['IsAdd']) ){
    		$InfoID = intval( $_POST['InfoID'] );
    		$MemberID = intval( $_POST['MemberID'] );
    		if( !app_member_exist($MemberID) || !app_can_favorite($MemberID)){
    			$this->ApiReturn(null, L('LoginFirst'), 0, API_FORMAT);
    		}
    		$where['InfoID'] = $InfoID;
    		$where['MemberID'] = $MemberID;
	    	if( $_POST['IsAdd'] == 1){
	    		//先判断用户是否已经收藏当前文章
		    	$n = $m->where($where)->count();
		    	if( $n > 0 ){
		    		$this->ApiReturn(null, L('FavoriteSuccess'), 1, API_FORMAT);
		    	}else{
		    		$data['InfoID'] = $InfoID;
		    		$data['MemberID'] = $MemberID;
		    		$data['FavoriteTime'] = date('Y-m-d H:i:s');
		    		if( $m->add($data) ){
		    			$this->ApiReturn(null, L('FavoriteSuccess'), 1, API_FORMAT);
		    		}else{
		    			$this->ApiReturn(null, L('FavoriteFail'), 0, API_FORMAT);
		    		}
		    	}
    		}else{  //取消收藏
    			$m->delFavorite($InfoID, array('MemberID'=>$MemberID));
    			$this->ApiReturn(null, L('CancelFavorite'), 1, API_FORMAT);
    		}
    	}else{ //==主要在本地调用==
	    	$MemberID = intval( session('MemberID') );
	    	if( empty($MemberID) ){
	    		$this->ApiReturn(null, L('LoginFirst'), 2, API_FORMAT);
	    	}
	    	if( !app_can_favorite($MemberID) ){
	    		$this->ApiReturn(null, L('FavoriteFail'), 0, API_FORMAT);
	    	}
	    	$where['InfoID'] = intval( $_REQUEST['InfoID'] );
	    	$where['MemberID'] = $MemberID;
	    	$n = $m->where($where)->count();
	    	if( $n > 0 ){
	    		$this->ApiReturn(null, L('FavoriteSuccess'), 1, API_FORMAT);
	    	}else{
	    		$data['InfoID'] = intval( $_REQUEST['InfoID'] );
	    		$data['MemberID'] = $MemberID;
	    		$data['FavoriteTime'] = date('Y-m-d H:i:s');
	    		if( $m->add($data) ){
	    			$this->ApiReturn(null, L('FavoriteSuccess'), 1, API_FORMAT);
	    		}else{
	    			$this->ApiReturn(null, L('FavoriteFail'), 0, API_FORMAT);
	    		}
	    	}
    	}
    }
    
    /**
     * 验证签名是否正确
     */
    private function checkSign(){
    	//return true; //调试模式，不校验签名
    	if(API_SIGN){ //只有签名存在的时候才进行服务器端认证
    		//先检查是否接口权限
    		$m = D('Admin/Secret');
    		$AppSecret = $m->checkSecret($_POST['AppID'], P_ACTION_NAME);
    		if(empty($AppSecret)){
    			$this->ApiReturn(null, L('ApiNoPermission'), 0, API_FORMAT);
    		}
    		
    		//签名认证
	    	$temp = app_para_filter($_REQUEST);
	    	ksort($temp); reset($temp);
	    	$sign = app_build_sign($temp, $AppSecret);
	    	//判断签名是否正确
	    	if(API_SIGN != $sign){
	    		$this->ApiReturn(null, L('AppSignError'), 0, API_FORMAT);
	    	}
	    	
	    	//判断时间戳是否正确
	    	$MaxTimeout = 30; //超时时间
	    	$timestamp = intval($_REQUEST['Timestamp']);
	    	$diff = time() - $timestamp;
	    	if($diff > $MaxTimeout){
	    		$this->ApiReturn(null, L('AppTimestampError'), 0, API_FORMAT);
	    	}
    	}else{
    		//如果是同域认证，就没有必要进行签名认证
    	}
    }
    
    function AddAppFeedback(){
    	$this->checkSign();
    	$ip = get_client_ip();
    	if( !app_can_feedback($ip) ){
    		$this->ajaxReturn(null, L('FeedbackFail') , 0, API_FORMAT);
    	}
    	
    	$m = D('Admin/AppFeedback');
    	if( $_POST['AppFeedbackContent'] == '' ){
    		$this->ApiReturn(null, L('AppFeedbackContentRequired'), 0, API_FORMAT);
    	}
    	$data['AppFeedbackContent'] = $_POST['AppFeedbackContent'];
    	$data['AppFeedbackContact'] = $_POST['AppFeedbackContact'];
    	$data['Uuid'] = $_POST['Uuid'];
    	$data['MemberID'] = intval($_POST['MemberID']);
    	$data['AppFeedbackTime'] = date('Y-m-d H:i:s');
    	$data['AppFeedbackImage'] = app_remove_domain($_POST['AppFeedbackImage']);
    	$data['AppFeedbackIp'] = $ip;
    	if($m->add($data)){
    		$this->ApiReturn(null, L('FeedbackSuccess'), 1, API_FORMAT);
    	}else{
    		$this->ajaxReturn(null, L('FeedbackFail') , 0, API_FORMAT);
    	}
    }
    
    /**
     * 上传设备数据
     */
    function UploadDevice(){
    	$this->checkSign();
    	$Uuid = trim($_POST['Uuid']);
    	$ip = get_client_ip();
    	$time = date('Y-m-d H:i:s');
    	if(empty($Uuid) || !app_can_stat($ip)){
    		$this->ajaxReturn(null, null , 0, API_FORMAT);
    	}
    	
    	$m = D('Admin/AppStat');
    	$result = $m->where("Uuid='{$Uuid}'")->getField('Uuid');
    	if(!empty($result)){ //如果已经登记，则记录到活动表中
    		$ma = D('Admin/AppActive');
    		$active['Uuid'] = $Uuid;
    		$active['Ip'] = $ip;
    		$active['StartTime'] = $time;
    		$result = $ma->add($active);
    		$this->ApiReturn(null, null, 1, API_FORMAT);
    	}
    	
    	$data['Uuid'] = $Uuid;
    	$data['Platform'] = $_POST['Platform'];
    	$data['Model'] = $_POST['Model'];
    	$data['Manufacturer'] = $_POST['Manufacturer'];
    	$data['Ip'] = $ip;
    	$data['Time'] = $time;
    	//保存反馈
    	if($m->add($data)){
    		$this->ApiReturn(null, null, 1, API_FORMAT);
    	}else{
    		$this->ajaxReturn(null, null, 0, API_FORMAT);
    	}
    }
    
    /**
     * 修改个人密码
     */
    function ModifyPassword(){
    	$this->checkSign();
    	$MemberID = intval($_POST['MemberID']);
    	$OldPassword = trim($_POST['OldPassword']);
    	$NewPassword = trim($_POST['NewPassword']);
    	$ConfirmPassword = trim($_POST['ConfirmPassword']);
    	//会员ID
    	if( empty($MemberID) ){
    		$this->ApiReturn(null, L('ModifyPwdFail'), 0, API_FORMAT);
    	}
    	//旧密码
    	if( empty($OldPassword) ){
    		$this->ApiReturn(null, L('OldPasswordRequired'), 0, API_FORMAT);
    	}
    	//新密码
    	if( empty($NewPassword) ){
    		$this->ApiReturn(null, L('NewPasswordRequired'), 0, API_FORMAT);
    	}
    	//确认密码
    	if( empty($ConfirmPassword) ){
    		$this->ApiReturn(null, L('ConfirmPasswordRequired'), 0, API_FORMAT);
    	}
    	if( $NewPassword != $ConfirmPassword ){
    		$this->ApiReturn(null, L('PasswordUnmatch'), 0, API_FORMAT);
    	}
    	if( $NewPassword == $OldPassword ){
    		$this->ApiReturn(null, L('NewOldPasswordCanNotSame'), 0, API_FORMAT);
    	}
    	
    	//判断原始密码是否正确
    	$m = D('Admin/Member');
    	$where['MemberID'] = $MemberID;
    	$where['MemberPassword'] = md5($OldPassword);
    	$n = $m->where( $where )->count();
    	if($n == 0){
    		$this->ApiReturn(null, L('OldPasswordIncorrect'), 0, API_FORMAT);
    	}

    	//修改密码
    	$result = $m->where("MemberID=$MemberID")->setField('MemberPassword', md5($NewPassword) );
    	if($result){
    		$this->ApiReturn(null, L('ModifyPwdSuccess'), 1, API_FORMAT);
    	}else{
    		$this->ApiReturn(null, L('ModifyPwdFail'), 0, API_FORMAT);
    	}
    }
    
    /**
     * 修改个人资料
     */
    function ModifyMemberInfo(){
    	$this->checkSign();
    	$MemberAvatar = $_POST['MemberAvatar']; 
    	$data['MemberAvatar'] = app_remove_domain($MemberAvatar); //保存的时候必须移除前缀
    	$data['MemberGender'] = intval($_POST['MemberGender']);
    	$data['MemberMobile'] = $_POST['MemberMobile'];
    	$data['MemberTelephone'] = $_POST['MemberTelephone'];
    	$data['MemberEmail'] = $_POST['MemberEmail'];
    	$data['MemberQQ'] = $_POST['MemberQQ'];
    	
    	$m = D('Admin/Member');
    	//增加RegisterTime和RegisterIP作为查询条件，增强安全性
    	$where['MemberID'] = intval($_POST['MemberID']);
    	$where['RegisterTime'] = $_POST['RegisterTime'];
    	$where['RegisterIP'] = $_POST['RegisterIP'];
    	$where['IsCheck'] = 1;
    	$where['IsLock'] = 0;
    	$result = $m-> where($where)->setField($data);
    	if($result===false){ //修改失败
    		$this->ApiReturn(null, L('ModifyFail'), 0, API_FORMAT);
    	}else{
    		$data['MemberAvatar'] = $MemberAvatar; //返回的地址必须包含域名前缀
    		$this->ApiReturn(array('Data'=>$data), L('ModifySuccess'), 1, API_FORMAT);
    	}
    }
    
    /**
     * 上传文件
     */
    function UploadFile(){
    	$this->checkSign();
    	$d = &$GLOBALS['Config'];
    	import("ORG.Net.UploadFile");
    	$upload = new UploadFile();
    	//设置上传文件大小
    	$upload->maxSize  = $d['MAX_UPLOAD_SIZE'] ; //最大上传大小
    	//设置上传文件类型，禁止上传asp,aspx,jsp,php,ashx,js,html,htm，增强安全性
    	$deniedExt = array('asa','asp', 'aspx', 'cdx','ascx', 'vbs', 'ascx', 'jsp', 'ashx', 'js',  'reg',  'cgi','html', 'htm','shtml',
    			'cfm', 'cfc', 'pl', 'bat', 'exe',  'com',  'dll',  'htaccess', 'cer', 'php5', 'php4', 'php3', 'php2', 'php');
    	$allowExts = str_ireplace($deniedExt, '', $d['UPLOAD_FILE_TYPE']);
    	$upload->allowExts  = explode('|', $allowExts);
    	//设置附件上传目录
    	$AppUploadDir = $d['UPLOAD'].'app/';
    	if( !is_dir($AppUploadDir) ){
    		mkdir($AppUploadDir,0755,true);
    	}
    	$upload->savePath =  $AppUploadDir;
    	$upload->saveRule= time;
    	
    	//IMG_20170129_114000.jpg?1487235976450，插入的图片文件包含?，必须去掉
    	$offset = strpos($_FILES['appfile']['name'], '?');
    	if( $offset !== false){
    		$_FILES['appfile']['name'] = substr($_FILES['appfile']['name'], 0, $offset);
    	}
    	
    	if($upload->upload()) {
    		$info =  $upload->getUploadFileInfo();
    		//上传后文件的路径
    		$path = __ROOT__.'/'.substr($AppUploadDir.$info[0]['savename'], 2);
    		$data['Data'] = app_to_fullurl($path); //加上域名前缀
    		$this->ApiReturn($data, '', 1, API_FORMAT);
    	}else{
    		$data['Data'] = '';
    		$this->ApiReturn($data, '', 0, API_FORMAT);
    	}
    }
    
    /**
     * 获取推送消息
     */
    function GetAppMessage(){
    	//接口参数
    	$params['AppMessageType'] = $_REQUEST['AppMessageType'];
    	$NowPage = isset($_REQUEST['NowPage']) ? $_REQUEST['NowPage'] : 1;
    	$PageSize = isset($_REQUEST['PageSize']) ? $_REQUEST['PageSize'] : 20;
    	
    	$m = D('Admin/AppMessage');
    	$Total = $m->getAppMessageCount($params);
    	//初始化结果
    	$result = array('Data' => false, 'PageSize' => $PageSize, 'PageCount' => 0, 'NowPage' => $NowPage, 'HasNextPage' => 0 );
    	if( $Total > 0 ) {
    		$offset = ($NowPage - 1 > 0) ? ($NowPage - 1)*$PageSize : 0;
    		$data = $m->getAppMessage($offset, $PageSize, $params);
    		if( !empty($data)){
    			$domain = get_current_url();
    			$n = count( $data );
    			for($i=0; $i<$n; $i++){
    				$timestamp = strtotime( $data[$i]['AppMessageTime'] );
    				$data[$i]['AppMessageTime'] = yd_friend_date($timestamp);
    				$data[$i]['AppMessageContent'] = yd_relative_to_absolute(ParseTag( $data[$i]['AppMessageContent'] ) );
    			}
    			 
    			$result['Data'] = $data;  //数据
    			$result['Total'] = $Total;  //信息总条数
    			$result['PageSize'] = $PageSize;  //分页大小
    			$result['PageCount'] = ceil($Total/$PageSize); //总页数
    			$result['NowPage'] = $NowPage;
    			$result['HasNextPage'] = ( $NowPage >= $result['PageCount']) ? 0 : 1;
    		}
    	}
    	$this->ApiReturn($result, '', 1, API_FORMAT);
    }
    
    /**
     * 查找推送消息
     */
    public function FindAppMessage(){
    	$m = D('Admin/AppMessage');
    	$data = $m->findAppMessage($_REQUEST['id']); //可以是id或文件名
    	if(empty($data)){
    		$this->ApiReturn(false, '', 0, API_FORMAT);
    	}
    	$data['AppMessageContent'] = yd_relative_to_absolute(ParseTag( $data['AppMessageContent'] ));
    	$data['AppMessageTime'] = yd_friend_date(strtotime( $data['AppMessageTime'] ));
    	$this->ApiReturn(array('Data'=>$data), '', 1, API_FORMAT);
    }
    
    /**
     * Ajax数据返回
     * @param mix $data 返回的数据
     * @param string $info 状态文本信息
     * @param int $status 状态 1：成功，0：失败
     * @param string $format 返回的格式，如：json，xml
     */
    private function ApiReturn($data, $msg='', $status=1, $format='json') {
    	$data['Status'] = $status;
    	$data['Message'] = $msg;
    	if(empty($format)) $format = 'json';
    	if(API_SHOW_TIME){
    		$ApiExecTime = microtime(TRUE) - $GLOBALS['ApiStartTime'];
    		$data['Debug']['ApiExecTime'] = number_format($ApiExecTime, 3) . 's';
    		if(MEMORY_LIMIT_ON) {
    			$ApiUseMemory = (memory_get_usage() - $GLOBALS['ApiStartMemory'])/1024/1024;
    			$data['Debug']['ApiUseMemory'] = number_format($ApiUseMemory,3).'M';
    		}
    		if( class_exists('Db',false) ) {
    			$data['Debug']['ApiDbRead'] = N('db_query');
    			$data['Debug']['ApiDbWrite'] = N('db_write');
    		}
    		$data['Debug']['ApiLoadFile'] = count(get_included_files());
    		$fun  =  get_defined_functions();
    		$data['Debug']['UserFunction'] = count($fun['user']);
    		$data['Debug']['InternalFunction'] = count($fun['internal']);
    	}
    	//表示获取配置数据
    	if(API_HAS_CONFIG){
    		$data['Config']= $this->GetConfigData();
    	}
    	switch(strtoupper($format)){
    		case 'JSON':
    			header('Content-Type:text/html; charset=utf-8');
    			$this->OutuptAllOrginHeader();
    			$data = json_encode($data);
    			exit($data);
    		//case 'JSONP':  //有很大的风险
    		//	header('Content-Type:text/html; charset=utf-8');
    		//	$data = json_encode($data);
    		//	exit(API_JSONP_CALLBACK."({$data});");
    		case 'XML':
    			header('Content-Type:text/xml; charset=utf-8');
    			$this->OutuptAllOrginHeader();
    			$data = xml_encode($data);
    			exit($data);
    		default:
    			exit();
    	}
    }
    
    /**
     * 是否允许输出Access-Control-Allow-Origin头
     */
    private function OutuptAllOrginHeader(){
    	$bOutput = false;
    	if(API_SIGN) {
    		$bOutput = true;
    	}else{
    		//下面这些函数任何人都可以调用，不需要控制权限，需要输出跨域头
    		$list = array('findappmessage'=>'', 'findinfo'=>'', 'getappmessage'=>'','getchannel'=>'',
    		'getcomment'=>'','getconfig'=>'','getinfo'=>'','statcomment'=>'',);
    		$name = strtolower(ACTION_NAME);
			if(key_exists($name, $list)){
				$bOutput = true;
			}
    	}
    	if($bOutput){
    		header("Access-Control-Allow-Origin: *");
    	}
    }
}

/**
 * 判断信息是否存在
 * @param int $InfoID
 * @return int
 */
function app_info_exist($InfoID){
	$m = D('Admin/Info');
	$where['InfoID'] = intval($InfoID);
	$where['IsEnable'] = 1;
	$id = $m->where($where)->getField('InfoID');
	return $id;
}

/**
 * 判断会员是否存在
 * @param int $MemberID
 */
function app_member_exist($MemberID){
	$m = D('Admin/Member');
	$where['MemberID'] = intval($MemberID);
	$where['IsCheck'] = 1;
	$where['IsLock'] = 0;
	$id = $m->where($where)->getField('MemberID');
	return $id;
}

/**
 * 判断会员是否可以收藏
 * @param int $MemberID
 */
function app_can_favorite($MemberID){
	$MaxFavoritePerDay = 50; //定义每个会员每天最大收藏数
	$m = D('Admin/Favorite');
	$MemberID = intval($MemberID);
	$where = "to_days(FavoriteTime) = to_days(now()) and MemberID=$MemberID";
	$n = $m->where($where)->count();
	if( $n > $MaxFavoritePerDay){
		return false;
	}else{
		return true;
	}
}

/**
 * 判断指定ip是否能添加反馈
 * @param string $ip
 */
function app_can_feedback($ip){
	$MaxFeedbackPerIp = 10; //定义每个ID每天最大反馈数
	$m = D('Admin/AppFeedback');
	$ip = addslashes(stripslashes($ip)); //过滤危险字符
	$where = "to_days(AppFeedbackTime) = to_days(now()) and AppFeedbackIp='{$ip}'";
	$n = $m->where($where)->count();
	if( $n > $MaxFeedbackPerIp){
		return false;
	}else{
		return true;
	}
}

/**
 * 判断指定ip是否能加入设备统计
 * @param string $ip
 */
function app_can_stat($ip){
	$MaxDevicePerIp = 10; //定义每个IP每天最大提交的设备数
	$m = D('Admin/AppStat');
	$ip = addslashes(stripslashes($ip)); //过滤危险字符
	$where = "to_days(Time) = to_days(now()) and Ip='{$ip}'";
	$n = $m->where($where)->count();
	if( $n > $MaxDevicePerIp){
		return false;
	}else{
		return true;
	}
}

/**
 * 判断指定ip是否可以注册
 * @param string $ip
 */
function app_can_reg($ip){
	$MaxRegPerIp = 5; //定义每个IP每天最大注册数量
	$m = D('Admin/Member');
	$ip = addslashes(stripslashes($ip)); //过滤危险字符
	$where = "to_days(RegisterTime) = to_days(now()) and RegisterIP='{$ip}'";
	$n = $m->where($where)->count();
	if( $n > $MaxRegPerIp){
		return false;
	}else{
		return true;
	}
}

/**
 * 参数过滤
 * @param array $para 参数
 */
function app_para_filter($para) {
	$para_filter = array();
	foreach ($para as $key=>$val) {
		//去除调试参数：&XDEBUG_SESSION_START=ECLIPSE_DBGP&KEY=14868670618872
		if(!is_array($val) && $val !== '' && $key != 'Sign' && $key !='XDEBUG_SESSION_START' && $key !='KEY') {
			$para_filter[$key] = $para[$key];
		}
	}
	return $para_filter;
}

/**
 * 生成签名
 * @param array $para
 * @param array $AppSecret 秘钥
 */
function app_build_sign($para,$AppSecret) {
	//把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
	//由于js客户端在计算参数时用了encodeURIComponent，所以服务器端参数也必须urlencode编码
	//原因：同一中文字符使用 js md5.createHash()和php md5函数的结果不一样，所以必须编码
	//Upload(1).jpg encodeURIComponent: Upload%2F1(1).jpg，
	//                                 urlencode结果:   Upload%2F1%281%29.jpg，2者结果不一样
	$str = app_link_string($para,false);
	$sign = md5($str.$AppSecret);
	return $sign;
}

/**
 * 连接参数
 * @param array $para
 * @param boo $urlEncode 是否编码
 * @return string
 */
function app_link_string($para, $urlEncode=true) {
	$arg  = '';
	foreach ($para as $key=>$val ) {
		if($urlEncode) $val = urlencode($val);
		$arg .= "{$key}={$val}&";
	}
	//去掉最后一个&字符
	$arg = substr($arg, 0, -1);
	//如果存在转义字符，那么去掉转义
	if(get_magic_quotes_gpc()){
		$arg = stripslashes($arg);
	}
	return $arg;
}
