<?php
defined( 'ABSPATH' ) or die( 'Please don&rsquo;t call the plugin directly. Thanks :)' );
///////////////////////////////////////////////////////////////////////////////////////////////////
//Admin Columns PRO
///////////////////////////////////////////////////////////////////////////////////////////////////
if ( is_plugin_active( 'admin-columns-pro/admin-columns-pro.php' )) {
    add_action( 'ac/column_types', 'ac_register_column_sp_title' );
    function ac_register_column_sp_title( AC_ListScreen $list_screen ) {
        if ( 'post' === $list_screen->get_group() ) {
            require_once plugin_dir_path( __FILE__ ) . 'admin-columns/ac-column-sp_title.php';
            $list_screen->register_column_type( new AC_Column_sp_title );
        }
    }

    add_action( 'ac/column_types', 'ac_register_pro_column_sp_title' );
    function ac_register_pro_column_sp_title( AC_ListScreen $list_screen ) {
        if ( 'post' === $list_screen->get_group() ) {
            require_once plugin_dir_path( __FILE__ ) . 'admin-columns/ac-column-sp_title.php';
            require_once plugin_dir_path( __FILE__ ) . 'admin-columns/acp-column-sp_title.php';
            $list_screen->register_column_type( new ACP_Column_sp_title );
        }
    }

    add_action( 'ac/column_types', 'ac_register_column_sp_desc' );
    function ac_register_column_sp_desc( AC_ListScreen $list_screen ) {
        if ( 'post' === $list_screen->get_group() ) {
            require_once plugin_dir_path( __FILE__ ) . 'admin-columns/ac-column-sp_desc.php';
            $list_screen->register_column_type( new AC_Column_sp_desc );
        }
    }

    add_action( 'ac/column_types', 'ac_register_pro_column_sp_desc' );
    function ac_register_pro_column_sp_desc( AC_ListScreen $list_screen ) {
        if ( 'post' === $list_screen->get_group() ) {
            require_once plugin_dir_path( __FILE__ ) . 'admin-columns/ac-column-sp_desc.php';
            require_once plugin_dir_path( __FILE__ ) . 'admin-columns/acp-column-sp_desc.php';
            $list_screen->register_column_type( new ACP_Column_sp_desc );
        }
    }

    add_action( 'ac/column_types', 'ac_register_column_sp_noindex' );
    function ac_register_column_sp_noindex( AC_ListScreen $list_screen ) {
        if ( 'post' === $list_screen->get_group() ) {
            require_once plugin_dir_path( __FILE__ ) . 'admin-columns/ac-column-sp_noindex.php';
            $list_screen->register_column_type( new AC_Column_sp_noindex );
        }
    }

    add_action( 'ac/column_types', 'ac_register_pro_column_sp_noindex' );
    function ac_register_pro_column_sp_noindex( AC_ListScreen $list_screen ) {
        if ( 'post' === $list_screen->get_group() ) {
            require_once plugin_dir_path( __FILE__ ) . 'admin-columns/ac-column-sp_noindex.php';
            require_once plugin_dir_path( __FILE__ ) . 'admin-columns/acp-column-sp_noindex.php';
            $list_screen->register_column_type( new ACP_Column_sp_noindex );
        }
    }

    add_action( 'ac/column_types', 'ac_register_column_sp_nofollow' );
    function ac_register_column_sp_nofollow( AC_ListScreen $list_screen ) {
        if ( 'post' === $list_screen->get_group() ) {
            require_once plugin_dir_path( __FILE__ ) . 'admin-columns/ac-column-sp_nofollow.php';
            $list_screen->register_column_type( new AC_Column_sp_nofollow );
        }
    }

    add_action( 'ac/column_types', 'ac_register_pro_column_sp_nofollow' );
    function ac_register_pro_column_sp_nofollow( AC_ListScreen $list_screen ) {
        if ( 'post' === $list_screen->get_group() ) {
            require_once plugin_dir_path( __FILE__ ) . 'admin-columns/ac-column-sp_nofollow.php';
            require_once plugin_dir_path( __FILE__ ) . 'admin-columns/acp-column-sp_nofollow.php';
            $list_screen->register_column_type( new ACP_Column_sp_nofollow );
        }
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
//Request Alexa Rank
///////////////////////////////////////////////////////////////////////////////////////////////////
function seopress_request_alexa_rank() {
    check_ajax_referer( 'seopress_request_alexa_rank_nonce', $_GET['_ajax_nonce'], true );

    delete_transient( 'seopress_results_alexa_rank');
    if ( false === ( $seopress_results_alexa_rank_cache = get_transient( 'seopress_results_alexa_rank' ) ) ) {
        $response = wp_remote_get('https://data.alexa.com/data?cli=10&url='.get_home_url());

        if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {

            $response_body = __( 'An error occurred, please try again.', 'wp-seopress-pro' );
            
        } else {
            $response_body = wp_remote_retrieve_body($response);
        }

        $seopress_results_alexa_rank_cache = $response_body;
        set_transient( 'seopress_results_alexa_rank', $seopress_results_alexa_rank_cache, 365 * DAY_IN_SECONDS );
    }
    wp_send_json_success($data);
}
add_action('wp_ajax_seopress_request_alexa_rank', 'seopress_request_alexa_rank');

///////////////////////////////////////////////////////////////////////////////////////////////////
//Request Reverse domains
///////////////////////////////////////////////////////////////////////////////////////////////////
function seopress_request_reverse() {
    check_ajax_referer( 'seopress_request_reverse_nonce', $_GET['_ajax_nonce'], true );

    delete_transient('seopress_results_reverse');
    if ( false === ( $seopress_results_reverse_cache = get_transient( 'seopress_results_reverse' ) ) ) {
        $clean_url = str_replace( array('http://', 'https://'), "", ''.get_home_url() ); 
        
        $response = wp_remote_post('https://domains.yougetsignal.com/domains.php?remoteAddress='.$clean_url);

        if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {

            $response_body = __( 'An error occurred, please try again.', 'wp-seopress-pro' );
            
        } else {
            $response_body = wp_remote_retrieve_body($response);
        }
        
        $seopress_results_reverse_cache = $response_body;
        set_transient( 'seopress_results_reverse', $seopress_results_reverse_cache, 365 * DAY_IN_SECONDS );
    }
    wp_send_json_success($data);
}
add_action('wp_ajax_seopress_request_reverse', 'seopress_request_reverse');

///////////////////////////////////////////////////////////////////////////////////////////////////
//Request Google Page Speed
///////////////////////////////////////////////////////////////////////////////////////////////////
function seopress_request_page_speed() {
    check_ajax_referer( 'seopress_request_page_speed_nonce', $_GET['_ajax_nonce'], true );

    $seopress_google_api_key = 'AIzaSyBqvSx2QrqbEqZovzKX8znGpTosw7KClHQ';
    
    if ( isset( $_GET['data_permalink'] ) ) {
        $seopress_get_site_url = $_GET['data_permalink'];
        delete_transient( 'seopress_results_page_speed');
    } else {
        $seopress_get_site_url = get_home_url();
    }

    $args = array('timeout' => 30);

    if ( false === ( $seopress_results_page_speed_cache = get_transient( 'seopress_results_page_speed' ) ) ) {
       $seopress_results_page_speed = wp_remote_retrieve_body(wp_remote_get('https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url='.$seopress_get_site_url.'&key='.$seopress_google_api_key.'&screenshot=true&strategy=desktop&locale='.get_locale(), $args));
       $seopress_results_page_speed_cache = $seopress_results_page_speed;
       set_transient( 'seopress_results_page_speed', $seopress_results_page_speed_cache, 365 * DAY_IN_SECONDS );
    }
    
    $data = array('url' => admin_url('admin.php?page=seopress-pro-page#tab=tab_seopress_page_speed$3'));
    wp_send_json_success($data);
}
add_action('wp_ajax_seopress_request_page_speed', 'seopress_request_page_speed');

///////////////////////////////////////////////////////////////////////////////////////////////////
//Reset License
///////////////////////////////////////////////////////////////////////////////////////////////////
function seopress_reset_license() {
    check_ajax_referer( 'seopress_request_reset_license_nonce', $_GET['_ajax_nonce'], true );

    delete_option('seopress_pro_license_status');
    delete_option('seopress_pro_license_key');

    $data = array('url' => admin_url('admin.php?page=seopress-license'));
    wp_send_json_success($data);
}
add_action('wp_ajax_seopress_reset_license', 'seopress_reset_license');

///////////////////////////////////////////////////////////////////////////////////////////////////
//Lock Google Analytics view
///////////////////////////////////////////////////////////////////////////////////////////////////
function seopress_google_analytics_lock() {
    check_ajax_referer( 'seopress_google_analytics_lock_nonce', $_POST['_ajax_nonce'], true );

    update_option('seopress_google_analytics_lock_option_name', '1', 'yes');
    
    wp_send_json_success();
}
add_action('wp_ajax_seopress_google_analytics_lock', 'seopress_google_analytics_lock');

///////////////////////////////////////////////////////////////////////////////////////////////////
//Request Google Analytics
///////////////////////////////////////////////////////////////////////////////////////////////////
function seopress_request_google_analytics() {
    check_ajax_referer( 'seopress_request_google_analytics_nonce', $_GET['_ajax_nonce'], true );

    function seopress_google_analytics_auth_option() {
        $seopress_google_analytics_auth_option = get_option("seopress_google_analytics_option_name");
        if ( ! empty ( $seopress_google_analytics_auth_option ) ) {
            foreach ($seopress_google_analytics_auth_option as $key => $seopress_google_analytics_auth_value)
                $options[$key] = $seopress_google_analytics_auth_value;
             if (isset($seopress_google_analytics_auth_option['seopress_google_analytics_auth'])) { 
                return $seopress_google_analytics_auth_option['seopress_google_analytics_auth'];
             }
        }
    }

    function seopress_google_analytics_auth_client_id_option() {
        $seopress_google_analytics_auth_client_id_option = get_option("seopress_google_analytics_option_name");
        if ( ! empty ( $seopress_google_analytics_auth_client_id_option ) ) {
            foreach ($seopress_google_analytics_auth_client_id_option as $key => $seopress_google_analytics_auth_client_id_value)
                $options[$key] = $seopress_google_analytics_auth_client_id_value;
             if (isset($seopress_google_analytics_auth_client_id_option['seopress_google_analytics_auth_client_id'])) { 
                return $seopress_google_analytics_auth_client_id_option['seopress_google_analytics_auth_client_id'];
             }
        }
    }

    function seopress_google_analytics_auth_secret_id_option() {
        $seopress_google_analytics_auth_secret_id_option = get_option("seopress_google_analytics_option_name");
        if ( ! empty ( $seopress_google_analytics_auth_secret_id_option ) ) {
            foreach ($seopress_google_analytics_auth_secret_id_option as $key => $seopress_google_analytics_auth_secret_id_value)
                $options[$key] = $seopress_google_analytics_auth_secret_id_value;
             if (isset($seopress_google_analytics_auth_secret_id_option['seopress_google_analytics_auth_secret_id'])) { 
                return $seopress_google_analytics_auth_secret_id_option['seopress_google_analytics_auth_secret_id'];
             }
        }
    }
    
    function seopress_google_analytics_auth_token_option() {
        $seopress_google_analytics_auth_token_option = get_option("seopress_google_analytics_option_name1");
        if ( ! empty ( $seopress_google_analytics_auth_token_option ) ) {
            foreach ($seopress_google_analytics_auth_token_option as $key => $seopress_google_analytics_auth_token_value)
                $options[$key] = $seopress_google_analytics_auth_token_value;
                if (isset($seopress_google_analytics_auth_token_option['access_token'])) {
                    return $seopress_google_analytics_auth_token_option['access_token'];
                }
        }
    }
    
    function seopress_google_analytics_refresh_token_option() {
        $seopress_google_analytics_refresh_token_option = get_option("seopress_google_analytics_option_name1");
        if ( ! empty ( $seopress_google_analytics_refresh_token_option ) ) {
            foreach ($seopress_google_analytics_refresh_token_option as $key => $seopress_google_analytics_refresh_token_value)
                $options[$key] = $seopress_google_analytics_refresh_token_value;
                if (isset($seopress_google_analytics_refresh_token_option['refresh_token'])) {
                    return $seopress_google_analytics_refresh_token_option['refresh_token'];
                }
        }
    }
    
    function seopress_google_analytics_auth_code_option() {
        $seopress_google_analytics_auth_code_option = get_option("seopress_google_analytics_option_name1");
        if ( ! empty ( $seopress_google_analytics_auth_code_option ) ) {
            foreach ($seopress_google_analytics_auth_code_option as $key => $seopress_google_analytics_auth_code_value)
                $options[$key] = $seopress_google_analytics_auth_code_value;
                if (isset($seopress_google_analytics_auth_code_option['code'])) {
                    return $seopress_google_analytics_auth_code_option['code'];
                }
        }
    }
    
    function seopress_google_analytics_debug_option() {
        $seopress_google_analytics_debug_option = get_option("seopress_google_analytics_option_name1");
        if ( ! empty ( $seopress_google_analytics_debug_option ) ) {
            foreach ($seopress_google_analytics_debug_option as $key => $seopress_google_analytics_debug_value)
                $options[$key] = $seopress_google_analytics_debug_value;
                if (isset($seopress_google_analytics_debug_option['debug'])) {
                    return $seopress_google_analytics_debug_option['debug'];
                }
        }
    }

    if (seopress_google_analytics_auth_option() !='' && seopress_google_analytics_auth_token_option() !='') {
    
        require_once __DIR__ . '/../functions/google-analytics/vendor/autoload.php';

        //session_start(); 

        # get saved data
        if( !$widget_options = get_option( 'seopress_ga_dashboard_widget_options' ) )
        $widget_options = array();

        # check if saved data contains content
        $seopress_ga_dashboard_widget_options_period = isset( $widget_options['period'] ) 
            ? $widget_options['period'] : false;

        $seopress_ga_dashboard_widget_options_type = isset( $widget_options['type'] ) 
            ? $widget_options['type'] : false;

        # custom content saved by control callback, modify output
        if( $seopress_ga_dashboard_widget_options_period ) {
            $period = $seopress_ga_dashboard_widget_options_period;
        } else {
            $period = '30daysAgo';
        }

        if (seopress_google_analytics_auth_client_id_option() !='') {
            $client_id = seopress_google_analytics_auth_client_id_option();
        }

        if (seopress_google_analytics_auth_secret_id_option() !='') {
            $client_secret = seopress_google_analytics_auth_secret_id_option();
        }
        
        $ga_account = 'ga:'.seopress_google_analytics_auth_option();
        $redirect_uri = admin_url('admin.php?page=seopress-google-analytics');

        $client = new Google_Client();
        $client->setApplicationName("Client_Library_Examples");
        $client->setClientId($client_id);
        $client->setClientSecret($client_secret);
        $client->setRedirectUri($redirect_uri);
        $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
        $client->setApprovalPrompt('force');   // mandatory to get this fucking refreshtoken
        $client->setAccessType('offline'); // mandatory to get this fucking refreshtoken

        $client->setAccessToken(seopress_google_analytics_debug_option());
                
        if ($client->isAccessTokenExpired()) {
            $client->refreshToken(seopress_google_analytics_debug_option());
            
            $seopress_new_access_token = $client->getAccessToken(seopress_google_analytics_debug_option());

            $seopress_google_analytics_options = get_option('seopress_google_analytics_option_name1');
            $seopress_google_analytics_options['access_token'] = $seopress_new_access_token['access_token'];
            $seopress_google_analytics_options['refresh_token'] = $seopress_new_access_token['refresh_token'];
            $seopress_google_analytics_options['debug'] = $seopress_new_access_token;
            update_option('seopress_google_analytics_option_name1', $seopress_google_analytics_options, 'yes');
        }
        
        $service = new Google_Service_Analytics($client);

        if ( false === ( $seopress_results_google_analytics_cache = get_transient( 'seopress_results_google_analytics' ) ) ) {
            $seopress_results_google_analytics_cache = array();

            //Request Google Stats
            $ga_sessions = $service->data_ga->get($ga_account, $period,'today','ga:sessions', array('dimensions' => 'ga:date', 'sort' => 'ga:date'));
            $ga_users = $service->data_ga->get($ga_account, $period,'today','ga:users', array('dimensions' => 'ga:date', 'sort' => 'ga:date'));
            $ga_pageviews = $service->data_ga->get($ga_account, $period,'today','ga:pageviews', array('dimensions' => 'ga:date', 'sort' => 'ga:date'));
            $ga_pageviewsPerSession = $service->data_ga->get($ga_account, $period,'today','ga:pageviewsPerSession', array('dimensions' => 'ga:date', 'sort' => 'ga:date'));
            $ga_avgSessionDuration = $service->data_ga->get($ga_account, $period,'today','ga:avgSessionDuration', array('dimensions' => 'ga:date', 'sort' => 'ga:date'));
            $ga_bounceRate = $service->data_ga->get($ga_account, $period,'today','ga:bounceRate', array('dimensions' => 'ga:date', 'sort' => 'ga:date'));
            $ga_percentNewSessions = $service->data_ga->get($ga_account, $period,'today','ga:percentNewSessions', array('dimensions' => 'ga:date', 'sort' => 'ga:date'));
            
            //Cache datas
            $seopress_results_google_analytics_cache['sessions']                = $ga_sessions['totalsForAllResults']['ga:sessions'];
            $seopress_results_google_analytics_cache['users']                   = $ga_users['totalsForAllResults']['ga:users'];
            $seopress_results_google_analytics_cache['pageviews']               = $ga_pageviews['totalsForAllResults']['ga:pageviews'];
            $seopress_results_google_analytics_cache['pageviewsPerSession']     = round($ga_pageviewsPerSession['totalsForAllResults']['ga:pageviewsPerSession'], 2);
            $seopress_results_google_analytics_cache['avgSessionDuration']      = gmdate("i:s",$ga_avgSessionDuration['totalsForAllResults']['ga:avgSessionDuration']);
            $seopress_results_google_analytics_cache['bounceRate']              = round($ga_bounceRate['totalsForAllResults']['ga:bounceRate'], 2);
            $seopress_results_google_analytics_cache['percentNewSessions']      = round($ga_percentNewSessions['totalsForAllResults']['ga:percentNewSessions'], 2);
        
            switch ($seopress_ga_dashboard_widget_options_type) {
                case 'ga_sessions':
                    $ga_sessions_rows = $ga_sessions->getRows();
                    $seopress_ga_dashboard_widget_options_title = __('Sessions','wp-seopress-pro');
                    break;
                case 'ga_users':
                    $ga_sessions_rows = $ga_users->getRows();
                    $seopress_ga_dashboard_widget_options_title = __('Users','wp-seopress-pro');
                    break;
                case 'ga_pageviews':
                    $ga_sessions_rows = $ga_pageviews->getRows();
                    $seopress_ga_dashboard_widget_options_title = __('Page Views','wp-seopress-pro');
                    break;
                case 'ga_pageviewsPerSession':
                    $ga_sessions_rows = $ga_pageviewsPerSession->getRows();
                    $seopress_ga_dashboard_widget_options_title = __('Page Views Per Session','wp-seopress-pro');
                    break;
                case 'ga_avgSessionDuration':
                    $ga_sessions_rows = $ga_avgSessionDuration->getRows();
                    $seopress_ga_dashboard_widget_options_title = __('Average Session Duration','wp-seopress-pro');
                    break;
                case 'ga_bounceRate':
                    $ga_sessions_rows = $ga_bounceRate->getRows();
                    $seopress_ga_dashboard_widget_options_title = __('Bounce Rate','wp-seopress-pro');
                    break;
                case 'ga_percentNewSessions':
                    $ga_sessions_rows = $ga_percentNewSessions->getRows();
                    $seopress_ga_dashboard_widget_options_title = __('New Sessions','wp-seopress-pro');
                    break;
                default:
                    $ga_sessions_rows = $ga_sessions->getRows();
                    $seopress_ga_dashboard_widget_options_title = __('Sessions','wp-seopress-pro');
            }

            function seopress_ga_dashboard_get_sessions_labels($ga_sessions_rows){
                $labels = array();
                foreach ($ga_sessions_rows as $key => $value) {
                    foreach ($value as $_key => $_value) {
                        if ($_key == 0) {
                            array_push($labels, date_i18n( get_option( 'date_format' ), strtotime( $_value )));
                        }
                    }
                }
                return $labels;
            }

            function seopress_ga_dashboard_get_sessions_data($ga_sessions_rows){
                $data = array();
                foreach ($ga_sessions_rows as $key => $value) {
                    foreach (array_slice($value, 1) as $_key => $_value) {
                        array_push($data, $_value);
                    }
                }
                return $data;
            }

            $seopress_results_google_analytics_cache['sessions_graph_labels']       = seopress_ga_dashboard_get_sessions_labels($ga_sessions_rows);
            $seopress_results_google_analytics_cache['sessions_graph_data']         = seopress_ga_dashboard_get_sessions_data($ga_sessions_rows);
            $seopress_results_google_analytics_cache['sessions_graph_title']        = $seopress_ga_dashboard_widget_options_title;

            //Transient
            set_transient( 'seopress_results_google_analytics', $seopress_results_google_analytics_cache, 1 * HOUR_IN_SECONDS );
        }

        //Return
        $seopress_results_google_analytics_transient = get_transient('seopress_results_google_analytics');

        wp_send_json_success( $seopress_results_google_analytics_transient );
    }

    die();
}
add_action('wp_ajax_seopress_request_google_analytics', 'seopress_request_google_analytics');

///////////////////////////////////////////////////////////////////////////////////////////////////
//Clear Google Page Speed cache
///////////////////////////////////////////////////////////////////////////////////////////////////
function seopress_clear_page_speed_cache() {
    check_ajax_referer( 'seopress_clear_page_speed_cache_nonce', $_GET['_ajax_nonce'], true );

    global $wpdb;
    
    $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_seopress_results_page_speed' ");
    $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_timeout_seopress_results_page_speed' ");
    
    die();
}
add_action('wp_ajax_seopress_clear_page_speed_cache', 'seopress_clear_page_speed_cache');

///////////////////////////////////////////////////////////////////////////////////////////////////
//Email report - Google Page Speed
///////////////////////////////////////////////////////////////////////////////////////////////////
function seopress_email_page_speed() {
    check_ajax_referer( 'seopress_email_page_speed_nonce', $_GET['_ajax_nonce'], true );

    function seopress_set_html_mail_content_type() {
        return 'text/html';
    }
    add_filter( 'wp_mail_content_type', 'seopress_set_html_mail_content_type' );
    
    $to = wp_get_current_user()->user_email;
    $subject = 'SEOPress: Page Speed Report';

    if ( get_transient( 'seopress_results_page_speed' ) !='' ) {
        $body = "<style>
            #wrapper {
                background-color: #F9F9F9;
                margin: 0;
                padding: 70px 0 70px 0;
                -webkit-text-size-adjust: none !important;
                width: 100%;
            }

            #template_container {
                box-shadow:0 0 0 1px #f3f3f3 !important;
                background-color: #ffffff;
                border: 1px solid #e9e9e9;
                padding: 0;
            }

            #template_header {
                color: #333;
                font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;
            }

            #template_header h1,
            #template_header h1 a {
                color: #232323;
            }

            #template_footer td {
                padding: 0;
            }

            #template_footer #credit {
                font-family: courier, 'Helvetica Neue', Helvetica, Arial, 'Lucida Grande', sans-serif;
                font-size: 12px;
                line-height: 125%;
                text-align: center;
                padding: 12px 28px 28px 28px;
            }

            #body_content {
                background-color: #ffffff;
                max-width: 600px;
            }

            #body_content table td {
                padding: 48px;
            }

            #body_content table td td {
                padding: 12px;
            }

            #body_content table td th {
                padding: 12px;
            }

            #body_content p {
                margin: 0 0 16px;
            }

            #body_content_inner {
                color: #505050;
                font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;
                font-size: 14px;
                line-height: 150%;
                word-break: break-word;
                max-width:600px;
            }
            .td {
                color: #505050;
                border: 1px solid #E5E5E5;
            }

            .text {
                color: #505050;
                font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;
            }

            .link {
                color: #232323;
            }

            #header_wrapper {
                padding: 12px 0 8px 60px;
                display: block;
                border-bottom: 1px solid #F1F1F1;
            }

            h1 {
                color: #232323;
                font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;
                font-size: 18px;
                margin: 0;
                -webkit-font-smoothing: antialiased;
            }

            h2 {
                color: #232323;
                display: block;
                font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;
                font-size: 18px;
                font-weight: bold;
                line-height: 130%;
                margin: 16px 0 8px;
            }

            h3 {
                color: #232323;
                display: block;
                font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;
                font-size: 16px;
                font-weight: bold;
                line-height: 130%;
                margin: 16px 0 8px;
            }

            a {
                color: #232323;
                font-weight: normal;
                text-decoration: underline;
            }

            img {
                border: none;
                display: inline;
                font-size: 14px;
                font-weight: bold;
                height: auto;
                line-height: 100%;
                outline: none;
                text-decoration: none;
                text-transform: capitalize;
            }
        </style>";
        $body .= '<body leftmargin="0" marginwidth="0" topmargin="0" marginheight="0" offset="0">
            <div id="wrapper">
                <table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%">
                    <tr>
                        <td align="center" valign="top">
                            <table border="0" cellpadding="0" cellspacing="0" width="600" id="template_container">
                                <tr>
                                    <td align="center" valign="top">
                                        <!-- Header -->
                                        <table border="0" cellpadding="0" cellspacing="0" width="600" id="template_header">
                                            <tr>
                                                <td id="header_wrapper">
                                                    <h1><img style="height:40px;width:40px;vertical-align: middle;margin-right: 10px;" src="data:image/png;base64, ">'. __("Page Speed report","wp-seopress-pro").'</h1>
                                                </td>
                                            </tr>
                                        </table>
                                        <!-- End Header -->
                                    </td>
                                </tr>
                                <tr>
                                    <td align="center" valign="top">
                                        <!-- Body -->
                                        <table border="0" cellpadding="0" cellspacing="0" width="600" id="template_body">
                                            <tr>
                                                <td valign="top" id="body_content">
                                                    <!-- Content -->
                                                    <table border="0" cellpadding="20" cellspacing="0" width="100%">
                                                        <tr>
                                                            <td valign="top">
                                                                <div id="body_content_inner">';
            $seopress_page_speed_results = json_decode(get_transient( 'seopress_results_page_speed' ), true);

            $body .= '<img style="text-align:center" width="'.$seopress_page_speed_results['screenshot']['width'].'" height="'.$seopress_page_speed_results['screenshot']['height'].'" src="data:'.$seopress_page_speed_results['screenshot']['mime_type'].';base64,'.str_replace(array('-', '_'), array('+', '/'), $seopress_page_speed_results['screenshot']['data']).'"/><br/><br/>';

            $body .= '<p><strong>'.__('URL: ','wp-seopress-pro').'</strong>'.$seopress_page_speed_results['id'].'<br/>';
            $body .= '<strong>'.__('Title: ','wp-seopress-pro').'</strong>'.$seopress_page_speed_results['title'].'</p>';

            $body .= '<div style="background:#F1F1F1;height:1px;width:100%"></div>';

            $body .= '<h2>'.__('Your Google Page Speed Score','wp-seopress-pro').'</h2>';
            $body .= '<p>'.$seopress_page_speed_results['ruleGroups']['SPEED']['score'].'%</p>';

            $body .= '<h2>'.__('Suggestions','wp-seopress-pro').'</h2>';
            $body .= '<ul>';
            
            $seopress_page_speed_rules_order = array();
            
            foreach ($seopress_page_speed_results['formattedResults']['ruleResults'] as $key => $value) {
                array_push($seopress_page_speed_rules_order, $value['ruleImpact']);
            }
            array_multisort($seopress_page_speed_rules_order, SORT_DESC, $seopress_page_speed_results['formattedResults']['ruleResults']);

            foreach ($seopress_page_speed_results['formattedResults']['ruleResults'] as $key => $value) {

                $seopress_page_speed_variables_array = array(
                    '{{BEGIN_LINK}}', 
                    '{{END_LINK}}',
                    '{{NUM_SCRIPTS}}',
                    '{{NUM_CSS}}',
                );

                if (isset($value['summary']['args'])) {
                    $seopress_page_speed_replace_array = array(
                        '<a href="'.$value['summary']['args'][0]['value'].'" target="_blank">',
                        '</a>',
                        $value['summary']['args'][0]['value'],
                        $value['summary']['args'][1]['value'],
                    );
                }

                $body .= '<li>';
                    if ($value['ruleImpact']=='0') {
                        $body .= '<h3><span class="dashicons dashicons-yes"></span>'.$value['localizedRuleName'].'</h3>';
                    } else {
                        $body .= '<h3><span class="dashicons dashicons-warning"></span>'.$value['localizedRuleName'].'</h3>';
                    }
                   
                    //Summary
                    if (isset($value['summary']['format'])) {
                        $seopress_page_speed_results_summary = str_replace($seopress_page_speed_variables_array, $seopress_page_speed_replace_array, $value['summary']['format']);
                    }
                    
                    $body .= '<ul>';
                        $body .= '<li>'.$seopress_page_speed_results_summary.'</li>';
                    $body .= '</ul>';

                    //URLS
                    if (isset($value['urlBlocks'][0]['urls'])) {
                        $body .= '<ul>';
                            foreach ($value['urlBlocks'][0]['urls'] as $key => $value) {
                                $body .= '<ul class="advice-details">';
                                    foreach ($value['result']['args'] as $_key => $_value) {
                                        $body .= '<li>';
                                            $body .= $_value['value'];
                                        $body .= '</li>';
                                    }
                                $body .= '</ul>';
                            }
                        $body .= '</ul>';
                    }
                $body .= '</li>';
            }
        $body .= '</ul>';
                                                        $body .= '</div>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                    <!-- End Content -->
                                                </td>
                                            </tr>
                                        </table>
                                        <!-- End Body -->
                                    </td>
                                </tr>
                                <tr>
                                    <td align="center" valign="top">
                                        <!-- Footer -->
                                        <table border="0" cellpadding="10" cellspacing="0" width="600" id="template_footer">
                                            <tr>
                                                <td valign="top">
                                                    <table border="0" cellpadding="10" cellspacing="0" width="100%">
                                                        <tr>
                                                            <td colspan="2" id="credit" style="border:0;color: #878787; border-top: 1px solid #F1F1F1;" valign="middle">
                                                                <p><a href="https://www.seopress.org/fr">SEOPress</a></p>
                                                                Made with love in Biarritz - France</td>
                                                        </tr>
                                                    </table>
                                                </td>
                                            </tr>
                                        </table>
                                        <!-- End Footer -->
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>
            </div>
        </body>';
    }
     
    wp_mail( $to, $subject, $body );
     
    remove_filter( 'wp_mail_content_type', 'seopress_set_html_mail_content_type' );

    die();
}
add_action('wp_ajax_seopress_email_page_speed', 'seopress_email_page_speed');

///////////////////////////////////////////////////////////////////////////////////////////////////
//Save htaccess file
///////////////////////////////////////////////////////////////////////////////////////////////////
function seopress_save_htaccess() {
    check_ajax_referer( 'seopress_save_htaccess_nonce', $_POST['_ajax_nonce'], true );

    if (current_user_can('manage_options') && is_admin()) { 
        $filename = get_home_path().'/.htaccess';

        if ( isset( $_POST['htaccess_content'])) {
            $current_htaccess = stripslashes($_POST['htaccess_content']);
        }

        if (is_writable($filename)) {

            if (!$handle = fopen($filename, 'w')) {
                 _e('Impossible to open file: ','wp-seopress-pro').$filename;
                 exit;
            }

            if (fwrite($handle, $current_htaccess) === FALSE) {
                _e('Impossible to write in file: ','wp-seopress-pro').$filename;
                exit;
            }

            _e('htaccess successfully updated!','wp-seopress-pro');

            fclose($handle);

        } else {
            _e('Your htaccess is not writable.','wp-seopress-pro');
        }
    }
}
add_action('wp_ajax_seopress_save_htaccess', 'seopress_save_htaccess');

///////////////////////////////////////////////////////////////////////////////////////////////////
//Get backlinks from Majestic API
///////////////////////////////////////////////////////////////////////////////////////////////////
function seopress_backlinks() {
    check_ajax_referer( 'seopress_backlinks_nonce', $_GET['_ajax_nonce'], true );

    function seopress_backlinks_majestic_key_option() {
        $seopress_backlinks_majestic_key_option = get_option("seopress_pro_option_name");
        if ( ! empty ( $seopress_backlinks_majestic_key_option ) ) {
            foreach ($seopress_backlinks_majestic_key_option as $key => $seopress_backlinks_majestic_key_value)
                $options[$key] = $seopress_backlinks_majestic_key_value;
                if (isset($seopress_backlinks_majestic_key_option['seopress_backlinks_majestic_key'])) {
                    return $seopress_backlinks_majestic_key_option['seopress_backlinks_majestic_key'];
                }
        }
    }
    
    if (seopress_backlinks_majestic_key_option() !='') {
        delete_transient( 'seopress_results_majestic');
        
        if ( false === ( $seopress_results_majestic_cache = get_transient( 'seopress_results_majestic' ) ) ) {
            if (is_ssl()) {
                $ssl = 'https://';
            } else {
                $ssl = 'http://';
            }

            $response = wp_remote_get($ssl.'api.majestic.com/api/json?app_api_key='.seopress_backlinks_majestic_key_option().'&cmd=GetBackLinkData&item='.get_home_url().'&Count=100&datasource=fresh');
            

            if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {

                $response_body = __( 'An error occurred, please try again.', 'wp-seopress-pro' );
                
            } else {
                $response_body = wp_remote_retrieve_body($response);
            }

            $seopress_results_majestic_cache = json_decode($response_body);
            set_transient( 'seopress_results_majestic', $seopress_results_majestic_cache, 1 * DAY_IN_SECONDS );

            $backlinks = $seopress_results_majestic_cache->DataTables->BackLinks->Data;

            foreach ($backlinks as $backlink) {
                if(!get_page_by_title( $backlink->SourceURL, '',  'seopress_backlinks')) {
                    wp_insert_post(array(
                        'post_title' => $backlink->SourceURL, 
                        'post_type' => 'seopress_backlinks', 
                        'post_status' => 'publish',
                        'meta_input'   => array(
                            'seopress_backlinks_target_url' => $backlink->TargetURL,
                            'seopress_backlinks_anchor_text' => $backlink->AnchorText,
                            'seopress_backlinks_source_citation_flow' => $backlink->SourceCitationFlow,
                            'seopress_backlinks_source_trust_flow' => $backlink->SourceTrustFlow,
                            'seopress_backlinks_target_citation_flow' => $backlink->TargetCitationFlow,
                            'seopress_backlinks_target_trust_flow' => $backlink->TargetTrustFlow,
                            'seopress_backlinks_found_date' => $backlink->FirstIndexedDate,
                            'seopress_backlinks_last_update' => $backlink->LastSeenDate,
                        ),
                    ));
                }
            }
        }
    }
    
    die();
}
add_action('wp_ajax_seopress_backlinks', 'seopress_backlinks');

