<?php

/*
Plugin Name: GOAuth
Description: Go and OAuthenticate plugin
Version: 2.20
Author: igroykt
Author URI: https://profiles.wordpress.org/igroykt
Text Domain: goauth
Domain Path: /languages
*
*/
if ( !defined( 'ABSPATH' ) ) {
    die;
}
// Create a helper function for easy SDK access.
function ga_fs()
{
    global  $ga_fs ;
    
    if ( !isset( $ga_fs ) ) {
        // Include Freemius SDK.
        require_once dirname( __FILE__ ) . '/freemius/start.php';
        $ga_fs = fs_dynamic_init( array(
            'id'             => '2662',
            'slug'           => 'goauth-admin',
            'type'           => 'plugin',
            'public_key'     => 'pk_30000a04b7c6d2d4c89cc34a221e3',
            'is_premium'     => false,
            'has_addons'     => false,
            'has_paid_plans' => true,
            'menu'           => array(
            'slug'    => 'goauth-admin.php',
            'contact' => false,
            'support' => false,
            'parent'  => array(
            'slug' => 'options-general.php',
        ),
        ),
            'is_live'        => true,
        ) );
    }
    
    return $ga_fs;
}

// Init Freemius.
ga_fs();
// Signal that SDK was initiated.
do_action( 'ga_fs_loaded' );
if ( is_admin() ) {
    require_once dirname( __FILE__ ) . '/goauth-admin.php';
}
require_once dirname( __FILE__ ) . '/vendor/autoload.php';
define( 'GA_TOKENS_TABLE', 'goauth_tokens' );
define( 'GA_TTR', '256' );
class GOAuth
{
    private  $db_version = '1.1' ;
    function __construct()
    {
        $this->set_plugin_language();
        $this->check_requirements();
        
        if ( option::plugin_enabled() ) {
            func::load_materialize_login();
            if ( option::force_login_enabled() ) {
                $this->set_force_login();
            }
            if ( option::hide_navigation_enabled() ) {
                $this->hide_navigation();
            }
            if ( option::hide_loginform_enabled() ) {
                if ( !$this->antilockout() ) {
                    $this->hide_loginform();
                }
            }
            if ( option::xmlrpc_disabled() ) {
                $this->disable_xmlrpc();
            }
            if ( option::api_disabled() ) {
                $this->restrict_api_access();
            }
            if ( option::user_enumeration_disabled() ) {
                $this->disable_user_enumeration();
            }
            
            if ( ga_fs()->is_free_plan() ) {
                $this->upgrade_to_premium_notice();
                $this->review_plugin_notice();
            }
        
        }
    
    }
    
    function activate()
    {
        $this->create_tokens_table();
        flush_rewrite_rules();
    }
    
    function deactivate()
    {
        flush_rewrite_rules();
    }
    
    function set_plugin_language()
    {
        add_action( 'plugins_loaded', function () {
            load_plugin_textdomain( 'goauth', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
        }, 1 );
    }
    
    function set_force_login()
    {
        add_action( 'wp', function () {
            if ( !is_user_logged_in() ) {
                auth_redirect();
            }
        } );
    }
    
    function disable_user_enumeration()
    {
        if ( !function_exists( 'is_user_logged_in' ) ) {
            require ABSPATH . 'wp-includes/pluggable.php';
        }
        
        if ( !is_user_logged_in() ) {
            if ( preg_match( '/author=([0-9]*)/i', $_SERVER['QUERY_STRING'] ) ) {
                wp_die( 'Forbidden.' );
            }
            add_filter(
                'redirect_canonical',
                function ( $redirect, $request ) {
                if ( preg_match( '/\\?author=([0-9]*)(\\/*)/i', $request ) ) {
                    wp_die( 'Forbidden.' );
                }
                return $redirect;
            },
                10,
                2
            );
        }
    
    }
    
    function antilockout()
    {
        $client_ip = $_SERVER['REMOTE_ADDR'];
        $cidr = get_option( 'goauth_antilockout' );
        if ( func::ip_cidr_check( $client_ip, $cidr ) ) {
            return true;
        }
        return false;
    }
    
    function check_requirements()
    {
        add_action( 'admin_notices', function () {
            
            if ( !func::secure_auth_key() ) {
                ?>
                <div class="notice notice-error is-dismissible">
                    <p><?php 
                _e( '<b>GOAuth:</b> Secure authentication key not set. Plugin disabled.', 'goauth' );
                ?></p>
                </div>
                <?php 
                update_option( 'goauth_enable', false );
            }
            
            $modules = array(
                "curl",
                "bcmath",
                "intl",
                "openssl"
            );
            foreach ( $modules as $module ) {
                $mod = func::module_loaded( $module );
                
                if ( $mod[1] === false ) {
                    ?>
                    <div class="notice notice-error is-dismissible">
                        <p><?php 
                    _e( '<b>GOAuth:</b> Module "' . $mod[0] . '" not loaded. Plugin disabled.', 'goauth' );
                    ?></p>
                    </div>
                    <?php 
                    update_option( 'goauth_enable', false );
                }
            
            }
        } );
    }
    
    function upgrade_to_premium_notice()
    {
        add_action( 'admin_notices', function () {
            
            if ( isset( $_GET['page'] ) && $_GET['page'] == 'goauth-admin.php' ) {
                ?>
                <div class="wrap right">
                    <a id="scale-demo" href="options-general.php?page=goauth-admin.php-pricing" class="btn-floating btn-large pulse"><i class="material-icons">attach_money</i></a> <?php 
                _e( 'Buy', 'goauth' );
                ?>
                </div>
                <?php 
            }
        
        } );
    }
    
    function review_plugin_notice()
    {
        add_action( 'admin_notices', function () {
            
            if ( isset( $_GET['page'] ) && $_GET['page'] == 'goauth-admin.php' ) {
                ?>
                <div class="wrap right">
                    <a id="scale-demo" href="https://wordpress.org/support/plugin/goauth/reviews/#new-post" target="_blank" class="btn-floating btn-large pulse"><i class="material-icons">grade</i></a> <?php 
                _e( 'Rate', 'goauth' );
                ?>
                </div>
                <?php 
            }
        
        } );
    }
    
    function hide_navigation()
    {
        add_filter( 'allow_password_reset', '__return_false' );
        add_action( 'login_head', function () {
            ?>
            <style>#nav,#backtoblog{display:none}</style>
            <style>.forgetmenot{display:none;}</style>
            <?php 
        } );
    }
    
    function hide_loginform()
    {
        add_action( 'login_head', function () {
            ?>
            <style>label[for="user_login"]{display:none;}</style>
            <style>.input{display:none;}</style>
            <style>.user-pass-wrap{display:none;}</style>
            <style>.submit{display:none;}</style>
            <?php 
        } );
    }
    
    function disable_xmlrpc()
    {
        add_filter( 'wp_headers', function ( $headers ) {
            unset( $headers['X-Pingback'] );
            return $headers;
        } );
        add_filter( 'xmlrpc_methods', function ( $methods ) {
            unset( $methods['pingback.ping'] );
            return $methods;
        } );
        add_filter( 'xmlrpc_enabled', '__return_false' );
    }
    
    function restrict_api_access()
    {
        add_filter( 'rest_authentication_errors', function ( $result ) {
            if ( !empty($result) ) {
                return $result;
            }
            if ( !is_user_logged_in() ) {
                return new WP_Error( 'restricted_api_access', 'Restricted Access.', array(
                    'status' => 401,
                ) );
            }
            return $result;
        } );
    }
    
    function create_tokens_table()
    {
        global  $wpdb ;
        $table_name = $wpdb->prefix . GA_TOKENS_TABLE;
        
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$table_name}'" ) != $table_name ) {
            $charset_collate = $wpdb->get_charset_collate();
            $sql = "CREATE TABLE {$table_name} (\n                id bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n                uid int(11) NOT NULL,\n                useragent varchar(255) NOT NULL,\n                hashval varchar(255) NOT NULL,\n                refresh_token varchar(255) NOT NULL,\n                created int(11) NOT NULL,\n                provider varchar(255) NOT NULL,\n                PRIMARY KEY  (id)\n            ) {$charset_collate};";
            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
            dbDelta( $sql );
            add_option( 'goauth_db_version', $this->db_version );
        }
    
    }

}
if ( class_exists( 'GOAuth' ) ) {
    $_goauth = new GOAuth();
}
register_activation_hook( __FILE__, array( $_goauth, 'activate' ) );
register_deactivation_hook( __FILE__, array( $_goauth, 'deactivate' ) );
function ga_fs_uninstall_cleanup()
{
    
    if ( !option::goauth_save_data_enabled() ) {
        $options = array(
            'goauth_2fa_enable',
            'goauth_2fa_salt',
            'goauth_2fa_show_qr',
            'goauth_api_disabled',
            'goauth_auto_register',
            'goauth_autocorrect_userinfo',
            'goauth_button_style',
            'goauth_client_id',
            'goauth_client_secret',
            'goauth_domain',
            'goauth_enable',
            'goauth_force_login',
            'goauth_google_enable',
            'goauth_hide_forget',
            'goauth_hide_loginform',
            'goauth_locale_autodetect',
            'goauth_logo_url',
            'goauth_remove_profile_email',
            'goauth_remove_profile_name',
            'goauth_remove_profile_password',
            'goauth_save_on_uninstall',
            'goauth_xmlrpc_disabled',
            'goauth_antilockout',
            'goauth_disable_user_enum',
            'goauth_hide_wp_version',
            'goauth_default_role',
            'goauth_recover_button_style',
            'goauth_auto_register_exclude'
        );
        foreach ( $options as $option ) {
            delete_option( $option );
        }
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        global  $wpdb ;
        $table_name = $wpdb->prefix . GA_TOKENS_TABLE;
        $wpdb->query( "DROP TABLE IF EXISTS {$table_name}" );
    }

}

ga_fs()->add_action( 'after_uninstall', 'ga_fs_uninstall_cleanup' );
function ga_fs_custom_icon()
{
    return dirname( __FILE__ ) . '/assets/icon-128x128.jpg';
}

ga_fs()->add_filter( 'plugin_icon', 'ga_fs_custom_icon' );
if ( class_exists( 'AuthenticatorLib' ) ) {
    new AuthenticatorLib();
}
if ( class_exists( 'GoogleLib' ) ) {
    new GoogleLib();
}