<?php
// ========================================================
// User Login Form
// ========================================================
function serpentsoft_create_login($just_login = false) {
    global $user_ID, $user_identity, $user_level;
    if($user_ID):
        if($just_login == false): ?>

            <div id="logged-in">
                <p class="welcome"><?php _e('Welcome', 'serpentsoft'); ?><strong><?php echo $user_identity; ?></strong> .</p>
                <span class="avatar-container"><?php echo get_avatar($user_ID, $size = '65'); ?></span>
                <ul class="icons-ul">
                    <li><i class="icon-li icon-caret-right"></i><a href="<?php echo esc_url( home_url('/') ); ?>wp-admin/"><?php _e('Dashboard', 'serpentsoft'); ?></a></li>
                    <li><i class="icon-li icon-caret-right"></i><a href="<?php echo esc_url( home_url('/') ); ?>wp-admin/profile.php"><?php _e('Your Profile', 'serpentsoft'); ?></a></li>
                    <li><i class="icon-li icon-caret-right"></i><a href="<?php echo esc_url( wp_logout_url( get_permalink() ) ); ?>"><?php _e('Logout', 'serpentsoft'); ?></a></li>
                </ul>

                <ul class="author-personal-info social-networks clearfix">
                    <?php serpentsoft_login_user_social_icons_list($user_ID); ?>
                </ul>
            </div>
    <?php endif; // Just Login
    
    else: // else UserID ?>

        <div id="frmLogin">

            <form action="<?php echo esc_url( home_url('/') ); ?>wp-login.php" method="post" class="login-form">

                <!-- UserName Input -->
                <div class="input-prepend input-block-level">
                    <span class="add-on"><i class="icon-envelope"></i></span>
                    <input id="log" name="log" class="span10" type="text" placeholder="User Name" required="required" value="<?php _e('UserName', 'serpentsoft'); ?>"
                           onfocus="if(this.value == '<?php _e('UserName', 'serpentsoft'); ?>') { this.value = ''; }" 
                           onblur="if(this.value == '') { this.value = '<?php _e('UserName', 'serpentsoft'); ?>'; }"  size="33" />
                </div>

                <!-- Password Input -->
                <div class="input-prepend input-block-level">

                    <span class="add-on"><i class="icon-key"></i></span>
                    <input id="pwd" name="pwd" class="span10" type="password" placeholder="Password" required="required" value="<?php _e('Password', 'serpentsoft'); ?>" 
                           onfocus="if(this.value == '<?php _e('Password', 'serpentsoft'); ?>') { this.value = ''; }"
                           onblur="if(this.value == '') { this.value = '<?php _e('Password', 'serpentsoft'); ?>'; }" size="33" />

                </div>

                <button type="submit" name="submit" class="btn-theme" value="<?php _e('Log in', 'serpentsoft'); ?>"><?php _e('Log in', 'serpentsoft'); ?></button>
                <input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" />

                
                <label class="checkbox" for="rememberme">
                    <input name="rememberme" id="rememberme" type="checkbox" /><?php _e('Remember Me', 'serpentsoft'); ?>
                </label>


            </form>

            <ul class="login-lost-pass icons-ul">
        <?php if(get_option('users_can_register')) : wp_register('<li><i class="icon-li icon-circle"></i>', '</li>', true); endif; ?>
                <li><i class="icon-li icon-circle"></i><a href="<?php echo esc_url( home_url('/') ); ?>wp-login.php?action=lostpassword"><?php _e('Lost your password?', 'serpentsoft'); ?></a></li>
            </ul>

        </div>

    <?php endif; // UserID ?>

<?php } // Function 


// ========================================================
// Sound Cloud Function
// ========================================================
function serpentsoft_soundcloud($url, $autoplay = 'false', $artwork = 'true') {
    return '<iframe width="100%" height="166" scrolling="no" frameborder="no"
           src="https://w.soundcloud.com/player/?url=' . $url .
           '&amp;auto_play=' . $autoplay . '&amp;show_artwork=' . $artwork . '"></iframe>';
}

// ========================================================
// Google Map Function
// ========================================================
function serpentsoft_googlemap($url, $height = '385', $view_large_map = 'false') {
    if($height == '' || $height <= 0) {
        $height = '385';
    }
    $large_map_code = '';
    if($view_large_map == 'true') {
        $large_map_code = '<br /><small><a href="' . $url . '" target="_blank">' . __('View Larger Map', 'serpentsoft') . '</a></small>';
    }
    return '<iframe width="100%" height="' . $height . '" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"
        src="' . $url . '&amp;output=embed"></iframe>' . $large_map_code;
}

// ========================================================
// Social Networks Icons
// ========================================================
//function serpentsoft_social_icons($open_newTab = true, )


// ========================================================
// CURL Json Array
// ========================================================
/* function serpentsoft_is_curl() {
    return function_exists('curl_version');
}

function serpentsoft_curl_collect_data($url) {
    if(serpentsoft_is_curl()) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        $raw = curl_exec($ch);
        curl_close($ch);
        return $raw;
    } else {
        return '"CURL is NOT <span style=\"color:red\">installed</span> on this server"';
    } 
}
*/

function serpentsoft_remote_get_body($url){
    $hash = wp_remote_get($url);
    $srpnt_data_json = json_decode( wp_remote_retrieve_body($hash) );
    return $srpnt_data_json;
}

// ========================================================
// Social Counter functions
// ========================================================
function serpentsoft_counter_GetJsonArray($provider, $pageId) {
    $x_followers = 0;

    switch ($provider) {
        case 'facebook': {
                try {
                    /* $srpnt_data_json = json_decode(serpentsoft_curl_collect_data('http://graph.facebook.com/' . $pageId), true);
                    $x_followers = $srpnt_data_json['likes']; */
                    $hash = wp_remote_get('http://graph.facebook.com/' . $pageId);
                    $srpnt_data_json = json_decode( wp_remote_retrieve_body($hash) );
                    $x_followers = $srpnt_data_json->{'likes'};
                    
                } catch (Exception $ex) {
                    $x_followers = 0;
                }
            }
            break;

        case 'youtube': {
                try {
                    /* $srpnt_data_json = json_decode(serpentsoft_curl_collect_data('http://gdata.youtube.com/feeds/api/users/' . $pageId . '?alt=json'), true);
                    $x_followers = $srpnt_data_json['entry']['yt$statistics']['subscriberCount']; */
                    $hash = wp_remote_get('http://gdata.youtube.com/feeds/api/users/' . $pageId . '?alt=json');
                    $srpnt_data_json = json_decode( wp_remote_retrieve_body($hash) );
                    $x_followers = $srpnt_data_json->{'entry'}->{'yt$statistics'}->{'subscriberCount'};
                    
                } catch (Exception $ex) {
                    $x_followers = 0;
                }
            }
            break;

        case 'vimeo': {
                try {
                    /* $srpnt_data_json = json_decode(serpentsoft_curl_collect_data('http://vimeo.com/api/v2/channel/' . $pageId . '/info.json'), true);
                    $x_followers = $srpnt_data_json['total_subscribers']; */
                    $hash = wp_remote_get('http://vimeo.com/api/v2/channel/' . $pageId . '/info.json');
                    $srpnt_data_json = json_decode( wp_remote_retrieve_body($hash) );
                    $x_followers = $srpnt_data_json->{'total_subscribers'};
                } catch (Exception $ex) {
                    $x_followers = 0;
                }
            }
            break;

        case 'dribbble': {
                try {
                    /* $srpnt_data_json = json_decode(serpentsoft_curl_collect_data('http://api.dribbble.com/' . $pageId), true);
                    $x_followers = $srpnt_data_json['followers_count']; */
                    $hash = wp_remote_get('http://api.dribbble.com/' . $pageId);
                    $srpnt_data_json = json_decode( wp_remote_retrieve_body($hash) );
                    $x_followers = $srpnt_data_json->{'followers_count'};
                } catch (Exception $ex) {
                    $x_followers = 0;
                }
            }
            break;

        default :
            $x_followers = 0;
            break;
    }
    return $x_followers;
}

function serpentsoft_counter_twitter($screenName = NULL, $consKEY = '', $consSECRET = '') {
    // some variables
    $consumerKey = $consKEY;
    $consumerSecret = $consSECRET;
    $token = get_option('cfTwitterToken');

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

    // 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('cfTwitterToken', $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('count_NumberOfFollowers');
            // uncomment below to debug
            //die($response->get_error_message());
        }

        // cache for minute
        set_transient('cached_TwitterFollowers', $numberOfFollowers, 1 * 60);
        update_option('count_NumberOfFollowers', $numberOfFollowers);
    }
    return $numberOfFollowers;
}

function serpentsoft_counter_facebook($pageName) {

    $cached_FacebookFans = get_transient('cached_FacebookFans');

    // Check cached not exist or expired
    if($cached_FacebookFans === false) {

        $count_FacebookFans = serpentsoft_counter_GetJsonArray('facebook', $pageName);

        // Update Number in DB
        if(!get_option('count_FacebookFans')) {
            update_option('count_FacebookFans', $count_FacebookFans);
        } else {
            if(get_option('count_FacebookFans') != $count_FacebookFans) {
                update_option('count_FacebookFans', $count_FacebookFans);
            }
        }
        $cached_FacebookFans = get_option('count_FacebookFans');
        // Cache for minute
        set_transient('cached_FacebookFans', $cached_FacebookFans, 1 * 60);
    }

    return $cached_FacebookFans;
}

function serpentsoft_counter_youtube($channelName) {
    $cached_YoutubeSubscribers = get_transient('cached_YoutubeSubscribers');

    // Check cached not exist or expired
    if($cached_YoutubeSubscribers === false) {

        $count_YoutubeSubscribers = serpentsoft_counter_GetJsonArray('youtube', $channelName);
        // Update Number in DB
        if(!get_option('count_YoutubeSubscribers')) {
            update_option('count_YoutubeSubscribers', $count_YoutubeSubscribers);
        } else {
            if(get_option('count_YoutubeSubscribers') != $count_YoutubeSubscribers) {
                update_option('count_YoutubeSubscribers', $count_YoutubeSubscribers);
            }
        }

        $cached_YoutubeSubscribers = get_option('count_YoutubeSubscribers');
        // Cache for minute
        set_transient('cached_YoutubeSubscribers', $cached_YoutubeSubscribers, 1 * 60);
    }
        
    return $cached_YoutubeSubscribers;
}

function serpentsoft_counter_vimeo($channelName) {
    $cached_VimeoSubscribers = get_transient('cached_VimeoSubscribers');

    // Check cached not exist or expired
    if($cached_VimeoSubscribers === false) {

        $count_VimeoSubscribers = serpentsoft_counter_GetJsonArray('vimeo', $channelName);
        // Update Number in DB
        if(!get_option('count_VimeoSubscribers')) {
            update_option('count_VimeoSubscribers', $count_VimeoSubscribers);
        } else {
            if(get_option('count_VimeoSubscribers') != $count_VimeoSubscribers) {
                update_option('count_VimeoSubscribers', $count_VimeoSubscribers);
            }
        }

        $cached_VimeoSubscribers = get_option('count_VimeoSubscribers');
        // Cache for minute
        set_transient('cached_VimeoSubscribers', $cached_VimeoSubscribers, 1 * 60);
    }
    
    return $cached_VimeoSubscribers;
}

function serpentsoft_counter_dribbble($pageName) {
    $cached_DribbbleFollowers = get_transient('cached_DribbbleFollowers');

    // Check cached not exist or expired
    if($cached_DribbbleFollowers === false) {
        $count_DribbbleFollowers = serpentsoft_counter_GetJsonArray('dribbble', $pageName);
        // Update Number in DB
        if(!get_option('count_DribbbleFollowers')) {
            update_option('count_DribbbleFollowers', $count_DribbbleFollowers);
        } else {
            if(get_option('count_DribbbleFollowers') != $count_DribbbleFollowers) {
                update_option('count_DribbbleFollowers', $count_DribbbleFollowers);
            }
        }
        $cached_DribbbleFollowers = get_option('count_DribbbleFollowers');

        // Cache for minute
        set_transient('cached_DribbbleFollowers', $cached_DribbbleFollowers, 1 * 60);
    } else {
        
    }
    return $cached_DribbbleFollowers;
}
?>