getTimestamp(); // Ensure the configuration file is valid.. if (!isValidConfiguration($config)) { echo generateErrorResponse(0x80000001, "Invalid configuration file detected."); exit; } // Attempt to get the cached data.. $data = getCachedData($cacheFile); if ($data !== false) { // Check if the cached data has expired.. if (json_decode($data)->timestamp + $config['cache']['lifetime'] > $timestamp) { // Erase configurations from memory.. unset($config); // Data is still valid, use it.. echo $data; exit; } } /** * No cached data present or it is invalid or expired. Instead, we must query the * database for the needed information to populate the cache with new data. */ try { // Connect to the database.. $db = new PDO("mysql:host={$config['db']['host']};port={$config['db']['port']};dbname={$config['db']['name']}", $config['db']['user'], $config['db']['pass']); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Empty the database configurations.. unset($config['db']); // Query the database for the current online counts.. $sql = $db->query("SELECT COUNT(DISTINCT(client_addr)) AS u, COUNT(*) AS t FROM accounts_sessions;")->fetchall(); if (!is_array($sql) || count($sql) !== 1) { // Invalid results, return an error.. echo generateErrorResponse(0x80000002, 'Failed to query database for count information.'); exit; } // Build the new server information array.. $data = array( 'status' => 0, 'version' => ASHITA_PSCAPI_VERSION, 'timestamp' => $timestamp, 'lifetime' => $config['server']['lifetime'], 'name' => $config['server']['name'], 'levelcap' => $config['server']['levelcap'], 'ip' => $config['server']['ip'], 'website' => $config['server']['website'], 'discord' => $config['server']['discord'], 'total' => $sql[0]['t'], 'unique' => $sql[0]['u'] ); try { // Open the cache file for writing.. $f = fopen($cacheFile, 'w'); if ($f === FALSE) { echo generateErrorResponse(0x80000003, 'Failed to update cache file. (1)'); exit; } // Write the data to the cache file.. fwrite($f, json_encode($data)); fclose($f); } catch (Exception $e) { echo generateErrorResponse(0x80000003, 'Failed to update cache file. (2)'); exit; } // Cleanup the pdo objects.. $sql = null; $db = null; // Echo the new data.. echo json_encode($data); exit; } catch (Exception $e) { echo generateErrorResponse(0x80000004, 'Failed to get server information.'); exit; }