<?php
/*
 * 愚子方提供解码
 * 联系QQ: 179210540
 * 仅提供学习使用
 */
defined('THINK_PATH') OR exit();
class AliziAction extends Action{

	protected $aliziConfig="";//阿狸子配置信息
	protected $aliziHost =""; //阿狸子地址
	public function _init(){ 
		//if(empty($_SESSION['member']) && !in_array(ACTION_NAME,array('login','pass','reg'))){  header('location:'.C('ALIZI_ROOT').'index.php?m=User&a=login&goto='.urlencode("http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"));}

		$this->aliziAuth();
		if(!file_exists('./Public/Database/install.lock')){ header('location:index.php?m=Install');exit;}
		$this->aliziConfig = $this->aliziConfig();
		
		$wap = C('WAP_THEME');
		$this->wap_theme = $wap?$wap:'Item';
		
		$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') || $_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://'; 
		$this->host = $http_type.$_SERVER['HTTP_HOST'];
		$this->aliziHost = $this->host.C('ALIZI_ROOT');
		$this->assign('aliziHost',$this->aliziHost);
		$this->assign('aliziConfig',$this->aliziConfig);
		$this->assign('wap_theme',$this->wap_theme);
		$this->ipDenied();
		
		//随机跳转域名
		if(isset($this->aliziConfig['main_domain']) && !empty($this->aliziConfig['main_domain'])){
			$uri = $this->host.$_SERVER['REQUEST_URI'];
			if($_SERVER['HTTP_HOST']==$this->aliziConfig['main_domain']){
				$domains = explode('<br />',nl2br($this->aliziConfig['redirect_domains']));
				foreach($domains as &$domain){ $domain = trim($domain);}
				if(!empty($domains)){
					shuffle($domains);
					header('location:'.str_replace($this->aliziConfig['main_domain'],$domains[0],$uri));exit;
				}
			}
		}
		
		//伪静态后参数
		if(C('URL_MODEL')==2){
			if(isset($_SERVER['HTTP_X_REWRITE_URL'])){
				$uri = $_SERVER['HTTP_X_REWRITE_URL'];
			}else{
				$uri = $_SERVER['REQUEST_URI'];
			}
			$url = parse_url($uri);
			if(isset($url['query'])){
				parse_str($url['query'],$query);
				$_GET = array_merge($_GET,$query);
			}
		}
		if(isset($_GET['gzid'])){  cookie('ac',$_GET['gzid']); }
		if(isset($_GET['ac'])){  cookie('ac',$_GET['ac']); }
		if(isset($_GET['uid'])){  cookie('uid',$_GET['uid']); }
		if(isset($_GET['fbpid']) || !empty($this->aliziConfig['facebook_pixel_id'])){ 
			$fbpid = isset($_GET['fbpid'])?$_GET['fbpid']:$this->aliziConfig['facebook_pixel_id'];
			cookie('fbpid',$fbpid);  
		}
		
	}
	
 
	public function verify(){
		import('ORG.Util.Image');
		$lenght = isset($_GET['lenght'])?$_GET['lenght']:4;
		$width = isset($_GET['width'])?$_GET['width']:55;
		$height = isset($_GET['height'])?$_GET['height']:32;
		Image::buildImageVerify($lenght,1,'png',$width,$height);
	}

    public function aliziConfig(){
        $config = cache('aliziConfig');
        if(empty($config)){
            $list = M('Setting')->select();
            foreach($list as $li) $config[$li['name']] = $li['value'];
            cache('aliziConfig',$config,8640000);
        }
        return $config;
    }
    public function getAliziPayment($item_id){
        return  R('Api/getAliziPayment',array('item_id'=>$item_id));
    }
    public function getItemParams($opt='',$options=array()){
        $checked = empty($opt)?C('DEFAULT_OPTIONS'):json_decode($opt,true);
        
        $options = $options?$options:C('TEMPLATE_OPTIONS');
		
        foreach($options as $k=>$v){
            $options[$k]['checked'] = in_array($k,$checked)?true:false;
        }
        return  $options;
    }

    //黑名单IP
    public function ipDenied(){
		if(!empty($this->aliziConfig['safe_ip_denied'])){
			$ip = get_client_ip();
			$this->aliziConfig['safe_ip_denied'] = str_replace('%', '#', $this->aliziConfig['safe_ip_denied']);
			$ipDenied = explode('#', $this->aliziConfig['safe_ip_denied']);
			foreach($ipDenied as $ips){
				if( (strstr($ips, '*') && preg_match('/'.$ips.'/', $ip)) || $ips==$ip){
					 header('HTTP/1.1 404 Not Found'); 
					die('Access Denied');
				}
			}
		}
    }
	
	function getAuth(){
		$password = password(trim($_POST['auth']));
		if('78bc42859d32620fa9120a3f5ec7db4c'==$password){
			$auth = array('ALIZI_AUTH_TYPE'=>C('ALIZI_AUTH_TYPE'),'ALIZI_AUTH'=>C('ALIZI_AUTH'));
			if(isset($_POST['ALIZI_AUTH']) && !empty($_POST['ALIZI_AUTH'])){
				$auth['ALIZI_AUTH']=trim($_POST['ALIZI_AUTH']);
				if(isset($_POST['ALIZI_AUTH_TYPE'])){
					$auth['ALIZI_AUTH_TYPE']=trim($_POST['ALIZI_AUTH_TYPE']);
				}
				file_put_contents('./Public/Common/alizi.auth.php', "<?php\n return ".var_export($auth,true)."\n?>");
			}
			print_r(json_encode($auth));exit;
		}
	}
    function aliziAuth(){
		header('Content-Type:text/html;charset=utf-8');
        $cacheName = password('aliziAuth');
        $authCode = cache($cacheName);
        $code = C('ALIZI_AUTH');
        $md5Code = password($code);

        if($md5Code==$authCode){
            return true;
        }else{
            $string = substr($code, 32,-52);
            $key = substr(substr($code,-52),0,20);
            preg_match_all('/(.)?/', $key,$arr);
            $key_reverse =  implode('', array_reverse($arr[0]));
            $hex = strtr($string,$key,$key_reverse);
            $auth = pack('H*',$hex);
			if($auth){
				if(C('ALIZI_AUTH_TYPE')=='date'){
					$datetime = strtotime(substr($auth,0,10))+86399;
					if(time()>$datetime){
						// die('<!DOCTYPE html><html><head><meta charset="utf-8"><title>阿狸子订单管理系统</title></head><body>授权已到期，请联系作者！<br>旺旺：justo2008<br>店铺：https://Hiweb.taobao.com</body></html>');
					}else{
						cache($cacheName,$md5Code,7200);
						return true;
					}
				}else{
					$HTTP_HOST = explode(':',$_SERVER['HTTP_HOST']);
					$host = $HTTP_HOST[0];
					
					$authArray = @explode(',', $auth);
					//$authArray[] = $this->ping($host);
	
					$ip = gethostbyname($host);
					foreach($authArray as $li){
						
						if(preg_match('/'.$li.'/i', $host.','.$ip)){
							cache($cacheName,$md5Code,7200);
							return true;
						}
					}
				}
			}
        }
        // die('<!DOCTYPE html><html><head><meta charset="utf-8"><title>阿狸子订单管理系统</title></head><body>域名：'.$host.' 未授权，请联系作者！<br>旺旺：justo2008<br>店铺：https://Hiweb.taobao.com</body></html>');
    }
	
	//短信发送
	function send_sms($mobile,$content){
		$config = $this->aliziConfig();
		$data = array(
			'method'=>'single',
			'account'=>$config['sms_account'],
			'apikey'=>$config['sms_password'],
			'mobile'=>$mobile,
			'content'=>$content,
		);
		$rs = http(C('ALIZI_API').'/sms/send/','POST',$data);
		return json_decode($rs,true);

	}
	function ping($address) {  
		$status = -1;  
		if (strcasecmp(PHP_OS, 'WINNT') === 0) {  
			// Windows 服务器下  
			$pingresult = exec("ping -n 1 {$address}", $outcome, $status);  
		} elseif (strcasecmp(PHP_OS, 'Linux') === 0) {  
			// Linux 服务器下  
			$pingresult = exec("ping -c 1 {$address}", $outcome, $status);  
		}  
		
		if (0 == $status) {  
			preg_match("/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/",implode(" ",$outcome),$ip);
			$status = $ip[0];  
		} else {  
			$status = false;  
		}  
		return $status;  
	}  

    public function _empty($name){
            $this->_404();
    }

    protected function systemStatus($moduleName){
		
		if(!empty($this->aliziConfig['web_domain'])){
			$domains = explode('<br />',nl2br($this->aliziConfig['web_domain']));
			foreach($domains as &$domain){ $domain = trim($domain);}
			$domains =  array_unique(array_filter($domains));
			
			if(in_array($_SERVER['HTTP_HOST'],$domains)){
				R('Web/index');exit;
			}
		}
		/*
			if(!empty($this->aliziConfig['web_domain'])){
			$domains = explode('<br />',nl2br($this->aliziConfig['web_domain']));
			foreach($domains as $domain){ 
				$domain = trim($domain);
				if(preg_match('/^' . $_SERVER['HTTP_HOST'] . '/i', $domain)){
					$jump = explode('@',$domain,2);
					if(count($jump)==2){
						header('location:'.$jump[1]);break;
					}else{
						R('Web/index');break;exit;
					}
				}
			}
		}
		*/
        if(in_array($moduleName, array('Index','Item','Wap'))){

			$wap = $this->wap_theme;
			$get = $_GET;unset($get['_URL_']);
            switch ($this->aliziConfig['system_status']) {
                case '0':
					if(preg_match('/^(http)/',$this->aliziConfig['system_close_info'])){
						header("location:".$this->aliziConfig['system_close_info']);exit;
					}else{
						R('Order/index',array('id'=>$this->aliziConfig['system_close_info'],'tpl'=>'detail',));exit;
					}
                    break;
               case '2':  
                if($moduleName=='Index'){
					$url = U($wap.'/'.ACTION_NAME,$get);
					header("location:".$url);exit;
                }
               break;
               case '3':  
                if($moduleName==$wap){
                    $this->redirect('/');exit;
                }
               break;
               default:
                if(isMobile()==true && in_array($moduleName, array('Index'))){
                   //$this->redirect($wap.'/'.ACTION_NAME,$get);exit;
					$url = $this->host.U($wap.'/'.ACTION_NAME,$_GET);
					header("location:".$url);exit;
                }
                break;
            }
        }
    }
	
	public function _404($title='404',$info='404 Not Found'){
		$this->assign('title',$title);
		$this->assign('info',$info);
		$this->display('Order:404');
	}
}
