#!/usr/local/bin/php getenv('DA_BASE_URL') ?: 'https://127.0.0.1:2222', 'user' => getenv('DA_API_USER') ?: '', 'key' => getenv('DA_API_LOGIN_KEY') ?: '', 'audit_log' => getenv('MAIL_LOGIN_AUDIT_LOG') ?: '/usr/local/hitme_plugins/mail-login-helper/logs/audit.log', ]; if ($config['user'] === '' || $config['key'] === '') { fwrite(STDERR, "DirectAdmin API credentials are required for cleanup\n"); exit(2); } $base = rtrim($config['base_url'], '/'); $now = time(); $entries = apiRequest('GET', $base . '/api/login-keys/urls', $config); if (!is_array($entries)) { fwrite(STDERR, "DirectAdmin returned invalid login URL list\n"); exit(1); } $deleted = 0; foreach ($entries as $entry) { if (!is_array($entry) || empty($entry['id']) || empty($entry['expires'])) { continue; } $expires = strtotime((string)$entry['expires']); if ($expires !== false && $expires < $now) { apiRequest('DELETE', $base . '/api/login-keys/urls/' . rawurlencode((string)$entry['id']), $config); $deleted++; } } audit($config['audit_log'], [ 'event' => 'cleanup_expired_login_urls', 'result' => 'success', 'deleted' => $deleted, ]); echo "Deleted expired login URLs: {$deleted}\n"; /** * @param array $config * @return mixed */ function apiRequest(string $method, string $url, array $config): mixed { $ch = curl_init($url); if ($ch === false) { throw new RuntimeException('Cannot initialize curl'); } curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_USERPWD => $config['user'] . ':' . $config['key'], CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 20, CURLOPT_HTTPHEADER => ['Accept: application/json'], ]); $body = curl_exec($ch); $code = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE); $error = curl_error($ch); curl_close($ch); if ($body === false || $code >= 400) { throw new RuntimeException($error !== '' ? $error : 'DirectAdmin API request failed'); } if ($method === 'DELETE') { return true; } return json_decode((string)$body, true, 512, JSON_THROW_ON_ERROR); } /** * @param array $fields */ function audit(string $path, array $fields): void { $dir = dirname($path); if (!is_dir($dir)) { mkdir($dir, 0700, true); } $fields['timestamp'] = gmdate('c'); file_put_contents($path, json_encode($fields, JSON_UNESCAPED_SLASHES) . "\n", FILE_APPEND | LOCK_EX); chmod($path, 0600); }