<?php
/**
 * +============================================+
 * |                                            |
 * |   Xagio – Fail Safe File                   |
 * |                                            |
 * |   used to attempt recovery of your         |
 * |   WordPress installation in case of a      |
 * |   fatal error or malicious problem.        |
 * |                                            |
 * +============================================+
 */

/**
 *  Start the session
 */
session_start();

/**
 *  Show all errors
 */
@ini_set('display_errors', TRUE);
@error_reporting(E_ALL);

/**
 *  Fixes for if PHP version 7.4 or below and WordPress version is 5.7 or above
 */
if (!function_exists('str_contains')) {
    function str_contains($haystack, $needle)
    {
        return ('' === $needle || false !== strpos($haystack, $needle));
    }
}

if (!function_exists('absint')) {
    function absint($maybeint)
    {
        return abs((int)$maybeint);
    }
}

/**
 *  Send the output back to browser
 */
function v3_send_output($status = 'info', $message = '', $data = FALSE)
{

    if (XAG_IS_AJAX === TRUE) {

        header('Content-Type: application/json');
        echo json_encode([
            'status'  => $status,
            'message' => $message,
            'data'    => $data,
        ]);

    } else {

        header('Content-Type: text/html');

        $page = <<<EOF
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>%%STATUS%%</title>
    <style type="text/css">

        ::selection { background-color: #f07746; color: #fff; }
        ::-moz-selection { background-color: #f07746; color: #fff; }

        body {
            background-color: #f1f1f1;
            margin: 40px auto;
            max-width: 1024px;
            font: 16px/24px sans-serif;
            color: #808080;
        }

        a {
            color: #dd4814;
            background-color: transparent;
            font-weight: normal;
            text-decoration: none;
        }

        a:hover {
            color: #97310e;
        }

        h1 {
            color: #fff;
            border-bottom: 1px solid #d0d0d0;
            font-size: 22px;
            font-weight: bold;
            margin: 0 0 14px 0;
            padding: 5px 15px;
            line-height: 40px;
            font-family: sans-serif;
        }

        h1.error {
            background-color: #dd1414;
        }

        h1.info {
            background-color: #4b78dc;
        }

        h1.warning {
            background-color: #efb03f;
        }

        h2 {
            color:#404040;
            margin:0;
            padding:0 0 10px 0;
        }

        code {
            font-family: sans-serif;
            font-size: 13px;
            background-color: #f5f5f5;
            border: 1px solid #e3e3e3;
            border-radius: 4px;
            color: #002166;
            display: block;
            margin: 14px 0 14px 0;
            padding: 12px 10px 12px 10px;
        }

        #container {
            margin: 10px;
            background: #fff;
            border: 1px solid #ccd0d4;
            box-shadow: 0 1px 3px rgba(0,0,0,.04);    
        }

        p {
            margin: 0 0 10px;
            padding:0;
        }

        #body {
            margin: 0 15px 0 15px;
            font-family: sans-serif;
            padding-bottom: 20px;
        }
        .hidden {
            display: none;
        }

        a {
            display: block;
            font-size: 12px;
            margin-top: 12px;
        }
    </style>
</head>
<body>
<div id="container">
    <h1 class="%%CLASS%%">%%STATUS%%</h1>
    <div id="body">
        %%MESSAGE%%
        <a href="javascript:history.back()" class="%%GOBACK%%">Go back to previous page</a>
    </div>
</div>
</body>
</html>
EOF;

        $page = str_replace('%%CLASS%%', $status, $page);
        $page = str_replace('%%STATUS%%', ucfirst($status), $page);
        $page = str_replace('%%MESSAGE%%', $message, $page);
        if ($data === TRUE) {
            $page = str_replace('%%GOBACK%%', '', $page);
        } else {
            $page = str_replace('%%GOBACK%%', 'hidden', $page);
        }
        echo $page;

    }

    die();
}

/**
 *  Show a specific page
 */
function v3_show_page($pagename = '', $args = [])
{
    global $version;


    $page = '';

    if ($pagename == 'menu') {

        $page = <<<EOF
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8">
    <title>xagio Recovery - Menu</title>

    <link rel="stylesheet" href="//use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">

    <style type="text/css">

        ::selection { background-color: #f07746; color: #fff; }
        ::-moz-selection { background-color: #f07746; color: #fff; }

        body {
            background-color: #f1f1f1;
            margin: 40px auto;
            max-width: 600px;
            font: 16px/24px sans-serif;
            color: #808080;
            padding-top: 1%;
        }

        a {
            color: #dd4814;
            background-color: transparent;
            font-weight: normal;
            text-decoration: none;
        }

        a:hover {
            color: #97310e;
        }

        h1 a {
            background-image: url(https://app.xagio.net/assets/images/xagio-logo-dark.png);
            background-size: 250px;
            background-position: center top;
            background-repeat: no-repeat;
            color: #444;
            height: 120px;
            font-size: 20px;
            font-weight: 400;
            line-height: 1.3;           
            padding: 0;
            text-decoration: none;            
            text-indent: -9999px;
            outline: 0;
            overflow: hidden;
            display: block;
       }

        h1.error {
            background-color: #dd1414;
        }

        h1.info {
            background-color: #4b78dc;
        }

        h1.warning {
            background-color: #efb03f;
        }

        h2 {
            color:#404040;
            margin:0;
            padding:0 0 10px 0;
        }

        code {
            font-family: sans-serif;
            font-size: 13px;
            background-color: #f5f5f5;
            border: 1px solid #e3e3e3;
            border-radius: 4px;
            color: #002166;
            display: block;
            margin: 14px 0 14px 0;
            padding: 12px 10px 12px 10px;
        }

        #container {        
            font-weight: 400;
            overflow: hidden;
            background: #fff;
            border: 1px solid #ccd0d4;
            box-shadow: 0 1px 3px rgba(0,0,0,.04);
        }
        
        .message {
            border-left: 4px solid #00a0d2;
            padding: 12px;
            margin-left: 0;
            margin-bottom: 20px;
            background-color: #fff;
            box-shadow: 0 1px 1px 0 rgba(0,0,0,.1);
            font-size: 14px;
        }
        
        p {
            margin: 0 0 10px;
            padding:0;
        }

        #body {
            margin: 30px 15px 0 15px;
            font-family: sans-serif;
            padding-bottom: 20px;
        }
        .hidden {
            display: none;
        }

        a {
            display: block;
            font-size: 12px;
            margin-top: 12px;
        }
        input {
            display: block;
            height: 45px;
            max-width: 300px;
            padding: 10px;
            box-sizing: border-box;
            border: 1px solid #d8d8d8;
            font-size: 19px;
            width: 100%;
            margin-left: auto;
            margin-right: auto;
        }

        form > input:first-child {
            border-bottom: 0;
            border-top-left-radius: 5px;
            border-top-right-radius: 5px;
        }

        form > input:first-child + input {
            border-bottom-left-radius: 5px;
            border-bottom-right-radius: 5px;
        }

        .clear {
            clear: both;
        }
        
        .half {
            width: 50%;
            float: left;
            padding: 5px;
            box-sizing: border-box;
        }
        
        button.option {
            width: 100%;
            padding: 18px;
            line-height: 20px;
            font-size: 14px;
        }
        
        button.option i {
            display: block;
            font-size: 38px;
            margin-bottom: 10px;
        }

        button {
            display: block;
         
            border-width: 1px;
            border-style: solid;
            -webkit-appearance: none;
            border-radius: 3px;

            min-height: 30px;
            line-height: 28px;
            padding: 0 12px 2px;

            font-size: 15px;
         
            background: #007cba;
            border-color: #007cba;
            color: #fff;
            text-decoration: none;
            text-shadow: none;

            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;

            cursor: pointer;
        }

        button:hover {

            background: #008ec2;
            border-color: #006799;
            color: #fff;

        }

        h2 {
            padding: 0;
            margin: 0 auto;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: #4a78dc;
            line-height: 61px;
            color: white;
            text-align: center;
            border: 1px solid #9c9c9c;
            margin-bottom: 30px;
            box-shadow: 0px 6px 6px 1px #a5a5a5;
        }

        ul.options {
            list-style: none;
            padding: 0 10px;
        }

        li {
            padding: 7px 10px;
            background: #f7f7f7;
            margin-bottom: 12px;
            border: 1px solid #e0e0e0;
            border-radius: 5px;
            position: relative;
        }

        li > a {
            font-size: 16px;
            margin: 0;
            color: #505050;
            padding-left: 42px;
        }

        span.psv3-version {
            text-align: center;
            width: 100%;
            display: block;
            font-size: 28px;
            color: #2c3e50;
        }

        li:hover {
            background: #ffffff;
        }

        li:hover > a {
            color: #06111e;
        }

        li.divider {
            padding: 0;
            width: 50%;
            margin-left: auto;
            margin-right: auto;
            border-color: #eaeaea;
        }

        li > a > i {
            position: absolute;
            top: 0;     
            bottom: 0;
            left: 0;
            width: 37px;
            font-size: 22px;
            line-height: 37px !important;
            text-align: center;
            background: #35a0d2;
            color: white;
        }

        .list li:first-child {
            margin-top: 10px !important;           
        }

        .list li {
            border-radius: 0;
            margin: 0 0 -1px 0px;       
        }
        
        a.delete-plugin, a.delete-theme {
            position: absolute;
            right: 10px;
            top: 8px;
            font-size: 13px;
            padding: 0 !important;
            color: #ab0000 !important;
        }

        a.activate-plugin, a.activate-theme {
            position: absolute;
            right: 60px;
            top: 8px;
            font-size: 13px;
            padding: 0 !important;
            color: green !important;
        }

        a.deactivate-plugin {
            position: absolute;
            right: 60px;
            top: 8px;
            font-size: 13px;
            padding: 0 !important;
            color: #8e5600 !important;
        }

        .list li > a:first-child > i {
            left: 30px;
        }

        .list li > a > i {
            font-size: 11px;
            line-height: 25px !important;
            background: transparent;
            cursor: pointer;
            width: 25px;
            color: #4978dc;
            text-align: center;
            border-right: 1px solid #e2e2e2;
        }

        li.obj {
            color: #505050;
            font-weight: 700;
        }

        b.active-theme {
            position: absolute;
            top: 8px;
            color: #35a0d2;
            right: 8px;
            font-size: 14px;
        }

        .list li > a > i:hover {
            color: #1b3f8c;
        }

        ul.list {
            list-style: none;
        }

        i.fa.fa-trash {
            color: #a20000;
        }

        i.fa.fa-check-square {
            color: green;
        }

        i.fa.fa-window-close {
            color: orange;
        }

        .plugin-options {
            padding-left: 53px;
            margin-top: 6px;
        }

    </style>

</head>
<body>

<h1>
    <a href="https://xagio.net/">Powered by Xagio</a>
    <span class="psv3-version">$version</span>
</h1>

<p class="message">	
From here, you are able to disable/remove plugins or themes that cause issues on your website. Also, you can upgrade or downgrade Xagio installation.
</p>

<div id="container">
   
    <div id="body">

        <ul class="options">

            <li><a href="#" class="action-upgrade-downgrade"><i class="fa fa-upload"></i> Update/Rollback Xagio</a>

                <div class="plugin-options hidden">
                   
                   <div class="half">
                        <button class="option upgrade"><i class="fa fa-upload"></i> Update to the Latest Version</button>
                   </div>
                   <div class="half">
                        <button class="option downgrade"><i class="fa fa-download"></i> Rollback to Previous Version</button>
                   </div>
                   <div class="clear"></div>                                                           

                </div>

            </li>

            <li class="divider"></li>

            <li><a href="#" class="action-manage-plugins"><i class="fa fa-plug"></i> Manage Plugins</a>

                <ul class="plugins list hidden">

                </ul>

            </li>
            <li><a href="#" class="action-manage-themes"><i class="fa fa-paint-brush"></i> Manage Themes</a>

                <ul class="themes list hidden">
                    <li><a href="#"><i class="fa fa-window-close"></i></a><a href="#" class="delete-theme" title="Delete this Theme"><i class="fa fa-trash"></i></a> Test Theme</li>
                </ul>

            </li>

            <li class="divider"></li>

            <li><a href="#" class="action-exit-recovery"><i class="fa fa-power-off"></i> Exit Recovery</a></li>

        </ul>

    </div>
</div>

<script
        src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>

<script>

    let actions = {

        plugin_options: function(){
            $(document).on('click', '.action-upgrade-downgrade', function(e){
                e.preventDefault();

                let options = $('.plugin-options');
                options.toggleClass('hidden');

            });
        },

        exit_recovery: function(){
            $(document).on('click', '.action-exit-recovery', function(e){

                e.preventDefault();

                $.post(window.location.pathname, 'action=exit&rmt=1', function(d){
                    alert(d.message);
                    document.location.href = window.location.pathname;
                });

            });
        },


        manage_plugins: function(){
            $(document).on('click', '.action-manage-plugins', function(e){
                e.preventDefault();

                let list = $('.plugins.list');
                list.toggleClass('hidden');

                if (list.is(':visible')) {
                    actions.load_plugins();
                }
            });
        },

        load_plugins: function() {

            $.post(window.location.pathname, 'action=list-plugins&rmt=1', function(d){

                let list = $('.plugins.list');
                list.empty();
                for (let obj in d.data) {
                    let activated = d.data[obj];
                    if (activated) {
                        list.append('<li class="obj" data-plugin="'+obj+'"><a href="#" class="deactivate-plugin" title="Deactivate Plugin">Deactivate</a><a href="#" class="delete-plugin" title="Delete this Plugin">Delete</a> '+obj+'</li>');
                    } else {
                        list.append('<li class="obj" data-plugin="'+obj+'"><a href="#" class="activate-plugin" title="Activate Plugin">Activate</a><a href="#" class="delete-plugin" title="Delete this Plugin">Delete</a> '+obj+'</li>');
                    }
                }

            })

        },

        deactivate_plugin: function(){
            $(document).on('click', '.deactivate-plugin', function(e){
                e.preventDefault();

                let plugin = $(this).parents('li.obj').attr('data-plugin');
                $.post(window.location.pathname, 'action=deactivate-plugin&plugin='+plugin+'&rmt=1', function(d){
                    alert(d.message);
                    actions.load_plugins();
                })

            });
        },

        activate_plugin: function(){
            $(document).on('click', '.activate-plugin', function(e){
                e.preventDefault();

                let plugin = $(this).parents('li.obj').attr('data-plugin');
                $.post(window.location.pathname, 'action=activate-plugin&plugin='+plugin+'&rmt=1', function(d){
                    alert(d.message);
                    actions.load_plugins();
                })

            });
        },

        delete_plugin: function(){
            $(document).on('click', '.delete-plugin', function(e){
                e.preventDefault();

                let plugin = $(this).parents('li.obj').attr('data-plugin');
                
                if (confirm('Are you sure you want to delete this plugin?')) {
                    $.post(window.location.pathname, 'action=delete-plugin&plugin='+plugin+'&rmt=1', function(d){
                        alert(d.message);
                        actions.load_plugins();
                    });
                }                                

            });
        },


        manage_themes: function(){
            $(document).on('click', '.action-manage-themes', function(e){
                e.preventDefault();

                let list = $('.themes.list');
                list.toggleClass('hidden');

                if (list.is(':visible')) {
                    actions.load_themes();
                }
            });
        },

        load_themes: function() {

            $.post(window.location.pathname, 'action=list-themes&rmt=1', function(d){

                let list = $('.themes.list');
                list.empty();
                for (let obj in d.data) {
                    let activated = d.data[obj];
                    if (activated) {
                        list.append('<li class="obj" data-theme="'+obj+'">'+obj+' <b class="active-theme">(Active)</b></li>');
                    } else {
                        list.append('<li class="obj" data-theme="'+obj+'"><a href="#" class="activate-theme" title="Activate Theme">Activate</a><a href="#" class="delete-theme" title="Delete this Theme">Delete</a> '+obj+'</li>');
                    }
                }

            })

        },

        activate_theme: function(){
            $(document).on('click', '.activate-theme', function(e){
                e.preventDefault();

                let theme = $(this).parents('li.obj').attr('data-theme');
                $.post(window.location.pathname, 'action=activate-theme&theme='+theme+'&rmt=1', function(d){
                    alert(d.message);
                    actions.load_themes();
                })

            });
        },

        delete_theme: function(){
            $(document).on('click', '.delete-theme', function(e){
                e.preventDefault();

                let theme = $(this).parents('li.obj').attr('data-theme');
                
                if (confirm('Are you sure you want to delete this theme?')) {
                 
                    $.post(window.location.pathname, 'action=delete-theme&theme='+theme+'&rmt=1', function(d){
                        alert(d.message);
                        actions.load_themes();
                    })
                  
                }                                

            });
        },

        upgrade: function(){
            $(document).on('click', '.upgrade', function(e){
                e.preventDefault();

                if (confirm('Are you sure you want to update Xagio to the latest version?')) {


                    $.post(window.location.pathname, 'action=upgrade-downgrade&type=latest&rmt=1', function(d){

                        alert(d.message);

                    });

                }

            });
        },
        downgrade: function(){
            $(document).on('click', '.downgrade', function(e){
                e.preventDefault();

                if (confirm('Are you sure you want to rollback Xagio to a previous version?')) {

                    $.post(window.location.pathname, 'action=upgrade-downgrade&type=previous&rmt=1', function(d){

                        alert(d.message);

                    });

                }

            });
        }
    };

    $(document).ready(function(){

        actions.plugin_options();
        actions.exit_recovery();

        actions.manage_plugins();
        actions.deactivate_plugin();
        actions.activate_plugin();
        actions.delete_plugin();

        actions.manage_themes();
        actions.activate_theme();
        actions.delete_theme();

        actions.upgrade();
        actions.downgrade();

    });

</script>

</body>
</html>
EOF;

    } else if ($pagename == 'login') {

        $page = <<<EOF
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>xagio Recovery - Login</title>
    <style type="text/css">

        ::selection { background-color: #f07746; color: #fff; }
        ::-moz-selection { background-color: #f07746; color: #fff; }

        body {
            background-color: #f1f1f1;
            margin: 40px auto;
            max-width: 350px;
            font: 16px/24px sans-serif;
            padding-top: 1%;
            color: #444;
        }

        a {
            color: #dd4814;
            background-color: transparent;
            font-weight: normal;
            text-decoration: none;
        }

        a:hover {
            color: #97310e;
        }

   
        h1.error {
            background-color: #dd1414;
        }

        h1.info {
            background-color: #4b78dc;
        }

        h1.warning {
            background-color: #efb03f;
        }

        h2 {
            color:#404040;
            margin:0;
            padding:0 0 10px 0;
        }

        code {
            font-family: sans-serif;
            font-size: 13px;
            background-color: #f5f5f5;
            border: 1px solid #e3e3e3;
            border-radius: 4px;
            color: #002166;
            display: block;
            margin: 14px 0 14px 0;
            padding: 12px 10px 12px 10px;
        }

        #container {
            margin: auto;
            width: 350px !important;
        }

        p {
            margin: 0 0 10px;
            padding:0;
        }

        #body {
            margin-top: 20px;
            margin-left: 0;
            padding: 26px 24px 46px;
            font-weight: 400;
            overflow: hidden;
            background: #fff;
            border: 1px solid #ccd0d4;
            box-shadow: 0 1px 3px rgba(0,0,0,.04);
        }
        .hidden {
            display: none;
        }

        a {
            display: block;
            font-size: 12px;
            margin-top: 12px;
        }
        input {
            font-size: 24px;
            line-height: 1.33333333;
            width: 100%;
            padding: .1875rem .3125rem;
            margin: 0 6px 16px 0;
            min-height: 40px;
            max-height: none;
            background: #fbfbfb;
            box-shadow: 0 0 0 transparent;
            border-radius: 4px;
            color: #32373c;
            border: .0625rem solid #7e8993;
            box-sizing: border-box;
        }

        form > input:first-child {
            border-bottom: 0;
            border-top-left-radius: 5px;
            border-top-right-radius: 5px;
        }

        form > input:first-child + input {
            border-bottom-left-radius: 5px;
            border-bottom-right-radius: 5px;
        }

        button {
            display: block;
            margin-left: auto;

            border-width: 1px;
            border-style: solid;
            -webkit-appearance: none;
            border-radius: 3px;

            height: 30px;
            line-height: 28px;
            padding: 0 12px 2px;

            font-size: 15px;
         
            background: #007cba;
            border-color: #007cba;
            color: #fff;
            text-decoration: none;
            text-shadow: none;

            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;

            cursor: pointer;

        }

        button:hover {
            background: #0071a1;
            border-color: #0071a1;
            color: #fff;
        }

        h2 {
            padding: 0;
            margin: 0 auto;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: #4a78dc;
            line-height: 61px;
            color: white;
            text-align: center;
            border: 1px solid #9c9c9c;
            margin-bottom: 30px;
            box-shadow: 0px 6px 6px 1px #a5a5a5;
        }
        
        h1 a {
       		background-image: url(https://app.xagio.net/assets/images/xagio-logo-dark.png);
            background-size: 250px;
            background-position: center top;
            background-repeat: no-repeat;
            color: #444;
            height: 120px;
            font-size: 20px;
            font-weight: 400;
            line-height: 1.3;           
            padding: 0;
            text-decoration: none;            
            text-indent: -9999px;
            outline: 0;
            overflow: hidden;
            display: block;
       }

        label {
            font-size: 14px;
            line-height: 1.5;
            display: inline-block;
            margin-bottom: 3px;
        }
        
        p {
            margin-bottom: 0;
            line-height: 1.5;
        }
        
        .message {
            border-left: 4px solid #00a0d2;
            padding: 12px;
            margin-left: 0;
            margin-bottom: 20px;
            background-color: #fff;
            box-shadow: 0 1px 1px 0 rgba(0,0,0,.1);
            font-size: 14px;
        }
        
        span.psv3-version {
            text-align: center;
            width: 100%;
            display: block;
            font-size: 28px;
            color: #2c3e50;
        }
        
    </style>
</head>
<body>

<h1>
    <a href="https://xagio.net/">Powered by Xagio</a>
    <span class="psv3-version">$version</span>
</h1>

<p class="message">	
Welcome to <b>Xagio Recovery</b>! To continue, please log in using your WordPress credentials!
</p>

<div id="container">
  
    <div id="body">

        <form method="POST">

            <p>
                <label for="user_login">Username or Email Address</label>
                <input id="user_login" name="user" type="text"/>
            </p>
            
            <p>
                <label for="user_pass">Password</label>
                <input id="user_pass" name="password" type="password"/>
            </p>
            
            <button type="submit">Log In</button>

        </form>

    </div>
</div>
</body>
</html>
EOF;

    } else {

        $page = 'Access Denied.';

    }

    header('Content-Type: text/html');
    foreach ($args as $arg => $val) {
        $page = str_replace('%%' . $arg . '%%', $val, $page);
    }
    echo $page;
    die();

}

/**
 *  Remove dir recursively
 */
function v3_remove_dir($dir)
{
    if (is_dir($dir)) {
        $objects = scandir($dir);
        foreach ($objects as $object) {
            if ($object != "." && $object != "..") {
                if (is_dir($dir . "/" . $object))
                    v3_remove_dir($dir . "/" . $object); else
                    @unlink($dir . "/" . $object);
            }
        }
        rmdir($dir);
    }
}

/**
 *  Establishes a database connection
 */
global $wpdb;

function v3_get_version()
{
    global $wpdb;
    $row = $wpdb->get_row('SELECT * FROM ' . $wpdb->prefix . 'options WHERE option_name = "XAGIO_CURRENT_VERSION"', ARRAY_A);
    return $row['option_value'];
}

function v3_get_option($field_name)
{
    global $wpdb;
    $row = $wpdb->get_row('SELECT * FROM ' . $wpdb->prefix . 'options WHERE option_name = "' . $field_name . '"', ARRAY_A);
    return @$row['option_value'];
}

function v3_db_communication()
{
    global $table_prefix;

    // wp-config.php is neded for DB credentials
    // BUT, we create a clone of it, and comment out the require_once to
    // prevent wordpress errors from affecting this file
    if (!file_exists(XAG_DROP_PATH . 'wp-config-failsafe.php')) {
        file_put_contents(XAG_DROP_PATH . 'wp-config-failsafe.php', str_replace('require_once', '//require_once', file_get_contents(XAG_REC_ABS_PATH . 'wp-config.php')));
    }
    require_once(XAG_DROP_PATH . 'wp-config-failsafe.php');

    /**
     *  WP Related vars
     */
    if (!defined('WP_DEBUG')) {
        define('WP_DEBUG', FALSE);
    }
    if (!defined('WP_DEBUG_DISPLAY')) {
        define('WP_DEBUG_DISPLAY', FALSE);
    }

    // wp-db.php contains code for wpdb
    require_once(XAG_REC_ABS_PATH . 'wp-includes' . DIRECTORY_SEPARATOR . 'class-wp-error.php');
    require_once(XAG_REC_ABS_PATH . 'wp-includes' . DIRECTORY_SEPARATOR . 'wp-db.php');

    $wpdb = FALSE;
    $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
    $wpdb->set_prefix($table_prefix);
    return $wpdb;
}

function mbstring_binary_safe_encoding($reset = FALSE)
{
    static $encodings = [];
    static $overloaded = NULL;

    if (is_null($overloaded))
        $overloaded = function_exists('mb_internal_encoding') && (ini_get('mbstring.func_overload') & 2);

    if (FALSE === $overloaded)
        return;

    if (!$reset) {
        $encoding = mb_internal_encoding();
        array_push($encodings, $encoding);
        mb_internal_encoding('ISO-8859-1');
    }

    if ($reset && $encodings) {
        $encoding = array_pop($encodings);
        mb_internal_encoding($encoding);
    }
}

function v3_unzip_file($zip_file)
{

    // Check if download was a success
    if (file_exists($zip_file)) {

        // Now unzip the update
        if (class_exists('ZipArchive')) {

            $zip = new ZipArchive();
            $res = $zip->open($zip_file);
            if ($res === TRUE) {

                @$zip->extractTo(XAG_PLUGIN_DIR);
                $zip->close();

            } else {

                v3_send_output('error', 'ZipArchive failed to unzip the update zip.');

            }

        } else {

            v3_send_output('error', 'ZipArchive is not installed.');

        }

    }

    return file_exists(XAG_PATH);

}

function v3_download_file($location, $file)
{
    if (file_exists($location)) {
        @unlink($location);
    }

    $fp = fopen($location, 'w+');
    $ch = curl_init($file);

    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
}

/**
 * Reset the mbstring internal encoding to a users previously set encoding.
 *
 * @see mbstring_binary_safe_encoding()
 *
 * @since 3.7.0
 */
function reset_mbstring_encoding()
{
    mbstring_binary_safe_encoding(TRUE);
}

function is_wp_error($thing)
{
    return ($thing instanceof WP_Error);
}

function esc_sql($data)
{
    global $wpdb;
    return $wpdb->_escape($data);
}

function wp_load_translations_early()
{
    v3_send_output('error', 'Failed to connect to database.');
}

function apply_filters($tag, $value)
{
    return $value;
}

function has_filter($ignore = FALSE, $ignore2 = FALSE)
{
    return TRUE;
}

function is_multisite()
{
    if (defined('MULTISITE'))
        return MULTISITE;

    if (defined('SUBDOMAIN_INSTALL') || defined('VHOST') || defined('SUNRISE'))
        return TRUE;

    return FALSE;
}

/**
 *  Check the provided username / password
 */
function v3_verify_auth()
{
    global $wpdb;
    if (isset($_REQUEST['key'])) {
        $api_key    = $_REQUEST['key'];
        $db_api_key = v3_get_option('XAGIO_API');

        if ($db_api_key == $api_key) {

            return TRUE;

        } else {

            return FALSE;

        }

    } else if (isset($_POST['user'], $_POST['password'])) {

        // Check if the user exists
        $username = $wpdb->_escape($_POST['user']);
        $user     = $wpdb->get_row("SELECT * FROM {$wpdb->prefix}users WHERE user_login = '$username' OR user_email = '$username';", ARRAY_A);

        if ($user === NULL) {
            v3_send_output('error', 'Invalid credentials, please try again.', TRUE);
        }

        require_once(XAG_REC_ABS_PATH . 'wp-includes' . DIRECTORY_SEPARATOR . 'class-phpass.php');
        $wp_hasher = new PasswordHash(8, TRUE);

        $password = $_POST['password'];
        $check    = $wp_hasher->CheckPassword($password, $user['user_pass']);

        if ($check == FALSE) {
            v3_send_output('error', 'Invalid credentials, please try again.', TRUE);
        }

        $_SESSION["loggedIn"] = TRUE;
        return TRUE;

    } else if (!isset($_SESSION["loggedIn"])) {
        return FALSE;
    } else {
        return $_SESSION["loggedIn"];
    }

}

/**
 *  Check for actions
 */
function v3_process_actions()
{

    global $wpdb;

    if (!isset($_REQUEST['action'])) {
        return FALSE;
    }

    $action = $_REQUEST['action'];

    switch ($action) {

        case 'exit':
            $_SESSION["loggedIn"] = FALSE;
            v3_send_output('info', 'You have been logged out of recovery.');
            break;

        case 'list-themes':

            $active_theme = $wpdb->get_row('SELECT * FROM ' . $wpdb->prefix . 'options WHERE option_name = "template"', ARRAY_A);
            $active_theme = $active_theme['option_value'];

            chdir(XAG_THEME_DIR);
            $all_themes = array_filter(glob('*'), 'is_dir');

            $formatted_themes = [];

            foreach ($all_themes as $theme) {
                if ($active_theme == $theme) {
                    $formatted_themes[$theme] = TRUE;
                } else {
                    $formatted_themes[$theme] = FALSE;
                }
            }

            v3_send_output('info', 'Theme data received.', $formatted_themes);

            break;

        case 'activate-theme':

            $theme = esc_sql($_POST['theme']);

            if (empty($theme)) {
                v3_send_output('error', 'Theme cannot be empty.');
            }

            $wpdb->update($wpdb->prefix . 'options', [
                'option_value' => $theme,
            ], [
                'option_name' => 'template',
            ]);

            $wpdb->update($wpdb->prefix . 'options', [
                'option_value' => $theme,
            ], [
                'option_name' => 'stylesheet',
            ]);

            v3_send_output('info', 'Theme "' . $theme . '" has been activated.');

            break;

        case 'delete-theme':

            $theme = esc_sql($_POST['theme']);

            if (empty($theme)) {
                v3_send_output('error', 'Theme cannot be empty.');
            }

            v3_remove_dir(XAG_THEME_DIR . $theme);

            v3_send_output('info', 'Theme "' . $theme . '" has been removed.');

            break;

        case 'list-plugins':

            $active_plugins = $wpdb->get_row('SELECT * FROM ' . $wpdb->prefix . 'options WHERE option_name = "active_plugins"', ARRAY_A);
            $active_plugins = unserialize($active_plugins['option_value']);

            array_walk($active_plugins, function (&$item1, $key) {
                $item1 = dirname($item1);
            });

            chdir(XAG_PLUGIN_DIR);
            $all_plugins = array_filter(glob('*'), 'is_dir');

            $formatted_plugins = [];

            foreach ($all_plugins as $plugin) {
                if (in_array($plugin, $active_plugins)) {
                    $formatted_plugins[$plugin] = TRUE;
                } else {
                    $formatted_plugins[$plugin] = FALSE;
                }
            }

            v3_send_output('info', 'Plugin data received.', $formatted_plugins);

            break;

        case 'deactivate-plugin':

            $plugin = esc_sql($_POST['plugin']);

            if (empty($plugin)) {
                v3_send_output('error', 'Plugin cannot be empty.');
            }

            $active_plugins = $wpdb->get_row('SELECT * FROM ' . $wpdb->prefix . 'options WHERE option_name = "active_plugins"', ARRAY_A);
            $active_plugins = unserialize($active_plugins['option_value']);

            $new_active_plugins = [];
            foreach ($active_plugins as $plugin_dir) {
                $name = dirname($plugin_dir);
                if ($name != $plugin) {
                    $new_active_plugins[] = $plugin_dir;
                }
            }

            $wpdb->update($wpdb->prefix . 'options', [
                'option_value' => serialize($new_active_plugins),
            ], [
                'option_name' => 'active_plugins',
            ]);

            v3_send_output('info', 'Plugin "' . $plugin . '" has been deactivated.');

            break;

        case 'activate-plugin':

            $plugin = esc_sql($_POST['plugin']);

            if (empty($plugin)) {
                v3_send_output('error', 'Plugin cannot be empty.');
            }

            $active_plugins = $wpdb->get_row('SELECT * FROM ' . $wpdb->prefix . 'options WHERE option_name = "active_plugins"', ARRAY_A);
            $active_plugins = unserialize($active_plugins['option_value']);

            $active_plugins[] = $plugin . DIRECTORY_SEPARATOR . $plugin . '.php';

            $wpdb->update($wpdb->prefix . 'options', [
                'option_value' => serialize($active_plugins),
            ], [
                'option_name' => 'active_plugins',
            ]);

            v3_send_output('info', 'Plugin "' . $plugin . '" has been activated.');

            break;

        case 'delete-plugin':

            $plugin = esc_sql($_POST['plugin']);

            if (empty($plugin)) {
                v3_send_output('error', 'Plugin cannot be empty.');
            }

            $active_plugins = $wpdb->get_row('SELECT * FROM ' . $wpdb->prefix . 'options WHERE option_name = "active_plugins"', ARRAY_A);
            $active_plugins = unserialize($active_plugins['option_value']);

            $new_active_plugins = [];
            foreach ($active_plugins as $plugin_dir) {
                $name = dirname($plugin_dir);
                if ($name != $plugin) {
                    $new_active_plugins[] = $plugin_dir;
                }
            }

            $wpdb->update($wpdb->prefix . 'options', [
                'option_value' => serialize($active_plugins),
            ], [
                'option_name' => 'active_plugins',
            ]);

            v3_remove_dir(XAG_PLUGIN_DIR . $plugin);

            v3_send_output('info', 'Plugin "' . $plugin . '" has been removed.');

            break;

        case 'upgrade-downgrade':

            $type = $_REQUEST['type'];
            $URL  = 'https://app.xagio.net/api/download/Repo/' . $type;

            v3_download_file(XAG_PLUGIN_DIR . 'xagio.zip', $URL);

            if (v3_unzip_file(XAG_PLUGIN_DIR . 'xagio.zip')) {

                v3_send_output('info', 'Successfully upgraded/downgraded Xagio.');

            } else {

                v3_send_output('error', 'Failed to upgrade/downgrade Xagio.');

            }

            break;

        default:
            v3_send_output('error', 'Requested action does not exist.');
            break;

    }

    return TRUE;

}

/**
 *  Whether the request is ajax
 */
define('XAG_IS_AJAX', isset($_REQUEST['rmt']));

/**
 *  Xagio Absolute Path
 */
define('XAG_PATH', '/home/advagaml/public_html/wp-content/plugins/xagio-seo' . DIRECTORY_SEPARATOR);

/**
 *  Get Dir Paths
 */
define('XAG_CONTENT_DIR', str_replace('plugins' . DIRECTORY_SEPARATOR . 'xagio-seo' . DIRECTORY_SEPARATOR, '', XAG_PATH));
define('XAG_PLUGIN_DIR', XAG_CONTENT_DIR . 'plugins' . DIRECTORY_SEPARATOR);
define('XAG_THEME_DIR', XAG_CONTENT_DIR . 'themes' . DIRECTORY_SEPARATOR);

$XAG_REC_ABS_PATH     = '';
$XAG_REC_CURRENT_PATH = dirname(__FILE__) . '/';
$XAG_DROP_PATH        = $XAG_REC_CURRENT_PATH;

// if name of current directory is xagio
if (basename($XAG_REC_CURRENT_PATH) == 'xagio-seo') {
    $XAG_REC_ABS_PATH = str_replace('/wp-content/plugins/xagio-seo', '', $XAG_REC_CURRENT_PATH) . '/';
}

// Check if wp-load.php is present in the root directory
if (!file_exists($XAG_REC_ABS_PATH . 'wp-load.php')) {
    // this is probably wp engine or something like that
    $XAG_REC_ABS_PATH = '/wordpress/';
}

define('XAG_REC_ABS_PATH', $XAG_REC_ABS_PATH);
define('XAG_DROP_PATH', $XAG_DROP_PATH);

/**
 *  Check if wp-config.php is present
 *  if it is, continue with initialization
 */
if (file_exists(XAG_REC_ABS_PATH . 'wp-config.php')) {

    // Establish DB connection
    $wpdb = v3_db_communication();

    // Get Psv3 Version
    $version = v3_get_version();

    // Check if logged in
    if (v3_verify_auth()) {

        // Check if actions
        if (!v3_process_actions()) {

            // Show the log in screen
            v3_show_page('menu');

        }

    } else {

        // Show the log in screen
        v3_show_page('login');

    }


} else {
    // wp-config.php is missing, possibly this file is in the wrong directory, or wp-config is missing.
    v3_send_output('error', 'Cannot find wp-config.php in ' . dirname(__FILE__) . '. Please make sure you have this file placed in your root directory, or if this file is indeed in the root directory, make sure wp-config.php is present.');
}


