<?php
//΄ϊΑμΜα½»
require 'common.php';

$url=daddslashes($_GET['url']);
$key=daddslashes($_GET['key']);

if(!empty($url) && !empty($key)){
	$kmrow=$DB->get_row("SELECT * FROM qiu_kms WHERE km='$key' and kind=1 limit 1");
	if(!$kmrow['id'])
		exit('{"code":-9}');
	if($kmrow['isuse']==1)
		exit('{"code":-4}');

	$data = get_curl($url,0,0,0,1);
	preg_match("/Location: (.*?)\r\n/iU", $data, $urls);
	if(!$urls[1]) $long_url=$url;else $long_url=$urls[1];
	if(strpos($long_url,'www.battleofballs.com')===false){
		exit('{"code":-3}');
	}
	$refer = str_replace("?","/index_mobile_share.html?",$long_url);
	$account = explode('Account=',$refer);
	$account = urldecode($account[1]);
	$id = intval(trim(getSubstr($refer,"id=","&A")));

	$row=$DB->get_row("SELECT * FROM qiu_job WHERE id='$id' limit 1");
	if($row){
		if($row['endtime']>$date)
			$endtime=date("Y-m-d H:i:s", strtotime("+ {$kmrow['value']} days", strtotime($row['endtime'])));
		else
			$endtime=date("Y-m-d H:i:s", strtotime("+ {$kmrow['value']} days"));
		if(!$DB->query("update qiu_kms set isuse='1',user='$id',usetime='$date' where id='{$kmrow['id']}'"))exit('{"code":-5}');
		if(!$DB->query("update qiu_job set endtime='$endtime' where jobid='{$row['jobid']}'"))exit('{"code":-6}');
		exit('{"id":"'.$id.'","account":"'.$account.'","keyday":"'.$kmrow['value'].'","oldendtime":"'.$row['endtime'].'","newendtime":"'.$endtime.'","code":1}');
	}else{
		$endtime=date("Y-m-d H:i:s", strtotime("+ {$kmrow['value']} days"));
		if(!$DB->query("update qiu_kms set isuse='1',user='$id',usetime='$date' where id='{$kmrow['id']}'"))exit('{"code":-5}');
		if(!$DB->query("insert into `qiu_job` (`id`,`addtime`,`endtime`) values ('".$id."','".$date."','".$endtime."')"))exit('{"code":-8}');
		exit('{"id":"'.$id.'","account":"'.$account.'","keyday":"'.$kmrow['value'].'","endtime":"'.$endtime.'","code":0}');
	}
}else{
	exit('{"code":-2}');
}