<?php
require 'conn/conn.php';
require 'conn/function.php';

$url=$_POST["url"];
$url=urldecode($url);

if($_SESSION["ym"]==""){
	die("{\"code\":\"error\",\"msg\":\"请勿跨站！\",\"long\":\"".$url."\"}");
}

if(CheckUrl($url)){
	$url=urlencode($url);
	$sql="select * from sl_short where S_url='".$url."'";
			$result = mysqli_query($conn, $sql);
			$row = mysqli_fetch_assoc($result);
			if (mysqli_num_rows($result) > 0) {
				$S_id=$row["S_id"];
				$S_vip=$row["S_vip"];
				$S_short=$row["S_short"];
			}else{
				if($C_day==0){
					$S_vip=1;
				}else{
					$S_vip=0;
				}

				mysqli_query($conn,"insert into sl_short(S_url,S_time,S_vip) values('".$url."','".date('Y-m-d H:i:s')."',".$S_vip.")");
				$S_id=getrs("select * from sl_short where S_url='".$url."'","S_id");

				if(getrs("select count(D_id) as D_count from sl_domain","D_count")>0){
					$D_domain=getrs("select D_domain from sl_domain order by rand()","D_domain");
					$D_http=getrs("select D_http from sl_domain order by rand()","D_http");
					$short=$D_http.$D_domain."/s?".dec62($S_id);
				}else{
					$short=gethttp().$_SERVER["HTTP_HOST"]."/s?".dec62($S_id);
				}
				
				$info=getbody("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$C_wxid."&secret=".$C_wxkey,"");
				$access_token=json_decode($info)->access_token;
				$info=getbody("https://api.weixin.qq.com/cgi-bin/shorturl?access_token=".$access_token,"{\"action\":\"long2short\",\"long_url\":\"".$short."\"}");
				$short_url=json_decode($info)->short_url;

				if($short_url==""){
					$S_short=$short;
				}else{
					$S_short=$short_url;
				}
				mysqli_query($conn,"update sl_short set S_short='$S_short' where S_id=".$S_id);
			}
	
	echo "{\"code\":\"success\",\"id\":\"".$S_id."\",\"vip\":\"".$S_vip."\",\"short\":\"".$S_short."\",\"long\":\"".urldecode($url)."\"}";
}else{
	echo "{\"code\":\"error\",\"msg\":\"网址格式不正确！\",\"long\":\"".$url."\"}";
}
?>