<?php
/*
'**************************************************************************************************
' 软件名称: 搜一次 Content Management System
' 版本编号: Version 1.X
' 官方网站: http://www.syccms.com
' 官方论坛：http://bbs.syccms.com
' 版权所有: 搜一次运营团队
' 法律顾问: 杭州市元茂律师事务所 严飞律师
' 郑重声明:
'    1、任何个人或组织不得在未经授权的情况下删除、修改、拷贝本软件及其他副本上一切关于版权的信息；
'    2、搜一次网络事业部保留此软件的法律追究权利
'**************************************************************************************************
*/
session_start();
//include "../admin_loginstate.php";
include "../../include/conn.php";
include "../../include/function.php";
include '../../include/class/http.class.php';
include "../admin_version.php";
set_time_limit(0);

$from_player = array(
	'bdyy'=>'bdhd',
	'youku'=>'youku',
	//'letv',
	'qiyi'=>'qiyi',
	'sohu'=>'sohu',
	'qqplay'=>'qq',
	'kumi'=>'swf',
	'ppvod'=>'ppvod',
	'tudou'=>'tudou',
	'6rooms'=>'6rooms',
	'qvod'=>'qvod',
	'ku6'=>'ku6hd',
	'goxunlei',
	//'JOY',
	'56play'=>'56hd',
	'sina'=>'sina',
	'gvod'=>'gvod',
);

$iscurl = 0;
if (function_exists('curl_init')) {
	$iscurl = 1;
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>影片管理</title>
</head><body><?php

class ui_resource{
	public function videolist($ServerUrl,$Page,$ClassID,$VideoID,$iPageSize,$Mark,$action){
		global $db;
		$url = httpbuildquery('page,cj_type,keyword,cj_urla,mark','list').unionids($Mark);
		
		$contentlist = http::curl_http($url);
		if (!empty($contentlist)) {
			echo str_replace('A_ID', 'A_ID[]', $contentlist);
		}else{
			exit('远程无法访问');
		}
	}

	public function Serverlist(){
		echo file_get_contents('http://www.seayuan.net/');	
    }	
}

$ServerUrl 	= 'http://www.seayuan.net/';
$action 	= SafeRequest("action");
$Page 		= SafeRequest("page");
$ClassID 	= SafeRequest('cj_type');
$VideoID 	= SafeRequest("moveid");
$pagenum 	= SafeRequest("pagenum");
$Mark 		= SafeRequest("mark");
$types 		= SafeRequest("cj_type");
$key 		= SafeRequest("keyword");
$Syc 		= SafeRequest("Syc");

if(!IsNul($Page)){$Page=1;}
if(!IsNul($ClassID)){$ClassID=0;}

if($action=="caiji" and $VideoID==""  and $ClassID==""){
		die("<script>alert('请选择要采集的数据!');history.back();</script>");
	}

$ui=new ui_resource;
switch($action){
	case 'serverlist':
		Serverlist();
		break;
	case 'set':
		$url = httpbuildquery('mark,cj_urla,shouquan','set','set.asp');
		echo http::curl_http($url);
		break;
	case 'cjselect'://采集选中
		$_REQUEST['ids'] = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : $_REQUEST['A_ID'];
		$url = httpbuildquery('mark,cj_urla,ids,page','cjselect');
		Caiji($url,$Mark);
		break;
	case 'cjday':
		$url = httpbuildquery('mark,cj_urla,page','cjday');
		Caiji($url,$Mark);
		break;
	case 'cjtype'://debug 要解决翻页的问题
		$url = httpbuildquery('mark,cj_urla,cj_type,page','cjtype');
		Caiji($url,$Mark);
		break;
	case "soso":
		$url = httpbuildquery('mark,page,cj_urla,keyword,cj_type','list','type.asp').unionids($Mark);
		echo http::curl_http($url);
		break;
	case 'cj':
		$url = urldecode($_REQUEST['url']);
		parse_str($url);
		Caiji($url,$mark);
		break;
	case 'list':
		$ui->videolist($ServerUrl,$Page,$ClassID,$VideoID,10,$Mark,$action);
		break;
	case 'showcon':
		$url = httpbuildquery('mark,cj_urla,moveid','showcon');
		echo http::curl_http($url);
		break;
	case 'binding':
		$cjtype = SafeRequest('cj_type');
		$servername = SafeRequest('severname');
		$Mark = SafeRequest('mark');
		$backurl = $_SERVER['HTTP_REFERER'];
		$bindstr = ',SY_'.$Mark.$cjtype.',';
		$bindid = 0;
		$res = $db->getOne('select `S_ID` from s_class where `S_TieID` like \'%'.$bindstr.'%\'');
		if ($res) {
			$bindid = $res;
		}
		$getClassInfo = getClassInfo(1);
		$classStr = '';
		foreach ($getClassInfo as $key=>$val){
			$classStr .= '<option value="'.$key.'"'.(($key==$bindid)?' selected="selected"':'').'>'.$val.'</option>';
		}
		echo <<<EOD
<form action="?action=bindingsave" method="post">
<TABLE width="96%" border=0 align=center cellpadding="4" cellSpacing=1 class=tbtitle style="BACKGROUND: #cad9ea;">

  <TBODY>
  <input name="cj_type" type="hidden" value="{$cjtype}">
  <input name="backurl" type="hidden" value="{$backurl}">
 
  <input name="mark" type="hidden" value="{$Mark}">
    <TR>
      <TD width="20%" vAlign=center bgcolor="#FFFFFF" class="tdxingmu">提示信息：</TD>
      <TD bgcolor="#FFFFFF" class="tdback"> 将资源库分类: <font color="red">{$servername}</font> 绑定到
	  </TD>
    </TR>
    <TR>
      <TD width="20%" vAlign=center bgcolor="#FFFFFF" class="tdxingmu">本地分类：</TD>
      <TD bgcolor="#FFFFFF" class="tdback">
      &nbsp;  
        <select name="cid">
      	<option value="0">请选择绑定的分类</option>
			 {$classStr}
		 </select>
	  </TD>
    </TR>
    <TR align="center" bgcolor="#f8fbfb">
      <TD colspan="2"><input class=inputbut type=submit value=绑定分类 name=Submit> &nbsp;<input name="jiecbd" type="button" onclick="this.form.action='?action=bindingkill';this.form.submit();" value="解除绑定"></TD>
    </TR>
  </TBODY>
 
</TABLE>
 </form>
EOD;
		break;
	case 'bindingsave':
		$cjtype = SafeRequest('cj_type','post');
		$Mark = SafeRequest('mark','post');
		$backurl = SafeRequest('backurl','post');
		$cid = intval($_POST['cid']);
		$str = '\,SY_'.$Mark.$cjtype.'\,';
		//去掉所有该分类的绑定信息
		$db->query("update s_class set `S_TieID` = replace(`S_TieID`,'{$str}','')");
		$db->query("update s_class set `S_TieID` = concat(`S_TieID`,'{$str}') where `S_ID`={$cid}");
		if ($db->affected_rows()) {
			if(isset($_SESSION['caijibind_'.$Mark])) unset($_SESSION['caijibind_'.$Mark]);
			echo '跳转中。。。。';
			echo '<script type="text/javascript">alert("操作成功");setTimeout(function(){window.location.href="'.$backurl.'"},1000);</script>';
		} else {
			echo '跳转中。。。。';
			echo '<script type="text/javascript">alert("绑定失败");setTimeout(function(){window.location.href="'.$backurl.'"},1000);</script>';
		}
		break;
	case 'bindingkill':
		$cjtype = SafeRequest('cj_type','post');
		$Mark = SafeRequest('mark','post');
		$backurl = SafeRequest('backurl','post');
		$cid = intval($_POST['cid']);
		$str = ',SY_'.$Mark.$cjtype.',';
		//去掉所有该分类的绑定信息
		$db->query("update s_class set `S_TieID` = replace(`S_TieID`,'{$str}','') where `S_ID`={$cid}");
		if(isset($_SESSION['caijibind_'.$Mark])) unset($_SESSION['caijibind_'.$Mark]);
		echo '<script type="text/javascript">alert("操作成功");window.location.href="'.$backurl.'";</script>';
		break;
	default:
		break;
	}	


function Serverlist(){
	global $ui;
	 $ui->Serverlist();
	}

function httpbuildquery($param = '', $action='list', $file = 'type.asp'){
	global $ServerUrl;
	$param = explode(',', $param);
	$array = array();
	if (!empty($action)) {
		$array['action'] = $action;
	}
	foreach ($param as $value) {
		$array[$value] = (isset($_REQUEST[$value]) && is_array($_REQUEST[$value])) ? implode(',', $_REQUEST[$value]) : SafeRequest($value);
	}
	return $ServerUrl.$file.'?'.http_build_query($array).'&HostUrl='.$_SERVER['HTTP_HOST'].'&kftype=soyici';
}

//判断绑定
function checkisbind($mark){
	if (isset($_SESSION['caijibind_'.$mark])) {
		$ids = $_SESSION['caijibind_'.$mark];
	} else {
		global $db;
		$query = $db->query('select `S_ID`,`S_TieID` from s_class where `S_SystemID`=1 and `S_TieID` like \'%,SY_'.$mark.'%\'');
		$ids = array();
		while ($row=$db->fetch_array($query)){
			if (preg_match_all('/,SY_'.$mark.'([\d]+),/', $row['S_TieID'], $array)) {
				foreach ($array[1] as $cj_type){
					$ids[$cj_type] = $row['S_ID'];
				}
			}
		}
		$_SESSION['caijibind_'.$mark] = $ids;	
	}
	return $ids;
}

function unionids($mark){
	$unionids = '&unionids=';
	$ids = checkisbind($mark);
	if (is_array($ids)) {
		$ids = array_keys($ids);
		foreach ($ids as $value) {
			$unionids .= ','.$mark.$value.',';
		}
	}
	return $unionids;
}
	
function Caiji($url, $mark){
		$SHENGMING = 'sb6y5bz+08nL0dK7tM7Qrdb6v6q3oqOst72x49W+s6SyybyvtdrI/be9t9bP7c341b7K08a1xNrI3aOsx+vO8NPD09q3x7eo08PNvtLUvLDJzNK1wPvS5g';
		global $db;
		global $from_player;
		//分析数据，是否有需要采集的内容
		$content = http::curl_http($url);
		if (!empty($content)) {
			//首先分析绑定信息，如果正确，将分类绑定信息存SESSION
			$ids = checkisbind($mark);
			if (empty($ids)) {
				exit('你还没有绑定任何分类，无法采集');
			}
			
			//继续读取参数
			$renewpic = SafeRequest('renewpic')==1 ? 1 : 0;
			$renewdec = SafeRequest('renewdec')==1 ? 1 : 0;
			$notypet = SafeRequest('notypet')==1 ? 1 : 0;
			
			$list = explode('#$#CV#$#', $content); 
			if (!isset($list[4])) {
				exit($content);
			}
			unset($content);
			
			$list[4] = explode('||||', $list[4]);
			foreach ($list[4] as $key=>$value){
				$list[4][$key] = explode('##CV##', $list[4][$key] );
			}
			//0 => 3 当前采集多少条数据
			//1 => 1 pagenow
			//2 => 1 pagecount
			//3 => 3 movecount	
			echo("<div style=\" width:100%; background: #F9FBFD; border-top:4px solid #DEEFFA; border-bottom:1px solid #DEEFFA;color:#008EBD; font-size:12px; height:30px; line-height:30px;font-weight:bold; margin:0 auto;\">&nbsp;正在采集视频第<font style='color:red; font-size:12px; font-style:italic'>".$list[1]."</font>页，剩<font style='color:red; font-size:12px; font-style:italic'>".($list[2]-$list[1])."</font>页,总共<font style='color:red; font-size:12px; font-style:italic'>".$list[2]."</font></div>");
			if ($iscurl) {
				echo '<font color=red>&nbsp;&nbsp;主机空间不支持curl采集扩展，忽略图片更新</font>';
			}
			$count = count($list[4]);
			$remote = $local = array();//初始化需要采集的图片
			for($i=0;$i<$count;$i++){
				$S_Name=$list[4][$i][0];
				$S_ClassID=isset($ids[$list[4][$i][1]]) ? $ids[$list[4][$i][1]] : 0;
				if (!$S_ClassID && !$notypet) {
					echo "<font color=red>&nbsp;&nbsp;".$S_Name."</font>没有分类绑定信息，采集跳过！<br/>";
					continue;
				}
				$S_Remark=(!empty($list[4][$i][2])) ? $list[4][$i][2] : '';
				$S_Keywords='';
				$S_Remark=(!empty($list[4][$i][2])) ? $list[4][$i][2] : '';
				$S_Author=str_replace(',', ' ', $list[4][$i][4]);
				$S_Direct='';
				$S_IsEnd=($S_Remark=='完结')?1:0;
				
				$S_Source = strtolower($list[4][$i][6]);
				if (!isset($from_player[$S_Source])) {
					echo "<font color=red>&nbsp;&nbsp;".$S_Name."</font>没有播放器".$S_Source."对应信息，请添加相应播放器后修改admin_revod.php头部采集！<br/>";
					continue;
				}
				$S_Source = $from_player[$S_Source];
				
				$S_Content=$list[4][$i][5];
				$S_VData=$list[4][$i][7];
				$S_Year='未知';
				$S_Area=$list[4][$i][8];
				$S_Language=$list[4][$i][9];
				$S_Pic=$list[4][$i][3];
				$S_AddTime=date('Y-m-d H:i:s');
				if($S_Area==""){$S_Area="未知";}
				if($S_Language==""){$S_Language="未知";}
				
				//开始处理数据
				if(!IsNul($S_Source) or !IsNul($S_VData)){
				 	echo "&nbsp;&nbsp;<font color=red>".$S_Name."&nbsp;".$S_Remark."</font>&nbsp;&nbsp;数据不完整，不进行入库处理！<br/>";
				} else {
					if (!$S_ClassID && $notypet) {//临时库
						$sql = 'select `S_ID` from tempvideo where S_Name = \''.$S_Name.'\' limit 1';
						$S_ID = $db->getOne($sql);
						if ($S_ID) {
							$db->query('delete from tempvideo where S_ID = '.$S_ID);
						}
						$sql="insert tempvideo (S_Name,S_Keywords,S_Remark,S_Pic,S_ClassID,S_Author,S_Content,S_Direct,S_IsEnd,S_Source,S_VData,S_Year,S_Area,S_Language,S_AddTime) values ('".$S_Name."','".$S_Keywords."','".$S_Remark."','".$S_Pic."',".$S_ClassID.",'".$S_Author."','".$S_Content."','".$S_Direct."',".$S_IsEnd.",'".$S_Source."','".$S_VData."','".$S_Year."','".$S_Area."','".$S_Language."','".$S_AddTime."')";
						if($db->query($sql)){
							echo "<font color=red>&nbsp;&nbsp;".$S_Name."</font>判断采集到临时库，采集成功！<br/>";
						}else{
							echo "<font color=red>&nbsp;&nbsp;".$S_Name."</font>判断采集到临时库，但采集失败！<br/>";
						}
						continue;
					}
					
					//判断数据是否相同
					$sql2="select S_ID,S_Source,S_VData,S_Pic from s_video where S_ClassID='".$S_ClassID."' and S_Name='".$S_Name."' order by S_AddTime desc limit 1";
					$result2=$db->query($sql2);
					if ($result2 && $db->num_rows($result2)!=0) {
						while ($row3=$db->fetch_array($result2)){
							if($row3['S_Source']==$S_Source and $row3['S_VData']==$S_VData){
								echo "&nbsp;&nbsp;<font color=red>".$S_Name." &nbsp;".$S_Remark."</font>&nbsp;&nbsp;数据相同，暂无不需要更新<br/>";
							} else {
								if(stristr($row3['S_Source'],$S_Source)){
									  $Temp_Source=explode('$$',$row3['S_Source']);
									  $Temp_VData=explode('$$$',$row3['S_VData']);
									  for($j=0;$j<count($Temp_Source);$j++){
										  if($Temp_Source[$j]==$S_Source){
											  $Temp_VData[$j]=$S_VData;
											  }
										  }
									  $R_VData=join("$$$",$Temp_VData);
									  $S_Source=$row3['S_Source'];
									  $S_VData=$R_VData;
								} else {
									  $S_Source=$row3['S_Source'].'$$'.$S_Source;
									  $S_VData=$row3['S_VData'].'$$$'.$S_VData;
								}
								$sql="update s_video set S_Name='".$S_Name."',S_Remark='".$S_Remark."',S_ClassID=".$S_ClassID.",S_Author='".$S_Author."',S_Content='".$S_Content."',S_IsEnd=".$S_IsEnd.",S_Source='".$S_Source."',S_Vdata='".$S_VData."',S_Year='".$S_Year."',S_Area='".$S_Area."',S_Language='".$S_Language."',S_Direct='".$S_Direct."',S_Keywords='".$S_Keywords."',S_AddTime='".$S_AddTime."' where S_ID=".$row3['S_ID']."";
								if ($renewpic==1) {
									$remote[$i] = $S_Pic; $local[$i] = _SYC_ROOT_.'images/vodpic/'.$row3['S_Pic'];
								}
								if ($renewdec==1) {
									$sql="update s_video set S_Name='".$S_Name."',S_Remark='".$S_Remark."',S_ClassID=".$S_ClassID.",S_Author='".$S_Author."',S_IsEnd=".$S_IsEnd.",S_Source='".$S_Source."',S_Vdata='".$S_VData."',S_Year='".$S_Year."',S_Area='".$S_Area."',S_Language='".$S_Language."',S_Direct='".$S_Direct."',S_Keywords='".$S_Keywords."',S_AddTime='".$S_AddTime."' where S_ID=".$row3['S_ID']."";
								}
								if($db->query($sql)){
									 echo "&nbsp;&nbsp;<font color=red>".$S_Name."&nbsp;".$S_Remark."</font>&nbsp;&nbsp;数据有变动，数据已更新完成！<br>";
								}
							}
						}
					}else{
						$path_parts = pathinfo($S_Pic);
						if ($iscurl) {
							$filename = uniqid().'.'.$path_parts['extension'];
							$remote[$i] = $S_Pic; $local[$i] = _SYC_ROOT_.'images/vodpic/'.$filename;							
						} else {
							$filename = $S_Pic;
						}

						$sql="insert s_video (S_Name,S_Keywords,S_Remark,S_Pic,S_ClassID,S_Author,S_Content,S_Direct,S_IsEnd,S_Source,S_VData,S_Year,S_Area,S_Language,S_AddTime) values ('".$S_Name."','".$S_Keywords."','".$S_Remark."','".$filename."',".$S_ClassID.",'".$S_Author."','".$S_Content."','".$S_Direct."',".$S_IsEnd.",'".$S_Source."','".$S_VData."','".$S_Year."','".$S_Area."','".$S_Language."','".$S_AddTime."')";
						if($db->query($sql)){
							echo "<font color=red>&nbsp;&nbsp;".$S_Name."</font>数据库中没有记录，已采集完成！<br/>";
						}
					}
				}	
			}
			if ($iscurl && !empty($remote)) {//批量下载图片
				http::curlDownload($remote, $local);
			}
			
			if ($list[1]>=$list[2]) {//判断采集完成
				unset($list);
				$url = $_SERVER['PHP_SELF'].'?action=list&mark='.SafeRequest('mark').'&cj_type='.SafeRequest('cj_type').'&cj_urla=http://www.seayuan.net/type.asp&HostUrl='.$_SERVER['HTTP_HOST'].'&kftype=soyici'.unionids($mark);
				echo('</br>&nbsp;&nbsp;<b>恭喜您，全部采集完成啦。。。。。</b><script>alert("恭喜你,全部采集OK了!");window.location="'.$url.'"</script>');
			} else {
				$url = $_SERVER['PHP_SELF'].'?action='.SafeRequest('action').'&mark='.SafeRequest('mark').'&cj_type='.SafeRequest('cj_type').'&cj_urla=http://www.seayuan.net/type.asp&ids='.SafeRequest('ids').'&HostUrl='.$_SERVER['HTTP_HOST'].'&kftype=soyici&page='.($list[1]+1);
				echo("</br>&nbsp;&nbsp;<b><img src='../images/loading2.gif'>&nbsp;第".($list[1])."页采集完毕,暂停3秒继续。。。。。</b><script>setTimeout('updatenext();',3000);function updatenext(){location.href='{$url}';}</script>");
			}				
		} else {
			exit('意外终止，无法连接到采集服务器');
		}
	}
?></body>
</html>