# wt-security/2.3.39/services.php

WebTotem Security, version 2.3.39. 438 lines.

- Page: https://pluginprobe.com/plugins/wt-security/2.3.39/code/services.php
- Raw: https://pluginprobe.com/plugins/wt-security/2.3.39/raw/services.php
- Modified: 2021-05-27T03:07:34+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/wt-security/2.3.39/code/services.php#L10-L20`.

```php
<?php defined('ABSPATH') or die("Protected By WT!");

function wtsec_cmd($cmd, $service, $_service, $uid, $status, $domain = '')
{
    global $wp_filesystem;

    //bug fix with wp file system, which return null
    if (empty($wp_filesystem)) {
        require_once(ABSPATH . '/wp-admin/includes/file.php');
        WP_Filesystem();
    }

    //retry checking
    if (empty($wp_filesystem)) {
        WTSEC_LIBRARY_Session::setNotification("error", "WP FileSystem path error");
        return false;
    }

    switch ($cmd) {
        case $_service . "_install":
            try {
                $file = wtsec_generateFile($uid, $service);
                if (is_null($file['name'])) {
                    WTSEC_LIBRARY_Session::setNotification("error", __( 'Failed to download agent file.', 'wtotem' ));
                    return false;
                }
                if ($service === "WAF") {
                    $plugin_path = str_replace(ABSPATH, $wp_filesystem->abspath(), WTSEC_INSTALLATION_DIR);
                    $path = $plugin_path;
                    $target_dir = $wp_filesystem->find_folder($path);
                    if (!$wp_filesystem->is_dir($path)) {
                        $wp_filesystem->mkdir($target_dir);
                    }
                    $target_file = trailingslashit($target_dir) . $file['name'];
                    if (!$wp_filesystem->put_contents($target_file, $file['file'], FS_CHMOD_FILE)) {
                        WTSEC_LIBRARY_Session::setNotification("warning", sprintf( __( 'Unable to install the %s file in the %s', 'wtotem' ), $service, $target_dir ));
                    } else {
                        wtsec_app()->set($_service . '_installed_file', $file['name']);
                    }
                } else {
                    $target_dir = $wp_filesystem->find_folder($wp_filesystem->abspath());
                    $target_file = trailingslashit($target_dir) . $file['name'];
                    if (!$wp_filesystem->put_contents($target_file, $file['file'])) {
                        WTSEC_LIBRARY_Session::setNotification("warning", sprintf( __( 'Unable to install the %s file in the %s', 'wtotem' ), $service, $target_dir ));
                    } else {
                        wtsec_app()->set($_service . '_installed_file', $file['name']);
                        if ($service === "AM") {
                            wtsec_addCheckFile($file['name']);
                        }
                    }
                }
                if ($service !== "AM") {
                    //wtsec_serviceConnect($uid, $service, $domain . '/' . $file['name']);
                }

            } catch (Exception $e) {
                WTSEC_LIBRARY_Session::setNotification("error", $e->getMessage());
                return false;
            }
            break;
        case $_service . "_start":
            WTSEC_LIBRARY_WT::changeStatus($status['config_id'], $uid);
            wtsec_app()->set($_service . '_status', "start");
            break;
        case $_service . "_stop":
//            WTSEC_LIBRARY_WT::changeStatus($status['config_id'],$uid);
            wtsec_app()->set($_service . '_status', "stop");
            break;
        case $_service . "_connect":
            $file = wtsec_getInstalledFile($_service);
            if ($file) {
                //wtsec_serviceConnect($uid, $service, $domain . '/' . $file);
            } else {
                WTSEC_LIBRARY_Session::setNotification("warning", sprintf( __( 'The %s service file not found', 'wtotem' ), $service ));
            }
            break;
        case $_service . "_uninstall":
            try {
                $file = wtsec_getInstalledFile($_service);
                if ($service === "WAF") {
                    $plugin_path = str_replace(ABSPATH, $wp_filesystem->abspath(), WTSEC_INSTALLATION_DIR);
                    $mainDir = $plugin_path;
                } else {
                    $mainDir = $wp_filesystem->abspath();
                }
                $target_dir = $wp_filesystem->find_folder($mainDir);
                $target_file = trailingslashit($mainDir) . $file;
                if (!$wp_filesystem->delete($target_file)) {
                    WTSEC_LIBRARY_Session::setNotification("warning", sprintf( __( 'Unable to uninstall the %s file in the %s', 'wtotem' ), $service,$target_dir ));
                }
                wtsec_app()->set($_service . '_status', "uninstalled");
                WTSEC_LIBRARY_App::deleteOption($_service . '_installed_file');
            } catch (Exception $e) {
                WTSEC_LIBRARY_Session::setNotification("error", $e->getMessage());
                return false;
            }
            break;
    }
    return true;
}

// Add check file if plugin is activated
function wtsec_addCheckFile($name){
    global $wp_filesystem;

    if (empty($wp_filesystem)) {
        require_once(ABSPATH . '/wp-admin/includes/file.php');
        WP_Filesystem();
    }

    //retry checking
    if (empty($wp_filesystem)) {
        WTSEC_LIBRARY_Session::setNotification("error", "WP FileSystem path error");
        return false;
    }

    $target_dir = $wp_filesystem->find_folder(WTSEC_PLUGIN_PATH);
    $target_file = trailingslashit($target_dir) . 'generate.php';

    if ($wp_filesystem->put_contents($target_file, '<?php exit(); ?>'.$name, FS_CHMOD_FILE)) {
        return true;
    }
    return false;
}

function wtsec_checkStatus($id, $service)
{
    $service = ucfirst(strtolower($service));
    $is_active = null;
    $config_id = null;
    $result = WTSEC_LIBRARY_WT::checkStatus($id, $service);
    $data = $result['data']['auth']['viewer']['sites']['one']['configs'];
    foreach ($data as &$cfg) {
        if (!empty($cfg)) {
            $is_active = $cfg['isActive'];
            $config_id = $cfg['id'];
        }
    }

    return ['active' => $is_active, 'config_id' => $config_id];
}

function wtsec_deleteAllAgentsFiles(){
    global $wp_filesystem;

    if (empty($wp_filesystem)) {
        require_once(ABSPATH . '/wp-admin/includes/file.php');
        WP_Filesystem();
    }
    $target_dir = $wp_filesystem->find_folder($wp_filesystem->abspath());
    $list = $wp_filesystem->dirlist($target_dir);

    foreach ($list as $item){
        $target_item = trailingslashit($target_dir) . $item['name'];
        $recursive = ($item['type'] == 'd') ? true : false;
        if( wtsec_multineedle_stripos( $item['name'], ['.am.php','.waf.php','.av.php','wtotem_'] ) ){
            $wp_filesystem->delete($target_item, $recursive, $item['type']);
        }
    }
    return true;
}

function wtsec_DeactivatedPlugin(){
    if(WTSEC_LIBRARY_App::_get('api_key')){
        $host = WTSEC_LIBRARY_WT::getOwnSite();
        if(!empty($host)){
            if(WTSEC_LIBRARY_WT::deleteAm($host['id'])){
                wtsec_deleteAllAgentsFiles();
            }
        }
    } else{
        wtsec_deleteAllAgentsFiles();
    }
}

function wtsec_multineedle_stripos($haystack, $needles, $offset = 0) {
    foreach($needles as $needle) {
        if(stripos($haystack, $needle, $offset)){
            return true;
        }
    }
    return false;
}

function wtsec_generateFile($id, $service)
{
    if ($service === "AM") {
        $result = WTSEC_LIBRARY_WT::generateAmFile($id);
        if (!isset($result['data']['auth']['am']['install'])) {
            $file = ['filename' => null, "body" => null];
        } else {
            $result = $result['data']['auth']['am']['install'];

            $url = $result['downloadLink'];
            $amFilename = $result['amFilename'];

            if($result['wafFilename']){
                wtsec_app()->set('waf_installed_file', $result['wafFilename']);
            }
            if($result['avFilename']){
                wtsec_app()->set('av_installed_file', $result['avFilename']);
            }

            $file = WTSEC_LIBRARY_WT::getFileByUrl($url, $amFilename);
            if (empty($file)) {
                $file = WTSEC_LIBRARY_WT::getFileByUrl($url, $amFilename);
            }
        }

        $name = $file["filename"];
        $file = $file["body"];
    } else {
        $result = WTSEC_LIBRARY_WT::generateFile($id, $service);
        $name = $result['data']['auth']['agents']['generate']['agentName'];
        $file = WTSEC_LIBRARY_WT::requestURL(WTSEC_FILE_URL . '/' . $name);
        if (empty($file)) {
            $file = WTSEC_LIBRARY_WT::requestURL(WTSEC_FILE_URL . '/' . $name);
        }
    }

    return ['file' => $file, 'name' => $name];
}

function wtsec_serviceConnect($id, $service, $domain = '')
{
    $result = WTSEC_LIBRARY_WT::serviceConnect($id, $service);
    $status = isset($result['errors']) && !isset($result['data']['auth']['agents']['check']) ? false : true;
    if (!$status) {
        WTSEC_LIBRARY_Session::setNotification("warning", sprintf( __( 'Unable to connect to %s service by the url: %s', 'wtotem' ), $service, $domain ));
    }
    return $status;
}

function wtsec_servicePing($service, $domain = '')
{
    if ($domain == NULL) return false;
    if (stripos($domain, "http") === false) {
        $domain = "http://" . $domain;
    }
    $args = [
        'timeout' => '10',
        'sslverify' => false,
        'redirection' => 3,
    ];
    $response = wp_remote_get($domain, $args);
    $httpcode = wp_remote_retrieve_response_code($response);
    if ($httpcode >= 200 && $httpcode < 400) {
        return true;
    } else {
        WTSEC_LIBRARY_Session::setNotification("warning", sprintf( __( 'Unable to connect to %s service by the url: %s', 'wtotem' ), $service, $domain ));
        return false;
    }
}

function wtsec_AVLogsData($logs){
    foreach ($logs as $key => $log){
        $statuses = wtsec_getStatuses();
        $log = $log['node'];
        $log['originPath'] = $log['filePath'];
        $log['filePath'] = urldecode($log['filePath']);
        $log['text'] = (strlen($log['filePath']) > 45) ? substr($log['filePath'],0,45   ).'...' : $log['filePath'];
        $log['time'] = convertTimeToReadable($log['time']);
        $log['class_path'] = '';
        $log['class_info'] = '';

        if ($log['event'] === 'modified') {
            $log['info'] = __( 'normal file', 'wtotem' );
            $log['class_path'] = "wtotem_file-table__td_changed";
            $log['class_info'] = "wtotem_file-table__td_normal";
            $log['description'] = $statuses['changed'];
        } elseif ($log['event'] === 'quarantine') {
            $log['info'] = __( 'in quarantine', 'wtotem' );
            $log['class_path'] = "wtotem_file-table__td_changed";
            $log['class_info'] = "wtotem_file-table__td_normal";
            $log['description'] = $statuses['quarantine'];
        } elseif ($log['event'] === 'infected') {
            $log['info'] = __( 'backdoor virus', 'wtotem' );
            $log['class_path'] = "wtotem_file-table__td_critical";
            $log['class_info'] = "wtotem_file-table__td_critical";
            $log['description'] = $statuses['infected'];
        } elseif ($log['event'] === 'deleted') {
            $log['info'] = __( 'deleted file', 'wtotem' );;
            $log['description'] = $statuses['deleted'];
        }elseif ($log['event'] === 'new'){
            $log['info'] = __( 'normal file', 'wtotem' );
            $log['description'] = $statuses['new'];
        }elseif ($log['event'] === 'scanned'){
            $log['info'] = __( 'normal file', 'wtotem' );
            $log['description'] = $statuses['scanned'];
        }else{
            $log['info'] = $statuses['error'];
            $log['description'] = $statuses['error'];
        }

        $logs[$key]['node'] = $log;
    }
    return $logs;
}

function wtsec_getConfigs($host_id)
{
    $config = WTSEC_LIBRARY_WT::getConfigs($host_id);
    return wtsec_arrayIndex($config['data']['auth']['viewer']['sites']['one']['configs'], 'service');
}

function wtsec_arrayIndex($array, $key){
    $newArray = [];
    foreach ($array as $item){
        if(array_key_exists($key,$item)){
            $newArray[$item[$key]] = $item;
        }
    }
    return $newArray;
}

function wtsec_button($label = '', $class = '')
{
    return '<button class="ww-button ' . $class . '">' . $label . '</button>';
}

function wtsec_main_button($label = '', $class = '')
{
    return '<button class="ww-button ' . $class . '">' . $label . '</button>';
}

function wtsec_generateButtons($uid, $_service, $service, $status, $domain = '')
{
    $url = esc_url(admin_url('admin-post.php'));
    $buttons = [];

    $form = '<form action="' . $url . '" method="post" style="display:inline-block;">
        <input type="hidden" name="service" value="' . $_service . '">
        <input type="hidden" name="action" value="ajax_cmd">
        <input type="hidden" name="uid" value="' . $uid . '">
        <input type="hidden" name="cmd" value="{{{cmd}}}">{{{button}}}</form>';
    $result = [];
    $installedFile = wtsec_checkInstalledFile($_service);
    $disable_uninstall = false;
    $first_class = "ww-button--block ";

    if ($service === "AM") {
        if (!$installedFile['status']) {
            $cmd = $_service . '_install';
            $buttons[] = ['place' => 'first', 'button' => wtsec_button(__( 'Install', 'wtotem' ), $first_class . "ww-button--success"), 'cmd' => $cmd];
        } else {
//            $url = $domain.'/'.$installedFile['file'];
//        $connected = wtsec_servicePing($service,$url);
            if (!$disable_uninstall) {
                $cmd = $_service . '_uninstall';
                $buttons[] = ['place' => 'first', 'button' => wtsec_button(__( 'Uninstall', 'wtotem' ), $first_class . "ww-button--attention"), 'cmd' => $cmd];
            }
        }
    } else {
        if ($service === "WAF") {
            $first_class = "";
        }

        if ($status === "not_installed") {
            $cmd = $_service . '_install';
            $buttons[] = ['place' => 'first', 'button' => wtsec_button(__( 'Install', 'wtotem' ), $first_class . "ww-button--success"), 'cmd' => $cmd];
        }
    }


    foreach ($buttons as $btn) {
        $newform = $form;
        $newform = str_replace("{{{cmd}}}", $btn['cmd'], $newform);
        $newform = str_replace("{{{button}}}", $btn['button'], $newform);
        $result[$btn['place']] = $newform;
    }
    return $result;
}

function wtsec_checkInstalledFile($service)
{
    $file = wtsec_getInstalledFile($service);
    $root = ABSPATH;

    return ['status' => ((bool)$file) && is_file($root . $file), 'file' => $file];
}

function wtsec_getInstalledFile($service)
{
    return wtsec_app()->get($service . "_installed_file");
}

function wtsec_getStatuses()
{
    return [
        'warning' => __( 'Warning', 'wtotem' ),
        'error' => __( 'Error', 'wtotem' ),
        'invalid' => __( 'Invalid', 'wtotem' ),
        'ok' => __( 'Everything is OK', 'wtotem' ),
        'expired' => __( 'Expired', 'wtotem' ),
        'expires' => __( 'Expires', 'wtotem' ),
        'expires_today' => __( 'Expires today', 'wtotem' ),
        'missing' => __( 'Missing', 'wtotem' ),
        'success' => __( 'Success', 'wtotem' ),
        'info' => __( 'Info', 'wtotem' ),
        'active' => __( 'Active', 'wtotem' ),
        'inactive' => __( 'Inactive', 'wtotem' ),
        'pending' => __( 'Pending', 'wtotem' ),
        'pause' => __( 'Disabled', 'wtotem' ),
        'available' => __( 'Available', 'wtotem' ),
        'unavailable' => __( 'Unavailable', 'wtotem' ),
        //
        'not_registered' => __( 'Not registered', 'wtotem' ),
        'unsupported' => __( 'Unsupported', 'wtotem' ),
        'clean' => __( 'Clean', 'wtotem' ),
        'clear' => __( 'Clear', 'wtotem' ),
        'blacklisted' => __( 'Infected', 'wtotem' ),
        'miner_detected' => __( 'Infected', 'wtotem' ),
        'deface' => __( 'Deface', 'wtotem' ),
        'modified' => __( 'Modified', 'wtotem' ),
        'detected' => __( 'Detected', 'wtotem' ),
        'open' => __( 'Open', 'wtotem' ),
        'blocked' => __( 'Blocked', 'wtotem' ),
        'connected' => __( 'Connected', 'wtotem' ),
        'attacks_detected' => __( 'Attacks detected', 'wtotem' ),
        'signature_found' => __( 'Signature found', 'wtotem' ),
        'file_changes' => __( 'File changes', 'wtotem' ),
        //
        'no_cert' => __( 'No cert', 'wtotem' ),
        'down' => __( 'Down', 'wtotem' ),
        'up' => __( 'Up', 'wtotem' ),
        'infected' => __( 'Infected', 'wtotem' ),
        'not_installed' => __( 'Need to install', 'wtotem' ),
        'working' => __( 'Working', 'wtotem' ),

        "critical" => __( 'Critical', 'wtotem' ),
        "deleted" => __( 'Deleted', 'wtotem' ),
        "changed" => __( 'Changed', 'wtotem' ),
        "new" => __( 'New', 'wtotem' ),
        "scanned" => __( 'Scanned', 'wtotem' ),
        "quarantine" => __( 'In quarantine', 'wtotem' ),
    ];
}

```
