#!/usr/bin/perl -w

use strict;
use lib './extlib';
use lib './plugins/FacebookCommenters/extlib';
use WWW::Facebook::API;

my $api_key = 'AvP[VID';
my $secret = 'V[NbgID';
my $counter = 10; # LOɕ\鐔

my $fb = WWW::Facebook::API->new(
	api_key => $api_key,
	secret  => $secret,
	format  => 'JSON',
);

my $list;
<mt:Entries lastn="0">
$list->{'<mt:EntryPermalink />'} = '<mt:EntryTitle regex_replace="/'/","\\'" regex_replace="/\./","\\." />';</mt:Entries>

my $url = '"'. join('","', keys %$list) . '"';
my $query = 'SELECT url, like_count from link_stat where url IN(' . $url . ') and like_count > 0';

my $res = $fb->fql->query(query => $query);
my @sort = sort {$b->{like_count} <=> $a->{like_count}} @{$res};

my $buf = <<EOF;
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="<$mt:BlogURL$>facebook-styles.css" type="text/css" title="Default" media="screen,tv" />
<title>ˁILO</title>
</head>
<body>
<div id="fb-root"></div>
<ol class="ranking">
EOF

foreach my $data (@sort) {
	if ($counter && $data->{like_count}) {
		$list->{$data->{url}} =~ s/\\././;
		$list->{$data->{url}} =~ s/\\'/'/;
		$buf .= '<li><a href="' . $data->{url} . '" target="_blank">' . $list->{$data->{url}} . '</a> <iframe src="http://www.facebook.com/plugins/like.php?href=' . $data->{url} . '&amp;layout=button_count&amp;show_faces=false&amp;width=150&amp;action=like&amp;font&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:150px; height:21px;" allowTransparency="true"></iframe></li>';
	}
	$counter--;
}

$buf .= <<EOF;
</ol>
<script>
(function() {
	var e = document.createElement('script');
	e.async = true;
	e.src = document.location.protocol + '//connect.facebook.net/ja_JP/all.js';
	document.getElementById(\'fb-root\').appendChild(e);
}());
window.fbAsyncInit = function() {
	FB.init({
		appId: $api_key,
		status: true,
		cookie: true,
		oauth: true
	});
	FB.Canvas.setAutoGrow();
};
</script>
</body>
</html>
EOF

open(FILE,">./ranking.php.new");
print FILE $buf;
close(FILE);
rename('ranking.php.new', 'ranking.php');
