<!--#include file="admin_conn.asp"-->
<%
chkLogin
dim action,status,wjs
action = be("get","action")
wjs = be("get","url")

Server.ScriptTimeOut = 9999999
select case action
	case "downpic" : downpic
	case "syncpic" : headAdmin "视频远程图片同步" : syncpic
	case "syncartpic" : headAdmin "文章远程图片同步" : syncartpic
	case "del" : del
	case "picchk","picchkedit" : picchkedit
	case else : headAdmin "图片管理" : pic
end select
dispseObj()

sub del
	dim fn,fnames,fnamesarr,MyFile,x
    fnames = be("post","fname")
    fnamesarr = split(fnames,",")
    set MyFile=Server.CreateObject("Scripting.FileSystemObject")
	for x=0 to ubound(fnamesarr)
		fn = fnamesarr(x)
		if left(fn,9) <> "../upload" or ubound( split(fn,"../") ) > 1 then
			
		else
    		fn = Server.Mappath(fn)
			if MyFile.FileExists(fn) then MyFile.DeleteFile(fn)
		end if
    next
    set MyFile=nothing
    writeA "删除记录成功!"
end sub

sub downpic()
	dim path,url
	path = be("get","path")
	url = be("get","url")
	savepic url,path
end sub

sub syncpic()
	dim j,page,rs,pagecount,d_pic,ranNum,extName,picname,picpath,sql,flag,pic_fw,pic_fwdate,pic_xx
	
	pic_fw = be("all","pic_fw") : pic_fwdate = be("all","pic_fwdate")
	pic_xx = be("all","pic_xx")
	
	flag = "#err" & getDate("yy-mm-dd",now)
	sql = "SELECT d_id,d_pic FROM {pre}vod WHERE d_pic LIKE 'http://%' "
	
	if pic_fw="2" and pic_fwdate<>"" then
		sql = sql & " AND year(d_time)="&Year(pic_fwdate)&" AND month(d_time)="&month(pic_fwdate)&" AND day(d_time)="&day(pic_fwdate)
	end if
	
	if pic_xx="1" then
		if app_dbtype="mssql" then
			sql = sql & " and charindex('#err',d_pic)=0 "
		else
			sql = sql & " and instr(d_pic,'#err')=0 "
		end if
	elseif pic_xx="2" then
		if app_dbtype="mssql" then
			sql = sql & " and charindex('"&flag&"',d_pic)=0 "
		else
			sql = sql & " and instr(d_pic,'"&flag&"')=0 "
		end if
	elseif pic_xx="3" then
		if app_dbtype="mssql" then
			sql = sql & " and charindex('#err',d_pic)>0 "
		else
			sql = sql & " and instr(d_pic,'#err')>0 "
		end if
	end if
	set rs = objdb.DB(sql,"rs3")
	
	if rs.eof and rs.bof then
		writeE "<script>alert('恭喜，所有外部图片已经成功同步到本地！');location.href='admin_vod.asp';</script>"
	else
		page = be("get","page") : if isN(page) then page=1 else page=cint(page)
		rs.PageSize = 20 : rs.AbsolutePage = rs.pagecount
		writeA "<font color=red>同步失败的图片不再把图片地址设置为空，只能隔天后再同步！<br>共"&rs.recordcount &"条数据需要同步下载，每次同步20个数据,正在开始同步第"& rs.pagecount &"页数据的的图片</font><br>"
		
		for j=1 to rs.pagesize
			if rs.eof then exit for
			d_pic = rs("d_pic")
			if instr(d_pic,"#err") >0 then
				d_pic = split(d_pic,"#err")(0)
			end if
			status = false
			
			randomize
			ranNum=int(90000*rnd)+10000
			picname=year(now)&month(now)&day(now)&hour(now)&minute(now)&second(now)&ranNum
			extName = right(d_pic,4)
			
			if instr(","&extName,".") =0 then  extName = ".jpg"
			picpath = "../upload/vod" & "/" & getSavePicPath() & "/" & picname & extName
			picpath = replaceStr(picpath,"///","/")
			picpath = replaceStr(picpath,"//","/")
			objFile.createFilePath picpath
			
			savepic d_pic,picpath
			if status then
				rs("d_pic") = replaceStr(picpath,"../","")
			else
				rs("d_pic") = d_pic & flag
			end if
			rs.update
			rs.movenext
		next
		writeA "<br><font color=red>暂停5秒后继续同步远程图片</font><br><script>setTimeout(""updatenext();"",5000);function updatenext(){location.href='admin_pic.asp?action=syncpic&page="&page + 1&"&pic_fw="&pic_fw&"&pic_fwdate="&pic_fwdate&"&pic_xx="&pic_xx&"';}</script>"
	end if
	objdb.c(rs)
end sub

sub syncartpic()
	dim j,page,rs,pagecount,a_pic,a_content,ranNum,extName,picname,picpath,ids,sql,des
	
	ids = be ("get", "ids")
	sql = "SELECT a_id,a_content FROM {pre}art WHERE a_content LIKE '%src=""http://%'"
	if not isN(ids) then 
		sql = sql & " and a_id not in ("& ids &") "
	else
		ids="0"
	end if
	
	set rs = objdb.DB(sql,"rs3")
	if rs.eof and rs.bof then
		if ids <>"0" then 
			des= "以下文章ID:"& right(ids,len(ids)-2) &"的图片同步失败，请检查图片链接是否失效"
		else
			des = "恭喜，所有外部图片已经成功同步到本地！"
		end if
		writeE "<script>alert('"&des&"');location.href='admin_art.asp';</script>"
	else
		page = be("get","page") : if isN(page) then page=1 else page=cint(page)
		rs.PageSize = 20 : rs.AbsolutePage = rs.pagecount
		writeA "<font color=red>共"&rs.recordcount &"条数据需要同步下载，每次同步20个条数据,正在开始同步第"& rs.pagecount &"页数据的的图片</font><br>"
		
		dim Reg,match,matches
		
		for j=1 to rs.pagesize
			if rs.eof then exit for
			a_content = rs("a_content")
			
			set Reg = New Regexp
			Reg.Global = True
			Reg.Ignorecase = True
			Reg.Pattern = "<img[^>]*src\s*=\s*['"&CHR(34)&"]?([\w/\-\:.]*)['"&CHR(34)&"]?[^>]*>"
			If Reg.test(a_content) Then
				Set matches = Reg.Execute(a_content)
				For Each Match in Matches
		        	'writee  Match.Value & "<br />"  & Match.SubMatches(0)
		        	a_pic = Match.SubMatches(0)
		        	randomize
					ranNum=int(90000*rnd)+10000
					picname=year(now)&month(now)&day(now)&hour(now)&minute(now)&second(now)&ranNum
					extName = right(a_pic,4)
					if instr(","&extName,".") =0 then  extName = ".jpg"
					picpath = "../upload/art" & "/" & getSavePicPath() & "/" & picname & extName
					picpath = replaceStr(picpath,"///","/")
					picpath = replaceStr(picpath,"//","/")
					objFile.createFilePath picpath
					
					savepic a_pic,picpath
					if status then
						a_content = replaceStr(a_content,a_pic,picpath)
					else
						a_content = replaceStr(a_content,a_pic,"")
					end if
		        Next
			end if
			rs("a_content") = a_content
			rs.update
			rs.movenext
		next
		set Match=nothing
		set matches=nothing
		set Reg=nothing
		writeA "<br><font color=red>暂停5秒后继续同步文章远程图片</font><br><script>setTimeout(""updatenext();"",5000);function updatenext(){location.href='admin_pic.asp?action=syncartpic&page="&page + 1&"&ids="&ids&"';}</script>"
	end if
	objdb.c(rs)
end sub

sub savepic(picUrl,picpath)
	dim imgsbyte,imgtext,imgsize
	imgsbyte= getImg(picUrl)
	imgtext= ","&bytesToBstr(imgsbyte,"gbk")
	imgsize= formatnumber(len(imgsbyte)/1024*2,2)
	
	if len(imgsbyte)<100 or  instr(imgtext,"<html") >0 or  instr(imgtext,"<HTML") >0 then
		writeF "保存失败：<font color=red>非正常的图片文件，请编辑数据复制图片地址在浏览器中访问测试下是否正常</font>图片地址是:<a target=_blank href="&picUrl&" >"&picUrl&"<a><br>"
		status=false
	else
		objFile.createBinaryFile picpath,imgsbyte
		if app_watermark =1 then 
			call ImgWriter(picpath)
		end if
		writeF "<a target=_blank href="&picpath&">"&picpath&"</a>保存成功：<font color=red>"&imgsize&"Kb</font><br>"
		status=true
	end if
	if not isN(wjs) then writeE "<script>parent.dstate=true;</script>"
end sub

sub pic
	dim rootPath : rootPath = be("get","rootPath")
%>
<script type="text/javascript">
	$(document).ready(function(){
		$("#btnDel").click(function(){
			if(confirm('确定要删除吗')){
				$("#form1").attr("action","?action=del");
				$("#form1").submit();
			}
			else{return false}
		});
		$("#btnChk").click(function(){
			if(confirm('确定要清理垃圾图片吗?')){
				location.href= "?action=picchk";
			}
			else{return false}
		});
		$('#form1').form({
		onSubmit:function(){
			if(!$("#form1").valid()) {return false;}
		},
	    success:function(data){
	        $.messager.alert('系统提示', data, 'info',function(){
	        	location.href=location.href;
	        });
	    }
		});
	});
</script>
</head>
<body>
<form action="?action=del" method="post" id="form1" name="form1"> 
<table class="tb">
	<tr>
	<td><strong>文件名</strong></td>
    <td width="10%"><strong>文件大小</strong></td>
    <td width="20%"><strong>修改时间</strong></td>
    <td width="15%"><strong>操作</strong>  </td>
	</tr>
<%
if rootPath = "" then rootPath = "../upload"
call bianliFolder(rootPath)
%>
<tr><td colspan=4>
<input type="checkbox" name="chkall" onClick="checkAll(this.checked,'fname')"/>全选
<input name=button type=submit class=input value=删除 id=btnDel>
<input name=button type=button class=input value=清理垃圾图片 id=btnChk>
</td>
</tr>
</table>
</form>
</body>
</html>
<%
end sub

function bianliFolder(currentPath)
	Dim nowpath,path,upperFolder,objFolder,objSubFolders,nextPath,fso,objSubFolder,filters
	
	if left(currentPath,9) <> "../upload" then currentPath = "../upload"
	upperFolder = left(currentPath,(InStrRev(currentPath,"/")-1))
	if  ubound( split(currentPath,"../") ) > 1 then 
		writeA "<tr><td colspan=""5""> 非法的目录请求 </td></tr>"
		exit function 
	end if
	
	if currentPath <> "../upload" then
		writeA "<tr><td colspan=""5""><img src=""../images/icons/dir2.gif""> <a href=""?rootPath=" &upperFolder&""">上级目录</a></td></tr>"
	end if
	filters = ",,cache,artcollect,downdata,playdata,export,vodcollect,"
	path = server.mapPath(currentPath)
	set fso = server.CreateObject("scripting.filesystemobject")
    set objFolder=fso.GetFolder(path)
    
    set objSubFolders=objFolder.Subfolders
    for each objSubFolder in objSubFolders 
        nowpath=objSubFolder.name
        if instr(filters, ","&nowpath&",") <=0 then 
        	nextPath = currentPath & "/" & objSubFolder.name
			writeA "<tr><td colspan=""5""><img src=""../images/icons/dir.gif""> <a href=""?rootPath="&nextPath&""">"&nowpath&"</a></td></tr>"
		end if
    next
    set objFolder=nothing
    set objSubFolders=nothing
    set fso = nothing
    
    Call bianliFile(currentPath)
end function
	
function bianliFile(currentPath)
	Dim Path,fso,objFolder,nowpath,objFiles,objFile,FileExt,objSubFolders,num,sumsize
    path = server.mapPath(currentPath) :num = 0 : sumsize = 0
    set fso=server.CreateObject("scripting.filesystemobject")
    set objFolder=fso.GetFolder(path)
    set objFiles=objFolder.Files
    for each objFile in objFiles
    	if instr(objFile.name,".html") <=0 and instr(objFile.name,".htm") <=0 then
			num = num + 1
			sumsize = sumsize + objFile.size
			writeA "<tr><td><img src=""../images/icons/asp.gif""> "&objFile.name&"</td><td>"&round(objFile.size/1024,3)&" KB</td><td >"&objFile.DateLastModified&"</td><td><a href="""&currentPath&"\"&objFile.name&""" target=""_blank"">浏览</a> &nbsp;<input type=""checkbox"" id=fname name=fname value="""&currentPath&"/"&objFile.name&"""></td></tr>"
		end if
     next
		writeA "<tr><td colspan=""4"">本目录下共有<font color=red><b>"&num&"</b></font>个文件; 占用<font color=red><b>"&sumsize&"</b></font><font color=#FF0000><b>K</b></font>空间&nbsp;&nbsp;&nbsp;&nbsp;<input type=hidden value=del Name=result></td></tr>"
    set objFolder=nothing
    set objSubFolders=nothing
    set fso = nothing
end function

sub picchkedit
	ListFolderContents Server.mappath("../upload/vod/")
	writeA "清理完毕"
end sub

sub ListFolderContents(path)
	dim fs,folder,Item,url,urll,fstream,tempurl,rs
	set fs = CreateObject("Scripting.FileSystemObject")
	set folder = fs.GetFolder(path)
	writeA "<b>&nbsp;<font color='#ff0000'>" & folder.Name & " >> 共&nbsp;" & folder.Files.Count & " 个文件 >> 大小:"
	if folder.SubFolders.Count > 0 then writeA folder.SubFolders.Count & " 文件夹, "
    writeF Round(folder.Size / 1024) & " KB </b></font><br>" 
	
	for each item in folder.SubFolders
	  ListFolderContents(item.Path)
	next
	
	for each item in folder.Files
		url = MapURL(item.path)
		if app_installdir <> "/" then tempurl = Replace(url,app_installdir, "")	else tempurl = Right(url, Len(url)-1)
		fstream = (instr(objFile.getfile(url),"server")>0 or instr(objFile.getfile(url),"file")>0)
		if fstream then
			writeA "&nbsp;<a href="""&url&""" target=_blank>"&item.Name&"</a> - " & item.Size & " 字节,修改时间 " & item.DateLastModified & " - <font color=blue>该文件为非正常图片数据，已经删除</font><br>"
			objFile.DelFile url
		else
			set rs = objdb.db("select * from {pre}vod where d_pic like '%" & tempurl &"%' or d_picthumb like '%" & tempurl &"%' or d_picslide like '%" & tempurl &"%' ","rs1")
			if rs.eof then
			writeA "&nbsp;<a href="""&url&""" target=_blank>"&item.Name&"</a> - " & item.Size & " 字节,修改时间 " & item.DateLastModified & " - <font color=red>数据库中不存在，已经删除</font><br>"
			objFile.DelFile url
			end if
			objdb.C(rs)
		end if
		writeF ""
	next
	writeF ""
   set fs = nothing
   set folder = nothing
end sub

function MapURL(path)
	dim rootPath,url
	rootPath = Server.MapPath("/")
	url = Right(path, Len(path) - Len(rootPath))
	MapURL = Replace(url, "\", "/")
end function 
%>