<?php

namespace Media\Controller;
use Think\Controller;

/**
 * 后台首页控制器222
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class DownController extends Controller {

    public function down_file($game_id = 0,$sdk_version=1){
        $host_name = $_SERVER['HTTP_NAME'];
        $promote_id = M('SiteApply')->where('site_url="$host_name"')->getField('promote_id');
        if(empty($promote_id)){
            $this->official_down_file($game_id,$sdk_version);
        }else{
            $this->promote_down_file($game_id,$promote_id,0,$sdk_version);
        }
    }


    /**
    *推广游戏下载
    *@param int $game_id [游戏关联id]
    *@param int $promote_id [推广员id]
    *@param int $system_type [系统环境] 0 win  1 苹果
    *@param int $sdk_version [sdk 类型] 1 安卓 2 苹果
    */
    public function promote_down_file($game_id=0,$promote_id=0,$system_type=0,$sdk_version=1){
        $applyModel = D('Apply');
        $map['status']        = 1;
        $map['enable_status'] = 1;
        $data = $applyModel
                ->field('game_id,tab_apply.game_name,promote_id,promote_account,relation_game_id,pack_url,plist_url,`status`,enable_status,tab_apply.sdk_version')
                ->join("tab_game ON tab_apply.game_id = tab_game.id AND promote_id = $promote_id AND relation_game_id = $game_id AND tab_apply.sdk_version = $sdk_version")
                ->where($map)
                ->find();
        if(empty($data)){
            $this->official_down_file($game_id,$sdk_version);
        }else{
            $pack_url = $data['pack_url'];
            M('Game','tab_')->where('id='.$data['game_id'])->setInc('dow_num');
            $this->add_down_stat($data['game_id']);
            if(!empty($pack_url)){
                if(preg_match("/oss/", $pack_url)){
                    $url=str_replace('-internal', '', $pack_url);
                    echo "<script>window.location.href='$url';</script>";
                }elseif(preg_match("/clouddn/", $pack_url)){
                    $url = "http://".$pack_url;
                    redirect($url);
                }elseif(preg_match("/myqcloud/", $pack_url)){                
                    redirect($pack_url);
                }elseif(preg_match("/bcebos/", $pack_url)){
                    redirect($pack_url);
                }else{
                    $this->down($pack_url);
                }
            }else{
                $this->error('原包地址不存在');
            }
        }
    }
    
    /**
    *官方游戏下载
    *@param int $game_id [游戏关联id]
    *@param int $sdk_version [sdk 类型] 1 安卓 2 苹果
    */
    public function official_down_file($game_id=0,$sdk_version=1){
        $model = M('Game','tab_');
        $map['tab_game.relation_game_id'] = $game_id;
        // $map['file_type'] = $type;
        $data = $model
            ->field('tab_game_source.*,tab_game.game_name,tab_game.id as game_id,tab_game.and_dow_address,tab_game.ios_dow_address,tab_game.add_game_address,tab_game.ios_game_address,tab_game.down_port')
            ->join("left join tab_game_source on tab_game.id = tab_game_source.game_id")
            ->where($map)
            ->order('file_type asc')
            ->select();
        
        $first_data = reset($data);
        $end_data   = end($data);
        if(empty($first_data)){
            $this->error('暂无原包!');
        }
        if(substr($first_data['and_dow_address'], 0 , 2)==".."){
            $first_data['and_dow_address']=substr($first_data['and_dow_address'],'1',strlen($first_data['and_dow_address']));
        }
        if(substr($end_data['ios_dow_address'], 0 , 2)==".."){
            $end_data['ios_dow_address']=substr($end_data['ios_dow_address'],'1',strlen($end_data['ios_dow_address']));
        }

        switch ($sdk_version) {
            case 1:
                M('Game','tab_')->where('id='.$first_data['game_id'])->setInc('dow_num');
                $this->add_down_stat($first_data['game_id']);
                if($first_data['down_port'] == 1){
                    if(varify_url($first_data['and_dow_address'])){
                        $this->down($first_data['and_dow_address'],$type);
                    }else{
                        $this->error('原包地址错误!');
                    }
                }else {
                    if(varify_url($first_data['add_game_address'])){
                        Header("HTTP/1.1 303 See Other");
                        Header("Location: ".$first_data['add_game_address']);
                    }else{
                        $this->error('第三方下载地址错误!');
                    }
                }
                break;
            
            default:
                M('Game','tab_')->where('id='.$end_data['game_id'])->setInc('dow_num');
                $this->add_down_stat($end_data['game_id']);
                if($end_data['down_port'] == 1){
                    if(varify_url($end_data['ios_dow_address'])){
                        $this->down($end_data['ios_dow_address'],$type);
                    }else{

                        $this->error('原包地址错误!');
                    }
                }else {
                    if(varify_url($end_data['ios_game_address'])){
                        Header("HTTP/1.1 303 See Other");
                        Header("Location: ".$end_data['ios_game_address']);
                    }else{
                        $this->error('下载地址未设置!');
                    }
                }
                break;
        }
                
    }

    function access_url($url) {    
        if ($url=='') return false;    
        $fp = fopen($url, 'r') or exit('Open url faild!');    
        if($fp){  
        while(!feof($fp)) {    
            $file.=fgets($fp)."";  
        }  
        fclose($fp);    
        }  
        return $file;  
    }  

    public function down($file,$type,$rename = NULL)
    {
        ob_clean();
        if(headers_sent())return false;
        if(!$file&&$type==1) {
            $this->error('安卓文件不存在哦 亲!');
            //exit('Error 404:The file not found!');
        }
        if(!$file&&$type==2) {
            $this->error('苹果文件不存在哦 亲!');
            //exit('Error 404:The file not found!');
        }
        $sourceFile = $file; //要下载的临时文件名  
        $outFile = $rename;
        $file_extension = strtolower(substr(strrchr($sourceFile, "."), 1)); //获取文件扩展名  
        //检测文件是否存在  
        if (!is_file($sourceFile)) {  
            die("<b>404 File not found!</b>");  
        }  
        $len = filesize($sourceFile); //获取文件大小  
        $filename = basename($sourceFile); //获取文件名字  
        $outFile_extension = $file_extension; //获取文件扩展名  
        //根据扩展名 指出输出浏览器格式  
        switch ($outFile_extension) {  
            case "exe" :  
                $ctype = "application/octet-stream";  
                break;  
            case "zip" :  
                $ctype = "application/zip";  
                break;  
            case "mp3" :  
                $ctype = "audio/mpeg";  
                break;  
            case "mpg" :  
                $ctype = "video/mpeg";  
                break;  
            case "avi" :  
                $ctype = "video/x-msvideo";  
                break;  
            default :  
                $ctype = "application/force-download";  
        }  
        
        //Begin writing headers  
        header("Cache-Control:");  
        header("Cache-Control: public");         
        //设置输出浏览器格式  
        header("Content-Type: $ctype");  
        // header("Content-Disposition: attachment; filename=" . $filename.".".$outFile_extension);  
        header("Content-Disposition: attachment; filename=" . $filename);  

        header("Accept-Ranges: bytes");  
        $size = filesize($sourceFile);  
        //如果有$_SERVER['HTTP_RANGE']参数  
        if (isset ($_SERVER['HTTP_RANGE'])) {  
            if (!preg_match('^bytes=\d*-\d*(,\d*-\d*)*$', $_SERVER['HTTP_RANGE'])) {
                header('HTTP/1.1 416 Requested Range Not Satisfiable');
                header('Content-Range: bytes */' . $size); // Required in 416.
                exit;
            }
            $ranges = explode(',', substr($_SERVER['HTTP_RANGE'], 6));
            foreach ($ranges as $range) {
                $parts = explode('-', $range);
                $start = $parts[0]; // If this is empty, this should be 0.
                $end = $parts[1]; // If this is empty or greater than than filelength - 1, this should be filelength - 1.

                if ($start > $end) {
                    header("HTTP/1.1 206 Partial Content");  
                    header("Content-Length: $new_length"); //输入总长  
                    header("Content-Range: bytes $range$size2/$size"); //Content-Range: bytes 4908618-4988927/4988928   95%的时候  
                    exit;
                }
            }
        } else {  
            //第一次连接  
            $size2 = $size -1;  
            header("Content-Range: bytes 0-$size2/$size"); //Content-Range: bytes 0-4988927/4988928  
            header("Content-Length: " . $size); //输出总长  
        }  
        //打开文件  
        $fp = fopen("$sourceFile", "rb+");  
        //设置指针位置  
        fseek($fp, $range);  
        //虚幻输出  
        while (!feof($fp)) {  
            //设置文件最长执行时间  
            set_time_limit(0);  
            print (fread($fp, 1024 * 8)); //输出文件  
            flush(); //输出缓冲  
            ob_flush();  
        }  
        fclose($fp);  
        exit ();
    }
    /** 获取header range信息
    * @param  int   $file_size 文件大小
    * @return Array
    */
    private function getRange($file_size){
        if(isset($_SERVER['HTTP_RANGE']) && !empty($_SERVER['HTTP_RANGE'])){
            $range = $_SERVER['HTTP_RANGE'];
            $range = preg_replace('/[\s|,].*/', '', $range);
            $range = explode('-', substr($range, 6));
            if(count($range)<2){
                $range[1] = $file_size;
            }
            $range = array_combine(array('start','end'), $range);
            if(empty($range['start'])){
                $range['start'] = 0;
            }
            if(empty($range['end'])){
                $range['end'] = $file_size;
            }
            return $range;
        }
        return null;
    }
    /**
    *游戏下载统计
    */
    public function add_down_stat($game_id=null){
        $model = M('down_stat','tab_');
        $data['promote_id'] = 0;
        $data['game_id'] = $game_id;
        $data['number'] = 1;
        $data['type'] = 0;
        $data['create_time'] = NOW_TIME;
        $model->add($data);
    }
}