<?php

if ( ! class_exists( 'uh_social_connection' ) ) :

class uh_social_connection {
	public $twitter_key = '';
	public $twitter_secret = '';
	public $twitter_publich_text = 'I am going to [TITLE]. Join me!';
	public $twitter_publish = false;
	
	public $googleplus_apiKey = '';
	public $googleplus_clientId = '';

	public $linkedin_app_key = '';
	public $facebook_app_id = '';
	public $post_type = array();
	public $URL = '';
	public $PATH = '';
	
	public function __construct() {
		$this->social_connection_settings();

		if ( ! is_admin() ) {
			$this->intercept_data();

			add_action( 'wp_enqueue_scripts', array( $this, 'script' ) );
			add_action( 'wp_print_scripts', array( $this, 'script_print' ) );
		}
	}
	
	function social_connection_settings(){
		$get_value = get_option('rhsco_options', '');
		
		foreach( array( 'twitter_key', 'twitter_secret', 'googleplus_apikey', 'googleplus_clientid', 'facebook_app_id', 'linkedin_app_key' ) as $option){
			$option_name = $option;
			switch($option){
				case 'googleplus_apikey':
					$option_name = 'googleplus_apiKey';
					break;
				case 'googleplus_clientid':
					$option_name = 'googleplus_clientId';
					break;
			}
			if(!empty($get_value[$option])){
				$this->$option_name = $get_value[$option];
			}
		}
	}

	public function script() {
		global $post;
		
			if(empty($this->URL)){
			$url1 = plugins_url( __FILE__ );
			$url2 = dirname(__FILE__);
			$url1 = explode('wp-content', $url1);
			$url2 = explode('wp-content', $url2);
			$url1 = $url1[0] .'wp-content'.  $url2[1];
			$url1 = str_replace("\\","/",$url1); // fix for windows hosted sites
			$this->URL = $url1;
			}
			
			$this->social_connection_settings();

			if ( ! empty( $this->linkedin_app_key ) ) {
				wp_enqueue_script( 'linkedin', '//platform.linkedin.com/in.js' );
				wp_add_inline_script( 'linkedin', "IN.init({ api_key: '$this->linkedin_app_key', authorize: true })" );
			}

	        wp_enqueue_script('fb','//connect.facebook.net/en_US/sdk.js'); 
	        wp_enqueue_script('googleplus','https://apis.google.com/js/client.js?onload=handleClientLoad'); 
	        wp_register_script('UH_social_frontend', $this->URL . '/social_connection.js','',date('Ymd.his') );
	        wp_localize_script('UH_social_frontend', 'UH_social_vars', array('fb_appID' => $this->facebook_app_id,'siteurl' => get_site_url(),'googleplus_clientId'=>$this->googleplus_clientId,'googleplus_apiKey'=>$this->googleplus_apiKey, 'wp_redirect_url' => wp_login_url( '?uh_social_data=true&uh_fn=wp_get' ),'wp_is_login' => is_user_logged_in(),'wp_runthrow' => get_site_url().'?uh_social_data=true&uh_fn=wp_get' ));  
	        wp_enqueue_script( 'UH_social_frontend');
	}

	public function script_print() {
		$this->social_connection_settings();

		echo '<div id="fb-root"></div>';
		echo '<button id="authorize-button" style="visibility: hidden;display:none;">Authorize</button>';

		if ( ! did_action( 'uh_social_enqueue_linkedin' ) ) {
			do_action( 'uh_social_enqueue_linkedin' );
		}
	}

	function intercept_data(){
		if(isset($_REQUEST['uh_social_data'])){
			if($_REQUEST['uh_fn']=='twitter'){
				$this->twitter_data();
			} else if($_REQUEST['uh_fn']=='twitter_destry_session'){
				$this->twitter_destry();
			} else if($_REQUEST['uh_fn']=='twitter_get'){
				$this->twitter_get();
			} else if($_REQUEST['uh_fn']=='twitter_publish'){
				$this->twitter_publish_fn();
			} else if($_REQUEST['uh_fn']=='wp_get'){
				$this->wp_get();
			}
			
			
			die();
		}
	}
	
	function check_post_type() {
		global $post, $typenow, $current_screen;
		
		$return = null;
		
		if(!empty($this->post_type) && in_array('-', $this->post_type))
			return true;
		elseif(empty($post->post_type))
			return false;
		elseif ( $post && $post->post_type )
			$return =  $post->post_type;
		elseif( $typenow )
			$return = $typenow;
		elseif( $current_screen && $current_screen->post_type )
			$return =  $current_screen->post_type;
		elseif( isset( $_REQUEST['post_type'] ) )
			$return = sanitize_key( $_REQUEST['post_type'] );
		
		return (!empty($this->post_type) && in_array($return, $this->post_type));
	}

	function wp_get() {
		if ( is_user_logged_in() ) {
			$current_user = wp_get_current_user();
			$tmp = $current_user->data;
		
			if ( ! empty( $tmp ) ) {
				unset( $tmp->user_pass );
				unset( $tmp->user_activation_key );

				$tmp->firstname = $current_user->user_firstname;
				$tmp->lastname = $current_user->user_lastname;
				$tmp->email = $current_user->user_email;
				
				$this->twitter_callback( $tmp, 'wp' );
			}
		}
	}
	
	
	
	
	
	// twitter
	
	function twitter_init(){
		if(!empty($_REQUEST['loginalways'])){
			$this->twitter_destry();
			unset($_REQUEST['loginalways']);
			unset($_SESSION['oauth_token']);
			unset($_SESSION['oauth_verifier']);
			
			unset($_SESSION['oauth_token_secret']);
			
			$tmp = $this->curPageURL();
			$tmp = str_replace('&loginalways=true', '', $tmp);
			
			header( 'Location:'.$tmp );
			die();
		} else {
			session_start();
		}
		
		
		require_once('twitteroauth/twitteroauth.php');
		
		$connection = '';
		
		if (empty($_SESSION['oauth_token']) || empty($_SESSION['oauth_token_secret'])) {
			$connection = new TwitterOAuth($this->twitter_key,$this->twitter_secret);

			$temporary_credentials = $connection->getRequestToken(site_url().'/?uh_social_data=true&uh_fn=twitter&'.http_build_query($_GET));
			$redirect_url = $connection->getAuthorizeURL($temporary_credentials);
			
			$_SESSION['oauth_token']  = $temporary_credentials['oauth_token'];
			$_SESSION['oauth_token_secret'] = $temporary_credentials['oauth_token_secret'];
			
			header('Location: '.$redirect_url);
		
		} else {
		
			if(!empty($_REQUEST['oauth_verifier'])){
				$_SESSION['oauth_verifier'] = $_REQUEST['oauth_verifier'];
			}

			$connection = new TwitterOAuth($this->twitter_key,$this->twitter_secret,$_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
			$access_token = $connection->getAccessToken($_SESSION['oauth_verifier']);
			
		}
		
		return $connection;
	}
	

	
	
	function twitter_get(){
		$connection = $this->twitter_init();
	
		if (!empty($connection)) {
			if(empty($_REQUEST['get_data'])){
				$_REQUEST['get_data'] = 'account/verify_credentials';
			}
			$content = $connection->get($_REQUEST['get_data']);
			
			if(!empty($_REQUEST['return_json'])){
				$this->twitter_callback_json($content);
			} else {
				$this->twitter_callback($content);
			}
		}
		
		die();
	}

	function twitter_publish_fn(){
		$connection = $this->twitter_init();
	
		if (!empty($connection)) {
			if(!empty($_REQUEST['publich_text'])){
				$this->twitter_publich_text = $_REQUEST['publich_text']; 
			}
			
			$when_true = $connection->post('statuses/update', array('status' => $this->twitter_publich_text));	

			die(json_encode(array('stats'=>$when_true)));

		}
		
		die();
	}	
	
	
	function twitter_data(){
		if(empty($_REQUEST['rating'])){
			$_REQUEST['rating'] = '';
			$_POST['rating'] = '';
			$_GET['rating'] = '';
		}				
		if(empty($_REQUEST['answer'])){
			$_REQUEST['answer'] = '';
			$_POST['answer'] = '';
			$_GET['answer'] = '';
		}

	
		$connection = $this->twitter_init();
	
		if (!empty($connection)) {
			if(empty($_REQUEST['get_data'])){
				$_REQUEST['get_data'] = 'account/verify_credentials';
			}
			
			$content = $connection->get($_REQUEST['get_data']);
			
			if(!empty($content->name)){
				$firstName = $lastName = '';
				$tmp_name = explode(' ', $content->name);
				
				for($i=0; $i<count($tmp_name); $i++){
					if($i==0){
						$firstName = $tmp_name[$i];
					} else {
						if(!empty($lastName)){
							$lastName .= ' ';
						}
						$lastName .= $tmp_name[$i];
					}
				}
				$content->firstName = utf8_decode($firstName) ;
				$content->lastName = utf8_decode($lastName);
			}
			
			$permalink = $posttile = $ical_feed = $fc_start_time = '';
			if(!empty($_REQUEST['postID'])){
				$content->postID = $_REQUEST['postID'];
			
			
				$permalink = get_permalink($_REQUEST['postID']);
				if(!empty($_REQUEST['event_rdate'])){
					if (strpos($permalink, '?') === false) {
					    $permalink .= '?event_rdate='.$_REQUEST['event_rdate'];
					} else {
					    $permalink .= '&event_rdate='.$_REQUEST['event_rdate'];
					}
				}
				$posttile = get_the_title($_REQUEST['postID']);
				$ical_feed = site_url().'/?rhc_action=get_icalendar_events&ID='.$_REQUEST['postID'];
				
				$fc_start_time = get_post_meta( $_REQUEST['postID'], 'fc_start_time', true );
				if(empty($fc_start_time)){
					$fc_start_time = '00:00';
				}
			}
			
			if(!empty($_REQUEST['event_rdate'])){
				$star_date = explode(',', $_REQUEST['event_rdate']);
				$star_date = $star_date[0];
				$star_date = date('F j, Y',strtotime($star_date));
			} else {
				$star_date = '';
			}
			
			if(!empty($_REQUEST['answer']) && !empty($this->twitter_publish) && $_REQUEST['answer'] > 0){
				$this->twitter_publich_text = str_replace(array('[LINK]','[TITLE]','[STARTDATE]','[STARTTIME]','[ICAL_FEED]','[ANSWER]'),array($permalink,$posttile,$star_date,$fc_start_time,$ical_feed,$_REQUEST['answer']),$this->twitter_publich_text);
				$connection->post('statuses/update', array('status' => $this->twitter_publich_text));	
			}

			if(!empty($_REQUEST['rating']) && !empty($this->twitter_publish) && $_REQUEST['rating'] > 0){
				$this->twitter_publich_text = str_replace(array('[LINK]','[TITLE]','[STARTDATE]','[STARTTIME]','[ICAL_FEED]','[RATING]'),array($permalink,$posttile,$star_date,$fc_start_time,$ical_feed,$_REQUEST['rating']),$this->twitter_publich_text);
				$connection->post('statuses/update', array('status' => $this->twitter_publich_text));	
			}


			if(!empty($_REQUEST['return_json'])){
				$this->twitter_callback_json($content);
			} else {
				$this->twitter_callback($content);
			}
		}
		
		die();
	}
	
	function twitter_callback_json($content){
		if(empty($content['R'])){
			$content['R'] = 'OK';
		}
		die(json_encode($content));
	}
		
	function twitter_callback($content,$type = 'twitter'){
		if(empty($_REQUEST['postID'])){
			$_REQUEST['postID'] = 0;
		}
		if(!empty($_REQUEST['return_function'])){
		?>
			<script>
				var tmp_object={<?php 
					$tmp_string = '';
					
					foreach($content as $tmp_key => $tmp_content){
						if(!is_object($tmp_content) and !is_array($tmp_content) ){
							if(!empty($tmp_string)){
								$tmp_string .= ',';
							}
							$tmp_string .= "'".$tmp_key."':'".$tmp_content."'";
						}
					}			
						echo $tmp_string;
				?>};

				try {   
		        	window.opener.<?php echo $_REQUEST['return_function']; ?>(tmp_object,<?php echo $_REQUEST['postID']; ?>,'<?php echo $type; ?>');
				}
		    	catch (err) {}
		    	
	    <?php } ?>
	
		    	
			   	window.close();
			</script>
		<?php
	}
	
	function twitter_destry(){
		session_start();
		session_destroy();
	}
	
	function curPageURL() {
		$pageURL = 'http';
		if (!empty($_SERVER["HTTPS"]) and $_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
		$pageURL .= "://";
		if ($_SERVER["SERVER_PORT"] != "80") {
			$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
		} else {
			$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
		}
	return $pageURL;
	}
	
}

endif;

new uh_social_connection();