<?php
if(!empty($_GET['act']) && $_GET['act']=='savecfg'){
	$data['sites'] = str_replace(array("\r","\n"), array('', ','), trim( stripslashes($_POST['sites'])) );
	$data['key'] = stripslashes($_POST['key']);
	$data['api'] = stripslashes($_POST['api']);
	$data['pid'] = stripslashes($_POST['pid']);
	if(empty($data['sites']) || empty($data['key']) || empty($data['api'])){
		$errmsg = '配置选项填写有误';
		$_GET['act']='config';
	}else{
		if(empty($data['pid'])){
			$num = count(explode(',', $data['sites']));
			if($num>10){
				$errmsg = '你的授权尚未激活，只能添加10个网站';
				$_GET['act']='config';
			}
		}else{
			
			$curlPost = 'domain='.urlencode($data['sites']);
			$ch = curl_init();
			curl_setopt($ch,CURLOPT_URL,'http://openapi.dedeapps.com/index.php?m=dedelink&pid='.$data['pid']);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
			$con = curl_exec($ch);
			curl_close($ch);
			if($con=='-1'){
				$errmsg = '你的授权码有误';
				$_GET['act']='config';
			}elseif(stripos($con, 'false:')!==false){
				$con = str_replace('false:', '', $con);
				$dnns = explode(',', $data['sites']);
				$edn = isset($dnns[$con])?$dnns[$con]:'';
				if($edn){
					$errmsg = '网址'.$edn.'尚未获得授权';
					$_GET['act']='config';
				}else{
					$errmsg = '未知错误';
					$_GET['act']='config';
				}
			}elseif(!empty($con)){
				$errmsg = '系统错误';
				$_GET['act']='config';
			}
		}
		
		if(empty($errmsg)){
			$var = var_export($data, true);
			file_put_contents('dedelink.inc.php', "<"."?php return ".$var.";");
			header("Location: ?");exit;
		}

	}
}
if(is_file("dedelink.inc.php")){
	$cfg = require "dedelink.inc.php";
	if((empty($_GET['act']) || $_GET['act']=='config') && !isset($_COOKIE['dlpid'])){
		header("Location: ?act=pid");
		exit;
	}
	if(!empty($_GET['act']) && $_GET['act']=='checkpid'){
		$key = $_POST['key'];
		if($cfg['key']==$key){
			setcookie('dlpid', 1, time()+3600*12, '/');
			header("Location: ?");exit;
		}else{
			$errmsg = '无法通过验证，请重新输入';
			$_GET['act']='pid';
		}
	}
	if(empty($_GET['act'])){
		if(empty($cfg['pid'])){
			$num = count(explode(',', $cfg['sites']));
			if($num>10){
				$errmsg = '抱歉，暂时无法使用';
				$_GET['act']='config';
			}
		}else{
			$curlPost = 'domain='.urlencode($cfg['sites']);
			$ch = curl_init();
			curl_setopt($ch,CURLOPT_URL,'http://openapi.dedeapps.com/index.php?m=dedelink&pid='.$cfg['pid']);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
			$con = curl_exec($ch);
			curl_close($ch);
			if($con=='-1' || stripos($con, 'false:')!==false){
				$errmsg = '抱歉，暂时无法使用';
				$_GET['act']='config';
			}
		}
	}
}elseif(@$_GET['act']!='config'){
	header("Location: ?act=config");
	exit;
}else{
	$cfg['sites'] = $cfg['api'] = $cfg['key'] = $cfg['pid'] = "";
}
?><!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=utf-8" />
<title>友情链接管理系统 - 站群友情链接管理系统，友情链接平台</title>
<script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
var apiurl;
var sitearr;
var dl_zt = new Array('未审核','内页','首页');
var issear = false;
var slock = 0;
var sites = "<?php echo $cfg['sites'];?>";
var api = "<?php echo $cfg['api'];?>";
var key =  "<?php echo $cfg['key'];?>";

$(function(){
	$(".wrap").show();
	
	//网址下拉列表
	sitearr = sites.split(",");
	var option = "";
	$.each(sitearr, function(i, v){
		option = option + "<option name='"+v+"'>"+v+"</option>";
	})
	$("select[name=allsite]").html(option);
	
	//行为
	$("select[name=allsite]").change(function(){
		load_site_link(true);
	})
	load_site_link(true);

	$(document).on('change', '#ids', function(){
		$(".ids").prop("checked", $(this).prop("checked"));
	})
	
	setInterval(function(){
		if($(".list input:checked").length>0){
			$(".delbtn").show();
		}else{
			$(".delbtn").hide();
		}
	}, 500);
});

function formatDate(now){
	return new Date( parseInt(now)*1000 ).toLocaleDateString();
}

function load_site_link(){
	if(arguments.length==1 && arguments[0]==true){
		issear = false;
	}
	if(issear==true){
		search_func();
		return;
	}
	addr = $("select[name=allsite]").val();
	apiurl = addr + "/" + api;
	post_to_api("ac=list", function(rs){
		liststr = '<tr>\
        	<th><label><input name="ids" id="ids" type="checkbox" value="1" /> 全选</label></th><th>网站名称</th><th>网址</th><th>分类</th><th>时间</th><th>链接位置</th><th>排列位置</th><th>管理</th>\
		</tr>';
		$.each(rs, function(i, r){
			liststr = liststr + "<tr><td align=center><input name=\""+addr+"\" type=\"checkbox\" value=\""+r.id.toString()+"\" class=\"ids\" /></td><td><a href='" + r.url + "' target='_blank'>" + r.webname + "</a></td><td><a href='" + r.url + "' target='_blank'>" + r.url + "</a></td><td>" + r.typename + "</td><td>" + formatDate(r.dtime) + "</td><td>" + dl_zt[r.ischeck] + "</td><td>" + r.sortrank + "</td><td><a href=\"javascript:edit_link("+r.id.toString()+");\">[更改]</a> <a href=\"javascript:del_link("+r.id.toString()+");\">[删除]</a></td></tr>";
		})
		$(".databox .qh").hide();
		$(".list table").html(liststr);
		$(".list").show();
	});
	$(".viewdata").attr("href", "http://check.links.cn/checklink.asp?checkbaiducount=1&checkbaidurank=1&checkpr=1&checkbacklink=1&checkbaiducachetime=1&weburl="+addr);
}

function post_to_api(data, callback, turl){
	$("#loading").show();
	if(typeof arguments[2] == "undefined"){
		surl = apiurl + "?" + data + "&sid=" + key + "&t="+Math.random()+"&jsoncallback=?";
	}else{
		surl = turl + "/" + api + "?" + data + "&sid=" + key + "&t="+Math.random()+"&jsoncallback=?";
	}
	$.getJSON(surl, function(r){
		if(r.status==0){
			switch(r.data){
				case "-1":
					alert("通信密钥不一致，通信不成功！");
				break;
			}
		}else if(r.status<0){
			callback( r.status );
		}else{
			callback( r.data );
		}
		$("#loading").hide();
	});
}

function edit_link(id){
	if(arguments.length==2){
		turl = arguments[1];
	}else{
		turl = addr;
	}
	post_to_api("ac=edit&id="+id, function(rs){
		str = '<tr><td width=65></td><td><input name="id" type="hidden" value="'+rs.flink.id+'" /></td><td>';
		str += '<tr><td width=65>网址：</td><td><input name="url" type="text" value="'+rs.flink.url+'" style="width:300px;" /></td><td>';
		str += '<tr><td width=65>排列位置：</td><td><input name="sortrank" type="text" value="'+rs.flink.sortrank+'" /></td><td>';
		str += '<tr><td width=65>网站名称：</td><td><input name="webname" type="text" value="'+rs.flink.webname+'" style="width:300px;" /></td><td>';
		str += '<tr><td width=65>网站简况：</td><td><textarea name="msg" style="width:300px;height:80px;">'+rs.flink.msg+'</textarea></td><td>';
		str += '<tr><td width=65>站长Email：</td><td><input name="email" type="text" value="'+rs.flink.email+'"  style="width:300px;"/></td><td>';
		str += '<tr><td width=65>链接位置：</td><td>';
		for(i=0; i<3; i++){
			ischeck = rs.flink.ischeck==i?" checked":"";
			str += '  <input type="radio" name="ischeck" value="' + i.toString() + '" ' + ischeck + '/>' + dl_zt[i];
		}
		str += '</td><td>';
		str += '<tr><td width=65>网站类型：</td><td><select name="typeid">';
		$.each(rs.flinktype, function(i, r){
			if(r.id==rs.flink.typeid){
				str += '<option value="' + r.id + '" selected>' + r.typename + '</option>';
			}else{
				str += '<option value="' + r.id + '">' + r.typename + '</option>';
			}
		});
		str += '</select></td><td>';
		str += '<tr><td colspan="2"><input class="btn tbg" onclick="edit_link_save(\''+turl+'\');" type="button" value="提交" /> <input class="btn tbg" onclick="load_site_link()" type="button" value="返回列表" /></td><td>';
		$(".databox .qh").hide();
		$(".edit table").html(str);
		$(".edit").show();
	}, turl);
}

function edit_link_save(turl){
	data = $(".editform").serialize();
	post_to_api("ac=edit&dopost=1&"+data, function(rs){
		load_site_link();
	}, turl);
}

function del_link(id){
	if(!confirm("?")) return;
	if(arguments.length==2){
		post_to_api("ac=del&id="+id, function(rs){
			search_func();
		}, arguments[1]);
	}else{
		post_to_api("ac=del&id="+id, function(rs){
			load_site_link();
		});
	}
}

function add_link(){
	addr = $("select[name=allsite]").val();
	post_to_api("ac=add", function(rs){
		str = '<tr><td width=65><b>添加至</b></td><td>';
		str += ' <label><input type="radio" name="zd" value="'+addr+'" onclick="sel_zd(1)" checked/>'+addr+'</label> <label><input type="radio" name="zd" value="2" onclick="sel_zd(2)"/>全部站点</label> <label><input type="radio" name="zd" value="3" onclick="sel_zd(3)"/>选择站点</label> ';
		str += '</td><td>';
		str += '<tr><td width=65></td><td><div class="ps cl"><ul>';
		var ps = "";
		$.each(sitearr, function(i, v){
			str += '<li><label><input name="ps[]" type="checkbox" value="' + v + '" />' + v.replace("http://", "") + "</label></li>";
		});
		str += '</ul></div></td><td>';
		str += '<tr><td width=65>网址：</td><td><input name="url" type="text" value="http://" style="width:300px;" /></td><td>';
		str += '<tr><td width=65>网站名称：</td><td><input name="webname" type="text" value="" style="width:300px;" /></td><td>';
		str += '<tr><td width=65>排列位置：</td><td><input name="sortrank" type="text" value="1" /></td><td>';
		str += '<tr><td width=65>网站简况：</td><td><textarea name="msg" style="width:300px;height:80px;"></textarea></td><td>';
		str += '<tr><td width=65>站长Email：</td><td><input name="email" type="text" value=""  style="width:300px;"/></td><td>';
		str += '<tr><td width=65>链接位置：</td><td>';
		str += '  <input type="radio" name="ischeck" value="1"/>' + dl_zt[1]+'  <input type="radio" name="ischeck" value="2" checked/>' + dl_zt[2];
		str += '</td><td>';
		str += '<tr class="typetr"><td width=65>网站类型：</td><td><select name="typeid">';
		$.each(rs, function(i, r){
			str += '<option value="' + r.id + '">' + r.typename + '</option>';
		});
		str += '</select></td><td>';
		str += '<tr><td colspan="2"><input class="btn tbg" onclick="add_link_save();" type="button" value="提交" /> <input class="btn tbg" onclick="load_site_link()" type="button" value="返回列表" /></td><td>';
		$(".databox .qh").hide();
		$(".add table").html(str);
		$(".add").show();
	});
}

function add_link_save(){
	str  = $(".addform").serialize();
	zd = $("input[name=zd]:checked").val();
	if(zd==3){
		var chk_value =[];
		$('input[name="ps\[\]"]:checked').each(function(){
			chk_value.push($(this).val());
		});
		if(chk_value.length==0){
			alert("请选择站点");
			return ;
		}
		link_save_all(chk_value, str);
	}else if(zd==2){
		link_save_all(sitearr, str);
	}else{
		post_to_api("ac=add&dopost=1&i=-1&"+str, function(rs){
			if(rs.status==-1){
				alert("链接已存在");
				$("input[name=url]").focus();
			}else{
				load_site_link();
			}
		});
	}
}

function link_save_all(arr, data){
	str = '<tr>\
        	<th>编号</th><th>站点</th><th>状态</th>\
		</tr>';
	num = arr.length;
	$.each(arr, function(i, r){
		str += "<tr><td>" + i + "</td><td>" + r + "</td><td id='" + i + "'><font color=green>发送中</font></td>";
		post_to_api("ac=add&dopost=1&i=" + i + "&" + data, function(rs){
			if(rs.status==1){
				$("#"+rs.id.toString()).html("成功");
				num--;
				if(num==0){
					alert("全部添加完成");
					load_site_link();
				}
			}else{
				$("#"+rs.id.toString()).html("<font color=red>已存在</font>");
			}
		}, r);
	})
	$(".databox .qh").hide();
	$(".list table").html(str);
	$(".list").show();
}

function sel_zd(i){
	if(i==3){
		$(".ps").show();
		$(".typetr").hide();
	}else if(i==2){
		$(".ps").hide();
		$(".typetr").hide();
	}else{
		$(".ps").hide();
		$(".typetr").show();
	}
}

function search_func(){
	issear = true;
	val = $("input[name=search]").val();
	if(val=='输入关键词搜索管理'){
		//alert('请输入搜索词');
		//return;
		val = "";
	}
	if(slock>0){
		return;
	}
	$(".databox .qh").hide();
	$(".list table").html('<tr>\
				<th><label><input name="ids" id="ids" type="checkbox" value="1" /> 全选</label></th><th>网站名称</th><th>网址</th><th>分类</th><th>时间</th><th>链接位置</th><th>排列位置</th><th>管理</th>\
			</tr>');
	$(".list").show();
	
	$.each(sitearr, function(i, s){
		slock++;
		post_to_api("ac=list&kw="+val, function(rs){
			slock--;
			$.each(rs, function(i, r){
				$(".list table").append( "<tr><td align=center><input name=\""+s+"\" type=\"checkbox\" value=\""+r.id.toString()+"\" class=\"ids\" /></td><td>" + r.webname + "</td><td>" + r.url + "</td><td>" + r.typename + "(" + s + ")</td><td>" + formatDate(r.dtime) + "</td><td>" + dl_zt[r.ischeck] + "</td><td>" + r.sortrank + "</td><td><a href=\"javascript:edit_link("+r.id.toString()+",'"+ s +"');\">[更改]</a> <a href=\"javascript:del_link("+r.id.toString()+",'"+ s +"');\">[删除]</a></td></tr>" );
			})
		}, s);
	});
	setTimeout(function(){
		slock = 0;
	},3500)
}

function del_func(){
	darr = new Array();
	$(".ids:checked").each(function(i){
		dname = $(this).prop("name");
		dval = $(this).val();
		if(typeof darr[dname] == "undefined"){
			var list = [];
			list.push(dval);
			darr[dname] = list;
		}else{
			darr[dname].push(dval);
		}
	})
	var i = 0;
	for(var x in darr){
		i++;
		sx = darr[x].join(',');
		post_to_api("ac=del&id="+sx, function(rs){
			i--;
			if(i==0) load_site_link();
		}, x);
	}
}

</script>
<style type="text/css">
body, h1, h2, h3, h4, h5, h6, hr, p, blockquote, dl, dt, dd, ul, ol, li, pre, form, fieldset, legend, button, input, textarea { margin:0; padding:0; }
body, button, input, select, textarea { font:12px/1.5 tahoma, arial, \5b8b\4f53, sans-serif; vertical-align: middle; }
ul, ol { list-style:none; }
a { text-decoration:none; color:#333; }
a:hover { text-decoration:underline; color:#F60; }
fieldset, img { border:0; }
button, input, select, textarea { font-size:100%; outline:none; resize:none; }
* { -webkit-text-size-adjust:none; }
.cl:after, .clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
.cl, .clearfix { zoom: 1; }
.clear { line-height: 0px; clear: both; height: 0px; font-size:0px; }
.fl { float:left; }
.fr { float:right; }
.wrap { padding:0px; }
.noscript { border:solid 1px #F60; padding:8px; width:100%; text-align:center; background-color:#F90; color:#FFF; font-weight:bold; margin-top:50px; position:fixed; bottom:50px; }
#loading { color:red; }
.allsite{ padding:10px; margin:0 0 20px; }
.allsite a{ color:#FFF; }
.list table { background-color:#CCC; }
.list table td, .list table th { background-color:#FFF; }
.ft{ font-size:12px; padding:10px 0; font-weight:bold; margin-top:20px; }
.ft a{ padding:8px; }
.tbg { background-color: #006dcc; color:#FFF; }
.btn{ padding:2px 7px; border:0; cursor:pointer; }
.edit,.add{ padding:0 10px; }
.addlink{ padding:5px 0 15px;}
.addlink a.tbg,.databox a.tbg,.viewdata{ padding:3px 5px; background:url(http://www.dedeapps.com/linkerbg.jpg) repeat-x; }
.ps{ border:solid 1px #CCC; padding:3px; display:none; }
.ps li{ width:19.99%; float:left; overflow:hidden; }
.delbtn{ display:none; }
</style>
</head>
<?php
if(!empty($_GET['act']) && $_GET['act']=='pid'){
?>
<body style="background-color:#999;">
<div style="width:400px; border:solid 2px #CCC; background-color:#FFF; margin:100px auto; padding:18px; border-radius:8px;">
<div class="title" style="font-size:16px; font-family:'Microsoft Yahei'; font-weight:bold;">验证登录信息</div>
<div style="font-size:12px; font-family:'Microsoft Yahei'; color:#999">请填写接口通信密钥，以便验证您的权限(24小时有效)</div>
<form method="post" action="?act=checkpid">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
	<tr height="35">
		<td>接口通信密钥：</td>
		<td><input name="key" type="text" value=""  style="width:280px;"/></td>
	</tr>
	<tr height="35">
		<td></td>
		<td><input name="sub" type="submit" value="验证" class="tbg" style="width:60px;"/></td>
	</tr>
		<tr height="35">
		<td></td>
		<td>开发：<a href="http://www.dedeadmin.com" target="_blank">织梦管理员之家</a> &nbsp;&nbsp;&nbsp; 客服经理QQ：<a href="http://wpa.qq.com/msgrd?v=3&amp;uin=79702151&amp;site=qq&amp;menu=yes" target="_blank">79702151</a></td>
	</tr>
</table>
</form>
</div>
<?php
}elseif(!empty($_GET['act']) && $_GET['act']=='config'){
?>
<body style="background-color:#999;">
<div style="width:400px; border:solid 2px #CCC; background-color:#FFF; margin:100px auto; padding:18px; border-radius:8px;">
<div class="title" style="font-size:16px; font-family:'Microsoft Yahei'; font-weight:bold;">配置站群信息</div>
<div style="font-size:12px; font-family:'Microsoft Yahei'; color:#999">请务必填写正确，配置错误将导致功能无法使用</div>
<form method="post" action="?act=savecfg">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
	<tr height="35">
		<td width="100">Api接口文件名：</td>
		<td><input name="api" type="text" value="<?php echo $cfg['api'];?>"  style="width:280px;"/></td>
	</tr>
	<tr height="35">
		<td>接口通信密钥：</td>
		<td><input name="key" type="text" value="<?php echo $cfg['key'];?>"  style="width:280px;"/></td>
	</tr>
	<tr height="35">
		<td>站群网址列表：<br>每行一个<br />未授权限添加10个<br />如：<br />http://abc.com</td>
		<td><textarea name="sites" style="width:280px; height:150px;"><?php echo str_replace(",","\r\n",$cfg['sites']);?></textarea></td>
	</tr>
	<tr height="35">
		<td>授权序列号：</td>
		<td><input name="pid" type="text" value="<?php echo $cfg['pid'];?>"  style="width:280px;"/></td>
	</tr>
	<tr height="35">
		<td></td>
		<td><input name="sub" type="submit" value="保存" class="tbg" style="width:60px;"/></td>
	</tr>
		<tr height="35">
		<td></td>
		<td>开发：<a href="http://www.dedeadmin.com" target="_blank">织梦管理员之家</a> &nbsp;&nbsp;&nbsp; 客服经理QQ：<a href="http://wpa.qq.com/msgrd?v=3&amp;uin=79702151&amp;site=qq&amp;menu=yes" target="_blank">79702151</a></td>
	</tr>
</table>
</form>
</div>
<?php
}else{
?>
<body>
<noscript>
<div class="noscript">本页面需要运行script脚本支持，您的浏览器限制了本地脚本运行，请点击浏览器阻止栏上的允许按钮继续操作</div>
</noscript>
<div class="wrap" style="display:none;">
	<div class="allsite tbg">
		选择站点：<select name="allsite">
		</select>
		<span><a href="###" onclick="load_site_link(true);">刷新</a> <a href="?act=config">配置站点</a></span> <span id="loading"> 正在加载中</span> 
	</div>
	<div class="addlink">
		<span style="float:right;">
		<input name="search" type="text" style="height:20px; line-height:20px; border:solid 1px #CCC; color:#CCC; padding:0 5px;" value="输入关键词搜索管理" onclick="if(this.value=='输入关键词搜索管理') this.value='';"  onblur="if(this.value=='') this.value='输入关键词搜索管理';"/>
		<a class="tbg" href="###" onclick="search_func();">一键搜索</a>
		</span>
		<a class="tbg" href="###" onclick="add_link();">添加链接</a>
	</div>
	<div class="databox">
		<div class="qh list">
			<table width="100%" border="0" cellpadding="3" cellspacing="1">
			</table>
			<a class="tbg delbtn" href="###" onclick="del_func();">删除选中</a>
		</div>
		<div class="qh edit">
		<form method="post" class="editform">
			<table width="100%" border="0" cellpadding="3" cellspacing="1">
			</table>
		</form>
		</div>
		<div class="qh add">
		<form method="post" class="addform">
			<table width="100%" border="0" cellpadding="3" cellspacing="1">
			</table>
		</form>
		</div>
	</div>
	<div class="ft"><a class="tbg viewdata" href="###" target="_blank">查看数据</a></div>
</div>
<?php
}
if(!empty($errmsg)){
	echo "<script>alert('{$errmsg}');</script>";
}
?>
<script type="text/javascript" src="http://js.tongji.linezing.com/3320517/tongji.js"></script>
</body>
</html>
