<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Vod extends CI_Controller {

	function __construct(){
		    parent::__construct();
        	$this->load->helper('url');
        	$this->load->helper('form');
            $this->load->library('session'); //加载session
		    $this->load->model('CsdjDB');
		    $this->load->model('CsdjSkins');
		    $this->load->model('CsdjVod');
		    $this->load->model('CsdjCache');
	}

    //视频主页
	public function index()
	{
            //判断运行模式
            $cscms=$this->input->get('cs', TRUE);
	        if(Web_Mode==3 && $cscms!="html"){ 
                    header("Location: ".str_replace('//','/',Web_Path.Html_Vindex).""); 
                    exit;
            }

	        $cache_id ="vod_index";
	        if(!($this->CsdjCache->start($cache_id))){
                echo $this->CsdjVod->index();
		        $this->CsdjCache->end();
	        }
	}

    //分类列表
	public function lists()
	{
            $fid = $this->uri->segment(3);   //方式
            $id = intval($this->uri->segment(4));   //ID
            $page  = intval($this->uri->segment(5));   //页数
            if($page==0) $page=1;
                
            if($id==0){
                exit($this->CsdjSkins->Msg_url('出错了，ID不能为空！',Web_Path));
            }

            //判断运行模式
            $cscms=$this->input->get('cs', TRUE);
	        if(Web_Mode==3 && $cscms!="html"){ 
                    $Htmllink=$this->CsdjSkins->LinkUrl('lists','vod',$fid,$id,$page);
                    header("Location: ".$Htmllink.""); 
                    exit;
            }

            $aliasname="";
		    $row=$this->CsdjDB->get_select ('vlist','CS_ID','*',''.$id.'');
		    if(!$row){
                    $aliasname=$id;
                    $row=$this->CsdjDB->get_select ('vlist','CS_AliasName','*',''.$id.'');
                    if(!$row){
                           exit($this->CsdjSkins->Msg_url('出错了，该分类不存在！',Web_Path));
                    }
		    }

	        $cache_id ="vod_list_".$fid."_".$id."_".$page;
	        if(!($this->CsdjCache->start($cache_id))){
                echo $this->CsdjVod->lists($fid,$id,$page,$row,$aliasname);
			    $this->CsdjCache->end();
			}
	}

    //搜索列表
	public function so()
	{
            $data='';$data_content='';
            $fid = $this->uri->segment(3);   //方式
            $key = $this->input->get_post('key');   //关键字
            $page  = intval($this->input->get('p', TRUE));   //页数
            if($page==0) $page=1;

            if($fid=='zm' && empty($key)){
                 $key=$this->uri->segment(4); 
            }

	        $key = $this->CsdjSkins->safe_replace(trim($key));
	        $key = htmlspecialchars(strip_tags($key));
	        $key = str_replace('%', '', $key);	//过滤'%'，用户全文搜索
            $key=$this->CsdjSkins->rurlencode($key);

            $CS_Template='so-vod-'.$fid.'.html';
            $this->load->get_templates();
		    $template=$this->load->view($CS_Template,$data,true);
		    $Mark_Text=$this->CsdjSkins->TopandBottom($template);
		    $Mark_Text=str_replace("{cscms:sokey}",$key,$Mark_Text);
            if($fid=='zm'){
		        $Mark_Text=str_replace("{cscms:title}","按字母".$key."搜索 - ".Web_Name,$Mark_Text);
            }elseif($fid=='tags'){
		        $Mark_Text=str_replace("{cscms:title}","按标签".$key."搜索 - ".Web_Name,$Mark_Text);
            }else{
		        $Mark_Text=str_replace("{cscms:title}","搜索视频".$key." - ".Web_Name,$Mark_Text);
            }
		    $Mark_Text=str_replace("{cscms:keywords}",$key,$Mark_Text);
		    $Mark_Text=str_replace("{cscms:description}",stripslashes(html_entity_decode(Web_Description)),$Mark_Text);

		    //预先除了分页
		    $pagenum=$this->CsdjSkins->GetPageNum($Mark_Text);
		    preg_match_all('/{cscms:vod(.*?pagesize=([\S]+).*?)}([\s\S]+?){\/cscms:vod}/',$Mark_Text,$page_arr);//判断是否有分页标识
		    if(!empty($page_arr) && !empty($page_arr[2])){

			      $zimu_arr=array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
			      $zimu_arr1=array(-20319,-20283,-19775,-19218,-18710,-18526,-18239,-17922,-1,-17417,-16474,-16212,-15640,-15165,-14922,-14914,-14630,-14149,-14090,-13318,-1,-1,-12838,-12556,-11847,-11055);
			      $zimu_arr2=array(-20284,-19776,-19219,-18711  ,-18527,-18240,-17923,-17418,-1,-16475,-16213,-15641,-15166,-14923,-14915,-14631,-14150,-14091,-13319,-12839,-1,-1,-12557,-11848,-11056,-2050);
                
		         if($fid=='zm' && in_array(strtoupper($key),$zimu_arr)){  //按字母搜索
			            $posarr=array_keys($zimu_arr,strtoupper($key));
			            $pos=$posarr[0];
			            $sqlstr="SELECT * FROM ".CS_SqlPrefix."vod where CS_YID=0 and CS_HID=0 and (((ord( substring( CS_Name, 1, 1 ) ) -65536>=".($zimu_arr1[$pos])." and  ord( substring( CS_Name, 1, 1 ) ) -65536<=".($zimu_arr2[$pos]).")) or UPPER(substring( CS_Name, 1, 1 ))='".$zimu_arr[$pos]."')";
		         }elseif($fid=='tags'){ //标签
                        $sqlstr="select * from ".CS_SqlPrefix."vod where CS_YID=0 and CS_HID=0 and CS_Tags like '%".$key."%' order by CS_AddTime desc";
		         }else{
                        $sqlstr="select * from ".CS_SqlPrefix."vod where CS_YID=0 and CS_HID=0 and (CS_Name like '%".$key."%' or CS_Tags like '%".$key."%' or CS_Daoy like '%".$key."%' or CS_Yany like '%".$key."%' or CS_Diqu like '%".$key."%' or CS_Yuyan like '%".$key."%' or CS_Year like '%".$key."%') order by CS_AddTime desc";
				 }


			     $Arr=$this->CsdjSkins->SpanPage($sqlstr,$page_arr[2][0],$pagenum,'so','vod',$fid,urlencode($key),1,$page);//sql,每页显示条数
			     $result=$this->CsdjDB->db->query($Arr[2]);
			     $recount=$result->num_rows();
			     if($recount==0){
                      if($fid=='zm'){
				           $data_content.="<div align=center><strong>对不起,没有找到字母《<font color=#FF0000>".$key."</font>》开头的相关视频!</strong></div>";
                      }else{
				           $data_content.="<div align=center><strong>对不起,没有找到《<font color=#FF0000>".$key."</font>》相关视频!</strong></div>";
                      }
				 }else{
				      if($result){
					      $sorti=1;
					      foreach ($result->result() as $row2) {
						      $datatmp=$this->CsdjSkins->DataVod($page_arr[0][0],$page_arr[3][0],$row2,$sorti);
						      $sorti=$sorti+1;
						      $data_content.=$datatmp;
					      }
				      }
				 }// end if recount
			     $Mark_Text=$this->CsdjSkins->Page_Mark($Mark_Text,$Arr);	
			     $Mark_Text=str_replace($page_arr[0][0],$data_content,$Mark_Text);
			     unset($Arr);
			}
		    unset($page_arr);
		    $this->CsdjSkins->skins($Mark_Text,$data);
		    $this->CsdjCache->end();
	}

    //内容页面
	public function show()
	{
            $fid = $this->uri->segment(3);   //方式
            $id = intval($this->uri->segment(4));   //ID
                
            //判断运行模式
            $cscms=$this->input->get('cs', TRUE);
	        if(Web_Mode==3 && $cscms!="html"){
                    $Htmllink=$this->CsdjSkins->LinkUrl('show','vod',$fid,1,$id);
                    header("Location: ".$Htmllink.""); 
                    exit;
            }
		    $row=$this->CsdjDB->get_select ('vod','CS_ID','*',''.$id.'');
		    if(!$row){
                exit($this->CsdjSkins->Msg_url('出错了，该视频不存在！',Web_Path));
		    }
            if($row[0]->CS_YID==1){
                exit($this->CsdjSkins->Msg_url('出错了，该视频没有审核！',Web_Path));
            }

	        $cache_id ="vod_show_".$fid."_".$id;
	        if(!($this->CsdjCache->start($cache_id))){
                echo $this->CsdjVod->show($fid,$id,$row);
			    $this->CsdjCache->end();
			}
	}

    //播放页面
	public function play()
	{
            $data=$data_content='';
            $id = intval($this->uri->segment(3));   //ID
            $zu = intval($this->uri->segment(4));   //组
            $ji = intval($this->uri->segment(5));   //集
                
		    $row=$this->CsdjDB->get_select ('vod','CS_ID','*',$id);
		    if(!$row){
                 exit($this->CsdjSkins->Msg_url('出错了，该视频不存在！',Web_Path));
		    }
            if($row[0]->CS_YID==1){
                 exit($this->CsdjSkins->Msg_url('出错了，该视频没有审核！',Web_Path));
            }

	        $cache_id ="vod_play_".$id."_".$zu."_".$ji;
	        if(!($this->CsdjCache->start($cache_id))){

		        if($this->session->userdata('cs_id')){
                     $uid=$this->session->userdata('cs_id');
                }else{
                     $uid=0;
                }
		        if($this->session->userdata('cs_name')){
                     $user=$this->session->userdata('cs_name');
                }else{
                     $user='';
                }

                if($row[0]->CS_Vip>0 || $row[0]->CS_Cion>0){
	                 $this->load->model('CsdjUser');
		             if(!$this->CsdjUser->User_Login(1)){
                          exit($this->CsdjSkins->Msg_url('出错了，请先登入后在下载！',site_url("user/login")));
                     }else{
		                  $rowu=$this->CsdjDB->get_select('user','CS_ID','CS_Vip,CS_Cion',$uid);
                          $vip=$rowu[0]->CS_Vip;
                          $cion=$rowu[0]->CS_Cion;
                     }
                     //判断级别
                     if($row[0]->CS_Vip>$vip){
                          exit($this->CsdjSkins->Msg_url('抱歉，您的级别不能观看该部视频，请先升级！',site_url("user/pay/vip/")));
                     }
                     $kd=0;

                     //判断级别权限
                     if($vip>0){
                        $sqlz="SELECT * FROM ".CS_SqlPrefix."userzu where cs_id=".$vip."";
		                $rowz=$this->CsdjDB->get_all($sqlz);
		                if(!$rowz){
                             exit($this->CsdjSkins->Msg_url('出错了，该会员组不存在！',site_url("user/pay/vip")));
                        }else{
                             if($this->CsdjSkins->Getqx('vod_'.$row[0]->CS_CID,$rowz[0]->CS_Quanx)!='ok'){
                                  exit($this->CsdjSkins->Msg_url('抱歉，您所在的会员组不能观看该部视频！',site_url("user/pay/vip")));
                             }
                        }
                     }

                     //扣除点数,VIP会员跳过
                     if($vip==0){
                        $lookvodtime=60*60*User_Downtime;
		                if($this->CsdjSkins->DateDiff($this->session->userdata('lookvodtime_'.$id),date("Y-m-d H:i:s"))>$lookvodtime){
                              //判断点数
                              if($row[0]->CS_Cion>$cion){
                                 exit($this->CsdjSkins->Msg_url('抱歉，您的点数不够观看该部视频，请先充值！',site_url("user/pay/")));
                              }
		                      $us['CS_Cion'] = $cion-$row[0]->CS_Cion;
                              $this->CsdjDB->get_update ('user',$uid,$us);
                              $kd=1;
		                      $downsj['lookvodtime_'.$id]=date("Y-m-d H:i:s");
                              $this->session->set_userdata($downsj);
						}
                    }

                    //写入消费记录
		            $down['CS_User']    = $user;
		            $down['CS_CID']     = $row[0]->CS_CID;	
		            $down['CS_DID']     = $row[0]->CS_ID;
		            $down['CS_SID']     = 2;
		            $down['CS_Ip']      = @$_SERVER["REMOTE_ADDR"];
                    if($vip==0){
		                $down['CS_Cion']    = $row[0]->CS_Cion;
                    }
		            $down['CS_Name']    = $row[0]->CS_Name;
		            $down['CS_AddTime'] = date('Y-m-d H:i:s');
                    if($kd==1){
		                  $this->CsdjDB->get_insert ('down',$down);
                    }
                }

                if(empty($row[0]->CS_Template)){
                      $CS_Template='vod-play.html';
                }else{
                      $CS_Template=$row[0]->CS_Template;
                }

                $this->load->get_templates();
		        $template=$this->load->view($CS_Template,$data,true);

        	    //SEO标题
        	    if (empty($row[0]->CS_Title)){
               		$seo_title="在线观看 - ".$row[0]->CS_Name." - ".Web_Name;
        	    }else{
               		$seo_title=$row[0]->CS_Title;
        	    }
        	    //SEO关键词
        	    if (empty($row[0]->CS_Keywords)){
               		$seo_keywords=$row[0]->CS_Name."观看,".$row[0]->CS_Name."介绍";
        	    }else{
              		$seo_keywords=$row[0]->CS_Keywords;
        	    }
        	    //SEO描述
        	    if (empty($row[0]->CS_Description)){
               		$seo_description=$row[0]->CS_Name." 是由".Web_Name."提供观看和下载。";
        	    }else{
               		$seo_description=$row[0]->CS_Description;
        	    }

	            $Data_Arr=explode("#cscms#",$row[0]->CS_PlayUrl);
                if($zu>=count($Data_Arr)){
                    exit($this->CsdjSkins->Msg_url('出错了，该视频地址不正确！',Web_Path));
                }
		        $DataList_Arr=explode("\r\n",$Data_Arr[$zu]);
		        $Dataurl_Arr=explode('$',$DataList_Arr[$ji]);

		        $xpurl="";  //下集播放地址
		        $laiyuan=$Dataurl_Arr[2]; //来源
		        $url=$Dataurl_Arr[1];  //地址
		        $pname=$Dataurl_Arr[0];  //当前集数

		        if(count($DataList_Arr)>($ji+1)){
			        $DataNext=$DataList_Arr[($ji+1)];
			        $DataNextArr=explode('$',$DataNext);
			        if(count($DataNextArr)==2) $DataNext=$DataNextArr[1];
			        $xurl=$this->CsdjSkins->VodPlayUrl($id,$zu,($ji+1));
		            $Dataurl_Arr2=explode('$',$DataList_Arr[($ji+1)]);
                    $xpurl=@$Dataurl_Arr2[1];  //下集播放地址
		        }else{
			        $DataNext=$DataList_Arr[$ji];
			        $DataNextArr=explode('$',$DataNext);
			        if(count($DataNextArr)==2) $DataNext=$DataNextArr[1];			
			        $xurl=$this->CsdjSkins->VodPlayUrl($id,$zu,$ji);
                    $xpurl='';  //下集播放地址
		        }
                if($ji==0){
			        $surl=$this->CsdjSkins->VodPlayUrl($id,$zu,$ji);
                }else{
			        $surl=$this->CsdjSkins->VodPlayUrl($id,$zu,($ji-1));
                }

		        $Mark_Text=str_replace("{cscms:title}",$seo_title,$template);
		        $Mark_Text=str_replace("{cscms:keywords}",$seo_keywords,$Mark_Text);
		        $Mark_Text=str_replace("{cscms:description}",$seo_description,$Mark_Text);
                        $Mark_Text=str_replace("[vod:qurl]",$url,$Mark_Text);
		        $Mark_Text=$this->CsdjSkins->Vod_Playlist($Mark_Text,$id,$row[0]->CS_Laiy,$row[0]->CS_PlayUrl,$zu,$ji);
		        $Mark_Text=str_replace("[url:name]",$pname,$Mark_Text);

                if(Pl_Modes==0){
			       $comment="<script language='javascript' src='".Web_Path."csdj/js/plajax.js'></script><script>var cs_sid='vod';var cs_did='".$id."';var cs_path='".Web_Path."';getpllist('1','".$id."','vod');</script><div id='cscms_pl'><div style='padding:5px;text-align:center;'><img src='".Web_Path."csdj/images/load.gif'/>&nbsp;&nbsp;评论载入中，请稍候.....</div></div>";
                }elseif(Pl_Modes==2){
			       $comment="<div style='padding:5px;text-align:center;'>&nbsp;&nbsp;评论已经被站长关闭!</div>";
                }else{
			       $comment="<div id=\"uyan_frame\"></div><script type=\"text/javascript\" id=\"UYScript\" src=\"http://v1.uyan.cc/js/iframe.js?UYUserId=0\" async=\"\"></script>";
                }
		        $Mark_Text=str_replace("[vod:pl]",$comment,$Mark_Text);

                //播放器
                $psname='';
			    for($j=0;$j<count($Data_Arr);$j++){
				   $jis='';
			       $Ji_Arr=explode("\r\n",$Data_Arr[$j]);
                   for($k=0;$k<count($Ji_Arr);$k++){
			            $Ly_Arr=explode('$',$Ji_Arr[$k]);
						$jis.=$Ly_Arr[0].'$$'.$Ly_Arr[2].'====';
				   }
				   $psname.=substr($jis,0,-4).'#cscms#';
			    }
                $player_arr=substr($psname,0,-7);
	            if($laiyuan=='xgvod'||$laiyuan=='jjvod'||$laiyuan=='yyxf'||$laiyuan=='bdhd'||$laiyuan=='qvod'){
				    $xpurl=str_replace("+","__",base64_encode($xpurl));
	                $url=str_replace("+","__",base64_encode($url));
			    }else{
				    $xpurl=$this->CsdjSkins->escape($xpurl);
	                $url=$this->CsdjSkins->escape($url);
			    }
		        $player="<script type='text/javascript'>var cs_did='".$id."';var player_name='".$player_arr."';var cs_pid='".$ji."';var cs_zid='".$zu."';var cs_vodname='[vod:name] - ".$pname."';var cs_root='".Web_Path."';var cs_width=".CS_Play_sw.";var cs_height=".CS_Play_sh.";var cs_surl='".$surl."';var cs_xurl='".$xurl."';var cs_url='".$url."';var cs_xpurl='".$xpurl."';var cs_laiy='".$laiyuan."';var cs_adloadtime='".CS_Play_AdloadTime."';</script><iframe border=\"0\" name=\"qireplay\" id=\"qireplay\" src=\"".Web_Path."csdj/player/vod/play.html\" marginwidth=\"0\" framespacing=\"0\" marginheight=\"0\" noresize=\"\" vspale=\"0\" style=\"z-index: 9998;\" frameborder=\"0\" height=\"".(CS_Play_sh+30)."\" scrolling=\"no\" width=\"100%\"></iframe>";

		        $Mark_Text=str_replace("[vod:player]",$player,$Mark_Text);
		        $Mark_Text=str_replace("[vod:surl]",$surl,$Mark_Text);
		        $Mark_Text=str_replace("[vod:xurl]",$xurl,$Mark_Text);
		        $Mark_Text=$this->CsdjSkins->Common_Mark($Mark_Text,$row[0]->CS_CID);
		        $Mark_Text=$this->CsdjSkins->DataVod($Mark_Text,$Mark_Text,$row[0],1);
		        $Mark_Text.="<script src=".site_url('vod/hits/id/'.$id)."></script>";//增加人气
		        $this->CsdjSkins->skins($Mark_Text,$data);
		        $this->CsdjCache->end();
			}
	}

    //增加人气
	public function hits()
	{
           $ac = $this->uri->segment(3);   //方式
           if($ac=='id'){

                $id = intval($this->uri->segment(4));   //ID
		        $row=$this->CsdjDB->get_select ('vod','CS_ID','CS_Rhits,CS_Zhits,CS_Yhits,CS_Hits,CS_PlayTime',''.$id.'');
		        if(!$row){
			        show_404();
		        }
                //增加舞曲播放人气
                $daytime =$this->CsdjSkins->DateBj("d",$row[0]->CS_PlayTime,date('Y-m-d H:i:s'));
	            if($daytime==0){
	                $updata['CS_Rhits']=$row[0]->CS_Rhits+1;
	            }else{
	                $updata['CS_Rhits']=1;
	            }
	            if($daytime < 7){
	                $updata['CS_Zhits']=$row[0]->CS_Zhits+1;
	            }else{
	                $updata['CS_Zhits']=1;
	            }
	            if($daytime <31){
	                $updata['CS_Yhits']=$row[0]->CS_Yhits+1;
	            }else{
	                $updata['CS_Yhits']=1;
	            }
	            $updata['CS_Hits']=$row[0]->CS_Hits+1;
	            $updata['CS_PlayTime']=date('Y-m-d H:i:s');
                $this->CsdjDB->get_update ('vod',$id,$updata);

           }elseif($ac=='dt'){   //静态模式、动态人气

                $op = $this->uri->segment(4);   //类型
                $id = intval($this->uri->segment(5));   //ID
	        	$row=$this->CsdjDB->get_select ('vod','CS_ID','CS_Xhits,CS_Shits,CS_Chits,CS_Dhits,CS_Rhits,CS_Zhits,CS_Yhits,CS_Hits',''.$id.'');
		        if(!$row){
			          show_404();
		        }

                if($op=='yhits'){
                      echo "document.write('".$row[0]->CS_Yhits."');";
                }elseif($op=='zhits'){
                      echo "document.write('".$row[0]->CS_Zhits."');";
                }elseif($op=='rhits'){
                      echo "document.write('".$row[0]->CS_Rhits."');";
                }elseif($op=='dhits'){
                      echo "document.write('".$row[0]->CS_Dhits."');";
                }elseif($op=='chits'){
                      echo "document.write('".$row[0]->CS_Chits."');";
                }elseif($op=='shits'){
                      echo "document.write('".$row[0]->CS_Shits."');";
                }elseif($op=='xhits'){
                      echo "document.write('".$row[0]->CS_Xhits."');";
                }else{
                      echo "document.write('".$row[0]->CS_Hits."');";
                }
           }
	}
}


