<?php
include_once(ONEZ_ROOT.'include/common.inc.php');
$A=array('type'=>$action);
switch($action){
  //按默认问题
  case 'default';
    $T=DB()->record("question","*","isdefault='1' order by asknum desc");
    $n=0;
    foreach($T as $rs){
      $n++;
      $A['list'][]='<span>'.$n.'、</span><a href="javascript:byQid('.$rs['qid'].')">'.$rs['content'].'</a>';
    }
    if($n==1){
      $A['list'][0]=str_replace('<span>1、</span>','',$A['list'][0]);
    }
    break;
  //页面信息
  case 'page';
    InitGP(array('A'),'P');
    settype($A,'array');
    $thesoft=$_SERVER["HTTP_USER_AGENT"];//浏览器
    switch(true){
      case strpos($thesoft,"NetCaptor"):
        $vsoft="NetCaptor";
        break;
      case strpos($thesoft,"MSIE 9"):
        $vsoft="MSIE 9.x";
        break;
      case strpos($thesoft,"MSIE 8"):
        $vsoft="MSIE 8.x";
        break;
      case strpos($thesoft,"MSIE 7"):
        $vsoft="MSIE 7.x";
        break;
      case strpos($thesoft,"MSIE 6"):
        $vsoft="MSIE 6.x";
        break;
      case strpos($thesoft,"MSIE 5"):
        $vsoft="MSIE 5.x";
        break;
      case strpos($thesoft,"MSIE 4"):
        $vsoft="MSIE 4.x";
        break;
      case strpos($thesoft,"Netscape"):
        $vsoft="Netscape";
        break;
      case strpos($thesoft,"Opera"):
        $vsoft="Opera";
        break;
      default:
        $vsoft="Other";
        break;
    }
    $vsoft=preg_replace("/MSIE ([0-9]).x/","Internet Explorer $1",$vsoft);
    switch(true){//操作系统
      case strpos($thesoft,"Windows NT 5.0"):
        $os="Win 2000";
        break;
      case strpos($thesoft,"Windows NT 5.1"):
        $os="Win XP";
        break;
      case strpos($thesoft,"Windows NT 5.2"):
        $os="Win 2003";
        break;
      case strpos($thesoft,"Windows NT"):
        $os="Windows NT";
        break;
      case strpos($thesoft,"Win 9x"):
        $os="Win 9x";
        break;
      case strpos($thesoft,"类Unix"):
        $os="类Unix";
        break;
      case strpos($thesoft,"Mac"):
        $os="Mac";
        break;
      default:
        $os="Other";
        break;
    }
    $A['vsoft']=$vsoft;
    $A['os']=$os;
    foreach($A as $k=>$v){
      if(!$k)continue;
      $v=trim($v);
      if(!$v)continue;
      DB()->replace('ufield',array(
        'uid'=>(int)$uid,
        'token'=>$k,
        'value'=>$v,
      ));
    }
    break;
  //聊天记录
  case 'history';
    InitGP(array('hid','qid','aid','ifusr','msg'),'P',0);
    DB()->insert('message',array(
      'hid'=>(int)$hid,
      'qid'=>(int)$qid,
      'aid'=>(int)$aid,
      'ifusr'=>(int)$ifusr,
      'time'=>$time,
      'content'=>$msg,
    ));
    break;
  //显示聊天记录
  case 'viewhistory';
    InitGP(array('hid'),'P',0);
    $T=DB()->record('message','*',"hid='$hid' order by mid asc");
    $html='<div class="showbox">';
    
    $botname=option('botname');
    
    foreach($T as $rs){
      $date=str_replace(date('Y-m-d ',$time),'',date('Y-m-d G:i:s',$rs['time']));
      if($rs['ifusr']){
        $html.='<div class="im_to">您&nbsp;&nbsp;'.$date.'</div>';
      }else{
        $html.='<div class="im_from">'.$botname.'&nbsp;&nbsp;'.$date.'</div>';
      }
      $html.='<div class="im_content">'.$rs['content'].'</div>';
    }
    exit($html);
    break;
  //失败信息
  case 'fail';
    InitGP(array('hid','ifusr','msg'),'P',0);
    DB()->insert('book',array(
      'token'=>'fail',
      'hid'=>(int)$hid,
      'caption'=>$msg,
      'time'=>$time,
      'ip'=>$onlineip,
    ));
    break;
  //按字符串检索
  case 'search';
    InitGP(array('msg','hid'));
    $msg=strip_tags($msg);
    $msg=trim($msg);
    $S=array();
    //管理功能
    if($admin){
      $msg=ltrim($msg,'#');
      list($plugin)=explode(' ',$msg);
      $plugin=trim(strtolower($plugin));
      $keyword=trim(substr($msg,strlen($plugin)));
      include(ONEZ_ROOT.'plugins/robot/base.php');
      $pluginFile=ONEZ_ROOT.'plugins/robot/'.$plugin.'/main.php';
      if(file_exists($pluginFile)){
        @include_once($pluginFile);
        if($data){
          $A['msg']=$data;
          break;
        }
      }
    }
    //插件预留
    if(substr($msg,0,1)=='#'){
      $msg=ltrim($msg,'#');
      list($plugin)=explode(' ',$msg);
      $plugin=trim(strtolower($plugin));
      $keyword=trim(substr($msg,strlen($plugin)));
      include(ONEZ_ROOT.'plugins/robot/base.php');
      $pluginFile=ONEZ_ROOT.'plugins/robot/'.$plugin.'/main.php';
      if(file_exists($pluginFile)){
        @include_once($pluginFile);
        if($data){
          $A['msg']=$data;
          break;
        }
      }
    }
    
    
    if($S){
      $A=array_merge($A,$S);
    }elseif($msg){
      $question=array();
      //第一阶段，完全匹配
      $qid=DB()->select('question','qid',"content='$msg'");
      $qid && $question[$qid]=1;
      //第二阶段，模糊匹配
      $T=DB()->record('question','qid',"content like '%$msg%' or (keywords<>'' and keywords like '%$msg%')");
      foreach($T as $rs){
        $question[$rs['qid']]=1;
      }
      //第三阶段，反向匹配
      $T=DB()->record('question','qid',var_export(strip_tags($msg),true)." like concat('%',content,'%') or (keywords<>'' and ".var_export(strip_tags($msg),true)." like concat('%',replace(keywords,'*','%'),'%'))");
      foreach($T as $rs){
        $question[$rs['qid']]=1;
      }
      //如果已取到结果
      if($question){
        $qids=array_keys($question);
        //用户看到过的答案列表
        $aids=array();
        $T=DB()->record('message','aid',"hid='$hid' and aid<>'0'");
        foreach($T as $rs){
          $aids[$rs['aid']]=1;
        }
        $aids=array_keys($aids);
        
        $isFound=0;
        //答案列表
        $T=DB()->record('answer','*',"aid in (select aid from $#faq where qid in (".implode(',',$qids).")) order by rand()");
        foreach($T as $rs){
          //如果答案中有未显示过的答案，优先显示
          if(!in_array($rs['aid'],$aids)){
            $isFound=1;
            onezAnswer($rs);
          }
        }
        if(!$isFound){
          onezAnswer($T[0]);
        }
      }else{
        //没有取到结果，尝试从接口中获取
        if(option('api_search')=='Y'){
          $link=@mysql_connect(option('api_host'), option('api_usr'), option('api_pwd'));
          if(!$link){
            $A['msg']='无法连接接口数据库！';
          }else{
            @mysql_select_db(option('api_name'), $link);
            if(option('api_charset'))@mysql_query('set names '.option('api_charset'),$link);
            $result=@mysql_query(str_replace('$msg',$msg,option('api_sql')),$link);
            $tmp=option('api_ti');
            $n=0;
            while($rs=@mysql_fetch_array($result,MYSQL_ASSOC)){
              $n++;
              @eval('$tmp.="'.str_replace('"','\"',option('api_text')).'";');
            }
            if(option('api_charset') && strtolower(option('api_charset'))!='utf8'){
              $tmp=oiconv(option('api_charset'),'utf-8',$tmp);
            }
            @mysql_free_result($result);
            @mysql_close($link);
            if($n>0)$A['msg']=$tmp;
          }
        }
      }
    }
    break;
  //按问题编号检索
  case 'byqid';
    InitGP('qid');
    $A['qid']=$qid;
    onezAnswer(DB()->one('answer','*',"aid in (select aid from $#faq where qid='$qid') order by asknum desc,rand()"));
    break;
  //按答案编号检索
  case 'byaid';
    InitGP('aid');
    onezAnswer(DB()->one('answer','*',"aid='$aid'"));
    break;
}
if($type=='QQ'){
  $data=$A['msg'];
}else{
  echo onez_json($A);
  exit();
}
?>