Uname:Linux ip-11-115-0-196 6.8.0-1039-aws #41~22.04.1-Ubuntu SMP Thu Sep 11 10:54:48 UTC 2025 x86_64

403WebShell
403Webshell
Server IP : 13.126.101.145  /  Your IP : 216.73.217.47
Web Server : Apache/2.4.52 (Ubuntu)
System : Linux ip-11-115-0-196 6.8.0-1039-aws #41~22.04.1-Ubuntu SMP Thu Sep 11 10:54:48 UTC 2025 x86_64
User : www-data ( 33)
PHP Version : 8.3.17
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : ON
Directory :  /var/www/html/rentals_updated/wp-content/plugins/Vision Link Api/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/rentals_updated/wp-content/plugins/Vision Link Api/working-diffeent-db-bkcp
<?php
/**
 * Plugin Name: API Fetch Button
 * Description: Adds a button to fetch API data with OAuth 2.0 authentication.
 * Version: 1.0
 * Author: Your Name
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

// Add admin menu
add_action('admin_menu', function() {
    add_menu_page('API Fetch', 'API Fetch', 'manage_options', 'api-fetch', 'api_fetch_page');
});

function api_fetch_page() {
    $fetched_api_data = get_option('fetched_api_data', 'No data fetched yet. Click the button.');
    ?>
    <div class="wrap">
        <h1>API Fetch</h1>
        <button id="fetchApiData" class="button button-primary">Fetch Data</button>
        <pre><?php print_r($fetched_api_data); ?></pre>
    </div>
    <script>
        document.getElementById('fetchApiData').addEventListener('click', function() {
            fetch(ajaxurl, {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'action=fetch_api_data'
            })
            .then(response => response.json())
            .then(data => {
                console.log('API Data Fetched');
                location.reload(); // Reload page to show updated data
            })
            .catch(error => console.error('Error:', error));
        });
    </script>
    <?php
}

// Handle AJAX request
add_action('wp_ajax_fetch_api_data', 'fetch_api_data');
// Insert or update multiple equipment records
function insert_equipment_data($api_data) {
    // Connect to the custom database (ut_data)
    $custom_db = new wpdb('root', '', 'ut_data', 'localhost');
    $table_name = 'wp_equipment_utilization'; // Table in ut_data

    if (!isset($api_data['utilizations']) || !is_array($api_data['utilizations'])) {
        error_log('No utilizations data found in API response.');
        return;
    }

    foreach ($api_data['utilizations'] as $utilization) {
        if (!isset($utilization['equipmentHeader']) || !isset($utilization['dailyUtilizations'])) {
            error_log('Missing equipmentHeader or dailyUtilizations in utilization record.');
            continue;
        }

        $equipment = $utilization['equipmentHeader'];
        $serial_number = $equipment['serialNumber'] ?? null;
        $make = $equipment['make'] ?? null;
        $model = $equipment['model'] ?? null;
        $product_family = $equipment['productFamily'] ?? null;

        // ✅ Find the latest date from the API data for this equipment
        $latest_utilization = end($utilization['dailyUtilizations']);
        $latest_report = $latest_utilization['latestUtilizationReport'] ?? null;
        $latest_report_date = !empty($latest_report) ? date('Y-m-d', strtotime($latest_report)) : null;

        if (!$latest_report_date) {
            continue;
        }

        // ✅ Check if this latest date is already saved for this serial number
        $existing = $custom_db->get_var(
            $custom_db->prepare(
                "SELECT COUNT(*) FROM $table_name WHERE serial_number = %s AND DATE(latest_report) = %s",
                $serial_number, $latest_report_date
            )
        );

        // ✅ If this latest date is not saved, insert it
        if ($existing == 0) {
            $custom_db->insert($table_name, [
                'serial_number' => $serial_number,
                'make' => $make,
                'model' => $model,
                'product_family' => $product_family,
                'latest_report' => date('Y-m-d H:i:s', strtotime($latest_report)),
                'hour_meter' => $latest_utilization['hourMeter'] ?? null,
                'runtime_hours' => $latest_utilization['runtimeHours'] ?? null,
                'distance_traveled' => $latest_utilization['distanceTraveledKms'] ?? null,
                'odometer' => $latest_utilization['odometer'] ?? null,
                'target_runtime_hours' => $latest_utilization['targetRuntimeHours'] ?? null,
                'device_status' => $latest_utilization['deviceStatus'] ?? null,
                'asset_status' => $latest_utilization['assetStatus'] ?? null
            ]);

            error_log("✅ Inserted latest record for Serial: $serial_number on Date: $latest_report_date");
        } else {
            error_log("⚠️ Skipped: Data for Serial: $serial_number on Date: $latest_report_date already exists.");
        }
    }
}




function fetch_all_equipment_data($token, $cursor = null) {
    global $wpdb;
    
    $api_url = 'https://services.cat.com/catDigital/utilizationHistory/v1/utilization';
    
    // Append cursor if provided
    if (!empty($cursor)) {
        $api_url .= '?cursor=' . urlencode($cursor);
    }

    // Fetch API data
    $response = wp_remote_get($api_url, [
        'headers' => [
            'Authorization' => 'Bearer ' . $token,
            'Content-Type' => 'application/json',
        ],
        'timeout' => 30,
    ]);

    if (is_wp_error($response)) {
        error_log('API Fetch Error: ' . $response->get_error_message());
        return;
    }

    $api_data = json_decode(wp_remote_retrieve_body($response), true);

    // Store fetched API data in options (for display)
    update_option('fetched_api_data', $api_data);

    // Insert data into the database
    if (!empty($api_data['utilizations'])) {
        insert_equipment_data($api_data);
    }

    // Check for nextCursor and fetch next page recursively
    if (!empty($api_data['responseMetadata']['nextCursor'])) {
        $next_cursor = $api_data['responseMetadata']['nextCursor'];
        fetch_all_equipment_data($token, $next_cursor);
    }
}

// ✅ Main function to fetch API data (with pagination support)
function fetch_api_data() {
    $token = get_access_token();
    if (!$token) {
        wp_send_json_error('Failed to obtain access token');
    }

    // Start fetching all pages recursively
    fetch_all_equipment_data($token);

    wp_send_json_success(['message' => 'All data fetched and stored successfully']);
}



// Get OAuth 2.0 access token
function get_access_token() {
    $token_url = 'https://fedlogin.cat.com/as/token.oauth2';
    $client_id = 'visionlink_dlr_J090_2_cc_client';
    $client_secret = 'xPeEMbWFFZ9UjKiBVkcsftksauDH3MqT2lgKtRaUcbG7PAkgD9LdPIj2I1oRk1im';
    
    $response = wp_remote_post($token_url, [
        'headers' => [
            'Authorization' => 'Basic ' . base64_encode("$client_id:$client_secret"),
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
        'body' => 'grant_type=client_credentials',
    ]);
    
    if (is_wp_error($response)) {
        return false;
    }
    
    $body = json_decode(wp_remote_retrieve_body($response), true);
    return $body['access_token'] ?? false;
}

Youez - 2016 - github.com/yon3zu
LinuXploit