<?php
/*
Plugin Name: TweetSuite
Plugin URI: http://danzarrella.com/tweetbacks-beta-v2.html
Description: A WordPress Plugin to integrate Twitter and WordPress
Version: 0.5
Author: Dan Zarrella
Author URI: http://danzarrella.com
*/

add_action('admin_menu', 'tb_menu');
add_filter('publish_post', 'decodeShortURLs');
add_filter('publish_post', 'ts_send_tweet');
//if( is_single() ) {
	add_filter('the_content', 'addTweetBacks');
//}
add_action('loop_end', 'updateTweetBacks');
register_activation_hook(__FILE__,'tweetbacks_install');
add_action('widgets_init', 'tweetsuite_widget_innit');

if (!wp_next_scheduled('tweetsuite_hourly_hook')) {
	wp_schedule_event( time(), 'hourly', 'tweetsuite_hourly_hook' );
}
add_action( 'tweetsuite_hourly_hook', 'tweetsuite_hourly' );



function ts_send_tweet($postID) {
	global $wpdb;
	$table_name = $wpdb->prefix . "shorturls";
	$line = $wpdb->get_row("select * from $table_name where postID=$postID");
   	if($line->postID==$postID) {
   	    $tinyurl = $line->tinyurl;
		$post = get_post($postID);
		if(get_option('tweetsuite_send_posts')) { tweetsuite_send(trim($post->post_title).' '.$tinyurl); }
	}
}

function tweetsuite_hourly() {
	global $wpdb;
	if(get_option('tweetsuite_favorites')) {
		$favorites = parseTweets('favorites');	
		$table_name = $wpdb->prefix . "ts_favorites";
		addTweets($table_name, $favorites);				
	}
	if(get_option('tweetsuite_mine')) {
		$mine =  parseTweets();
		$table_name = $wpdb->prefix . "ts_mine";
		addTweets($table_name, $mine);		
	}
}	



function updateTweetBacks() {
	global $post, $wpdb;
	getTweetBacks($post->ID);
}

//decodeShortURLs($postID);
//getTweetBacks($postID);

function addTweetBacks($content) {
if( is_single() ) {
	global $wpdb, $post;
	$postID =$post->ID;
	$table_name = $wpdb->prefix . "tweetbacks";
	$buff = $wpdb->get_results("SELECT * FROM $table_name WHERE postID = $postID order by datetime desc");
  $gmt_offset = get_option('gmt_offset');
  
	foreach ($buff as $line) {
		$count++;
		$tweet = strip_tags(stripslashes($line->tweet));
		$author = $line->author;
		$dt = $line->datetime;
		$avatar = $line->avatar;
		$posted = date('Y/m/d h:i a', $dt + $gmt_offset * 3600);
		
		if(get_option('tweetsuite_retweetthis')) {
			$rt = urlencode($tweet);
			$tt_url = "http://twitter.com/home?status=rt:+@$author+$rt";
			$rt_this = WP_CONTENT_URL.'/plugins/'.plugin_basename(dirname(__FILE__)).'/rt_this.gif';		  
			$rt_this_button = "<div style='float:right; margin-left:0px;'><a href='$tt_url'><img border='0' src='$rt_this'></a></div>";
		}
		
		//$output .="<li style='display: block; height: 50px; margin-bottom: 10px; overflow:hidden; list-style:none;'>$rt_this_button<div style='width:48px; height:48px; float:left; margin-right:5px;'><img width='48' src='$avatar' class='ts_user_avatar' /></div><b><A href='http://twitter.com/$author'>$author</a>:</b> $tweet <span style='color:#009900;'>$posted</span></li>";
		$output .="<li style='display: block; height: 50px; margin-bottom: 10px; overflow:hidden; list-style:none; font-size:10pt'>$rt_this_button<div style='width:48px; height:48px; float:left; margin-right:5px; background:url($avatar); border:1px solid #ccc;'></div><b><A href='http://twitter.com/$author'>$author</a>:</b> $tweet <span style='color:#009900;'>$posted</span></li>";
		
	}
	$table_name = $wpdb->prefix . "shorturls";
	$line = $wpdb->get_row("SELECT tweetthis FROM $table_name WHERE postID = $postID");
	$tweetthis = $line->tweetthis;
	if($count>0) {
		//$output = "<div id='tweetbacks'><b>$count Total TweetBacks:</b> (<a href='$tweetthis'>Tweet this post</a>) <ul>".$output."</ul></div>";
		$tweetthis_str = (get_option('tweetsuite_tweetthis')) ? " (<a href='$tweetthis'>Tweet this post</a>)" : "";
		$output = "<div id='tweetbacks'><b>$count Total TweetBacks:</b>" . $tweetthis_str . " <ul>".$output."</ul></div>";
	}
	else {
		//$output = "<div id='tweetbacks'><b>No TweetBacks yet.</b> (<a href='$tweetthis'>Be the first to Tweet this post</a>)</div>";
		$tweetthis_str = (get_option('tweetsuite_tweetthis')) ? " (<a href='$tweetthis'>Be the first to Tweet this post</a>)" : "";
		$output = "<div id='tweetbacks'><b>No TweetBacks yet.</b>" . $tweetthis_str . "</div>";
	}
	
	if(get_option('tweetsuite_tweetthis')) {
		$fn = 'rt-'.$count.'.png';
		if (file_exists(WP_CONTENT_URL.'/plugins/'.plugin_basename(dirname(__FILE__)).'/'.$fn)) {
			$src=WP_CONTENT_URL.'/plugins/'.plugin_basename(dirname(__FILE__)).'/'.$fn;
		}	
		else {
			$src = WP_CONTENT_URL.'/plugins/'.plugin_basename(dirname(__FILE__))."/rt-gif.php?count=$count";
		}	
		$float = get_option('tweetsuite_tweetthis_float');	
		if(!$float) { $float = 'left'; }
		$content = "<a href='$tweetthis'><img border='0' style='float:$float; margin-right5px;' src='$src'></a>".$content;
	}

	return $content . $output;
	}
	else {
		return $content;
	}
}

function addTweets($table_name, $entries) {
global $wpdb;
if(count($entries)>0) {
foreach($entries as $entry) {
		//print_r($entry);
		$tweet = $wpdb->escape($entry['tweet']);
		$author = $entry['author'];
		$link =  $entry['link'];
		$dt =  $entry['dt'];		
		$avatar =  $entry['avatar'];
		$q = "insert into $table_name ( datetime, tweet, author, link, avatar) values ($dt, '$tweet', '$author', '$link', '$avatar') ";
		//echo $q."<br/>";
		$results = $wpdb->query($q);				
	}
	}
}



function parseAtom($data) {
$chunks = split('<entry>', $data);
array_shift($chunks);
//print_r($chunks);
foreach($chunks as $chunk) {
	//$lines = split("\n", $chunk);
	//print_r($lines);
	$chunk = str_replace(array("\r", "\n"), '', $chunk);
	
	/*
	if(strstr($lines[9], '<author>')) {
		$author = split("\(", $lines[10]);
	}
	else {
		$author = split("\(", $lines[9]);
	}
	$author = trim(str_replace('<name>', '', $author[0]));
	*/
	preg_match('/<author>.*?<name>(.*?)\(.*?\)<\/name>/i', $chunk, $matches);
	$author = trim($matches[1]);
	
	//$tweet = trim(str_replace(array('<title>', '</title>', '<content type="html">', '</content>'), '', $lines[5]));	
  preg_match('/<title>(.*?)<\/title>/i', $chunk, $matches);
  $tweet = trim($matches[1]);
	
	//list($junk, $avatar) = split('href="', $lines[7]);
	//$avatar = str_replace('"/>', '', $avatar);
	preg_match('/<link type="image\/.*?" rel="image" href="(.*?)"\/>/i', $chunk, $matches);
	$avatar = trim($matches[1]);
	
	/*
	$dt = $lines[2];
	list($date, $time) = split('T', $dt);
	$time = str_replace('Z', '', $time);
	list($hour, $minute, $second) = split(':', $time);
	list($year, $month, $day) = split('-', $date);
	$year = trim(str_replace('<published>', '', $year));
	$dt = mktime($hour, $minute, $second, $month, $day, $year);
	*/
	preg_match('/<published>(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z<\/published>/i', $chunk, $matches);
	$dt = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
	
	//list($junk, $link) = split('href="', $lines[3]);
	//$link = str_replace('"/>', '', $link);
	preg_match('/<link type="text\/html" rel="alternate" href="(.*?)"\/>/i', $chunk, $matches);
	$link = trim($matches[1]);
	
	//$ret['tweet'] = strip_tags(html_entity_decode($tweet));
	$ret['tweet'] = $tweet;
	$ret['link'] = $link;
	$ret['author'] = $author;
	$ret['avatar'] = $avatar;
	$ret['dt'] = $dt;						
	$return[] = $ret;	
}
return $return;
}


function tweetbacks_install () {
   global $wpdb;
   $table_name = $wpdb->prefix . "tweetbacks";
   if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
   		$sql = "CREATE TABLE `".$table_name."` (
  id int(10) unsigned NOT NULL AUTO_INCREMENT,
  postID int(11) NOT NULL,
  datetime int(11) NOT NULL,
  link varchar(255) NOT NULL,
  avatar varchar(255) NOT NULL,
  tweet varchar(150) NOT NULL,
  author varchar(255) NOT NULL ,
   UNIQUE KEY id (id),
   UNIQUE KEY link (link)
) DEFAULT CHARSET=utf8;";
		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($sql);
		//echo "here";
   }
   
   $table_name = $wpdb->prefix . "ts_favorites";
   if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
   		$sql = "CREATE TABLE `".$table_name."` (
  id int(10) unsigned NOT NULL AUTO_INCREMENT,
  datetime int(11) NOT NULL,
  link varchar(255) NOT NULL,
  avatar varchar(255) NOT NULL,
  tweet varchar(150) NOT NULL,
  author varchar(255) NOT NULL ,
   UNIQUE KEY id (id),
   UNIQUE KEY link (link)
) DEFAULT CHARSET=utf8;";
		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($sql);
		//echo "here";
   }
   
   $table_name = $wpdb->prefix . "ts_mine";
   if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
   		$sql = "CREATE TABLE `".$table_name."` (
  id int(10) unsigned NOT NULL AUTO_INCREMENT,
  datetime int(11) NOT NULL,
  link varchar(255) NOT NULL,
  avatar varchar(255) NOT NULL,
  tweet varchar(150) NOT NULL,
  author varchar(255) NOT NULL ,
   UNIQUE KEY id (id),
   UNIQUE KEY link (link)
) DEFAULT CHARSET=utf8;";
		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($sql);
		//echo "here";
   }
   
   
   $table_name = $wpdb->prefix . "shorturls";
   if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
   		$sql = "CREATE TABLE `".$table_name."` (
  id int(10) unsigned NOT NULL AUTO_INCREMENT,
  postID int(11) NOT NULL,
  count int(11) NOT NULL,
   tweetthis varchar(255) NOT NULL,
  tinyurl varchar(255) NOT NULL,
  isgd varchar(150) NOT NULL,
  snipurl varchar(150) NOT NULL,
  trim varchar(150) NOT NULL,
  bitly varchar(255) NOT NULL,
   UNIQUE KEY id (id),
    UNIQUE KEY postID (postID)
   ) DEFAULT CHARSET=utf8;";
		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($sql);
   }
	ts_setDefaults();
}

function clearTweetBacks() {
	global $wpdb;
	$table_name = $wpdb->prefix . "tweetbacks";
	$results = $wpdb->query('delete from $table_name');	
}
function getTweetBacks($postID) {
	global $wpdb;
	$table_name = $wpdb->prefix . "shorturls";
	$q = "select * from $table_name where postID=$postID";
		$line = $wpdb->get_row("select * from $table_name where postID=$postID");
	if(!$line->postID) {
		decodeShortURLs($postID);
		$line = $wpdb->get_row("select * from $table_name where postID=$postID");
	}
	
	$tinyurl = $line->tinyurl;
	$bitly = $line->bitly;
	$snipurl = $line->snipurl;
	$trim = $line->trim;		
	$turl = 'http://search.twitter.com/search.atom?rpp=100&q=&ors=';
	if($tinyurl) {
		$turl .= urlencode($tinyurl).'+';
	}
	if($bitly) {
		$turl .= urlencode($bitly).'+';
	}
	if($snipurl) {
		$turl .= urlencode($snipurl).'+';
	}
	if($trim) {
		$turl .= urlencode($trim);	
	}
	if(substr($turl, -1) == '+'){
	  $turl = substr($turl, 0, -1);
	}
	$table_name = $wpdb->prefix . "tweetbacks";
	/*
	$line = $wpdb->get_row("select datetime from $table_name where postID=$postID order by datetime desc limit 1");
	$last = $line->datetime;
	*/
	$last = get_option('tweetsuite_updated_'.$postID);
	if(!$last) {$last = 1; }
	$delay = get_option('tweetsuite_delay');
	
	if(!$delay) { $delay = 300; }
	if( ($last+$delay)>mktime()) { 

		return false; 
	}
	update_option('tweetsuite_updated_'.$postID, mktime());
	$data = tb_get($turl);
	$entries = parseAtom($data);
	//print_r($array);
	if(count($entries)>0) {
	$own = get_option('tweetsuite_twitter_username');
	$hide_own = get_option('tweetsuite_own');
	foreach($entries as $entry) {
		//print_r($entry);
		$tweet = $wpdb->escape($entry['tweet']);
		$tweet = html_to_utf8($tweet);
		$author = $entry['author'];
		$link =  $entry['link'];
		$add = true;
		
		if(($hide_own) and (strtolower($author)==strtolower($own))) {
			$add = false;
		}
		if(stristr($tweet, 'http://bit.ly')) {
			if(strstr($tweet, $bitly)) {
				$add = true;
			}
			else {
				$add = false;
			}
		}
		if($add) {
			$dt =  $entry['dt'];		
			$avatar =  $entry['avatar'];
		
			//$q = "insert into $table_name (postID, datetime, tweet, author, link, avatar) values ($postID, $dt, '$tweet', '$author', '$link', '$avatar') ";
			// works on mysql 4.1 or later
			$q = "insert into $table_name (postID, datetime, tweet, author, link, avatar) values ($postID, $dt, '$tweet', '$author', '$link', '$avatar') ON DUPLICATE KEY UPDATE avatar = '$avatar'";
			$results = $wpdb->query($q);
		//$count++;
		}
	}
		$q = "select count(id) as c from $table_name where postID=$postID";	
		$line = $wpdb->get_row($q);
		$count = $line->c;
		//print_r($line);
		$table_name = $wpdb->prefix . "shorturls";
		$q = "update $table_name set count=$count where postID=$postID";
		$results = $wpdb->query($q);	
	}
	
	
}

function decodeShortURLs($postID) {
	global $wpdb;
   $table_name = $wpdb->prefix . "shorturls";
   
   $line = $wpdb->get_row("select * from $table_name where postID=$postID");
   if($line->postID==$postID) {
   	return false;
   }
   
	$url = get_permalink($postID);		
	$tinyurl = tinyUrl($url);
	//$isgd = isgd($url);
	$bitly = bitly($url);
	$snipurl = snipurl($url);
	$trim = getTrim($url);
	
	$from_name = get_option('tweetsuite_twitter_username');
	if($from_name) {
		$from = "+from:+@$from_name";
	}
	$post = get_post($postID);
	//$title = str_replace(' ', '+', trim($post->post_title));	
	$title = urlencode($post->post_title);
	$tt_url = "http://twitter.com/home?status=$title+$tinyurl$from";
	
	$insert = "INSERT INTO " . $table_name . " (postID, tinyurl, bitly, snipurl, trim, tweetthis) " .
            "VALUES ($postID, '" . $wpdb->escape($tinyurl) . "',
								'" . $wpdb->escape($bitly) . "',
								'" . $wpdb->escape($snipurl) . "',
								'" . $wpdb->escape($trim) . "',
								'".$wpdb->escape($tt_url)."'	)";
  $results = $wpdb->query( $insert );

	//if(get_option('tweetsuite_send_posts')) { tweetsuite_send(trim($post->post_title).' '.$tinyurl); }

}



function tb_menu() {
		add_options_page('TweetSuite Options', 'TweetSuite', 8, __FILE__, 'tb_options');

}


function ts_setDefaults() {
	//add_option('tweetbacks_enabled', 1);
	add_option('tweetsuite_retweetthis', 1);
	add_option('tweetsuite_mine', 1);
	add_option('tweetsuite_favorites', 1);
}

function tb_options() {

if($_POST) {
$page_options = split(',', $_POST['page_options']);
foreach($page_options as $opt) {
	//print_r($_POST);
	update_option('tb_max', $_POST['tb_max']);
	update_option('tweetsuite_twitter_username', $_POST['tweetsuite_twitter_username']);
	update_option('tweetsuite_twitter_password', $_POST['tweetsuite_twitter_password']);
	update_option('tweetsuite_tweetthis_float', $_POST['tweetsuite_tweetthis_float']);
	//[tb_noavatars
	//
	
	if($_POST['tb_noavatars']) {
		update_option('tb_noavatars', 1);
	}
	else {
		update_option('tb_noavatars', 0);
	}
		
	
	//tweetbacks_enabled
		if($_POST['tweetbacks_enabled']) {
		update_option('tweetbacks_enabled', 1);
	}
	else {
		update_option('tweetbacks_enabled', 0);
	}
	
		//tweetbacks_enabled
		if($_POST['tweetsuite_send_posts']) {
		update_option('tweetsuite_send_posts', 1);
	}
	else {
		update_option('tweetsuite_send_posts', 0);
	}
		//tweetsuite_own
		if($_POST['tweetsuite_own']) {
		update_option('tweetsuite_own', 1);
	}
	else {
		update_option('tweetsuite_own', 0);
	}
	
		//tweetsuite_tweetthis
		if($_POST['tweetsuite_tweetthis']) {
		update_option('tweetsuite_tweetthis', 1);
	}
	else {
		update_option('tweetsuite_tweetthis', 0);
	}
	
				//tweetsuite_mine
		if($_POST['tweetsuite_retweetthis']) {
		update_option('tweetsuite_retweetthis', 1);		
	}
	else {
		update_option('tweetsuite_retweetthis', 0);
	}
	
		//tweetsuite_mine
		if($_POST['tweetsuite_mine']) {
		update_option('tweetsuite_mine', 1);		
	}
	else {
		update_option('tweetsuite_mine', 0);
	}		
	
		//tweetsuite_favorites
		if($_POST['tweetsuite_favorites']) {
		update_option('tweetsuite_favorites', 1);
	}
	else {
		update_option('tweetsuite_favorites', 0);
	}
	
	
	if(($_POST['tweetsuite_favorites']) or ($_POST['tweetsuite_mine']) ) {
		tweetsuite_hourly();
	}
	
	if($_POST['tweetsuite_clear']) {
		clearTweetBacks();
	}
}
}
//tweetsuite_mine
?>
<div class="wrap">
<h2>TweetSuite</h2>
<form method="post" action="">
<?php wp_nonce_field('update-options'); ?>
<table class="form-table">
	

<tr valign="top">
<th scope="row">Display TweetBacks?</th>
<td><INPUT TYPE=CHECKBOX NAME="tweetbacks_enabled" <?php if(get_option('tweetbacks_enabled')) { echo "checked"; } ?>>
</td>
</tr>

<tr valign="top">
<th scope="row">Display Tweet-This button?</th>
<td><INPUT TYPE=CHECKBOX NAME="tweetsuite_tweetthis" <?php if(get_option('tweetsuite_tweetthis')) { echo "checked"; } ?>>
</td>
</tr>

<tr valign="top">
<th scope="row">Float Tweet-this Button:</th>
<td>
<select name="tweetsuite_tweetthis_float">
<option value='left' <?php if(get_option('tweetsuite_tweetthis_float')=='left') { echo 'selected'; } ?>>Left</option>
<option value='right' <?php if(get_option('tweetsuite_tweetthis_float')=='right') { echo 'selected'; } ?>>Right</option>
</select>
</td>
</tr>


<tr valign="top">
<th scope="row">Display ReTweet-This Buttons?</th>
<td><INPUT TYPE=CHECKBOX NAME="tweetsuite_retweetthis" <?php if(get_option('tweetsuite_retweetthis')) { echo "checked"; } ?>>
</td>
</tr>

<tr valign="top">
<th scope="row">Enable Favorites widget?</th>
<td><INPUT TYPE=CHECKBOX NAME="tweetsuite_favorites" <?php if(get_option('tweetsuite_favorites')) { echo "checked"; } ?>>
</td>
</tr>

<tr valign="top">
<th scope="row">Enable My Tweets widget?</th>
<td><INPUT TYPE=CHECKBOX NAME="tweetsuite_mine" <?php if(get_option('tweetsuite_mine')) { echo "checked"; } ?>>
</td>
</tr>

<tr valign="top">
<th scope="row">Maximum number of TweetBacks to display:</th>
<td><input type="text" size="3" name="tb_max" value="<?php echo get_option('tb_max'); ?>" /></td>
</tr>

<tr valign="top">
<th scope="row">Turn off Avatars?</th>
<td><INPUT TYPE=CHECKBOX NAME="tb_noavatars" <?php if(get_option('tb_noavatars')) { echo "checked"; } ?>>
</td>
</tr>

<tr valign="top">
<th scope="row">Send a Tweet when you publish a post?</th>
<td><INPUT TYPE=CHECKBOX NAME="tweetsuite_send_posts" <?php if(get_option('tweetsuite_send_posts')) { echo "checked"; } ?>>
</td>
</tr>

<tr valign="top">
<th scope="row">Twitter Username:</th>
<td><input type="text" size="20" name="tweetsuite_twitter_username" value="<?php echo get_option('tweetsuite_twitter_username'); ?>" /></td>
</tr>

<tr valign="top">
<th scope="row">Hide Tweets from you?</th>
<td><INPUT TYPE=CHECKBOX NAME="tweetsuite_own" <?php if(get_option('tweetsuite_own')) { echo "checked"; } ?>>
</td>
</tr>

<tr valign="top">
<th scope="row">Twitter Password:</th>
<td><input type="password" size="20" name="tweetsuite_twitter_password" value="<?php echo get_option('tweetsuite_twitter_password'); ?>" /></td>
</tr>

<tr valign="top">
<th scope="row">Clear TweetBacks DB?</th>
<td><INPUT TYPE=CHECKBOX NAME="tweetsuite_clear" >
</td>
</tr>

</table>
<p class="submit">
<input type="submit" name="Submit" value="<?php _e('Save Changes') ?>" />
</p>
</form>
</div>

<?php
}
function zima($url) {
		$bl = tb_get('http://zi.ma/?module=ShortURL&file=Add&mode=API&url='.$url);
		return trim($bl);
	}
function getTrim($url) {
		$bl = tb_get('http://tr.im/marklet?url='.$url);
		list($junk, $bl) = split('trimmed_url', $bl);
		$bl = split('"', $bl);
		return $bl[4];
	}
function tinyUrl($url) {
$tu = tb_get('http://tinyurl.com/create.php?url='.$url);
$tu = split('Open in new window', $tu);
list($junk, $tu) = split('following TinyURL which has a length of 25 characters:', $tu[0]);
$tu = strip_tags($tu);
$tu = str_replace('[', '', $tu);
$tu = trim($tu);
return $tu;
}

function bitly($url) {
$url = str_replace('http://', '', $url);
$auth =  '&login=danzarrella&apiKey=R_7cf7c341a2d94ff09b201bad6eb58d62';
$bl_url = 'http://api.bit.ly/shorten?version=2.0.1&longUrl='.$url.''.$auth;
$bl = tb_get($bl_url);
list($junk, $bl) = split('shortUrl', $bl);
$bl = split('"', $bl);
$bl = $bl[2];
return $bl;
}

function snipurl($url) {
	$su = 'http://snipurl.com/site/snip?link='.$url;
	$su = tb_get($su);
	list($junk, $su) = split('cSnPre', $su);
	$su = split(' ', $su);
	$su = str_replace("('", '', $su[0]);
	return $su;
}
function twurl($url) {
	$twurl = 'http://tweetburner.com/links/create?url='.$url;
	$tw = tb_get($twurl);
	list($junk, $tw) = split('id="twurl"', $tw);
	$tw = split('span', $tw);
	$tw = $tw[0];
	$tw = str_replace('>', '', $tw);
	$tw = str_replace('</', '', $tw);
	return $tw;
}

function tb_get($file) {
	if(function_exists('curl_init')) { 
    $curl_handle = curl_init();
    curl_setopt($curl_handle,CURLOPT_URL,"$file");
    curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
	curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
	if(stristr($file, 'twitter.com')) {		
		$password = get_option('tweetsuite_twitter_password');
		if($password) {
			$username = get_option('tweetsuite_twitter_username');
			curl_setopt($curl_handle,CURLOPT_USERPWD,"$username:$password");
		}
	}
    $data = curl_exec($curl_handle);
    $error = curl_error($curl_handle);
    curl_close($curl_handle);
	if(empty($error)) {
		return $data;
	  }
	  else {
	  	return $error;	
	  }
	 }
	 else {
	 	return tb_get1($url);
	 }
}

function tb_get1($url)
{

   // get the host name and url path
   $parsedUrl = parse_url($url);
   $host = $parsedUrl['host'];
   if (isset($parsedUrl['path'])) {
      $path = $parsedUrl['path'];
   } else {
      // the url is pointing to the host like http://www.mysite.com
      $path = '/';
   }

   if (isset($parsedUrl['query'])) {
      $path .= '?' . $parsedUrl['query'];
   }

   if (isset($parsedUrl['port'])) {
      $port = $parsedUrl['port'];
   } else {
      // most sites use port 80
      $port = '80';
	   }

   $timeout = 10;
   $response = '';

   // connect to the remote server
   $fp = @fsockopen($host, '80', $errno, $errstr, $timeout );

   if( !$fp ) {
    //  echo "Cannot retrieve $url";
   } else {
      // send the necessary headers to get the file
      fputs($fp, "GET $path HTTP/1.0\r\n" .
                 "Host: $host\r\n" .
                 "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.3) Gecko/20060426 Firefox/1.5.0.3\r\n" .
                 "Accept: */*\r\n" .
                 "Accept-Language: en-us,en;q=0.5\r\n" .
                 "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n" .
                 "Keep-Alive: 300\r\n" .
                 "Connection: keep-alive\r\n" .
                 "Referer: http://$host\r\n\r\n");

      // retrieve the response from the remote server
      while ( $line = fread( $fp, 4096 ) ) {
         $response .= $line;
      }

      fclose( $fp );

      // strip the headers
      $pos      = strpos($response, "\r\n\r\n");
      $response = substr($response, $pos + 4);
   }

   // return the file content
   return $response;
}

// all the widget functions go in this function this is your main
function tweetsuite_widget_innit() { if ( !function_exists('register_sidebar_widget') ) return;
global $post, $wpdb;


function tweetsuite_favorites_control() {
	if($_POST['ts_favorite_max']) { update_option('ts_favorite_max', $_POST['ts_favorite_max']); }
	$max = get_option('ts_favorite_max');
	if(!$max) {$max=5; }
		
	?><p><label for='ts_favorite_max'>Display at most:  <input style="width: 100px;" type='text'  name='ts_favorite_max' id='ts_favorite_max' value='<?php echo $max; ?>' /></label> tweets.</p><?php
}

function tweetsuite_mine_control() {
	if($_POST['ts_mine_max']) { update_option('ts_mine_max', $_POST['ts_mine_max']); }
	$max = get_option('ts_mine_max');
	if(!$max) {$max=5; }
		
	?><p><label for='ts_mine_max'>Display at most:  <input style="width: 100px;" type='text'  name='ts_mine_max' id='ts_mine_max' value='<?php echo $max; ?>' /></label> tweets.</p><?php
}

function tweetsuite_favorites_widget($args)
{ 
	global $wpdb;
    extract($args);
	echo $before_widget;
	echo $before_title . 'My Favorite Tweets' . $after_title;
	
	$max = get_option('ts_favorite_max');
	if(!$max) {$max=5; }
	
	$table_name = $wpdb->prefix . "ts_favorites";
	$buff = $wpdb->get_results("SELECT * FROM $table_name order by datetime desc limit $max");
	$gmt_offset = get_option('gmt_offset');
	
	foreach ($buff as $line) {
		$tweet = $line->tweet;
		$link = $line->link;
		$author = $line->author;
		$dt = date('Y/m/d h:i a', $line->datetime + $gmt_offset * 3600);
		$output .="<li><a href='http://twitter.com/$author'>$author</a>: $tweet <a href='$link'>$dt</a></li>";
	}
	echo $output;
	echo $after_widget;
}

function tweetsuite_mine_widget($args)
{ 
	global $wpdb;
    extract($args);
	echo $before_widget;
	echo $before_title . 'My Tweets' . $after_title;
	
	$max = get_option('ts_mine_max');
	if(!$max) {$max=5; }
	
	$table_name = $wpdb->prefix . "ts_mine";
	$buff = $wpdb->get_results("SELECT * FROM $table_name order by datetime desc limit $max");
	$gmt_offset = get_option('gmt_offset');
	
	foreach ($buff as $line) {
		$tweet = $line->tweet;
		$link = $line->link;
		$dt = date('Y/m/d h:i a', $line->datetime + $gmt_offset * 3600);
		$output .="<li>$tweet <a href='$link'>$dt</a></li>";
	}
	echo $output;
	echo $after_widget;
}

function tweetsuite_recent_widget($args)
{ 
	global $wpdb;
    extract($args);
	echo $before_widget;
	echo $before_title . 'Recently Tweeted' . $after_title;
	
	$max = get_option('recent_tweeted_max');
	if(!$max) {$max=5; }
	
	$table_name = $wpdb->prefix . "tweetbacks";
	$buff = $wpdb->get_results("SELECT distinct postID FROM $table_name order by datetime desc limit $max");
	
	foreach ($buff as $line) {
		$post = get_post($line->postID); 
		$title = $post->post_title;
		$url = get_permalink($line->postID);		
		$output .="<li><a href='$url'>$title</a></li>";
	}
	echo $output;
	echo $after_widget;
}
function tweetsuite_recent_widget_control() {
	

	if($_POST['recent_tweeted_max']) { update_option('recent_tweeted_max', $_POST['recent_tweeted_max']); }
	$max = get_option('recent_tweeted_max');
	if(!$max) {$max=5; }
		
	?><p><label for='recent_tweeted_max'>Display at most:  <input style="width: 100px;" type='text'  name='recent_tweeted_max' id='recent_tweeted_max' value='<?php echo $max; ?>' /></label> posts.</p><?php
}


function tweetsuite_most_widget($args)
{ 
	global $wpdb;
    extract($args);
	echo $before_widget;
	echo $before_title . 'Most Tweeted' . $after_title;
	
	$max = get_option('most_tweeted_max');
	if(!$max) {$max=5; }
	
	$table_name = $wpdb->prefix . "shorturls";
	$buff = $wpdb->get_results("SELECT * FROM $table_name order by count desc limit $max");
	
	foreach ($buff as $line) {
		$count = $line->count;
		$post = get_post($line->postID); 
		$title = $post->post_title;
		$url = get_permalink($line->postID);		
		$output .="<li><a href='$url'>$title</a> ($count Tweets)</li>";
	}
	echo $output;
	echo $after_widget;
}
function tweetsuite_most_widget_control() {
	

	if($_POST['most_tweeted_max']) { update_option('most_tweeted_max', $_POST['most_tweeted_max']); }
	$max = get_option('most_tweeted_max');
	if(!$max) {$max=5; }
		
	?><p><label for='most_tweeted_max'>Display at most:  <input style="width: 100px;" type='text'  name='most_tweeted_max' id='most_tweeted_max' value='<?php echo $max; ?>' /></label> posts.</p><?php
}

register_widget_control(array('Recently Tweeted', 'widgets'), 'tweetsuite_recent_widget_control', 200, 150);
register_sidebar_widget(array('Recently Tweeted','widgets'), 'tweetsuite_recent_widget');

register_widget_control(array('Most Tweeted', 'widgets'), 'tweetsuite_most_widget_control', 200, 150);
register_sidebar_widget(array('Most Tweeted','widgets'), 'tweetsuite_most_widget');

register_widget_control(array('My Favorite Tweets', 'widgets'), 'tweetsuite_favorites_control', 200, 150);
register_sidebar_widget(array('My Favorite Tweets','widgets'), 'tweetsuite_favorites_widget');

register_widget_control(array('My Tweets', 'widgets'), 'tweetsuite_mine_control', 200, 150);
register_sidebar_widget(array('My Tweets','widgets'), 'tweetsuite_mine_widget');

}

function tweetsuite_send($msg) {
$username = get_option('tweetsuite_twitter_username');
$password = get_option('tweetsuite_twitter_password');
if(($username) and ($password))  {
	$url = 'http://twitter.com/statuses/update.xml';
	$curl_handle = curl_init();
	curl_setopt($curl_handle, CURLOPT_URL, "$url");
	curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
	curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl_handle, CURLOPT_POST, 1);
	curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$msg");
	curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");
	$buffer = curl_exec($curl_handle);
	curl_close($curl_handle);
}

}


function parseTweets($type='tweets') {
	$user = get_option('tweetsuite_twitter_username');	
	if($type=='favorites') {$url = "http://twitter.com/favorites/$user.atom"; }
	else { $url = "http://twitter.com/statuses/user_timeline/$user.atom"; }
	//echo "parseTweet $url";
	//	print_r($return);	
	$data =tb_get($url);
$chunks = split('<entry>', $data);
array_shift($chunks);
foreach($chunks as $chunk) {	
	$lines = split("\n", $chunk);

	$author = split("\(", $lines[9]);
	$author = trim(str_replace('<name>', '', $author[0]));
	$tweet = trim(str_replace(array('<title>', '</title>', '<content type="html">', '</content>'), '', $lines[2]));	
	list($junk, $avatar) = split('href="', $lines[7]);
	$avatar = str_replace('"/>', '', $avatar);
	$dt = $lines[4];
	list($date, $time) = split('T', $dt);
	$time = str_replace('Z', '', $time);
	list($hour, $minute, $second) = split(':', $time);
	list($year, $month, $day) = split('-', $date);
	$year = trim(str_replace('<published>', '', $year));
	$dt = mktime($hour, $minute, $second, $month, $day, $year);	
	
	list($junk, $link) = split('href="', $lines[6]);
	$link = str_replace('"/>', '', $link);
	if($type=='tweets') {
		$ret['tweet'] = trim(str_replace($user.':', '', strip_tags(html_entity_decode($tweet))));
		$ret['author'] = $user;
	}
	else {
		$tws = split(': ', strip_tags(html_entity_decode($tweet)));
		$ret['author'] = array_shift($tws);
		$ret['tweet'] = join(': ', $tws);
	}
	$ret['tweet'] = html_to_utf8($ret['tweet']);
	$ret['link'] = $link;
	
	$ret['avatar'] = $avatar;
	$ret['dt'] = $dt;						
	$return[] = $ret;	
}			
return $return;
}

// http://tw2.php.net/manual/en/function.utf8-encode.php#75942
function html_to_utf8($data){
  return preg_replace("/\\&\\#([0-9]{3,10})\\;/e", '_html_to_utf8("\\1")', $data);
}

function _html_to_utf8 ($data){
  if($data > 127){
    $i = 5;
    while(($i--) > 0){
      if ($data != ($a = $data % ($p = pow(64, $i)))){
        $ret = chr(base_convert(str_pad(str_repeat(1, $i + 1), 8, "0"), 2, 10) + (($data - $a) / $p));
        for ($i; $i > 0; $i--)
          $ret .= chr(128 + ((($data % pow(64, $i)) - ($data % ($p = pow(64, $i - 1)))) / $p));
        break;
      }
    }
  }
  else
    $ret = "&#$data;";
  return $ret;
}
?>