| 1 |
<?php |
| 2 |
|
| 3 |
namespace DebugLogViewer\Admin\Controllers; |
| 4 |
|
| 5 |
use DebugLogViewer\Admin\Models\LogModel; |
| 6 |
use \DebugLogViewer\Admin\Helpers\Utils; |
| 7 |
|
| 8 |
if (!defined('ABSPATH')) { |
| 9 |
exit; // Exit if accessed directly |
| 10 |
} |
| 11 |
|
| 12 |
require_once realpath(__DIR__) . '/BaseController.php'; |
| 13 |
|
| 14 |
class LiveUpdatesController extends BaseController { |
| 15 |
|
| 16 |
|
| 17 |
public const LIVE_UPDATE_INTERVAL = 5; // seconds |
| 18 |
public const ITERATIONS_PER_SESSION = 12; // 1 minute |
| 19 |
public const DEBUG_LOG_LAST_FILESIZE = 'dbg_lv_dbg_log_last_filesize'; |
| 20 |
public const LOG_UPDATES_INTERVAL = 10; // seconds |
| 21 |
|
| 22 |
private $logModel; |
| 23 |
|
| 24 |
public function __construct( ?LogModel $logModel = null ) { |
| 25 |
$this->logModel = $logModel ?? new LogModel(); |
| 26 |
} |
| 27 |
|
| 28 |
public function run() { |
| 29 |
// phpcs:ignore WordPress.Security.NonceVerification.Missing |
| 30 |
$this->verifyAjaxRequest(); |
| 31 |
|
| 32 |
if (isset($_POST['initial']) && $_POST['initial'] === 'true') { |
| 33 |
update_option(LogModel::LAST_POSITION_OPTION_NAME, $this->logModel->getInitialLogPosition()); |
| 34 |
} |
| 35 |
|
| 36 |
// phpcs:ignore WordPress.Security.NonceVerification.Missing |
| 37 |
$group_entries = isset($_POST['group_entries']) && $_POST['group_entries'] === 'true'; |
| 38 |
|
| 39 |
$this->clearDebugLogFileStat(); |
| 40 |
$updates = $this->logModel->getNewEntries(); |
| 41 |
|
| 42 |
if (isset($updates['data'])) { |
| 43 |
echo $this->getUpdates($updates, $group_entries); |
| 44 |
} |
| 45 |
|
| 46 |
wp_die(); |
| 47 |
} |
| 48 |
|
| 49 |
public function clearDebugLogFileStat(): void { |
| 50 |
$path = $this->logModel->getLogFilePath(); |
| 51 |
if (is_file($path) && file_exists($path)) { |
| 52 |
clearstatcache(true, $path); |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
public function getUpdates( $updates, bool $group_entries = true ): string { |
| 57 |
$formatted = array_map(function ( $row ) { |
| 58 |
if (empty($row)) { |
| 59 |
return; |
| 60 |
} |
| 61 |
|
| 62 |
$datetime = LogModel::getDatetime($row); |
| 63 |
|
| 64 |
return [ |
| 65 |
'timestamp' => strtotime($datetime) * 1000, |
| 66 |
'datetime' => LogModel::formatDatetimeWithTimezone($datetime), |
| 67 |
'line' => LogModel::getLine($row), |
| 68 |
'file' => LogModel::getFile($row), |
| 69 |
'type' => LogModel::getType($row), |
| 70 |
'description' => [ |
| 71 |
'text' => LogModel::getDescription($row), |
| 72 |
'stack_trace' => LogModel::getStackTrace($row), |
| 73 |
], |
| 74 |
]; |
| 75 |
}, $updates['data']); |
| 76 |
|
| 77 |
$entries = array_values(array_filter($formatted)); |
| 78 |
|
| 79 |
if ($group_entries) { |
| 80 |
$entries = LogModel::groupEntries($entries); |
| 81 |
} |
| 82 |
|
| 83 |
return json_encode([ |
| 84 |
'action' => $updates['action'], |
| 85 |
'data' => $entries, |
| 86 |
]); |
| 87 |
} |
| 88 |
} |
| 89 |
|