<?php
/**
 *	LaboratorTweets
 *
 *	Twitter Widget by Arlind Nushi
 *
 *	Theme by: Art Ramadani
 *	Developed by: Arlind Nushi
 *
 *	www.mobanbus.cn
 */


class LaboratorTweets extends WP_Widget {
	
	public function __construct()
	{
		parent::__construct(false, '[Laborator] Latest Tweets', array('description' => 'Get the latest tweets from your twitter account. This widget is developed by Laborator team.'), array('width' => 340));
	}
	
	
	public function widget($args, $instance)
	{
		extract($args);
		
		$twitter_username = $instance['twitter_username'];
		$tweets_limit = $instance['tweets_limit'];
		
		$tweets = get_transient('laborator_latest_tweets');
		
		
		# Caching
		if( ! $tweets)
		{
			$tweets = $this->fetch_tweets($twitter_username, $tweets_limit);
			set_transient('laborator_latest_tweets', $tweets, $fetch_interval * 60);
		}
		
		

		
		// Before Widget
		echo PHP_EOL . $before_widget;
		
		// Display Title
		$title = apply_filters('widget_title', (empty($instance['title']) ? 'Tweets' : $instance['title']), $instance, $this->id_base);
		
		echo PHP_EOL . $before_title . $title . $after_title . PHP_EOL;
		
		
		// Display Tweets List
		$tweets_swtich_timeout = $instance['tweets_swtich_timeout'];
		
		?>
		<!-- tweets -->
		<ul class="tweets"<?php echo $tweets_swtich_timeout > 0 ? (' data-timeout="' . $tweets_swtich_timeout . '"') : ''; ?>>
		<?php
		
		if( ! is_array($tweets))
			$tweets = array();
		
		$tweets = array_splice($tweets, 0, $instance['tweets_limit']);
		
		
		foreach($tweets as $tweet)
		{
			$tweet_time = strtotime($tweet->created_at);
			
			$tweet_mo = __(date("M", $tweet_time), TD);
			$tweet_date = strtolower(date('d', $tweet_time) . ' ' . __($tweet_mo, TD));
			
			if(date('Y', $tweet_time) != date('Y'))
			{
				$tweet_date .= ', ' . date('Y', $tweet_time);
			}
			
			$text = popuplinks(make_clickable($tweet->text));
			
			# Replace @usernames links
			$text = preg_replace("/@([a-z0-9_]+)/i", '<a href="http://twitter.com/$1" target="_blank" title="$1">@$1</a>', $text);
			
			# Replace #hashtags links
			$text = preg_replace("/#([a-z0-9_]+)/i", '<a href="http://twitter.com/#!search/?q=%23$1&src=hash" target="_blank" title="$1">#$1</a>', $text);
			
			?>			
			<li>
				<!-- tweet item -->
				<div class="tweet">
					<?php echo $text; ?>
					<span class="timespan"><?php echo $tweet_date; ?></span><!-- tweet date -->
				</div>
				<!-- end: tweet item -->
			</li>
			<?php
		}
		?>
		</ul>
		<?php
		
		// After Widget
		echo $after_widget . PHP_EOL;
	}
	
	
	public function update($new_instance, $old_instance)
	{
		// Title		
		$title = $_POST['title'];
		$old_instance['title'] = $title;
		
		
		// Twiter Username		
		$twitter_username = $_POST['twitter_username'];
		$old_instance['twitter_username'] = $twitter_username;
		
		
		// Tweets Fetch Interval
		$fetch_interval = $_POST['fetch_interval'];
		
		if(is_numeric($fetch_interval) && $fetch_interval > 0)
			$old_instance['fetch_interval'] = $fetch_interval;
		
		
		// Tweets Limit (Count)
		$tweets_limit = $_POST['tweets_limit'];
		
		if(is_numeric($tweets_limit) && $tweets_limit > 0)
			$old_instance['tweets_limit'] = $tweets_limit;
		
		
		// Timeout to switch tweets (JavaScript)
		$tweets_swtich_timeout = $_POST['tweets_swtich_timeout'];
		
		if(is_numeric($tweets_swtich_timeout) && $tweets_swtich_timeout >= 0)
			$old_instance['tweets_swtich_timeout'] = $tweets_swtich_timeout;
		
		// Get new tweets
		if($_POST['fetch_now_tweets'])
		{
			$statuses = $this->fetch_tweets($twitter_username, $tweets_limit);
			
			update_option('laborator_fetch_tweets_last_check', time() + $fetch_interval * 60);
			update_option('laborator_fetch_tweets', $statuses);
			
			set_transient('laborator_latest_tweets', $statuses, $fetch_interval * 60);
		}
		
		return $old_instance;
	}
	
	
	public function form($instance)
	{	
		$statuses = $this->fetch_tweets($twitter_username, $tweets_limit);
		
		?>
		<p>
			<label for="title">Display Title:</label>
			<input type="text" id="title" name="title" value="<?php echo $instance['title']; ?>" />
		</p>
		
		<p>
			<label for="">Twitter Username (without @):</label>
			<input type="text" id="twitter_username" name="twitter_username" value="<?php echo $instance['twitter_username']; ?>" />
		</p>
		
		<p>
			<label for="fetch_interval">Check for new tweets every:</label>
			<input type="text" id="fetch_interval" name="fetch_interval" class="small-text" value="<?php echo $instance['fetch_interval'] ? $instance['fetch_interval'] : 30; ?>" />
			minutes
		</p>
		
		<p>
			<label for="tweets_limit">Tweets limit:</label>
			<input type="text" id="tweets_limit" name="tweets_limit" class="small-text" value="<?php echo $instance['tweets_limit'] ? $instance['tweets_limit'] : 10; ?>" />
		</p>
		
		<p>
			<label for="tweets_swtich_timeout">Tweets Switch Timeout:</label>
			<input type="text" id="tweets_swtich_timeout" name="tweets_swtich_timeout" class="small-text" value="<?php echo $instance['tweets_swtich_timeout']; ?>" />
			seconds
		</p>
		
		<p>
			<label>
				<input type="checkbox" name="fetch_now_tweets" id="fetch_now_tweets" value="1" />
				Fetch now (after clicking Save)
			</label>
		</p>
		<?php
	}
	
	
		
	private function fetch_tweets($twitter_username, $limit = 10)
	{
		include_once(ABSPATH . WPINC . '/feed.php');
		
		if($limit < 1 || $limit > 200)
			$limit = 10;
		
		$twitter_url = "http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name={$twitter_username}&count={$limit}";
		
		
		$statuses = $this->retrieve_contents($twitter_url, 'json');
			
		return $statuses;
	}
	
	private function retrieve_contents($url, $type = '')
	{
		if(function_exists('curl_init'))
		{
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			
			$response = curl_exec($ch);
			curl_close($ch);
		}
		else
		{
			$response = @file_get_contents($url);
		}
				
		if($type == 'json')
			$response = json_decode($response);
		
		$error = $response->error;
		if($error != 'Not authorized')
			echo '<div style="padding-bottom: 10px;">' . $error . '</div>';
		
		return $response;
	}
}

// Register widget
add_action('widgets_init', 'init_laborator_twitter_widget');

function init_laborator_twitter_widget(){
	
	register_widget('LaboratorTweets');

}