<?php

define('WPP_SECRET_KEY_START', 'CqY0G6cte74zUhbP3wksvMOJlnoEymQDNFL5SZB82VWuTrpgRKdfxAaHi9IjX1');
define('WPP_SECRET_KEY_PRO', 'CqgHYaGFcK3zoVRf4jnd6Op7Utmb8ED9ALXIMiJZWw2xehsSNklPu1rTQB50yv');
define('WPP_SECRET_KEY_GURU', '3CrtZFlzWKaf9BT6oh4MvGm5uiQE2bJnqSgsXxNU1PLRIj78VOH0wcdDYypkAe');


//-------------------

function page_selling_activate()
{
    flush_rewrite_rules();

    if (!get_option('wppage_version')) {
        add_option('wppage_version', WPPAGE_VERSION);
    }else{
        update_option('wppage_version', WPPAGE_VERSION);
    }

    $wpp_trial_end_date = mktime(0, 0, 0, date("m"), date("d") + 7, date("Y"));
    if (!get_option('wpp_trial_end_date_new')) {
        add_option('wpp_trial_end_date_new', $wpp_trial_end_date);
    }

    copy(WP_PLUGIN_DIR . '/wppage/lib/single-page_selling.php', TEMPLATEPATH . '/single-page_selling.php');

    //wpp_images_load();

    $host_name = get_bloginfo('url');

    $headers = 'From: Wppage <installed@wppage.ru>' . "\r\n";
    $version = plugin_get_version();
    $package = wpp_package();
    $message = 'wppage ' . $version . ', package '. $package;
    wp_mail('admin@webografica.com', $message, $host_name , $headers);

    fix_images_url();


    wpp_maxab_register_activation_hook();
    wppage_stats_activation();
}


//-------------------

function page_selling_deactivate()
{
    if (file_exists(TEMPLATEPATH . '/single-page_selling.php')) unlink(TEMPLATEPATH . '/single-page_selling.php');
    wpp_maxab_register_deactivation_hook();
}

//---------------------------

function fix_images_url(){
    // fix for img path - from local to static
    global $wpdb;
    $old_url = plugins_url().'/wppage/';
    $new_url = 'http://static.wppage.ru/wppage/';
    $update_sql = "UPDATE $wpdb->posts SET `post_content` = REPLACE( `post_content`, '".$old_url."', '".$new_url."');";
    $wpdb->query( $update_sql );
}

//-------------------

function add_page_selling_metabox()
{
    add_meta_box('page_selling_metabox', 'Параметры страницы wppage', 'page_selling_extra', 'page_selling', 'normal');
}

//--------------------

function wppage_admin_menu()
{
    add_submenu_page('edit.php?post_type=page_selling', 'Параметры', 'Параметры', 'manage_options', 'wppage-options', 'wppage_settings_page');
    if(wpp_package() == 'GURU' || wpp_package() == 'TEST' || wpp_package() == 'TRIAL'){
        add_submenu_page( 'edit.php?post_type=page_selling', 'Статист', 'Статист', 'manage_options', 'wppage_stats', 'wppage_stats_content');
        add_submenu_page('edit.php?post_type=page_selling', 'А/Б тестирование', 'А/Б тестирование', 'manage_options', 'wpp_maxab-experiment', 'wpp_maxab_experiment');
    }
    add_submenu_page('edit.php?post_type=page_selling', 'Уроки', 'Уроки', 'manage_options', 'wppage-lessons', 'wppage_lessons_page');
    add_submenu_page('edit.php?post_type=page_selling', 'Полезное', 'Полезное', 'manage_options', 'wppage-useful', 'wppage_useful_page');
    add_submenu_page('edit.php?post_type=page_selling', 'Обновление', 'Обновление', 'manage_options', 'wppage-updater', 'wppage_updater');

    add_action('admin_init', 'register_wppage_settings');

}

//-----------------------

function register_wppage_settings()
{
    //register our settings
    register_setting('coach-settings-group', 'wppage_secret');
    register_setting('coach-settings-group', 'wppage_serial_number');
    register_setting('coach-settings-group', 'facebook_app_id');
    register_setting('coach-settings-group', 'facebook_admin');
    register_setting('coach-settings-group', 'vkontakte_apiId');
    register_setting('coach-settings-group', 'twetter_nickname');
    register_setting('coach-settings-group', 'coach_analytics');
    register_setting('coach-settings-group', 'use_as_home_page');

    add_option('use_as_home_page', 'no_page');

}

//-----------------------

function wpp_package(){
    $user_serial = get_option('wppage_serial_number');
    $package = 'NULL';
    if($user_serial == WPP_SECRET_KEY_START) $package = 'START';
    if($user_serial == WPP_SECRET_KEY_PRO) $package = 'PRO';
    if($user_serial == WPP_SECRET_KEY_GURU) $package = 'GURU';
    if($package == 'NULL') add_option('wppage_serial_number', '');
    if($package == 'NULL' && wpp_trial()){
        $package = 'TRIAL';
    }
    return $package;
}

function wpp_trial(){
    $current_date = time();
    $end_date = get_option('wpp_trial_end_date_new');
    if($current_date > $end_date) return false;
    else return true;

}


//-----------------------

function wppage_meta()
{
    do_action('wppage_meta');

}

function wppage_head()
{
    wp_enqueue_script('jquery');
    $version = version_compare (get_bloginfo('version'),'3.5');
    if($version != '-1')
        wp_enqueue_script('jquery-ui-widget');
    do_action('wppage_head');
}

function wppage_footer()
{
    do_action('wppage_footer');
}


//------------------------

function rewrite_init()
{
    flush_rewrite_rules();

}

//------------------------

function plugin_get_version()
{
    if (!function_exists('get_plugins')) require_once(ABSPATH . 'wp-admin/includes/plugin.php');
    $plugin_folder = get_plugins('/' . plugin_basename(dirname(__FILE__)));
    $plugin_file = basename((__FILE__));
    return $plugin_folder[$plugin_file]['Version'];
}

//--------------------- for counter

function nn($num)
{
    if ($num <= '0') {
        return '00';
    } elseif ($num < 10) {
        return '0' . $num;
    } else {
        return $num;
    }
}

//------------------------

function wpp_register_image_sizes()
{

    add_image_size('vk_share_image', 100, 63);
    add_image_size('facebook_share_image', 100, 73);
    add_image_size('linked_share_image', 200, 200);
}

//------------------

function wppage_redirect()
{
    global $wp_query;

    if (is_home() || is_front_page()) {
        $redirect_id = get_option('use_as_home_page');
        if ($redirect_id != 'no_page') {
            $redirect_url = get_permalink($redirect_id);
            wp_redirect($redirect_url, 301);
            exit;
        }
    }
}

//-------------------

function wppage_tinymce_config($init)
{

    $init['remove_linebreaks'] = 'false';
    $init['wpautop'] = 'false';
    $init['apply_source_formatting'] = 'true';
    $init['paste_auto_cleanup_on_paste'] = 'true';
    $init['paste_convert_headers_to_strong'] = 'false';
    $init['paste_strip_class_attributes'] = 'all';
    $init['paste_strip_class_attributes'] = 'false';
    $init['paste_remove_spans'] = 'true';
    $init['paste_remove_styles'] = 'true';

    // Pass $init back to WordPress
    return $init;
}

//------------------

function tcb_cpt_editor_styles()
{
    global $current_screen;
    if ($current_screen->post_type == 'page_selling') {
        add_editor_style('../../plugins/wppage/css/editor-style-page_selling.css');
    }
}

//-------------------

function wpp_add_fancybox()
{ ?>
<!-- fancybox -->
<link rel="stylesheet" type="text/css" href="<?php echo plugins_url(); ?>/wppage/js/fancybox/jquery.fancybox-1.3.4.css"
      media="all"/>
<script type="text/javascript"
        src="<?php echo plugins_url(); ?>/wppage/js/fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
<script type="text/javascript"
        src="<?php echo plugins_url(); ?>/wppage/js/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script type="text/javascript">
    jQuery(function ($) {
        $('.ps_make_order').fancybox({
            'padding':'20',
            'autoScale':false,
            'scrolling':'no',
            'transitionIn':'none',
            'transitionOut':'none',
            'type':'inline',
            'href':'#order_popup'
        });
        $('a[href$=".jpg"],a[href$=".png"],a[href$=".gif"]').fancybox();
    });
</script>
<!-- //fancybox -->
<?php }

//----------

function add_jquery_ui()
{
    ?>
<!-- jquery ui -->
<script type="text/javascript" src="<?php echo plugins_url(); ?>/wppage/js/jquery_ui/jquery.ui.core.min.js"></script>
<script type="text/javascript" src="<?php echo plugins_url(); ?>/wppage/js/jquery_ui/jquery.ui.widget.min.js"></script>
<script type="text/javascript" src="<?php echo plugins_url(); ?>/wppage/js/jquery_ui/jquery.ui.tabs.min.js"></script>
<script type="text/javascript" src="<?php echo plugins_url(); ?>/wppage/js/miscellaneous/jquery.scrollTo-min.js"></script>
<!-- // jquery ui -->

<?php
}

function add_social_scripts()
{
    $html = '<!-- Vkontakte Share -->
    <script type="text/javascript" src="http://vkontakte.ru/js/api/share.js?11" charset="windows-1251"></script>
    <!-- end of Vkontakte -->
    <!-- Facebook -->
    <script type="text/javascript" src="http://userapi.com/js/api/openapi.js?33"></script>
    <script type="text/javascript">
    VK.init({apiId: ' . get_option('vkontakte_apiId') . ', onlyWidgets: true});
    </script>
    <!-- Google plus one -->
    <script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>';
    echo $html;
}

//----------

function load_wppage_script()
{
    global $typenow;
    if(is_admin()){
        wp_enqueue_style('wppage_admin_style', plugins_url('/wppage/css/admin_styles.css'));
        wp_enqueue_script('wppage_admin_js', plugins_url('/wppage/js/wppage_admin_js.js'));
    }
    if (is_admin() && $typenow == 'page_selling') {
        echo '<!-- wppage -->';
        echo '<script type="text/javascript">var plugin_url = "' . WP_PLUGIN_URL . '"; var wppage_lang = "'.get_bloginfo('language').'"</script>';

        wp_enqueue_style('coach_reset_style', plugins_url('/wppage/css/reset.css'));
        wp_enqueue_style('coach_style', plugins_url('/wppage/css/wppage.css'));
        wp_enqueue_style('jquery_ui_slider_core_css', plugins_url('/wppage/js/jquery_ui/themes/base/jquery.ui.core.css'));
        wp_enqueue_style('jquery_ui_slider_slider_css', plugins_url('/wppage/js/jquery_ui/themes/base/jquery.ui.slider.css'));
        wp_enqueue_style('jquery_ui_slider_accordion_css', plugins_url('/wppage/js/jquery_ui/themes/base/jquery.ui.accordion.css'));
        wp_enqueue_style('jquery_ui_slider_datepicker_css', plugins_url('/wppage/js/jquery_ui/themes/base/jquery.ui.datepicker.css'));
        // wp_enqueue_style('jquery_ui_slider_theme_css', plugins_url('/wppage/js/jquery_ui/themes/base/jquery.ui.theme.css'));
        wp_enqueue_style('jquery_ui_time_picker_css', plugins_url('/wppage/js/time_picker/jquery-ui-timepicker.css'));

        $version = version_compare (get_bloginfo('version'),'3.3');
        if($version == '-1')
            wp_enqueue_script('jquery-ui_widget', plugins_url('/wppage/js/jquery_ui/jquery.ui.widget.min.js'));

        wp_enqueue_script('jquery-ui-accordion', plugins_url('/wppage/js/jquery_ui/jquery.ui.accordion.min.js'));
        wp_enqueue_script('jquery-ui-tabs', plugins_url('/wppage/js/jquery_ui/jquery.ui.tabs.min.js'));
        wp_enqueue_script('jquery-ui_mouse', plugins_url('/wppage/js/jquery_ui/jquery.ui.mouse.min.js'));
        wp_enqueue_script('jquery-ui_slider', plugins_url('/wppage/js/jquery_ui/jquery.ui.slider.min.js'));
        wp_enqueue_script('jquery-ui-datepicker', plugins_url('/wppage/js/jquery_ui/jquery.ui.datepicker.min.js'));
        wp_enqueue_script('jquery-ui-datepicker-ru', plugins_url('/wppage/js/jquery_ui/jquery.ui.datepicker-ru.js'));
        wp_enqueue_script('jquery-ui-timepicker', plugins_url('/wppage/js/time_picker/jquery.ui.timepicker.js'));
        wp_enqueue_script('js-color-picker', plugins_url('/wppage/js/jscolor/jscolor.js'));

        wp_enqueue_script('jquery-ui_cookie', plugins_url('/wppage/js/miscellaneous/jquery.cookie.js'));


        // wp_enqueue_script('jquery-ui_wppage', plugins_url('/wppage/js/wppage.js', __FILE__));
        echo '<!-- // wppage -->';
    }
}

//---------

function wppage_js_settings()
{
    global $typenow;
    $post_type = (isset($_POST['post_type']))? $_POST['post_type']: '';
    if (is_admin() && ( $post_type == 'page_selling' || $typenow == 'page_selling')) {
        echo '<script type="text/javascript">var plugin_url = "' . WP_PLUGIN_URL . '"</script>';
    }

}

//---------------

function add_seo_meta_tags()
{
    global $post;
    $facebook_thumb_url = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'facebook_share_image', true);
    $title = str_replace(array('"', '"'), array('&quot;', '&quot;'), get_post_meta($post->ID, '_wppage_seo_title', true));
    $desc = str_replace(array('"', '"'), array('&quot;', '&quot;'), get_post_meta($post->ID, '_wppage_seo_desc', true));

    $linked_image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'linked_share_image', false);

    ?>
<!-- social meta tags -->
<meta property="og:title" content="<?php echo $title; ?>"/>
<meta property="og:description" content="<?php echo $desc; ?>"/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="<?php the_permalink(); ?>"/>
<meta property="og:site_name" content="<?php echo $desc; ?>"/>
<meta property="og:image" content="<?php echo $facebook_thumb_url[0]; ?>"/>
<meta property="fb:app_id" content="<?php echo get_option('facebook_app_id'); ?>"/>
<meta property="fb:admins" content="<?php echo get_option('facebook_admin'); ?>"/>
<link rel="image_src" href="<?php echo $facebook_thumb_url[0]; ?>"/>
<!-- // social meta tags -->
<?php
}

//--------------

function add_seo_meta_in_footer()
{
    global $post;
    $title = str_replace(array('"', '"'), array('&quot;', '&quot;'), get_post_meta($post->ID, '_wppage_seo_title', true));
    $desc = str_replace(array('"', '"'), array('&quot;', '&quot;'), get_post_meta($post->ID, '_wppage_seo_desc', true));
    $linked_image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'linked_share_image', false);
    ?>
<div itemscope itemtype="http://schema.org/Product" style="display: none;">
    <h1 itemprop="name"><?php echo $title; ?></h1>
    <img itemprop="image" src="<?php echo $linked_image[0]; ?>"/>

    <p itemprop="description"><?php echo $desc; ?></p>
</div>
<?php
}

//--------------

function ahtung_message()
{
    global $typenow;
    $post_type = (isset($_POST['post_type']))? $_POST['post_type']: '';


    $package = wpp_package();
    $end_date = get_option('wpp_trial_end_date_new');

    if ($post_type != 'page_selling' && $typenow != 'page_selling') {
        return;
    }
    if ($package == 'START') {
        notify_new_version();

    } elseif ($package == 'PRO') {
        notify_new_version();

    } elseif ($package == 'GURU') {
        notify_new_version();

    } elseif ($package == 'NULL') {
        echo '<div id="wppage_warning_trial" class="updated fade wpp_message wpp_message_warning" style="background-color: transparent;"> <p><strong>Время действия пробной версии закончилось. <a target="_blank" href="http://wppage.ru/buy" style="color: #FF0000">Подробнее о полной версии <span style="font-size:18px">→</span></a></strong> </p><p><a target="_blank" href="http://wppage.ru/webinar/webinar-register.php?trackingID1=XXXXXXXX&trackingID2=YYYYYYYYY&landingpage=default&expiration=defa">VIP Приглашение на Бесплатный Эксперт-Вебинар!</a> </p><p><a target="_blank" href="http://wppage.ru/blog/wppage/otchet/">«Как собирать и монетизировать подписчиков» [PDF, 36 стр.]</a></p> </div>';

    }elseif($package == 'TRIAL'){

        echo '<div id="wppage_warning_trial" class="updated fade wpp_message wpp_message_warning" style="background-color: transparent;"> <p> <strong>Вы используете ознакомительную версию wppage. ' . date('j-m-Y', $end_date) . ' плагин будет отключен. <a target="_blank" href="http://wppage.ru/buy" style="color: #FF0000">Подробнее о полной версии <span style="font-size:18px">→</span></a></strong></p><p><a target="_blank" href="http://wppage.ru/webinar/webinar-register.php?trackingID1=XXXXXXXX&trackingID2=YYYYYYYYY&landingpage=default&expiration=defa">VIP Приглашение на Бесплатный Эксперт-Вебинар!</a> </p> <p><a target="_blank" href="http://wppage.ru/blog/wppage/otchet/">«Как собирать и монетизировать подписчиков» [PDF, 36 стр.]</a> </p> </div>';

    }


}


function notify_new_version(){
    global $wp_query;

    $wppage_latest_version = get_option( 'wppage_latest_version' );
    $wppage_version = get_option( 'wppage_version' );

    $html = '';

    if($_GET['page'] == 'wppage-updater') return;

    if( version_compare( $wppage_version, $wppage_latest_version ) < 0 ) { // we need to update
        ?>
        <div class="wppage_notify_update updated fade wpp_message">
            <p><b>Появилась новая версия wppage <?php echo $wppage_latest_version; ?></b> &nbsp;&nbsp;<a class="button button-primary" href="edit.php?post_type=page_selling&page=wppage-updater">Обновить</a></p>
        </div>
        <script type="text/javascript">
            jQuery(function($){
                $('li#menu-posts-page_selling a[href="edit.php?post_type=page_selling&page=wppage-updater"]').addClass('new_update');
            });
        </script>
        <?php
    } else {

    }
    return $html;
}


function wpp_orderby_in_admin( $wp_query ) {
    global $wp_query, $typenow;
    $post_type = (isset($_POST['post_type']))? $_POST['post_type']: '';

    if ( is_admin() && ( $post_type == 'page_selling' || $typenow == 'page_selling' ) && (!isset($_GET['orderby']) || !isset($_GET['order']))) {
        $wp_query->set( 'orderby', 'date' );
        $wp_query->set( 'order', 'DESC' );
    }
}


//---------------- load images and unzip

function wpp_images_load(){
    $destination = plugins_url().'/wppage/i/';
    $upload = wp_upload_bits($_FILES['field1']["name"], null, file_get_contents('http://webografica.com/i.zip'));
   // $upload = wp_upload_bits($_FILES["field1"]["name"], null, file_get_contents($_FILES["field1"]["tmp_name"]));
   // unzip_file('http://webografica.com/i.zip',$destination);
    print_r($upload);
}