<?php
$fileman->checkPerms("weblink");
$locale->setSection("Web Links");

$linkId = $str->fromHTML($_REQUEST['linkId']);

$linkInfo = $weblinks->selectOne("*", array(
	array("uid", "=", "'".$auth->currentUserInfo['id']."'"),
	array("id", "=", "'".$linkId."'")
));

if (!$linkInfo) {
	echo "Invalid link ID!";
	exit();
}

$linkInfo['path'] = $weblinks->paths->selectOneCol("path", array("id", "=", "'".$linkInfo['pathid']."'"));
$filename = $fm->basename($linkInfo['path']);

$linkInfo['url'] = $weblinks->getURL(array(
	"id_rnd" => $linkInfo['id_rnd']
));


$url = 'https://www.googleapis.com/urlshortener/v1/url?key='.$settings->google_shortener_key;
$http = new Guzzle\Http\Client($url);
$http->setUserAgent('Afian/FileRun');
$req = $http->post($url, array(
	'Content-Type' => 'application/json',
), json_encode(array(
	'longUrl' => $linkInfo['url']
)));

$output = array();
$output['success'] = false;
$rs = false;
try {
	$rs = $req->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
	try {
		$r = $e->getResponse()->json();
	} catch (Guzzle\Common\Exception\RuntimeException $e) {
	}
	if ($r && $r['error']) {
		$output['error'] = '('.$r['error']['code'].') '.$r['error']['message'];
		if ($r['error']['errors'][0]['reason']) {
			$output['error'] .= ' ('.$r['error']['errors'][0]['domain'].') '.$r['error']['errors'][0]['reason'];
		}
	} else {
		$output['error'] = $e->getMessage();
	}
} catch (Guzzle\Http\Exception\CurlException $e) {
	$output['error'] = $e->getMessage();
}
if ($rs && $rs->isSuccessful()) {
	$serverResponse = $rs->json();
	$shortURL = $serverResponse['id'];
	$output['success'] = true;
	$output['url'] = $shortURL;
	$weblinks->update(array("short_url" => $shortURL), array("id", "=", "'".$linkInfo['id']."'"));
}

jsonOutput($output);