<?php if (!defined('PmWiki')) exit();
 
#########################################
## SHORTEN URLS USING HTTP://BIT.LY
## assembled for PmWiki by Adam Overton, July 2009
## using code by James Cridland, v0.2 24 May 08, http://james.cridland.net/code/bitly.html
## 
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published
## by the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## this code converts any url into a shortened version via the http://bit.ly API
## and is commonly used to shorten long urls for Twitter and other messaging services
## for more info on the API:
## http://code.google.com/p/bitly-api/wiki/ApiDocumentation
## 
## feel free to improve or expand this code ...
##########################################

$RecipeInfo['UrlShortening']['Version'] = '2009-07-22';

# must supply login and apiKey - register for free at http://bit.ly
# $bitLy_login = 'yourLogin';
# $bitLy_apiKey = 'yourApikey';

# MARKUP FUNCTION: BitLyUrl
## generates shortened url for use on webpages
Markup('BitLyUrl', 'inline',
	'/\\(:BitLyUrl\\s+(http[^\\s]+)\\s*:\\)/e',  # be sure not to send any spaces (\\s) along with url
	"bitly_shortened_url($bitLy_login, $bitLy_apiKey, '$1')");

# BIT.LY FUNCTION
function bitly_shortened_url($bitLy_login, $bitLy_apiKey, $url) {

	# must supply login and apiKey, or else it won't work
	if (!$bitLy_login || !$bitLy_apiKey) return false;

	#echo "http://api.bit.ly/shorten?version=2.0.1&longUrl=".$url."&login=".$bitly_login."&apiKey=".$bitLy_apiKey;
	
	$api_call = file_get_contents("http://api.bit.ly/shorten?version=2.0.1&longUrl=".$url."&login=".$bitLy_login."&apiKey=".$bitLy_apiKey);
	
	$bitlyinfo=json_decode(utf8_encode($api_call),true);
	
	if ($bitlyinfo['errorCode']==0) {
		return $bitlyinfo['results'][urldecode($url)]['shortUrl'];
	} else {
		return false;
	}
}