%PDF- %PDF-
| Direktori : /dom405686/wp-content/plugins/pws-core/admin/handlers/ |
| Current File : /dom405686/wp-content/plugins/pws-core/admin/handlers/class-audit-handler.php |
<?php
namespace GD_cORe\handlers;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* The admin-specific functionality of the plugin.
*
*
* @package GD_cORe
* @subpackage GD_cORe/admin
*/
class Audits extends Main {
const LIGHTHOUSE_TABLE = 'gdcore_lighthouse_reports';
public function __construct(){
parent::__construct();
}
/**
* Stores a lighthouse report in the local database
*
* @since 4.0.0
* @param string $report_id The unique report ID
* @param string $url The URL that was tested
* @param array $report_data The lighthouse report data
* @return int|false The ID of the inserted record, or false on failure
*/
public function storeLighthouseReport($report_id, $url, $report_data) {
global $wpdb;
$table_name = $wpdb->prefix . self::LIGHTHOUSE_TABLE;
$data = array(
'report_id' => $report_id,
'url' => $url,
'date_created' => current_time('mysql'),
'report_data' => json_encode($report_data)
);
$result = $wpdb->insert($table_name, $data);
if ($result) {
return $wpdb->insert_id;
}
return false;
}
/**
* Gets a lighthouse report by report ID
*
* @since 4.0.0
* @param string $report_id The unique report ID
* @return array|false The report data, or false if not found
*/
public function getLighthouseReportById($report_id) {
global $wpdb;
$table_name = $wpdb->prefix . self::LIGHTHOUSE_TABLE;
$query = $wpdb->prepare(
"SELECT * FROM $table_name WHERE report_id = %s",
$report_id
);
$result = $wpdb->get_row($query, ARRAY_A);
if ($result) {
$result['report_data'] = json_decode($result['report_data'], true);
return $result;
}
return false;
}
/**
* grabs all lighthouse reports from local database
*
* @since 4.0.0
* @return array
**/
public function getLhReports(){
global $wpdb;
$table_name = $wpdb->prefix . self::LIGHTHOUSE_TABLE;
$results = $wpdb->get_results(
"SELECT * FROM $table_name ORDER BY date_created DESC",
ARRAY_A
);
$reports = array();
if ($results) {
foreach ($results as $result) {
$reports[] = array(
'id' => $result['id'],
'reportID' => $result['report_id'],
'date' => $result['date_created'],
'url' => $result['url']
);
}
return array('response' => $reports);
}
return array('response' => array());
}
/**
* grabs stats from most recent lighthouse report
*
* @since 4.0.0
* @return array
**/
public function getLHStats($attemptedUpdate = false) {
global $wpdb;
$table_name = $wpdb->prefix . self::LIGHTHOUSE_TABLE;
$result = $wpdb->get_row(
"SELECT * FROM $table_name ORDER BY date_created DESC LIMIT 1",
ARRAY_A
);
if ($result) {
$decoded_data = json_decode($result['report_data'], true);
if (!$decoded_data) {
return array(); // Handle invalid JSON
}
$recent_test = array($decoded_data);
if (isset($recent_test[0]['pending']) && $recent_test[0]['pending']) {
// Avoid infinite recursion
if ($attemptedUpdate) {
return array();
}
// Report exists but is still pending — try to update
$reportFinished = $this->updateLighthouseReport($result['report_id'], '');
if ($reportFinished) {
return $this->getLHStats(true); // Prevent repeated attempts
} else {
return $recent_test;
}
}
return $recent_test;
}
return array();
}
/**
* requests another lighthouse report from the API and stores locally
*
* @since 4.0.0
* @return array
**/
public function requestLHReport() {
// Scan the site's own configured URL, never request-derived host data.
$url = home_url();
if (!\GD_cORe_Site_Auth::is_scan_url($url)) {
return null;
}
// Prepare request payload
$reportRequest = json_encode(['url' => $url]);
// Send report request
$result = $this->gdcore_http_response('lighthouse/reports?accountId=' . \GD_cORe_Site_Auth::account_id(), 'POST', $reportRequest);
$status = is_wp_error($result) ? 0 : (int) wp_remote_retrieve_response_code($result);
$response = $status >= 200 && $status < 300 ? json_decode(wp_remote_retrieve_body($result), true) : null;
if (!$response || !\GD_cORe_Site_Auth::is_report_id($response['id'] ?? null) || ($response['report'] ?? null) !== true) {
return null; // Never store upstream error bodies or synthetic success IDs.
}
// Only store confirmed created reports.
$report_id = $response['id'];
$report_data = [
'pending' => true,
'timestamp' => current_time('mysql'),
'message' => 'Report generation in progress',
'categories' => [
'performance' => ['score' => 0],
'pwa' => ['score' => 0],
'best-practices' => ['score' => 0],
'accessibility' => ['score' => 0],
'seo' => ['score' => 0],
]
];
// Log to local DB
$this->storeLighthouseReport($report_id, $url, $report_data);
return $response;
}
/**
* Gets the raw lighthouse report data from the API
*
* @since 4.0.0
* @param string $report_id The report ID
* @return array|null The report data or null if not available
*/
private function getRawReportFromApi($report_id) {
if (!\GD_cORe_Site_Auth::is_report_id($report_id)) {
return null;
}
$result = $this->gdcore_http_response("lighthouse/reports/{$report_id}?format=json&accountId=" . \GD_cORe_Site_Auth::account_id(), 'GET');
if (!is_wp_error($result) && (int) wp_remote_retrieve_response_code($result) === 404) {
return array('error' => true, 'message' => 'Report no longer available. Run a new scan.');
}
if (!is_wp_error($result) && (int) wp_remote_retrieve_response_code($result) === 200) {
$decoded = json_decode(wp_remote_retrieve_body($result), true);
// Handle case where API returns an array of results
if (is_array($decoded) && !empty($decoded) && isset($decoded[0])) {
return $decoded[0];
}
return $decoded;
}
return null;
}
/**
* sets circle color based on score
*
* @since 2.7
* @return string
**/
public function circleColor($num = null){
$color = '';
// Handle string values with % sign
if (is_string($num) && strpos($num, '%') !== false) {
$num = (int)$num; // Convert "33%" to 33
}
if(!$num || $num == 'N/A'){
$color = '#E8EAEB';
}else if($num <= 49){
$color = '#DB1802';
}else if($num >= 50 && $num <= 89){
$color = '#F38F48';
}else if($num >= 90 && $num <= 100){
$color = '#00A63F';
}
return $color;
}
/**
* Updates a lighthouse report with latest data from the API
*
* @since 4.0.0
* @param string $report_id The report ID to update
* @param string $url The URL that was tested
* @return bool Success or failure
*/
public function updateLighthouseReport($report_id, $url) {
$raw_report_data = $this->getRawReportFromApi($report_id);
if (!empty($raw_report_data['error'])) {
global $wpdb;
$table_name = $wpdb->prefix . self::LIGHTHOUSE_TABLE;
$existing = $wpdb->get_row($wpdb->prepare("SELECT id FROM $table_name WHERE report_id = %s", $report_id));
// Only update locally confirmed reports; a read cannot establish ownership.
return $existing ? $wpdb->update($table_name, array('report_data' => json_encode($raw_report_data)), array('report_id' => $report_id)) !== false : false;
}
if (!$raw_report_data || empty($raw_report_data['categories']) || (isset($raw_report_data['state']) && $raw_report_data['state'] === 'requested')) {
return false;
}
// Check if the report is ready by checking state property
if (isset($raw_report_data['state']) && $raw_report_data['state'] !== 'processed') {
return false;
}
// Get existing report to avoid duplicate entries
global $wpdb;
$table_name = $wpdb->prefix . self::LIGHTHOUSE_TABLE;
$existing = $wpdb->get_row($wpdb->prepare(
"SELECT id FROM $table_name WHERE report_id = %s",
$report_id
));
// If report exists, update instead of insert
if ($existing) {
$data = array(
'report_data' => json_encode($raw_report_data)
);
$where = array('report_id' => $report_id);
$result = $wpdb->update($table_name, $data, $where);
return ($result !== false);
} else {
// New report
return $this->storeLighthouseReport($report_id, $url, $raw_report_data);
}
}
}