<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
class Uc extends CI_Controller
{
  const UC_CLIENT_RELEASE = '20110501';
  const UC_CLIENT_VERSION = '1.6.0';
 
  const API_DELETEUSER = 1;
  const API_RENAMEUSER = 1;
  const API_GETTAG = 1;
  const API_SYNLOGIN = 1;
  const API_SYNLOGOUT = 1;
  const API_UPDATEPW = 1;
  const API_UPDATEBADWORDS = 1;
  const API_UPDATEHOSTS = 1;
  const API_UPDATEAPPS = 1;
  const API_UPDATECLIENT = 1;
  const API_UPDATECREDIT = 1;
  const API_GETCREDITSETTINGS = 1;
  const API_GETCREDIT = 1;
  const API_UPDATECREDITSETTINGS = 1;
 
  const API_RETURN_SUCCEED = 1;
  const API_RETURN_FAILED = -1;
  const API_RETURN_FORBIDDEN = -2;
 
  public function index()
  {
      include CSCMSPATH.'lib/Cs_Ucenter.php';
      if(Ucmode_Mode==2){
          echo 'UC同步已经关闭';
          return;
      }
      $get = $post = array();
      $code = $this->input->get('code', true);
      parse_str(self::authcode($code, 'DECODE', UC_KEY), $get);
      $timestamp = time();
      if ($timestamp - @$get['time'] > 3600)
      {
          echo '授权已过期';
          return;
      }
      if (empty($get))
      {
          echo '非法请求';
          return;
      }
      $post = self::unserialize(file_get_contents('php://input'));
      if (in_array($get['action'], array(
          'test',
          'deleteuser',
          'renameuser',
          'gettag',
          'synlogin',
          'synlogout',
          'updatepw',
          'updatebadwords',
          'updatehosts',
          'updateapps',
          'updateclient',
          'updatecredit',
          'getcreditsettings',
          'updatecreditsettings')))
      {
          echo $this->$get['action']($get, $post);
          return;
      }
      else
      {
          echo self::API_RETURN_FAILED;
          return;
      }
 
  }
 
  private function test($get, $post)
  {
      return self::API_RETURN_SUCCEED;
  }
 
  private function deleteuser($get, $post)
  {
      if ( ! self::API_DELETEUSER)
      {
          return self::API_RETURN_FORBIDDEN;
      }
      $uid = $get['ids'];

      //删除用户接口

            $this->load->model('CsdjDB');
            $this->load->model('CsdjSkins');
	    $row=$this->CsdjDB->get_select ('user','CS_Uid','CS_Name,CS_Logo',''.$uid.'');
	    if($row){
                 IF($this->CsdjSkins->getusercount($row[0]->CS_Name,'dance')>0){
                      exit;
                 }

                 IF($this->CsdjSkins->getusercount($row[0]->CS_Name,'vod')>0){
                      exit;
                 }

                 IF($this->CsdjSkins->getusercount($row[0]->CS_Name,'pic')>0){
                      exit;
                 }

		 $biglogo="./attachment/logo/".$row[0]->CS_Logo."_big.jpg";
		 $smalllogo="./attachment/logo/".$row[0]->CS_Logo."_small.jpg";
                 if(FTP_Fun==1){ //远程附件
                            $this->load->library('ftp');
                            $FTPUP['hostname'] = FTP_Server;
                            $FTPUP['port']     = FTP_Port;
                            $FTPUP['username'] = FTP_Name;
                            $FTPUP['password'] = FTP_Pass;
                            $FTPUP['passive']  = FTP_Ive;
                            $this->ftp->connect($FTPUP);
                            $this->ftp->delete_file($smalllogo);
                            $this->ftp->delete_file($biglogo);
                 }else{
	                 if(file_exists($biglogo)){
		            @unlink($biglogo);
		            @unlink($smalllogo);
	                 }
                 }

                 $this->db->query("delete from ".CS_SqlPrefix."funco where CS_Usera='".$row[0]->CS_Name."' or CS_Userb='".$row[0]->CS_Name."'");  //访客
                 $this->db->query("delete from ".CS_SqlPrefix."fans where CS_Usera='".$row[0]->CS_Name."' or CS_Userb='".$row[0]->CS_Name."'");  //粉丝
                 $this->db->query("delete from ".CS_SqlPrefix."friend where CS_Usera='".$row[0]->CS_Name."' or CS_Userb='".$row[0]->CS_Name."'");  //好友
                 $this->db->query("delete from ".CS_SqlPrefix."pl where CS_User='".$row[0]->CS_Name."'");  //评论
                 $this->db->query("delete from ".CS_SqlPrefix."down where CS_User='".$row[0]->CS_Name."'"); //下载
                 $this->db->query("delete from ".CS_SqlPrefix."fav where CS_User='".$row[0]->CS_Name."'");  //收藏
                 $this->db->query("delete from ".CS_SqlPrefix."dt where CS_User='".$row[0]->CS_Name."'");  //动态
                 $this->db->query("delete from ".CS_SqlPrefix."user where CS_UID=".$uid."");  //会员
	    }

      return self::API_RETURN_SUCCEED;
  }
 
  private function gettag($get, $post)
  {
      if ( ! self::API_GETTAG)
      {
          return self::API_RETURN_FORBIDDEN;
      }
      //
      return self::API_RETURN_SUCCEED;
  }
 
  private function synlogin($get, $post)
  {
      if ( ! self::API_SYNLOGIN)
      {
          return self::API_RETURN_FORBIDDEN;
      }
      header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
      $uid = $get['uid'];
      //同步登录的代码
      include CSCMSPATH.'uc_client/client.php';
      if ($uc_user = uc_get_user($uid, 1))
      {
          $this->load->library('session');
          $this->load->model('CsdjDB');
          $this->load->model('CsdjSkins');
	      $row=$this->CsdjDB->get_select ('user','CS_UID','CS_ID,CS_SID,CS_Cion,CS_Name,CS_Vip,CS_Pass,CS_EndTime,CS_LogTime,CS_LogNum',''.$uid.'');
	      if($row){
                      if($row[0]->CS_SID==1){
                           exit();
                      }else{

		                   if(Cion_Log>0 && date("Y-m-d",strtotime($row[0]->CS_LogTime))!=date('Y-m-d')){
                                   $us['CS_Cion']  = $row[0]->CS_Cion+Cion_Log;
                           }

                           //判断VIP
                           $viptime=$this->CsdjSkins->DateBj('n',$row[0]->CS_EndTime,date('Y-m-d H:i:s'));
                           IF($row[0]->CS_Vip>0 && $viptime>10){
	                                $us['CS_Vip']  = 0;
	                                $us['CS_VipTime']  = '00-00-00 00:00:00';
	                                $us['CS_EndTime']  = '00-00-00 00:00:00';
                           }

                           //修改登入时间、IP
		                   $us['CS_Logip']    = $this->CsdjSkins->GetIP();
		                   $us['CS_LogNum']   = $row[0]->CS_LogNum+1;
		                   $us['CS_Logtime']  = date('Y-m-d H:i:s');
		                   $us['CS_Zx']       = 1;
                           $this->CsdjDB->get_update ('user',$row[0]->CS_ID,$us);

		                   $udata = array(
                                           'cs_id'  => $row[0]->CS_ID,
                                           'cs_name'  => $row[0]->CS_Name,
                                           'cs_pass'  => md5($row[0]->CS_Pass)
                           );
                           $this->session->set_userdata($udata);
                       }
           }
      }
      return self::API_RETURN_SUCCEED;
  }
 
  private function synlogout($get, $post)
  {
      if ( ! self::API_SYNLOGOUT)
      {
          return self::API_RETURN_FORBIDDEN;
      }
      header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
          //同步退出
          $this->load->library('session');
          $this->load->model('CsdjDB');
		  $us['CS_Zx'] = 0;
                $this->CsdjDB->get_update('user',$this->session->userdata('cs_id'),$us);
		        $udata = array(
                          'cs_id'    => '',
                          'cs_name'  => '',
                          'cs_pass'  => ''
                );
                $this->session->unset_userdata($udata);

      return self::API_RETURN_SUCCEED;
  }
 
  private function updatepw($get, $post)
  {
      if ( ! self::API_UPDATEPW)
      {
          return self::API_RETURN_FORBIDDEN;
      }
      //修改密码操作
      $username=$get['username'];
      $edit['cs_pass']=md5($get['password']);
          $this->load->model('CsdjDB');
          $this->load->library('session');
          //修改
          $this->CsdjDB->get_update('user',$username,$edit,'CS_Name');
          //更新session
          $ulogin['cs_pass']=$edit['cs_pass'];
          $this->session->set_userdata($ulogin);

      return self::API_RETURN_SUCCEED;
  }
 
  private function updatebadwords($get, $post)
  {
      if ( ! self::API_UPDATEBADWORDS)
      {
          return self::API_RETURN_FORBIDDEN;
      }
      $cachefile = CSCMSPATH.'uc_client/data/cache/badwords.php';
      @unlink($cachefile);
      return self::API_RETURN_SUCCEED;
  }
 
  private function updatehosts($get, $post)
  {
      if ( ! self::API_UPDATEHOSTS)
      {
          return self::API_RETURN_FORBIDDEN;
      }
      $cachefile = CSCMSPATH.'uc_client/data/cache/hosts.php';
      @unlink($cachefile);
      return self::API_RETURN_SUCCEED;
  }
 
  private function updateapps($get, $post)
  {
      if ( ! self::API_UPDATEAPPS)
      {
          return self::API_RETURN_FORBIDDEN;
      }
      $cachefile = CSCMSPATH.'uc_client/data/cache/apps.php';
      @unlink($cachefile);
      return self::API_RETURN_SUCCEED;
  }
 
  private function updateclient($get, $post)
  {
      if ( ! self::API_UPDATECLIENT)
      {
          return self::API_RETURN_FORBIDDEN;
      }
      $cachefile = CSCMSPATH.'uc_client/data/cache/settings.php';
      @unlink($cachefile);
      return self::API_RETURN_SUCCEED;
  }
 
  private function updatecredit($get, $post)
  {
      if ( ! self::API_UPDATECREDIT)
      {
          return self::API_RETURN_FORBIDDEN;
      }
      return self::API_RETURN_SUCCEED;
  }
 
  private function getcredit($get, $post)
  {
      if ( ! self::API_GETCREDIT)
      {
          return self::API_RETURN_FORBIDDEN;
      }
      return self::API_RETURN_SUCCEED;
  }
 
  public static function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
  {
      $ckey_length = 4;
      $key = md5($key ? $key : UC_KEY);
      $keya = md5(substr($key, 0, 16));
      $keyb = md5(substr($key, 16, 16));
      $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
 
      $cryptkey = $keya.md5($keya.$keyc);
      $key_length = strlen($cryptkey);
 
      $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
      $string_length = strlen($string);
 
      $result = '';
      $box = range(0, 255);
 
      $rndkey = array();
      for($i = 0; $i <= 255; $i++)
      {
          $rndkey[$i] = ord($cryptkey[$i % $key_length]);
      }
 
      for($j = $i = 0; $i < 256; $i++)
      {
          $j = ($j + $box[$i] + $rndkey[$i]) % 256;
          $tmp = $box[$i];
          $box[$i] = $box[$j];
          $box[$j] = $tmp;
      }
 
      for($a = $j = $i = 0; $i < $string_length; $i++)
      {
          $a = ($a + 1) % 256;
          $j = ($j + $box[$a]) % 256;
          $tmp = $box[$a];
          $box[$a] = $box[$j];
          $box[$j] = $tmp;
          $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
      }
 
      if($operation == 'DECODE')
      {
          if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16))
          {
              return substr($result, 26);
          }
          else
          {
              return '';
          }
      }
      else
      {
          return $keyc.str_replace('=', '', base64_encode($result));
      }
  }
 
  public static function serialize($arr, $htmlOn = 0)
  {
      if ( ! function_exists('xml_serialize'))
      {
          require CSCMSPATH.'uc_client/lib/xml.class.php';
      }
      return xml_serialize($arr, $htmlOn);
  }
 
  public static function unserialize($xml, $htmlOn = 0)
  {
      if ( ! function_exists('xml_serialize'))
      {
          require CSCMSPATH.'uc_client/lib/xml.class.php';
      }
      return xml_unserialize($xml, $htmlOn);
  }
 
  public static function gbk2utf8($string)
  {
      return iconv("GB2312", "UTF-8//IGNORE", $string);
  }
 
  public static function utf82gbk($string)
  {
      return iconv("UTF-8", "GB2312//IGNORE", $string);
  }
 
}