<?php

define( 'CS_NOTIFIER_PLUGIN_NAME', 'Cloud Slider' );
define( 'CS_NOTIFIER_PLUGIN_SHORT_NAME', 'Cloud Slider' );
define( 'CS_NOTIFIER_PLUGIN_FOLDER_NAME', 'cloudslider' );
define( 'CS_NOTIFIER_PLUGIN_FILE_NAME', 'cloudslider.php' );
define( 'CS_NOTIFIER_PLUGIN_DOWNLOAD_PATH', "http://webuddysoft.com/cslider/update/" );
define( 'CS_NOTIFIER_PLUGIN_XML_FILE', "http://webuddysoft.com/cslider/update/notifier.xml" );
define( 'CS_PLUGIN_NOTIFIER_CACHE_INTERVAL', 21600 );

/* Adds an update notification to the WordPress Dashboard menu 
function cs_update_plugin_notifier_menu() {
$plugin_data;
if ( function_exists( 'simplexml_load_string' ) ) {
$xml = cs_get_latest_plugin_version( CS_PLUGIN_NOTIFIER_CACHE_INTERVAL );
if(is_admin())
$plugin_data = get_plugin_data( WP_PLUGIN_DIR . '/' . CS_NOTIFIER_PLUGIN_FOLDER_NAME . '/' . CS_NOTIFIER_PLUGIN_FILE_NAME );

if(isset($plugin_data['Version'])){
if ( (string) $xml->latest > (string) $plugin_data['Version'] ) {
if ( defined( 'CS_NOTIFIER_PLUGIN_SHORT_NAME' ) ) {
$menu_name = CS_NOTIFIER_PLUGIN_SHORT_NAME;
} else {
$menu_name = CS_NOTIFIER_PLUGIN_NAME;
}
add_dashboard_page( CS_NOTIFIER_PLUGIN_NAME . ' Plugin Updates', $menu_name . ' <span class="update-plugins count-1"><span class="update-count">New Updates</span></span>', 'administrator',get_admin_url().'update-core.php', 'cs_update_notifier');
}
}
}
}
add_action('admin_menu', 'cs_update_plugin_notifier_menu');

/* Adds an update notification to the WordPress 3.1+ Admin Bar 
function cs_update_notifier_bar_menu() {
$plugin_data;
if ( function_exists( 'simplexml_load_string' ) ) {
global $wp_admin_bar, $wpdb;

if ( ! is_super_admin() || ! is_admin_bar_showing() )
return;

$xml         = cs_get_latest_plugin_version( CS_PLUGIN_NOTIFIER_CACHE_INTERVAL );
if(is_admin())
$plugin_data     = get_plugin_data( WP_PLUGIN_DIR . '/' . CS_NOTIFIER_PLUGIN_FOLDER_NAME . '/' .CS_NOTIFIER_PLUGIN_FILE_NAME );

if(isset($plugin_data['Version'])){
if( (string) $xml->latest > (string) $plugin_data['Version'] ) {
$wp_admin_bar->add_menu( array( 'id' => 'plugin_update_notifier', 'title' => '<span>' . CS_NOTIFIER_PLUGIN_NAME . ' <span id="ab-updates">New Updates</span></span>', 'href' => get_admin_url() . 'update-core.php' ) );            }
}
}
}
add_action( 'admin_bar_menu', 'cs_update_notifier_bar_menu', 1000 );*/

/* Get the remote XML file contents and return its data (Version and Changelog) */
function cs_get_latest_plugin_version( $interval ) {
    $notifier_file_url = CS_NOTIFIER_PLUGIN_XML_FILE;
    $db_cache_field = 'cs-notifier-cache';
    $db_cache_field_last_updated = 'cs-notifier-cache-last-updated';
    $last = get_option( $db_cache_field_last_updated );
    $now = time();
    if ( ! $last || ( ( $now - $last ) > $interval ) ) {
        $response = wp_remote_post( $notifier_file_url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => array(),        
        'cookies' => array()
        )
        );
        if( is_wp_error( $response ) ){
            $cache = file_get_contents( $notifier_file_url );
        }else{
            $cache = $response['body']; 
        }        

        if ( $cache ) {
            update_option( $db_cache_field, $cache );
            update_option( $db_cache_field_last_updated, time() );
        }
        $notifier_data = get_option( $db_cache_field );
    }
    else {
        $notifier_data = get_option( $db_cache_field );
    }

    if( strpos( (string) $notifier_data, '<notifier>' ) === false ) {
        $notifier_data = '<?xml version="1.0" encoding="UTF-8"?><notifier><latest>1.0</latest><changelog></changelog></notifier>';
    }

    $xml = simplexml_load_string( $notifier_data );
    return $xml;
}

/* auto update cloud slider */
$plugin_file_name = CS_NOTIFIER_PLUGIN_FOLDER_NAME."/".CS_NOTIFIER_PLUGIN_FILE_NAME;

/* check for version if update available then add plugin info to transient for update */
add_filter('pre_set_site_transient_update_plugins', 'cs_check_update');
function cs_check_update($checked_data){
    if ( empty( $checked_data->checked ) ) {
        return $checked_data;
    }

    $request = wp_remote_post(CS_NOTIFIER_PLUGIN_DOWNLOAD_PATH, array('body' => array('action' => 'version')));
    $plugin_file_name = CS_NOTIFIER_PLUGIN_FOLDER_NAME."/".CS_NOTIFIER_PLUGIN_FILE_NAME;

    if (!is_wp_error($request) && $request['response']['code'] == 200) {
        $response = $request['body'];
        if (version_compare(CS_PLUGIN_VERSION, $response, '<')) {
            $obj = new stdClass();
            $t = explode('/', $plugin_file_name);
            $slug = str_replace('.php', '', $t[1]);
            $obj->slug = $slug;
            $obj->plugin = $plugin_file_name;
            $obj->new_version = $response;
            $obj->url = 'http://codecanyon.net/item/cloud-slider-responsive-wordpress-slider/11270213';
            $obj->package = '';
            $checked_data->response[$plugin_file_name] = $obj;
            return $checked_data;
        }
    }
}

/* update change log info in plugin data */
add_filter('plugins_api', 'cs_check_information', 10, 3);
function cs_check_information($false, $action, $arg)
{
    if (isset($arg->slug) && $arg->slug === CS_NOTIFIER_PLUGIN_FOLDER_NAME) {
        $req= wp_remote_post(CS_NOTIFIER_PLUGIN_DOWNLOAD_PATH.'?'.(time()), array('body' => array('action' => 'plugin_information')));
        if (!is_wp_error($req) || wp_remote_retrieve_response_code($req) === 200) {
            $response = unserialize($req['body']);
        }
        $pattern = array(
        '/^([\*\s])*(\d\d\.\d\d\.\d\d\d\d[^\n]*)/m',
        '/^\n+|^[\t\s]*\n+/m',
        '/\n/',
        );
        $replace = array(
        '<h4>$2</h4>',
        '</div><div>',
        '</div><div>'
        );
        $response->sections['changelog'] = '<div>'.preg_replace($pattern, $replace, $response->sections['changelog']).'</div>';
        return $response;
    }
    return false;
}

/* if update available then check apikey/username/purchasecode if correct then display for auto update */
add_filter('in_plugin_update_message-'.$plugin_file_name, 'addUpgradeMessageLink');
function addUpgradeMessageLink(){
    $username = get_option('cs_envato_username','');
    $api_key =  get_option('cs_envato_api_key','');
    $purchase_code =  get_option('cs_code','');
    $downloadURL='http://codecanyon.net/downloads';
    $networkURL='options-general.php?page=cloud-slider-list&cs_action=upgrade_cs_plugin';
    if(empty($username) || empty($api_key) || empty($purchase_code)) {
        echo ' <a href="'.$downloadURL.'">'.__('Download new version', 'CloudSlider').'</a> from CodeCanyon.';
    } else {
        echo ' <a href="'.wp_nonce_url( network_admin_url($networkURL)).'">'.__('update now', 'CloudSlider').'</a> from CodeCanyon.';
    }
}