<?php
@set_time_limit(0);
ob_implicit_flush();
require_once(dirname(__FILE__)."/admin_inc.php");
/*******************************************************************************************
' Software name: DJCMS Content Management System
' Version:3.0
' Web: http://www.djcms.net
' Author: 心情(qq:1130731)
' Copyright (C) 2009-2010 DJCMS官方 版权所有
' 法律申明：DJCMS程序所有代码100%原创、未引入任何网上代码,对一切抄袭行为、坚决严肃追究法律责任
'*******************************************************************************************/

$isref=0;//是否使用sock采集 0为不是用，1为使用
$gatherWaitTime=2; //资源库采集每页数据间隔时间
$gatherPicSet=0; //是否采集图片到本地,0为不采集,1为采集
$reslibMainSite="http://res.ekeke.net/";
if (!empty($backurl)) {
	if (strpos($backurl, "&") > 0) $backurl = urlencode($backurl);
}

switch ($action) {
	case "list":top();lista();bottom();break;
	case "select":gather();break;
	case "type":gatherType();break;
	case "day":gatherDay();break;
	case "bind":top();bindType();bottom();break;
	case "bindsubmit":bindSubmit();break; 
	default : top();main();bottom();break;
}

function bindSubmit() {
    global $curid,$class,$m_type,$bind_back,$m_oldtype;
	if (is_numeric($m_type)) {
		if (!empty($m_oldtype)) {
			$row = db::get_one("select m_id,m_unionid from {pre}type where m_id='$m_oldtype'");
			if (is_array($row)) {
				$unionid = delBindId($curid, $row["m_unionid"]);
				db::query("update {pre}type set m_unionid='$unionid' where m_id=".$row['m_id']);
			}
		}
		$row = db::get_one("select m_id,m_unionid from {pre}type where m_id='$m_type'");
		if (is_array($row)) {
			$unionid = addUnionid($curid, $row["m_unionid"]);
			db::query("update {pre}type set m_unionid='$unionid' where m_id=".$row['m_id']);
		}
		alertMsg("绑定成功", $bind_back);exit;
	} else {
		$row = db::get_one("select m_id,m_unionid from {pre}type where concat(',',m_unionid,',') like '%,".$curid.",%'");
		if (is_array($row)) {
			$unionid = delBindId($curid, $row["m_unionid"]);
			db::query("update {pre}type set m_unionid='$unionid' where m_id=".$row['m_id']);
		}
		alertMsg("解除绑定", $bind_back);exit;
	}
}

function unescapseCode($str) {
	if (empty($str)) return ""; else return urldecode(UnicodeUrl2Gbk($str));
}

function delBindId($bindid, $unionId) {
	if (empty($unionId)) {
		return $bindid;
	} else {
		if (strpos(" ,".$unionId.",",",".$bindid.",")) return ltrim(rtrim(str_replace(",".$bindid.",",",",",".$unionId.","),","),","); else return $unionId;
	}
}

function addUnionid($bindid, $unionId) {
	if (empty($unionId)) {
		return $bindid;
	} else {
		if (strpos(",".$unionId.",",",".$bindid.",")) return $unionId; else return $unionId.",".$bindid;
	}
}

function bindType() {
	global $tname,$curid,$class,$bind_back;
	$bind_back = getRefer();
	echo "<div class='bindtype'><form action='?action=bindsubmit&curid=".$curid."&class=".$class."' method='post' id='gatherform'  name='gatherform'><span>将资源库分类 <font  class='red'>".$tname."</font> 绑定到您的网站分类的</span><input type='hidden' value='".$bind_back."' name='bind_back' >&nbsp;&nbsp;<select name='m_type' id='m_type'><option value=''>请选择数据分类</option>";
	$typeid = getBindedLocalId($curid);
	makeTypeOptionSelected(0, "&nbsp;|&nbsp;", "", $typeid);
	echo "</select>&nbsp;&nbsp;<input type='hidden' name='m_oldtype' value='".$typeid."' /><input type='submit' value='绑  定'/>&nbsp;&nbsp;<input type='button' value='返  回' onClick='javascript:history.back();return false;'/></form></div>";
}

function gatherPicToServer($picurl, $vname){
	$isDownOk = false;
	$ps = explode("/", $picurl);
	$filename = $ps[count($ps)-1];
	$filePath = "../pic/".sitePic."/".$filename;
	if (!file_exists($filePath)) {
		$isDownOk = downSinglePic($picurl, "", $vname, $filePath, "");
	} else {
		echo "数据<font color=red>".$vname."</font>的图片已经存在 <a target=_blank href=".$filePath.">预览图片</a>";
		$isDownOk = true;
	}
	if ($isDownOk) {
		if (watermark == 1) writeFontWaterPrint($filePath);
		return replaceStr($filePath,"../","");
	} else {
		return "";
	}
}

function gatherPicHandle($str, $vname) {
	global $gatherPicSet;
	if ($gatherPicSet == 1){ return gatherPicToServer($str, $vname); } else { return $str;}
}

function intoDatabase($url, $gtype) {
	global $backurl,$gatherWaitTime,$ressite,$u,$type,$action,$page,$isref;
	$content = cget($url, $isref);
	$alertContent = getrulevalue(getrulevalue($content, 'alert'), 'content');
	if (!empty($alertContent)) {
		alertMsg($alertContent, "");
		exit("<script>history.go(-1)</script>");
	}
	if ($gtype == "type" || $gtype == "day") $page = getrulevalue(getrulevalue($content, 'pagenum'), 'content');
	echo "<div style='font-size:13px'><font color=red>资源库视频采集开始：</font><br>";
	$temparr = array();
	$temparr = getrulevaluearr($content, 'v');
	foreach ($temparr as $v) {
		$v_where = "";
		$vid = addslashes(unescapseCode(replaceCDATA(getrulevalue($v,'vid'))));
		$title = addslashes(unescapseCode(replaceCDATA(getrulevalue($v,'title'))));
		$title = msubstr($title,60);
		$libid = addslashes(getrulevalue($v,'cid'));
		$actor = addslashes(unescapseCode(replaceCDATA(getrulevalue($v,'act'))));
		$actor = msubstr(str_replace(" ",",",$actor),200);
		$pic = addslashes(replaceCDATA(getrulevalue($v,'imgurl')));
		$des = addslashes(unescapseCode(replaceCDATA(getrulevalue($v,'desc'))));
		$states = getrulevalue($v,'state');
		$publishyear = getrulevalue($v,'videotime');
		$publisharea = getrulevalue($v,'videoarea');
		$m_note = addslashes(replaceCDATA(getrulevalue($v,'note')));
		$publishyear = empty($publishyear) ? date('Y') : intval($publishyear);
		$states = empty($states) ? 0 : intval($states);
		$localId = getBindedLocalId($libid);
		if (!empty($title)) {
			$title = str_replace("]","】",str_replace("[","【",$title));
			if (is_numeric($localId)) {
				$titleArray = explode("/", $title);
				foreach ($titleArray as $v_title) {
					if (!empty($v_title)) $v_where .= " or concat('/',m_name,'/') like '%/".$v_title."/%' ";
				}
				$v_where = ltrim($v_where," or");
				$v_sql = "select m_id,m_playdata from {pre}data where ".$v_where." order by m_id desc";
				$rs = db::get_one($v_sql);
				if (!is_array($rs)) {
					$pic = gatherPicHandle($pic, $title);$m_enname=MoviePinYin($title);
					$sql = "insert into {pre}data(m_name,m_type,m_state,m_pic,m_actor,m_des,m_playdata,m_isunion,m_publishyear,m_publisharea,m_note,m_letter,m_addtime,m_enname,m_datetime) values('".$title."','".$localId."','".$states."','".$pic."','".$actor."','".$des."','".$vid."',1,'".$publishyear."','".$publisharea."','".$m_note."','".msubstr($m_enname,1)."','".time()."','$m_enname','".time()."')";
				} else {
					switch (gatherSet) {
				        case 0 :case 1 :case 2 :case 3 :
							$m_playdata = gatherIntoLibTransfer($rs['m_playdata'],$vid,gatherSet);$m_enname=MoviePinYin($title);
							$sql = "update {pre}data  set m_name='$title',m_state='$states',m_playdata='$m_playdata',m_isunion=1,m_addtime='".time()."',m_datetime='".time()."',m_letter` = '".msubstr($m_enname,1)."',m_enname='$m_enname' where m_id=".$rs['m_id'];
						break;
						case 4 :
							$pic = gatherPicHandle($pic, $title);$m_enname=MoviePinYin($title);
							$sql = "insert into {pre}data(m_name,m_type,m_state,m_pic,m_actor,m_des,m_playdata,m_isunion,m_publishyear,m_publisharea,m_note,m_letter,m_addtime,m_enname,m_datetime) values('$title','$localId','$states','$pic','$actor','$des','$vid',1,'$publishyear','$publisharea','$m_note','".msubstr($m_enname,1)."','".time()."','$m_enname','".time()."')";
						break;
						case 5 :
							$pic = gatherPicHandle($pic, $title);
							$sql = "update {pre}data set m_actor='$actor',m_pic='$pic',m_des='$des',m_publishyear='$publishyear',m_publisharea='$publisharea',m_note='$m_note',m_addtime='".time()."',m_datetime='".time()."' where m_id=".$rs['m_id'];
						break;
				    }
				}
				db::query($sql);
			} else {
				$libid = '000000';
				$titleArray = explode("/", $title);
				foreach ($titleArray as $v_title) {
					if (!empty($v_title)) $v_where .= " or concat('/',m_name,'/') like '%/".$v_title."/%' ";
				}
				$letter = getFirstLetter($title);
				$v_where = ltrim($v_where," or");
				$v_sql = "select m_id,m_playdata from {pre}temp where ".$v_where." order by m_id desc";
				$rs = db::get_one($v_sql);
				if (!is_array($rs)) {
					$sql = "insert into {pre}temp(m_name,m_type,m_state,m_pic,m_actor,m_des,m_playdata,m_publishyear,m_publisharea,m_addtime) values('$title','$libid','$states','$pic','$actor','$des','$vid','$publishyear','$publisharea','".time()."')";
				} else {
					switch (gatherSet) {
				        case 0 :case 1 :case 2 :case 3 :
						    $m_playdata = gatherIntoLibTransfer($rs['m_playdata'],$vid,gatherSet);
						    $sql = "update {pre}temp  set m_name='$title',m_state='$states',m_playdata='$m_playdata',m_addtime='".time()."' where m_id=".$rs['m_id'];
						break;
				        case 4 :
						    $sql = "insert into {pre}temp(m_name,m_type,m_state,m_pic,m_actor,m_des,m_playdata,m_publishyear,m_publisharea,m_addtime) values('$title','$libid','$states','$pic','$actor','$des','$vid','$publishyear','$publisharea','".time()."')";
					    break;
				        case 5 :
						    $sql = "update {pre}temp set m_pic='$pic',m_actor='$actor',m_des='$des',m_publishyear='$publishyear',m_publisharea='$publisharea',m_addtime='".time()."' where m_id=".$rs['m_id'];
						break;
					}
				}
				db::query($sql);
			}
		}
		echo "数据<font color=red>".$title."</font>已经采集成功<br>";
	}
	if (trim($page) == "") {
		if ($action == "day" || $action == "type") exit("<script>alert('恭喜，全部搞定');location.href='".urldecode($backurl)."'</script>");
		if ($action == "select") exit("<script>alert('恭喜，全部搞定');history.go(-1);</script>");
	} else {
		echo "<br/>暂停".$gatherWaitTime."秒--<font color=red>即将开始同步第".$page."页</font><br/></div>";
		if ($action == "day") {
			echo "<script language=\"javascript\">setTimeout(\"makeNextPage();\",".$gatherWaitTime."000);function makeNextPage(){location.href='?action=day&ressite=".$ressite."&page=".$page."&u=".$u."&backurl=".urlencode($backurl)."';}</script>";
		} else if ($action == "type") {
			echo "<script language=\"javascript\">setTimeout(\"makeNextPage();\",".$gatherWaitTime."000);function makeNextPage(){location.href='?action=type&ressite=".$ressite."&page=".$page."&type=".$type."&u=".$u."&backurl=".urlencode($backurl)."';}</script>";
		}
	}
}

function getBindedLocalId($libId) {
	global $dsql;
	$row = db::get_one("select count(*) as dd from {pre}type where m_unionid<>''");
	if (!is_array($row)) return '';
	$sqlStr = "select m_id,m_unionid from {pre}type where m_unionid<>''";
	$rows = db::select($sqlStr);
    foreach ($rows as $rowl) {
		$unionArray = explode(",", $rowl['m_unionid']); $arrayLen2 = count($unionArray);
		for ($i = 0;$i < $arrayLen2;$i++) {
			if (trim($unionArray[$i]) == trim($libId)) return $rowl['m_id'];
		}
	}
}

function getBindedLibIds() {
	global $dsql;
	$libIds = "";
	$sqlStr = "select m_id,m_unionid from {pre}type where m_unionid<>''";
	$rows = db::select($sqlStr);
    foreach ($rows as $row) {
		$libIds .= $row['m_unionid'].',';
	}
	$libIds = rtrim($libIds, ',');
	return $libIds;
}

function gatherDay() {
	global $u,$ressite,$page;
	$weburl = $u."?action=day&ressite=".$ressite."&u=".urlencode($u)."&page=".$page;
	intoDatabase($weburl, "day");
}

function gatherType() {
	global $u,$ressite,$type,$page;
	$weburl = $u."?action=type&ressite=".$ressite."&u=".urlencode($u)."&type=".$type."&page=".$page;
	intoDatabase($weburl, "type");
}

function gather() {
	global $u,$ressite;
	$ids = RequestBox("m_id");
	if (empty($ids)) {alertMsg("请选择采集数据","");last();}
	$weburl = $u."?action=select&ressite=".$ressite."&u=".urlencode($u)."&m_id=".$ids;
	intoDatabase($weburl, "select");
}

function getrulevalue($content, $str) {
	if (!empty($content) && !empty($str)) {
		$labelRule = buildregx("<".$str.">(.*?)"."</".$str.">","is");
		preg_match_all($labelRule,$content,$ar);
		return empty($ar[1][0]) ? '' : $ar[1][0];
	}
}

function getrulevaluearr($content, $str) {
	if (!empty($content) && !empty($str)) {
		$labelRule = buildregx("<".$str.">(.*?)"."</".$str.">","is");
		preg_match_all($labelRule,$content,$ar);
		return $ar[1];
	}
}

function replaceCDATA($str) {
	return str_replace(']]>','',str_replace('<![CDATA[','',$str));
}

function lista() {
	global $u,$isref,$ressite,$page,$type,$keyword;
	$weburl = $u."?action=list&ressite=".$ressite."&u=".$u."&page=".$page."&keyword=".$keyword."&type=".$type."&bindtype=".getBindedLibIds();
	echo str_replace("?action=", "?ressite=".$ressite."&action=", cget($weburl,$isref));
}

function main() {
	global $reslibMainSite,$isref;
	echo cget($reslibMainSite. "resindex.html", $isref);
}

function top() {
?>
    <!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=gbk">
    <title>djcms资源库采集程序</title>
   <link rel="stylesheet" type="text/css" href="imgs/res.css"/>
     <script src="../js/common.js"></script>
    </head>
    <body bgcolor="#F7FBFF">
<?php
}

function bottom() {
?>
<div align=center>Copyright 2005-2009 All rights reserved. <a target="_blank" href="http://www.djcms.net">djcms2.0</a></div>
</body>
    </html> 
<?php
}
?>
