<?php

class Leap_Social_Counter_Widget extends WP_Widget {

	function __construct() {
		$widget_ops	 = array( 'classname' => 'counter-widget', 'description' => '' );
		$control_ops = array( 'width' => 250, 'height' => 350, 'id_base' => 'counter-widget' );
		parent::__construct( 'counter-widget', 'LEAP: Social Counter', $widget_ops, $control_ops );
	}

	function widget( $args, $instance ) {
		extract( $args );

		$defaults	 = array(
			'title'					 => __( ' Social Counters', 'wiz' ),
			'new_window'			 => '',
			'rss'					 => '',
			'facebook'				 => '',
			'twitter_username'		 => '',
			'consumer_key'			 => '',
			'consumer_secret'		 => '',
			'access_token'			 => '',
			'access_token_secret'	 => '',
			'youtube'				 => '',
            'youtube_api_key'		 => '',
			'vimeo'					 => '',
			'dribbble'				 => '',
            'dribbble_access_token'	 => '',
			'soundcloud'			 => '',
			'soundcloud_client_id'	 => '',
			'behance'				 => '',
			'behance_api'			 => '',
			'instagram'				 => '',
			'instagram_client_api'	 => ''
		);
		$instance	 = wp_parse_args( (array) $instance, $defaults );

		$title					 = apply_filters( 'widget_title', $instance[ 'title' ], $instance, $this->id_base );
		$facebook_page			 = $instance[ 'facebook' ];
		$rss_id					 = $instance[ 'rss' ];
		$twitter_username		 = apply_filters( 'leap_widget_twitter_id', $instance[ 'twitter_username' ], $instance, $this->id_base );
		$consumer_key			 = apply_filters( 'leap_widget_consumer_key', $instance[ 'consumer_key' ], $instance, $this->id_base );
		$consumer_secret		 = apply_filters( 'leap_widget_consumer_secret', $instance[ 'consumer_secret' ], $instance, $this->id_base );
		$access_token			 = apply_filters( 'leap_widget_access_token', $instance[ 'access_token' ], $instance, $this->id_base );
		$access_token_secret	 = apply_filters( 'leap_widget_access_token_secret', $instance[ 'access_token_secret' ], $instance, $this->id_base );
		$channel_id 			 = apply_filters( 'leap_widget_channel', $instance[ 'youtube' ], $instance, $this->id_base );
        $youtube_api_key		 = apply_filters( 'leap_widget_youtube_api_key', $instance[ 'youtube_api_key' ], $instance, $this->id_base );
		$vimeo_url				 = $instance[ 'vimeo' ];
		$dribbble_username		 = $instance[ 'dribbble' ];
        $dribbble_access_token	 = apply_filters( 'leap_widget_dribbble_access_token', $instance[ 'dribbble_access_token' ], $instance, $this->id_base );
		$soundcloud_url			 = $instance[ 'soundcloud' ];
		$soundcloud_client_id	 = apply_filters( 'leap_widget_soundcloud_client_id', $instance[ 'soundcloud_client_id' ], $instance, $this->id_base );
		$behance_url			 = $instance[ 'behance' ];
		$behance_api			 = apply_filters( 'leap_widget_behance_api', $instance[ 'behance_api' ], $instance, $this->id_base );
		$instagram_username		 = $instance[ 'instagram' ];
		$instagram_access_token	 = apply_filters( 'leap_widget_instagram_access_token', $instance[ 'instagram_access_token' ], $instance, $this->id_base );
		$new_window				 = $instance[ 'new_window' ];

		if ( $new_window )
			$new_window	 = ' target="_blank" ';
		else
			$new_window	 = '';

		$counter = 0;
		if ( $rss_id )
			$counter ++;
		if ( $twitter_username )
			$counter ++;
		if ( $facebook_page )
			$counter ++;
		if ( $channel_id )
			$counter ++;
		if ( $vimeo_url )
			$counter ++;
		if ( $dribbble_username )
			$counter ++;
		if ( $soundcloud_url )
			$counter ++;
		if ( $behance_url )
			$counter ++;
		if ( $instagram_username )
			$counter ++;


		echo $before_widget;
		if ( !empty( $title ) ) {
			echo $before_title;
			echo $title;
			echo $after_title;
		}
		?>
		<div class="widget wdg-counter col<?php echo $counter; ?>">
			<ul>
				<?php if ( $rss_id ): ?>
					<li class="rss-subscribers">
						<a href="<?php echo $rss_id ?>"<?php echo $new_window ?>>
							<i class="fa fa-rss"></i>
							<div class="counter"><span><?php _e( 'Subscribe', 'wiz' ) ?><?php __( 'Subscribers', 'wiz' ) ?></span>
								<small><?php _e( 'RSS Feed', 'wiz' ) ?></small>
							</div>
						</a>
					</li>
				<?php endif; ?>
				<?php
				if ( $twitter_username ):
					$twitter = $this->leap_followers_count( $twitter_username, $consumer_key, $consumer_secret );
					?>
					<li class="twitter-followers">
						<a href="<?php echo $twitter[ 'twitter_url' ] ?>"<?php echo $new_window ?>>
							<i class="fa fa-twitter"></i>
							<div class="counter"><span><?php echo number_format( $twitter[ 'followers_count' ] ) ?></span>
								<small><?php _e( 'Followers', 'wiz' ) ?></small>
							</div>
						</a>
					</li>
				<?php endif; ?>
				<?php
				if ( $facebook_page ):
					$facebook = $this->leap_facebook_likes( $facebook_page );
					?>
					<li class="facebook-likes">
						<a href="<?php echo $facebook_page ?>"<?php echo $new_window ?>>
							<i class="fa fa-facebook"></i>
							<div class="counter"><span><?php echo number_format( $facebook ) ?></span>
								<small><?php _e( 'Likes', 'wiz' ) ?></small>
							</div>
						</a>
					</li>
				<?php endif; ?>
				<?php
				if ( $channel_id ):
					$youtube = $this->leap_youtube_subs( $channel_id, $youtube_api_key );
					?>
					<li class="youtube-subscribers">
						<a href="https://www.youtube.com/channel/<?php echo $channel_id ?>"<?php echo $new_window ?>>
							<i class="fa fa-youtube"></i>
							<div class="counter"><span><?php echo number_format( $youtube ) ?></span>
								<small><?php _e( 'Subscribers', 'wiz' ) ?></small>
							</div>
						</a>
					</li>
				<?php endif; ?>
				<?php
				if ( $vimeo_url ):
					$vimeo = $this->leap_vimeo_count( $vimeo_url );
					?>
					<li class="vimeo-subscribers">
						<a href="<?php echo $vimeo_url ?>"<?php echo $new_window ?>>
							<i class="fa fa-vimeo"></i>
							<div class="counter"><span><?php echo number_format( $vimeo ) ?></span>
								<small><?php _e( 'Subscribers', 'wiz' ) ?></small>
							</div>
						</a>
					</li>
				<?php endif; ?>
				<?php
				if ( $dribbble_username ):
					$dribbble = $this->leap_dribbble_count( $dribbble_username, $dribbble_access_token );
					?>
					<li class="dribbble-followers">
						<a href="https://dribbble.com/<?php echo $dribbble_username ?>"<?php echo $new_window ?>>
							<i class="fa fa-dribbble"></i>
							<div class="counter"><span><?php echo number_format( $dribbble ) ?></span>
								<small><?php _e( 'Followers', 'wiz' ) ?></small>
							</div>
						</a>
					</li>
				<?php endif; ?>
				<?php
				if ( $soundcloud_url && $soundcloud_client_id ):
					$soundcloud = $this->leap_soundcloud_count( $soundcloud_url, $soundcloud_client_id );
					?>
					<li class="soundcloud-followers">
						<a href="<?php echo $soundcloud_url ?>"<?php echo $new_window ?>>
							<i class="fa fa-soundcloud"></i>
							<div class="counter"><span><?php echo number_format( $soundcloud ) ?></span>
								<small><?php _e( 'Followers', 'wiz' ) ?></small>
							</div>
						</a>
					</li>
				<?php endif; ?>	
				<?php
				if ( $behance_url && $behance_api ):
					$behance = $this->leap_behance_count( $behance_url, $behance_api );
					?>
					<li class="behance-followers">
						<a href="<?php echo $behance_url ?>"<?php echo $new_window ?>>
							<i class="fa fa-behance"></i>
							<div class="counter"><span><?php echo number_format( $behance ) ?></span>
								<small><?php _e( 'Followers', 'wiz' ) ?></small>
							</div>
						</a>
					</li>
				<?php endif; ?>
				<?php
				if ( $instagram_username && $instagram_access_token ):
					$instagram = $this->leap_instagram_count( $instagram_username, $instagram_access_token );
					?>
					<li class="instagram-followers">
						<a href="https://instagram.com/<?php echo $instagram_username ?>"<?php echo $new_window ?>>
							<i class="fa fa-instagram"></i>
							<div class="counter"><span><?php echo number_format( $instagram ) ?></span>
								<small><?php _e( 'Followers', 'wiz' ) ?></small>
							</div>
						</a>
					</li>
				<?php endif; ?>


			</ul>
		</div>
		<?php echo $after_widget; ?>
		<?php
	}

	function update( $new_instance, $old_instance ) {
		$instance = $old_instance;

		$instance[ 'title' ]                  = sanitize_text_field( $new_instance[ 'title' ] );
        $instance[ 'new_window' ]             = sanitize_text_field( $new_instance[ 'new_window' ] );
        $instance[ 'facebook' ]               = esc_url( $new_instance[ 'facebook' ] );
        $instance[ 'rss' ]                    = esc_url( $new_instance[ 'rss' ] );
        $instance[ 'twitter_username' ]       = sanitize_text_field( $new_instance[ 'twitter_username' ] );
        $instance[ 'consumer_key' ]           = sanitize_text_field( $new_instance[ 'consumer_key' ] );
        $instance[ 'consumer_secret' ]        = sanitize_text_field( $new_instance[ 'consumer_secret' ] );
        $instance[ 'access_token' ]           = sanitize_text_field( $new_instance[ 'access_token' ] );
        $instance[ 'access_token_secret' ]    = sanitize_text_field( $new_instance[ 'access_token_secret' ] );
        $instance[ 'youtube' ]                = sanitize_text_field( $new_instance[ 'youtube' ] );
        $instance[ 'youtube_api_key' ]        = sanitize_text_field( $new_instance[ 'youtube_api_key' ] );
        $instance[ 'vimeo' ]                  = esc_url( $new_instance[ 'vimeo' ] );
        $instance[ 'dribbble' ]               = sanitize_text_field( $new_instance[ 'dribbble' ] );
        $instance[ 'dribbble_access_token' ]  = sanitize_text_field( $new_instance[ 'dribbble_access_token' ] );
        $instance[ 'soundcloud' ]             = esc_url( $new_instance[ 'soundcloud' ] );
        $instance[ 'soundcloud_client_id' ]   = sanitize_text_field( $new_instance[ 'soundcloud_client_id' ] );
        $instance[ 'behance' ]                = esc_url( $new_instance[ 'behance' ] );
        $instance[ 'behance_api' ]            = sanitize_text_field( $new_instance[ 'behance_api' ] );
        $instance[ 'instagram' ]              = sanitize_text_field( $new_instance[ 'instagram' ] );
        $instance[ 'instagram_access_token' ] = sanitize_text_field( $new_instance[ 'instagram_access_token' ] );


        delete_transient( 'fans_count' );
		delete_transient( 'leap_twitter_followers' );
		delete_transient( 'youtube_count' );
		delete_transient( 'vimeo_count' );
		delete_transient( 'dribbble_count' );
		delete_transient( 'soundcloud_count' );
		delete_transient( 'behance_count' );
		delete_transient( 'instagram_count' );


		return $instance;
	}

	function form( $instance ) {
		$defaults	 = array(
			'title'					 => __( ' Social Counters', 'wiz' ),
			'new_window'			 => '',
			'rss'					 => '',
			'facebook'				 => '',
			'twitter_username'		 => '',
			'consumer_key'			 => '',
			'consumer_secret'		 => '',
			'access_token'			 => '',
			'access_token_secret'	 => '',
			'youtube'				 => '',
            'youtube_api_key'		 => '',
			'vimeo'					 => '',
			'dribbble'				 => '',
            'dribbble_access_token'	 => '',
			'soundcloud'			 => '',
			'soundcloud_client_id'	 => '',
			'behance'				 => '',
			'behance_api'			 => '',
			'instagram'				 => '',
			'instagram_access_token' => ''
		);
		$instance	 = wp_parse_args( (array) $instance, $defaults );
		?>

		<p>
			<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title : </label>
			<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance[ 'title' ]; ?>" class="widefat" type="text" />
		</p>

		<p>
			<label for="<?php echo $this->get_field_id( 'new_window' ); ?>">Open links in a new window:</label>
			<input id="<?php echo $this->get_field_id( 'new_window' ); ?>" name="<?php echo $this->get_field_name( 'new_window' ); ?>" value="true" <?php if ( $instance[ 'new_window' ] ) echo 'checked="checked"'; ?> type="checkbox" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'rss' ); ?>">Feed URL : </label>
			<input id="<?php echo $this->get_field_id( 'rss' ); ?>" name="<?php echo $this->get_field_name( 'rss' ); ?>" value="<?php echo $instance[ 'rss' ]; ?>" class="widefat" type="text" />
		</p>

		<hr />

		<p>
			<label for="<?php echo $this->get_field_id( 'facebook' ); ?>">Facebook Page URL : </label>
			<input id="<?php echo $this->get_field_id( 'facebook' ); ?>" name="<?php echo $this->get_field_name( 'facebook' ); ?>" value="<?php echo $instance[ 'facebook' ]; ?>" class="widefat" type="text" />
			<small>Link must be like http://www.facebook.com/username/ or http://www.facebook.com/PageID/</small>
		</p>

		<hr />

		<p>
			<small>You need to create <a href="<?php echo esc_url( 'https://dev.twitter.com/apps' ); ?>" target="_blank">Twitter APP</a> to get this info.</small>
			<label for="<?php echo $this->get_field_id( 'twitter_username' ); ?>">Twitter Username : </label>
			<input id="<?php echo $this->get_field_id( 'twitter_username' ); ?>" name="<?php echo $this->get_field_name( 'twitter_username' ); ?>" value="<?php echo $instance[ 'twitter_username' ]; ?>" class="widefat" type="text" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'consumer_key' ); ?>">Consumer Key : </label>
			<input id="<?php echo $this->get_field_id( 'consumer_key' ); ?>" name="<?php echo $this->get_field_name( 'consumer_key' ); ?>" value="<?php echo $instance[ 'consumer_key' ]; ?>" class="widefat" type="text" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'consumer_secret' ); ?>">Consumer Secret : </label>
			<input id="<?php echo $this->get_field_id( 'consumer_secret' ); ?>" name="<?php echo $this->get_field_name( 'consumer_secret' ); ?>" value="<?php echo $instance[ 'consumer_secret' ]; ?>" class="widefat" type="text" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'access_token' ); ?>">Access Token : </label>
			<input id="<?php echo $this->get_field_id( 'access_token' ); ?>" name="<?php echo $this->get_field_name( 'access_token' ); ?>" value="<?php echo $instance[ 'access_token' ]; ?>" class="widefat" type="text" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'access_token_secret' ); ?>">Access Token Secret : </label>
			<input id="<?php echo $this->get_field_id( 'access_token_secret' ); ?>" name="<?php echo $this->get_field_name( 'access_token_secret' ); ?>" value="<?php echo $instance[ 'access_token_secret' ]; ?>" class="widefat" type="text" />
		</p>

		<hr />

		<p>
			<label for="<?php echo $this->get_field_id( 'youtube' ); ?>">Youtube Channel Id : </label>
			<input id="<?php echo $this->get_field_id( 'youtube' ); ?>" name="<?php echo $this->get_field_name( 'youtube' ); ?>" value="<?php echo $instance[ 'youtube' ]; ?>" class="widefat" type="text" />
            <small>Link must be like http://www.youtube.com/user/<b>Channel-ID</b></small>
		</p>
        
        <p>
			<label for="<?php echo $this->get_field_id( 'youtube_api_key' ); ?>">YouTube API Key : </label>
			<input id="<?php echo $this->get_field_id( 'youtube_api_key' ); ?>" name="<?php echo $this->get_field_name( 'youtube_api_key' ); ?>" value="<?php echo $instance[ 'youtube_api_key' ]; ?>" class="widefat" type="text" />
		</p>

		<hr />

		<p>
			<label for="<?php echo $this->get_field_id( 'vimeo' ); ?>">Vimeo Channel URL : </label>
			<input id="<?php echo $this->get_field_id( 'vimeo' ); ?>" name="<?php echo $this->get_field_name( 'vimeo' ); ?>" value="<?php echo $instance[ 'vimeo' ]; ?>" class="widefat" type="text" />
			<small>Link must be like http://vimeo.com/channels/username </small>
		</p>

		<hr />

		<p>
			<label for="<?php echo $this->get_field_id( 'dribbble' ); ?>">Dribbble Username: </label>
			<input id="<?php echo $this->get_field_id( 'dribbble' ); ?>" name="<?php echo $this->get_field_name( 'dribbble' ); ?>" value="<?php echo $instance[ 'dribbble' ]; ?>" class="widefat" type="text" />
		</p>
        
        <p>
			<label for="<?php echo $this->get_field_id( 'dribbble_access_token' ); ?>">Dribbble Access Token: </label>
			<input id="<?php echo $this->get_field_id( 'dribbble_access_token' ); ?>" name="<?php echo $this->get_field_name( 'dribbble_access_token' ); ?>" value="<?php echo $instance[ 'dribbble_access_token' ]; ?>" class="widefat" type="text" />
            <small>You need to create <a href="<?php echo esc_url( 'https://dribbble.com/account/applicationss' ); ?>" target="_blank">Dribbble APP</a> to get your access token.</small>
		</p>

		<hr />

		<p>
			<small>You need to create <a href="<?php echo esc_url( 'http://soundcloud.com/you/apps' ); ?>" target="_blank">SoundCloud APP</a> to get this info.</small><br />
			<label for="<?php echo $this->get_field_id( 'soundcloud' ); ?>">SoundCloud : </label>
			<input id="<?php echo $this->get_field_id( 'soundcloud' ); ?>" name="<?php echo $this->get_field_name( 'soundcloud' ); ?>" value="<?php echo $instance[ 'soundcloud' ]; ?>" class="widefat" type="text" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'soundcloud_client_id' ); ?>">SoundCloud  Client ID : </label>
			<input id="<?php echo $this->get_field_id( 'soundcloud_client_id' ); ?>" name="<?php echo $this->get_field_name( 'soundcloud_client_id' ); ?>" value="<?php echo $instance[ 'soundcloud_client_id' ]; ?>" class="widefat" type="text" />
		</p>

		<hr />

		<p>
			<small>You need to create <a href="<?php echo esc_url( 'http://www.behance.net/dev/apps' ); ?>" target="_blank">Behance APP</a> to get this info.</small><br />
			<label for="<?php echo $this->get_field_id( 'behance' ); ?>">Behance Profile URL : </label>
			<input id="<?php echo $this->get_field_id( 'behance' ); ?>" name="<?php echo $this->get_field_name( 'behance' ); ?>" value="<?php echo $instance[ 'behance' ]; ?>" class="widefat" type="text" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'behance_api' ); ?>">Behance API Key : </label>
			<input id="<?php echo $this->get_field_id( 'behance_api' ); ?>" name="<?php echo $this->get_field_name( 'behance_api' ); ?>" value="<?php echo $instance[ 'behance_api' ]; ?>" class="widefat" type="text" />
		</p>

		<hr />

		<p>
			<label for="<?php echo $this->get_field_id( 'instagram' ); ?>">Instagram Username : </label>
			<input id="<?php echo $this->get_field_id( 'instagram' ); ?>" name="<?php echo $this->get_field_name( 'instagram' ); ?>" value="<?php echo $instance[ 'instagram' ]; ?>" class="widefat" type="text" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'instagram_access_token' ); ?>">Instagram Access Token : </label>
			<input id="<?php echo $this->get_field_id( 'instagram_access_token' ); ?>" name="<?php echo $this->get_field_name( 'instagram_access_token' ); ?>" value="<?php echo $instance[ 'instagram_access_token' ]; ?>" class="widefat" type="text" />
            <small>Check <a href="<?php echo esc_url( 'http://jelled.com/instagram/access-token' ); ?>" target="_blank">this</a> tutorial to generate Instagram Access Token.</small>
		</p>



		<?php
	}

	function leap_remote_get( $url ) {
		$request = wp_remote_retrieve_body( wp_remote_get( $url, array( 'timeout' => 18, 'sslverify' => false ) ) );
		return $request;
	}

	function leap_followers_count( $screenName, $consumerKey, $consumerSecret ) {
		$token = get_option( 'leap_twitter_token' );

		// get follower count from cache
		$numberOfFollowers = get_transient( 'leap_twitter_followers' );

		// cache version does not exist or expired
		if ( false === $numberOfFollowers ) {
			// getting new auth bearer only if we don't have one
			if ( !$token ) {
				// preparing credentials
				$credentials = $consumerKey . ':' . $consumerSecret;
				$toSend		 = base64_encode( $credentials );

				// http post arguments
				$args = array(
					'method'		 => 'POST',
					'httpversion'	 => '1.1',
					'blocking'		 => true,
					'headers'		 => array(
						'Authorization'	 => 'Basic ' . $toSend,
						'Content-Type'	 => 'application/x-www-form-urlencoded;charset=UTF-8'
					),
					'body'			 => array( 'grant_type' => 'client_credentials' )
				);

				add_filter( 'https_ssl_verify', '__return_false' );
				$response = wp_remote_post( 'https://api.twitter.com/oauth2/token', $args );

				$keys = json_decode( wp_remote_retrieve_body( $response ) );

				if ( $keys ) {
					// saving token to wp_options table
					update_option( 'leap_twitter_token', $keys->access_token );
					$token = $keys->access_token;
				}
			}
			// we have bearer token wether we obtained it from API or from options
			$args = array(
				'httpversion'	 => '1.1',
				'blocking'		 => true,
				'headers'		 => array(
					'Authorization' => "Bearer $token"
				)
			);

			add_filter( 'https_ssl_verify', '__return_false' );
			$api_url	 = "https://api.twitter.com/1.1/users/show.json?screen_name=$screenName";
			$response	 = wp_remote_get( $api_url, $args );

			if ( !is_wp_error( $response ) ) {
				$followers			 = json_decode( wp_remote_retrieve_body( $response ) );
				$numberOfFollowers	 = $followers->followers_count;
			} else {
				// get old value and break
				$numberOfFollowers = get_option( 'leap_number_followers' );
				// uncomment below to debug
				//die($response->get_error_message());
			}

			// cache for an hour
			set_transient( 'leap_twitter_followers', $numberOfFollowers, 1 * 60 * 60 );
			update_option( 'leap_number_followers', $numberOfFollowers );
		}

		$twitter[ 'twitter_url' ]		 = 'https://www.twitter.com/' . $screenName;
		$twitter[ 'followers_count' ]	 = ($numberOfFollowers ? $numberOfFollowers : 0);

		return $twitter;
	}

	function leap_facebook_likes( $page_link ) {
		$face_link = parse_url( $page_link );

		if ( $face_link[ 'host' ] == 'www.facebook.com' || $face_link[ 'host' ] == 'facebook.com' ) {
			$fans = get_transient( 'fans_count' );
			if ( empty( $fans ) ) {
				try {
					$data	 = json_decode( $this->leap_remote_get( 'https://graph.facebook.com/fql?q=select%20%20like_count%20from%20link_stat%20where%20url=%22' . $page_link . '%22'), true );
                    
                    $fans	 = $data['data'][0]['like_count'];
                    
				} catch ( Exception $e ) {
					$fans = 0;
				}

				if ( !empty( $fans ) ) {
					set_transient( 'fans_count', $fans, 1200 );
					if ( get_option( 'fans_count' ) != $fans )
						update_option( 'fans_count', $fans );
				}

				if ( $fans == 0 && get_option( 'fans_count' ) )
					$fans = get_option( 'fans_count' );

				elseif ( $fans == 0 && !get_option( 'fans_count' ) )
					$fans = 0;
			}
			return $fans;
		}
	}

	function leap_youtube_subs( $channel_id = '', $api_ley = '' ) {

        $subs = get_transient( 'youtube_count' );
        if ( empty( $subs ) ) {
            try {
                $data	 = json_decode( $this->leap_remote_get( 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='.$channel_id.'&key='.$api_ley ), true );
                $subs	 = $data['items']['0']['statistics']['subscriberCount'];
            } catch ( Exception $e ) {
                $subs = 0;
            }

            if ( !empty( $subs ) ) {
                set_transient( 'youtube_count', $subs, 1200 );
                if ( get_option( 'youtube_count' ) != $subs )
                    update_option( 'youtube_count', $subs );
            }

            if ( $subs == 0 && get_option( 'youtube_count' ) )
                $subs = get_option( 'youtube_count' );

            elseif ( $subs == 0 && !get_option( 'youtube_count' ) )
                $subs = 0;
        }
        return $subs;
	}

	function leap_vimeo_count( $page_link ) {
		$vimeo_link = parse_url( $page_link );

		if ( $vimeo_link[ 'host' ] == 'www.vimeo.com' || $vimeo_link[ 'host' ] == 'vimeo.com' ) {
			$vimeo = get_transient( 'vimeo_count' );
			if ( empty( $vimeo ) ) {
				try {
					$page_name	 = substr( parse_url( $page_link, PHP_URL_PATH ), 10 );
					$data		 = json_decode( $this->leap_remote_get( 'http://vimeo.com/api/v2/channel/' . $page_name . '/info.json' ) );

					$vimeo = $data->total_subscribers;
				} catch ( Exception $e ) {
					$vimeo = 0;
				}

				if ( !empty( $vimeo ) ) {
					set_transient( 'vimeo_count', $vimeo, 1200 );
					if ( get_option( 'vimeo_count' ) != $vimeo )
						update_option( 'vimeo_count', $vimeo );
				}

				if ( $vimeo == 0 && get_option( 'vimeo_count' ) )
					$vimeo	 = get_option( 'vimeo_count' );
				elseif ( $vimeo == 0 && !get_option( 'vimeo_count' ) )
					$vimeo	 = 0;
			}
			return $vimeo;
		}
	}

	function leap_dribbble_count( $dribbble_username= '', $dribbble_access_token = '' ) {

        $dribbble = get_transient( 'dribbble_count' );
        if ( empty( $dribbble ) ) {
            try {
                $data		 = json_decode( $this->leap_remote_get( 'https://api.dribbble.com/v1/users/'.$dribbble_username.'/?access_token='.$dribbble_access_token ), true );

                $dribbble = $data['followers_count'];
            } catch ( Exception $e ) {
                $dribbble = 0;
            }

            if ( !empty( $dribbble ) ) {
                set_transient( 'dribbble_count', $dribbble, 1200 );
                if ( get_option( 'dribbble_count' ) != $dribbble )
                    update_option( 'dribbble_count', $dribbble );
            }

            if ( $dribbble == 0 && get_option( 'dribbble_count' ) )
                $dribbble	 = get_option( 'dribbble_count' );
            elseif ( $dribbble == 0 && !get_option( 'dribbble_count' ) )
                $dribbble	 = 0;
        }
        return $dribbble;
	}

	function leap_soundcloud_count( $page_link, $api ) {
		$soundcloud_link = parse_url( $page_link );
		if ( $soundcloud_link[ 'host' ] == 'www.soundcloud.com' || $soundcloud_link[ 'host' ] == 'soundcloud.com' ) {
			$soundcloud = get_transient( 'soundcloud_count' );
			if ( empty( $soundcloud ) ) {
				try {
					$username	 = substr( $soundcloud_link[ 'path' ], 1 );
					$data		 = json_decode( $this->leap_remote_get( "http://api.soundcloud.com/users/$username.json?consumer_key=$api" ), true );
					$soundcloud	 = (int) $data[ 'followers_count' ];
				} catch ( Exception $e ) {
					$soundcloud = 0;
				}

				if ( !empty( $soundcloud ) ) {
					set_transient( 'soundcloud_count', $soundcloud, 1200 );
					if ( get_option( 'soundcloud_count' ) != $soundcloud )
						update_option( 'soundcloud_count', $soundcloud );
				}

				if ( $soundcloud == 0 && get_option( 'soundcloud_count' ) )
					$soundcloud	 = get_option( 'soundcloud_count' );
				elseif ( $soundcloud == 0 && !get_option( 'soundcloud_count' ) )
					$soundcloud	 = 0;
			}
			return $soundcloud;
		}
	}

	function leap_behance_count( $page_link, $api ) {
		$behance_link = parse_url( $page_link );
		if ( $behance_link[ 'host' ] == 'www.behance.net' || $behance_link[ 'host' ] == 'behance.net' ) {
			$behance = get_transient( 'behance_count' );
			if ( empty( $behance ) ) {
				try {
					$username	 = substr( $behance_link[ 'path' ], 1 );
					$data		 = json_decode( $this->leap_remote_get( "http://www.behance.net/v2/users/$username?api_key=$api" ), true );
					$behance	 = (int) $data[ 'user' ][ 'stats' ][ 'followers' ];
				} catch ( Exception $e ) {
					$behance = 0;
				}

				if ( !empty( $behance ) ) {
					set_transient( 'behance_count', $behance, 1200 );
					if ( get_option( 'behance_count' ) != $behance )
						update_option( 'behance_count', $behance );
				}

				if ( $behance == 0 && get_option( 'behance_count' ) )
					$behance = get_option( 'behance_count' );
				elseif ( $behance == 0 && !get_option( 'behance_count' ) )
					$behance = 0;
			}
			return $behance;
		}
	}

	function leap_instagram_count( $username = '', $access_token = '' ) {
        $instagram = get_transient( 'instagram_count' );
        pr( 'sadasdas' );
        $id        = explode( ".", $access_token );
        if ( empty( $instagram ) ) {
            try {
                $search_user = json_decode( $this->leap_remote_get( "https://api.instagram.com/v1/users/search/?q=$username&access_token=$access_token" ), true );
                $id          = (int) $search_user['data']['0']['id'];
                $data        = json_decode( $this->leap_remote_get( "https://api.instagram.com/v1/users/" . $id . "/?access_token=$access_token" ), true );

                $instagram = (int) $data[ 'data' ][ 'counts' ][ 'followed_by' ];
            } catch ( Exception $e ) {
                $instagram = 0;
            }

            if ( !empty( $instagram ) ) {
                set_transient( 'instagram_count', $instagram, 1200 );
                if ( get_option( 'instagram_count' ) != $instagram )
                    update_option( 'instagram_count', $instagram );
            }

            if ( $instagram == 0 && get_option( 'instagram_count' ) )
                $instagram = get_option( 'instagram_count' );
            elseif ( $instagram == 0 && !get_option( 'instagram_count' ) )
                $instagram = 0;
        }
        return $instagram;
    }

}

function leap_social_counter_widget_box() {
	register_widget( 'Leap_Social_Counter_Widget' );
}

add_action( 'widgets_init', 'leap_social_counter_widget_box' );
