<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Twitter_com {
	var $titleMax = 40;		//コンテンツのタイトルとして表示する文字の最大桁数
	var $twicon   = true;		//コンテンツに Twicon を表示する
	var $expired  = 21600;		//Twitter ステータス再取得までの時間(秒) ( 21600秒 = 60秒 * 60分 * 6時間 )
	var $displaypic = array(
		"twitpic"  => true,	//コンテンツに Twitpic の thumbnail を表示する
		"movapic"  => true,	//コンテンツに 携帯百景 の thumbnail を表示する
		);
	var $longurl  = true;		//コンテンツに短縮URLがあれば、元のURLを復元して表示する
	var $hashtag  = true;		//コンテンツの hashtags を Sweetcron の tag に変換する

	function _twitter_username($original_permalink) {
		$twitter_username = preg_replace('/http:\/\/twitter\.com\/([^\/]+)\/statuses\/\d+/i','$1',trim($original_permalink));
		return $twitter_username;
	}

	function _tweet_title($title, $max_length = -1, $twitter_username = '') {
		if ( $max_length < 0 )
			$max_length = $this->titleMax;

		//remove username from front of posts
		if ( !empty($twitter_username) )
			$title = trim(preg_replace('/^' . preg_quote($twitter_username,'/') . ':/i', '', $title));
		$title = trim(preg_replace('/^[\-\.]/', '', $title));

		if ( $max_length > 0 )
			$title =  mb_strimwidth(strip_tags($title), 0, $max_length, ' ...', 'UTF-8');

		return $title;
	}

	function _tweet_content($item, $twitter_username = '') {
		//get content
		$content = trim($item->item_content);
		if ( empty($content) )
			$content = trim($item->item_title);
		$content = preg_replace('/<a href="([^"]*)"[^>]*>([^<]*[\.]+)<\/a>/i', '<a href="$1">$1</a>', $content);
		$content = strip_tags($content);

		//remove Twitter username
		if (!empty($twitter_username))
			$content = trim(preg_replace('/^' . preg_quote($twitter_username,'/') . ':/i', '', $content));

		//URL Auto link
		$content = preg_replace('/(s?https?|ftp)(:\/\/[-_.!~*\'()a-z0-9;\/?:\@&=+\$,%#]+)/i', '<a href="$1$2">$1$2</a>', $content);

		//hash tags to Twitter search link, @reply to Twitter user link
		$content = trim(preg_replace(
				array('/\s#([-_.!~*\'()a-z0-9;\/?:\@&=+\$,%#]+)(\s?)/i', '/(<a[^>]*>)?@([^\s\/\:]+)(<\/a>)?\s?/'),
				array(' <a href="http://twitter.com/#search?q=%23$1">#$1</a>$2', '@<a href="http://twitter.com/$2">$2</a> '),
				' ' . $content
				));

		//long URL Please
		if ($this->longurl)
			$content = $this->_long_url($content);

		return $content;
	}

	function _twitpic($title) {
		$image = null;
		$image_url = trim(preg_replace('/^.*(http:\/\/twitpic\.com\/[\da-z]+).*$/i', '$1', $title));
		if (!empty($image_url) && $title != $image_url) {
			$title = trim(preg_replace('/^[\-]/', '', str_replace($image_url, '', $title)));
			$image = str_replace('http://twitpic.com/', 'http://twitpic.com/show/thumb/', $image_url);
			$retval = array($title, $image);
		} else {
			$retval = false;
		}
		return $retval;
	}

	function _movapic($title) {
		$image = null;
		$image_url = trim(preg_replace('/^.*(http:\/\/movapic.com\/pic\/[\da-z]+).*$/i', '$1', $title));
		if (!empty($image_url) && $title != $image_url) {
			$title = trim(preg_replace('/^[\-]/', '', str_replace($image_url, '', $title)));
			$image = preg_replace('/^http:\/\/(movapic.com\/pic\/)([\da-z]+)$/i', 'http://image.$1t_$2.jpeg', $image_url);
			$retval = array($title, $image);
		} else {
			$retval = false;
		}
		return $retval;
	}

	function _get_image($title, $image = '') {
		$retval = false;

		//get Twitpic image
		if ( $this->displaypic["twitpic"] )
			$retval = $this->_twitpic($title);
		//get movapic image
		if ( $retval === false && $this->displaypic["movapic"] )
			$retval = $this->_movapic($title);

		return ( $retval !== false ? $retval : array($title, $image) );
	}

	function _fread($cache_file) {
		$fp = @fopen($cache_file, 'r');
		$content = @fread($fp, filesize($cache_file));
		@fclose($fp);
		return ($content);
	}

	function _fwrite($cache_file, $content) {
		$fp = @fopen($cache_file, 'w');
		@fwrite($fp, $content);
		@fclose($fp);
	}

	function _twitter_icon($twitter_username, $size = 'mini') {
		global $twitter_icons;

		$cache_file = dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '_icon.txt';
		if (!isset($twitter_icons)) {
			$twitter_icons = array();
			if (file_exists($cache_file) && filemtime($cache_file) + $this->expired > time())
				$twitter_icons = unserialize($this->_fread($cache_file));
		}

		if (!isset($twitter_icons[$twitter_username])) {
			$url ="http://twitter.com/users/show/{$twitter_username}.xml";
			$result = @file_get_contents($url, false, stream_context_create(array("http" => array("method" => "GET") ) ) );
			if ( $result !== false ) {
				$result = preg_replace("/[\r\n]*/","",$result);
				$icon_url = preg_replace("/^.*<profile_image_url>([^<]*)<\/profile_image_url>.*$/i",'$1',$result);
				$twitter_icons[$twitter_username] = $icon_url;

				$this->_fwrite($cache_file, serialize($twitter_icons));
			}
		}

		if (isset($twitter_icons[$twitter_username])) {
			$icon_url = $twitter_icons[$twitter_username];

			switch(strtolower($size)) {
			case 'mini': case 'small': case 's':
				$size = '_mini'; break;
			case 'bigger': case 'big': case 'large': case 'l':
				$size = '_bigger'; break;
			default:
				$size = '_normal'; break;
			}
			if ( $size != '_normal' )
				$icon_url = preg_replace('/_normal\.(jpe?g|png|gif|bmp)/i', $size . '.$1', $icon_url);
		} else {
			$icon_url = '';
		}

		return $icon_url;
	}

	function _long_url($content) {
		global $long_urls;

		$cache_file = dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '_url.txt';

		$pattern = '"(http:\/\/(tinyurl\.com|bit\.ly|is\.gd|sn(url|ipr|ipurl)\.com|nsfw\.in|qurlyq\.com|dwarfurl\.com|icanhaz\.com|tiny\.cc|urlenco\.de|piurl\.com|linkbee\.com|traceurl\.com|twurl\.nl)\/[^"]*)"';
		if ( preg_match_all('/href=' . $pattern . '/i', $content, $matches, PREG_SET_ORDER) ) {
			if (!isset($long_urls)) {
			$long_url = array();
				if (file_exists($cache_file))
					$long_urls = unserialize($this->_fread($cache_file));
			}

			$urls = array();
			foreach ((array) $matches as $match) {
				$tiny_url = trim($match[1]);
				if ( isset($long_urls[$tiny_url]) ) {
					$long_url = $long_urls[$tiny_url];
					$content  = str_replace($tiny_url, $long_url, $content);
				} else {
					$urls[] = urlencode($tiny_url);
				}
			}
			unset($match);

			if (count($urls) > 0) {
				$url = 'http://longurlplease.appspot.com/api/v1.1?q=' . implode('&q=', $urls);
				$result = @file_get_contents($url, false, stream_context_create(array("http" => array("method" => "GET") ) ) );
				if ($result !== false) {
					$result = explode(',', str_replace(array("\\",'{','}','"',' '), '', $result));
					foreach ((array) $result as $url) {
						list($tiny_1, $tiny_2, $long_1, $long_2) = explode(':', $url);
						$tiny_url = $tiny_1 . ':' . $tiny_2;
						$long_url = $long_1 . ':' . $long_2;
						$long_urls[$tiny_url] = $long_url;
						$content  = str_replace($tiny_url, $long_url, $content);
					}
				}
				unset($result);

				$this->_fwrite($cache_file, serialize($long_urls));
			}
			unset($urls);
		}
		unset($matches);

		return($content);
	}

	function pre_db($item, $original) {
		//remove username from front of posts
		$twitter_username = $this->_twitter_username($original->get_permalink());

		//get title
		$title =  $this->_tweet_title(trim($item->item_title), 0, $twitter_username);

		//get hash tags
		if ( $this->hashtag ) {
			if ( preg_match_all('/#([^\s]+)\s?/', $title, $matches, PREG_SET_ORDER) ) {
				$tags = array();
				foreach ((array) $matches as $match)
					$tags[] = trim($match[1]);
				unset ($match);
				$item->item_data['tags'] = $tags;
			}
			unset($matches);
		}

		//get content
		$content = $item->item_content;

		//filter out @replies (set as unpublished)
		if (substr($title, 0, 1) == '@')
			$item->item_status = 'draft';

		//set return value
		$item->item_title = $title;
		$item->item_content = $content;

		return $item;
	}

	function pre_display($item) {
		//get twitter username
		$twitter_username = $this->_twitter_username($item->item_data['permalink']);

		//get image
		$title = trim(strip_tags($item->item_title));
		$image_array = $this->_get_image($title);
		if ( $image_array !== false ) {
			list($title, $image) = $image_array;
			if ( !empty($image) )
				$item->item_data['image'] = $image;
		}

		//get title
		$title = $this->_tweet_title($title, $this->titleMax, $twitter_username);

		//get content
		$content = $this->_tweet_content($item, $twitter_username);

		//get twitter icon
		if ( $this->twicon ) {
			$icon_url = $this->_twitter_icon($twitter_username);
			if ( !empty($icon_url) )
				$content = "<img src=\"{$icon_url}\" width=\"24\" height=\"24\" style=\"float:left;margin:0 .25em;\" alt=\"$twitter_username\" />$content";
		}

		//set return value
		$item->item_title = $title;
		$item->item_content = $content;

		return $item;
	}


}
?>

