Enhance Torn Vault Tracker: Add documentation, improve exception handling, and update styles
Deploy website via FTP / Deploy (push) Skipped

- Updated .gitignore to exclude new directories and files.
- Enhanced config.php with detailed PHPDoc comments for better clarity.
- Refactored functions.php to include PHPDoc comments and improve code readability.
- Added custom exceptions in exceptions.php with detailed documentation.
- Improved utilities.php with better documentation and error handling.
- Updated index.php with structured comments and improved readability.
- Refined style.css for better visual consistency.
- Introduced phpcs.xml for coding style checks and standards enforcement.
This commit is contained in:
Keith Solomon
2026-08-03 12:07:16 -05:00
parent 8c68e81c2e
commit 2811fc83e5
8 changed files with 656 additions and 462 deletions
+2
View File
@@ -3,3 +3,5 @@ backup/
debug.log debug.log
data/* data/*
!data/.gitkeep !data/.gitkeep
.claude/
phpcs-results.txt
+13 -3
View File
@@ -1,10 +1,20 @@
<?php <?php
// Configuration file for settings like database and API keys /**
* Configuration file for settings like database and API keys
*
* PHP version 8.1+
*
* @category Configuration
* @package TornVaultTracker
* @author Keith Solomon <ksolomon@gmail.com>
* @license Unlicense https://unlicense.org/
* @link https://github.com/ksolomon/TornVaultTracker
*/
// Database settings // Database settings
define('DB_DSN', 'sqlite:data/vault.db'); // Path to your SQLite database define('DB_DSN', 'sqlite:data/vault.db'); // Path to your SQLite database
define('DB_USER', null); // Not needed for SQLite define('DB_USER', null); // Not needed for SQLite
define('DB_PASSWORD', null); // Not needed for SQLite define('DB_PASSWORD', null); // Not needed for SQLite
// User-specific keys for accessing logs // User-specific keys for accessing logs
const USER_KEYS = [ const USER_KEYS = [
+129 -102
View File
@@ -1,44 +1,58 @@
<?php <?php
// Include settings from a separate configuration file /**
* Functions for the Torn Vault Tracker application.
*
* PHP version 8.1+
*
* @category Functions
* @package TornVaultTracker
* @author Keith Solomon <ksolomon@gmail.com>
* @license Unlicense https://unlicense.org/
* @link https://github.com/ksolomon/TornVaultTracker
*/
// Include settings from configuration file
require_once __DIR__ . '/config.php'; require_once __DIR__ . '/config.php';
// Include utility functions // Include utility functions
require_once 'includes/exceptions.php'; require_once 'includes/exceptions.php';
require_once 'includes/utilities.php'; require_once 'includes/utilities.php';
/** Returns a PDO connection to the database /**
* Returns a PDO connection to the database
* This function creates the database connection and creates the database * This function creates the database connection and creates the database
* file if it doesn't exist, and the vault table if it doesn't exist. * file if it doesn't exist, and the vault table if it doesn't exist.
* *
* @return PDO * @return PDO
*/ */
function getDatabaseConnection() { function getDatabaseConnection() {
static $pdo = null; static $pdo = null;
// SQL to create the vault table if it doesn't exist // SQL to create the vault table if it doesn't exist
$createTableSQL = "CREATE TABLE IF NOT EXISTS vault ( $createTableSQL = "CREATE TABLE IF NOT EXISTS vault (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
user TEXT NOT NULL, user TEXT NOT NULL,
timestamp INTEGER NOT NULL, timestamp INTEGER NOT NULL,
description TEXT NOT NULL, description TEXT NOT NULL,
amount REAL NOT NULL amount REAL NOT NULL
);"; );";
if ($pdo === null) { if ($pdo === null) {
try { try {
$pdo = new PDO(DB_DSN, DB_USER, DB_PASSWORD); $pdo = new PDO(DB_DSN, DB_USER, DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec($createTableSQL); $pdo->exec($createTableSQL);
} catch (PDOException $e) { } catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage()); die("Database connection failed: " . $e->getMessage());
}
} }
}
return $pdo; return $pdo;
} }
/** Pulls and stores all vault transaction logs for a user from the Torn API. /**
* Pulls and stores all vault transaction logs for a user from the Torn API.
* *
* This function retrieves all transaction logs related to vault deposits and * This function retrieves all transaction logs related to vault deposits and
* withdrawals for a specified user. It continues fetching logs until no more * withdrawals for a specified user. It continues fetching logs until no more
@@ -48,96 +62,109 @@ function getDatabaseConnection() {
* authenticate requests to the Torn API. * authenticate requests to the Torn API.
* *
* @param string $user The user whose transaction logs are to be retrieved and stored. * @param string $user The user whose transaction logs are to be retrieved and stored.
*
* @throws ApiKeyMissingException If the user does not have an API key configured.
* @throws CurlErrorException If there is an error during the API call.
* @throws Exception If there is an error decoding the JSON response or if the response is invalid.
*
* @return void
*/ */
function firstRun($user) { function firstRun($user) {
$apiKey = USER_KEYS[$user]; $apiKey = USER_KEYS[$user];
$pdo = getDatabaseConnection();
$to = time();
$pdo = getDatabaseConnection(); do {
$url = "https://api.torn.com/v2/user?selections=log&log=5850,5851&to=$to";
$ch = curl_init($url);
$to = time(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt(
$ch, CURLOPT_HTTPHEADER, [
'accept: application/json',
"Authorization: ApiKey $apiKey"
]
);
do { $response = curl_exec($ch);
$url = "https://api.torn.com/v2/user?selections=log&log=5850,5851&to=$to";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_close($ch);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'accept: application/json',
"Authorization: ApiKey $apiKey"
]);
$response = curl_exec($ch); $data = json_decode($response, true);
curl_close($ch); if (empty($data['log'])) {
break;
}
$data = json_decode($response, true); foreach ($data['log'] as $key => $entry) {
$description = $entry['title'];
$timestamp = $entry['timestamp'];
$amount = isset($entry['data']['deposited']) ? $entry['data']['deposited'] : -$entry['data']['withdrawn'];
if (empty($data['log'])) { break; } $stmt = $pdo->prepare('INSERT INTO vault (ID, user, timestamp, description, amount) VALUES (:id, :user, :timestamp, :description, :amount)');
foreach ($data['log'] as $key => $entry) { $stmt->bindValue(':id', $key);
$description = $entry['title']; $stmt->bindValue(':user', $user);
$timestamp = $entry['timestamp']; $stmt->bindValue(':timestamp', $timestamp);
$amount = isset($entry['data']['deposited']) ? $entry['data']['deposited'] : -$entry['data']['withdrawn']; $stmt->bindValue(':description', $description);
$stmt->bindValue(':amount', $amount);
$stmt = $pdo->prepare('INSERT INTO vault (ID, user, timestamp, description, amount) VALUES (:id, :user, :timestamp, :description, :amount)'); $stmt->execute();
}
$stmt->bindValue(':id', $key); $to = end($data['log'])['timestamp'];
$stmt->bindValue(':user', $user); } while (true);
$stmt->bindValue(':timestamp', $timestamp);
$stmt->bindValue(':description', $description);
$stmt->bindValue(':amount', $amount);
$stmt->execute();
}
$to = end($data['log'])['timestamp'];
} while (true);
} }
/** Retrieves the user's log entries from the Torn API /**
* Retrieves the user's log entries from the Torn API
* *
* @param string $user The user to retrieve the log for * @param string $user The user to retrieve the log for
* @param boolean $debug Whether to output debug information (default: false) * @param boolean $debug Whether to output debug information (default: false)
* *
* @throws Exception If the user does not have an API key configured, * @throws Exception If the user does not have an API key configured,
* if the API call fails, or if the log data is invalid * if the API call fails, or if the log data is invalid
*
* @return void
*/ */
function getLog($user, $debug = false) { function getLog($user, $debug = false) {
$pdo = getDatabaseConnection(); $pdo = getDatabaseConnection();
ensureUserHasApiKey($user); ensureUserHasApiKey($user);
$stmt = $pdo->query("SELECT MAX(timestamp) AS max_timestamp FROM vault WHERE user = '$user'"); $stmt = $pdo->query("SELECT MAX(timestamp) AS max_timestamp FROM vault WHERE user = '$user'");
$row = $stmt->fetch(PDO::FETCH_ASSOC); $row = $stmt->fetch(PDO::FETCH_ASSOC);
$from = $row['max_timestamp']; $from = $row['max_timestamp'];
$to = time(); $to = time();
$apiKey = USER_KEYS[$user]; $apiKey = USER_KEYS[$user];
$apiEndpoint = "https://api.torn.com/user/?selections=log&log=5850,5851&to=$to&from=$from&key=$apiKey"; $apiEndpoint = "https://api.torn.com/user/?selections=log&log=5850,5851&to=$to&from=$from&key=$apiKey";
$responseData = executeApiCall($apiEndpoint); $responseData = executeApiCall($apiEndpoint);
validateApiResponse($responseData); validateApiResponse($responseData);
$checkStmt = prepareCheckStatement($pdo); $checkStmt = prepareCheckStatement($pdo);
$insertStmt = prepareInsertStatement($pdo); $insertStmt = prepareInsertStatement($pdo);
processLogEntries($responseData['log'], $user, $checkStmt, $insertStmt, $debug); processLogEntries($responseData['log'], $user, $checkStmt, $insertStmt, $debug);
} }
/** Generate the current balance for a user or all users /**
* Generate the current balance for a user or all users
* *
* @param string $name (optional) The user to get the balance for. If not provided, all users' balances will be added. * @param string $name (optional) The user to get the balance for. If not provided, all users' balances will be added.
* *
* @return string The balance as a formatted string * @return string The balance as a formatted string
*/ */
function generateBalance($name=null) { function generateBalance($name=null) {
$balance = vaultLoop($name); $balance = vaultLoop($name);
return number_format($balance, 0); // Format the balance as an integer return number_format($balance, 0); // Format the balance as an integer
} }
/** Calculate the available vault space for a user or all users. /**
* Calculate the available vault space for a user or all users.
* *
* This function calculates the remaining space in the vault based on the * This function calculates the remaining space in the vault based on the
* transactions for a specific user or all users. If a user is specified, * transactions for a specific user or all users. If a user is specified,
@@ -150,20 +177,20 @@ function generateBalance($name=null) {
* *
* @return string The available vault space as a formatted string. * @return string The available vault space as a formatted string.
*/ */
function getSpace($name=null) { function getSpace($name=null) {
$space = vaultLoop($name); $space = vaultLoop($name);
if ($name === null) { if ($name === null) {
$space = 1000000000 - $space; $space = 1000000000 - $space;
} else { } else {
$space = 500000000 - $space; $space = 500000000 - $space;
} }
return number_format($space, 0); // Format the balance as an integer return number_format($space, 0); // Format the balance as an integer
} }
/** Builds an HTML table of all transactions in the vault /**
* Builds an HTML table of all transactions in the vault
* *
* Loops over all records in the vault and builds a table of the user, timestamp, * Loops over all records in the vault and builds a table of the user, timestamp,
* description and amount of each transaction. Amounts are formatted as integers. * description and amount of each transaction. Amounts are formatted as integers.
@@ -171,29 +198,29 @@ function getSpace($name=null) {
* @return void * @return void
*/ */
function buildTable () { function buildTable () {
$records = fetchVaultRecords(); $records = fetchVaultRecords();
foreach ($records as $entry) { foreach ($records as $entry) {
$user = $entry['user']; $user = $entry['user'];
$timestamp = $entry['timestamp']; $timestamp = $entry['timestamp'];
$description = $entry['description']; $description = $entry['description'];
$amount = $entry['amount']; $amount = $entry['amount'];
$sign = getSign($amount); $sign = getSign($amount);
if ($description == 'Vault withdraw') { if ($description == 'Vault withdraw') {
$class = 'debit'; $class = 'debit';
$amount = substr($amount, 1); // Remove the negative sign $amount = substr($amount, 1); // Remove the negative sign
} else { } else {
$class = 'credit'; $class = 'credit';
}
$amount = number_format($amount, 0); // Format the amount as an integer
echo '<tr class="'.$class.'">';
echo '<td>'.$user.'</td>';
echo '<td>'.date("F j, Y / H:i", $timestamp).'</td>';
echo '<td>'.$description.'</td>';
echo '<td>'.$sign.$amount.'</td>';
echo '</tr>';
} }
$amount = number_format($amount, 0); // Format the amount as an integer
echo '<tr class="'.$class.'">';
echo '<td>'.$user.'</td>';
echo '<td>'.date("F j, Y / H:i", $timestamp).'</td>';
echo '<td>'.$description.'</td>';
echo '<td>'.$sign.$amount.'</td>';
echo '</tr>';
}
} }
+88 -12
View File
@@ -1,24 +1,100 @@
<?php <?php
/**
* Custom exceptions for API interactions.
*
* PHP version 8.1+
*
* @category Exception
* @package TornVaultTracker
* @author Keith Solomon <ksolomon@gmail.com>
* @license Unlicense https://unlicense.org/
* @link https://github.com/ksolomon/Torn-Vault-Tracker
*/
/**
* Exception thrown when API key is missing.
*
* @category Exception
* @package TornVaultTracker
* @author Keith Solomon <ksolomon@gmail.com>
* @license Unlicense https://unlicense.org/
* @link https://github.com/ksolomon/Torn-Vault-Tracker
*/
class ApiKeyMissingException extends Exception { class ApiKeyMissingException extends Exception {
public function __construct($message, $code = 0, Throwable $previous = null) { /**
parent::__construct($message, $code, $previous); * Constructor.
} *
* @param string $message The exception message.
* @param int $code The exception code.
* @param Throwable $previous The previous throwable.
*/
public function __construct($message, $code = 0, Throwable $previous = null) {
parent::__construct($message, $code, $previous);
}
} }
/**
* Exception thrown on CURL errors.
*
* @category Exception
* @package TornVaultTracker
* @author Keith Solomon <ksolomon@gmail.com>
* @license Unlicense https://unlicense.org/
* @link https://github.com/ksolomon/Torn-Vault-Tracker
*/
class CurlErrorException extends Exception { class CurlErrorException extends Exception {
public function __construct($message, $code = 0, Throwable $previous = null) { /**
parent::__construct($message, $code, $previous); * Constructor.
} *
* @param string $message The exception message.
* @param int $code The exception code.
* @param Throwable $previous The previous throwable.
*/
public function __construct($message, $code = 0, Throwable $previous = null) {
parent::__construct($message, $code, $previous);
}
} }
/**
* Exception thrown on JSON data errors.
*
* @category Exception
* @package TornVaultTracker
* @author Keith Solomon <ksolomon@gmail.com>
* @license Unlicense https://unlicense.org/
* @link https://github.com/ksolomon/Torn-Vault-Tracker
*/
class JsonDataException extends Exception { class JsonDataException extends Exception {
public function __construct($message, $code = 0, Throwable $previous = null) { /**
parent::__construct($message, $code, $previous); * Constructor.
} *
* @param string $message The exception message.
* @param int $code The exception code.
* @param Throwable $previous The previous throwable.
*/
public function __construct($message, $code = 0, Throwable $previous = null) {
parent::__construct($message, $code, $previous);
}
} }
/**
* Exception thrown on API validation errors.
*
* @category Exception
* @package TornVaultTracker
* @author Keith Solomon <ksolomon@gmail.com>
* @license Unlicense https://unlicense.org/
* @link https://github.com/ksolomon/Torn-Vault-Tracker
*/
class ApiValidationException extends Exception { class ApiValidationException extends Exception {
public function __construct($message, $code = 0, Throwable $previous = null) { /**
parent::__construct($message, $code, $previous); * Constructor.
} *
* @param string $message The exception message.
* @param int $code The exception code.
* @param Throwable $previous The previous throwable.
*/
public function __construct($message, $code = 0, Throwable $previous = null) {
parent::__construct($message, $code, $previous);
}
} }
+135 -96
View File
@@ -1,5 +1,21 @@
<?php <?php
/** Checks if the database is new and empty. /**
* Utility functions for the Torn Vault Tracker application.
*
* This file contains helper functions for database operations, API calls,
* and vault record management.
*
* PHP version 8.1+
*
* @category Utility
* @package TornVaultTracker
* @author Keith Solomon <ksolomon@gmail.com>
* @license Unlicense https://unlicense.org/
* @link https://github.com/ksolomon/Torn-Vault-Tracker
*/
/**
* Checks if the database is new and empty.
* *
* This function checks if the 'vault' table in the database has any entries. * This function checks if the 'vault' table in the database has any entries.
* If it does not, it returns true, indicating that the database is new and * If it does not, it returns true, indicating that the database is new and
@@ -8,25 +24,29 @@
* @return boolean True if the database is new and empty, false otherwise. * @return boolean True if the database is new and empty, false otherwise.
*/ */
function dbNew() { function dbNew() {
$pdo = getDatabaseConnection(); $pdo = getDatabaseConnection();
$stmt = $pdo->query("SELECT COUNT(*) FROM vault"); $stmt = $pdo->query("SELECT COUNT(*) FROM vault");
return $stmt->fetchColumn() == 0; return $stmt->fetchColumn() == 0;
} }
/** Ensures that a user has an API key configured. /**
* Ensures that a user has an API key configured.
* *
* @param string $user The user to check the API key for * @param string $user The user to check the API key for
* *
* @return void
*
* @throws Exception If the user does not have an API key configured * @throws Exception If the user does not have an API key configured
*/ */
function ensureUserHasApiKey($user) { function ensureUserHasApiKey($user) {
if (!array_key_exists($user, USER_KEYS)) { if (!array_key_exists($user, USER_KEYS)) {
throw new ApiKeyMissingException("User does not have an API key configured."); throw new ApiKeyMissingException("User does not have an API key configured.");
} }
} }
/** Executes a GET request to the given API endpoint and returns the JSON response as an associative array. /**
* Executes a GET request to the given API endpoint and returns the JSON response as an associative array.
* *
* @param string $apiEndpoint The URL of the API endpoint to call * @param string $apiEndpoint The URL of the API endpoint to call
* *
@@ -35,112 +55,125 @@ function ensureUserHasApiKey($user) {
* @return array The JSON response from the API * @return array The JSON response from the API
*/ */
function executeApiCall($apiEndpoint) { function executeApiCall($apiEndpoint) {
$headers = ["Content-Type: application/json"]; $headers = ["Content-Type: application/json"];
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiEndpoint); curl_setopt($ch, CURLOPT_URL, $apiEndpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch); $response = curl_exec($ch);
if (curl_errno($ch)) { if (curl_errno($ch)) {
throw new CurlErrorException("cURL error: " . curl_error($ch)); throw new CurlErrorException("cURL error: " . curl_error($ch));
} }
curl_close($ch); curl_close($ch);
$responseData = json_decode($response, true); $responseData = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) { if (json_last_error() !== JSON_ERROR_NONE) {
throw new JsonDataException("Failed to decode JSON response: " . json_last_error_msg()); throw new JsonDataException("Failed to decode JSON response: " . json_last_error_msg());
} }
return $responseData; return $responseData;
} }
/** Validates the API response data for the presence of a log array. /**
* Validates the API response data for the presence of a log array.
* *
* @param array $responseData The API response data to validate. * @param array $responseData The API response data to validate.
* *
* @return void
*
* @throws Exception If the log data is missing or not an array. * @throws Exception If the log data is missing or not an array.
*/ */
function validateApiResponse($responseData) { function validateApiResponse($responseData) {
if (!isset($responseData['log']) || !is_array($responseData['log'])) { if (!isset($responseData['log']) || !is_array($responseData['log'])) {
throw new ApiValidationException("Invalid log data received from the API."); throw new ApiValidationException("Invalid log data received from the API.");
} }
} }
/** Prepare a PDO statement for checking if a given vault transaction already exists in the database. /**
* Prepare a PDO statement for checking if a given vault transaction already exists in the database.
* *
* @param PDO $pdo The PDO instance to prepare the statement with * @param PDO $pdo The PDO instance to prepare the statement with
* *
* @return PDOStatement The prepared statement * @return PDOStatement The prepared statement
*/ */
function prepareCheckStatement($pdo) { function prepareCheckStatement($pdo) {
$checkQuery = "SELECT COUNT(*) FROM vault WHERE user = :user AND timestamp = :timestamp AND amount = :amount"; $checkQuery = "SELECT COUNT(*) FROM vault WHERE user = :user AND timestamp = :timestamp AND amount = :amount";
return $pdo->prepare($checkQuery); return $pdo->prepare($checkQuery);
} }
/** Prepare a PDO statement for inserting a new vault transaction into the database. /**
* Prepare a PDO statement for inserting a new vault transaction into the database.
* *
* @param PDO $pdo The PDO instance to prepare the statement with * @param PDO $pdo The PDO instance to prepare the statement with
* *
* @return PDOStatement The prepared statement * @return PDOStatement The prepared statement
*/ */
function prepareInsertStatement($pdo) { function prepareInsertStatement($pdo) {
$insertQuery = "INSERT INTO vault (ID, user, timestamp, description, amount) VALUES (:id, :user, :timestamp, :description, :amount)"; $insertQuery = "INSERT INTO vault (ID, user, timestamp, description, amount) VALUES (:id, :user, :timestamp, :description, :amount)";
return $pdo->prepare($insertQuery); return $pdo->prepare($insertQuery);
} }
/** Process an array of log entries retrieved from the Torn API. /**
* Process an array of log entries retrieved from the Torn API.
* *
* Goes through each log entry and checks if it's a vault deposit or withdrawal. * Goes through each log entry and checks if it's a vault deposit or withdrawal.
* If it is, it checks if the entry already exists in the database. If it * If it is, it checks if the entry already exists in the database. If it
* doesn't, it inserts the entry into the database. * doesn't, it inserts the entry into the database.
* *
* @param array $logEntries The array of log entries to process * @param array $logEntries The array of log entries to process
* @param string $user The user whose log entries are being processed * @param string $user The user whose log entries are being processed
* @param PDOStatement $checkStmt A prepared statement to check if an entry * @param PDOStatement $checkStmt A prepared statement to check if an entry
* already exists in the database * already exists in the database
* @param PDOStatement $insertStmt A prepared statement to insert a new entry * @param PDOStatement $insertStmt A prepared statement to insert a new entry
* into the database * into the database
* @param boolean $debug Whether to output debug information (default: false) * @param boolean $debug Whether to output debug information (default: false)
*
* @return void
*/ */
function processLogEntries($logEntries, $user, $checkStmt, $insertStmt, $debug) { function processLogEntries($logEntries, $user, $checkStmt, $insertStmt, $debug) {
foreach ($logEntries as $key =>$entry) { foreach ($logEntries as $key =>$entry) {
if ($debug) { if ($debug) {
$logMessage = "Raw entry:\n" . print_r($entry, true); $logMessage = "Raw entry:\n" . print_r($entry, true);
file_put_contents(__DIR__ . '/debug.log', $logMessage, FILE_APPEND); file_put_contents(__DIR__ . '/debug.log', $logMessage, FILE_APPEND);
}
$timestamp = $entry['timestamp'];
$description = $entry['title'];
$amount = $entry['log'] === 5850 ? $entry['data']['deposited'] : -$entry['data']['withdrawn'];
if ($debug) {
$logMessage = "Vault entry:\n\tUser: $user,\n\tTimestamp: $timestamp,\n\tDescription: $description,\n\tAmount: $amount\n";
file_put_contents(__DIR__ . '/debug.log', $logMessage, FILE_APPEND);
}
$checkStmt->execute(
[
':user' => $user,
':timestamp' => $timestamp,
':amount' => $amount
]
);
if ($checkStmt->fetchColumn() == 0) {
$insertStmt->execute(
[
':id' => $key,
':user' => $user,
':timestamp' => $timestamp,
':description' => $description,
':amount' => $amount
]
);
}
} }
$timestamp = $entry['timestamp'];
$description = $entry['title'];
$amount = $entry['log'] === 5850 ? $entry['data']['deposited'] : -$entry['data']['withdrawn'];
if ($debug) {
$logMessage = "Vault entry:\n\tUser: $user,\n\tTimestamp: $timestamp,\n\tDescription: $description,\n\tAmount: $amount\n";
file_put_contents(__DIR__ . '/debug.log', $logMessage, FILE_APPEND);
}
$checkStmt->execute([
':user' => $user,
':timestamp' => $timestamp,
':amount' => $amount
]);
if ($checkStmt->fetchColumn() == 0) {
$insertStmt->execute([
':id' => $key,
':user' => $user,
':timestamp' => $timestamp,
':description' => $description,
':amount' => $amount
]);
}
}
} }
/** Fetch vault records from the database /**
* Fetch vault records from the database
* If a user is provided, only that user's records * If a user is provided, only that user's records
* are returned. Otherwise, all records are returned. * are returned. Otherwise, all records are returned.
* *
@@ -149,29 +182,30 @@ function processLogEntries($logEntries, $user, $checkStmt, $insertStmt, $debug)
* @return array An array of records, or an empty array on error * @return array An array of records, or an empty array on error
*/ */
function fetchVaultRecords($user = null) { function fetchVaultRecords($user = null) {
$pdo = getDatabaseConnection(); $pdo = getDatabaseConnection();
if ($user) { if ($user) {
$query = "SELECT * FROM vault WHERE user = :user ORDER BY timestamp DESC"; $query = "SELECT * FROM vault WHERE user = :user ORDER BY timestamp DESC";
$params = [':user' => $user]; $params = [':user' => $user];
} else { } else {
$query = "SELECT * FROM vault ORDER BY timestamp DESC"; $query = "SELECT * FROM vault ORDER BY timestamp DESC";
$params = []; $params = [];
} }
try { try {
$stmt = $pdo->prepare($query); $stmt = $pdo->prepare($query);
$stmt->execute($params); $stmt->execute($params);
return $stmt->fetchAll(PDO::FETCH_ASSOC); return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { } catch (PDOException $e) {
echo "Error fetching records: " . $e->getMessage(); echo "Error fetching records: " . $e->getMessage();
return []; return [];
} }
} }
/** Iterate over all vault records for the given user (or all users if no user is given), /**
* Iterate over all vault records for the given user (or all users if no user is given),
* *
* @param string|null $name (optional) The user to loop over records for. * @param string|null $name (optional) The user to loop over records for.
* If not provided, all users' records will be looped over. * If not provided, all users' records will be looped over.
@@ -179,15 +213,18 @@ function fetchVaultRecords($user = null) {
* @return int The total balance of the given user (or all users if no user is given). * @return int The total balance of the given user (or all users if no user is given).
*/ */
function vaultLoop ($name=null) { function vaultLoop ($name=null) {
$vault = fetchVaultRecords($name); $vault = fetchVaultRecords($name);
$balance = 0; $balance = 0;
foreach ($vault as $entry) { $balance += $entry['amount']; } foreach ($vault as $entry) {
$balance += $entry['amount'];
}
return $balance; return $balance;
} }
/** Returns a string indicating the sign of a number, with a dollar symbol. /**
* Returns a string indicating the sign of a number, with a dollar symbol.
* *
* @param int|float $number The number to check. * @param int|float $number The number to check.
* *
@@ -195,7 +232,9 @@ function vaultLoop ($name=null) {
* number is negative. * number is negative.
*/ */
function getSign($number) { function getSign($number) {
if (substr($number, 0, 1) == '-') { return '-$'; } if (substr($number, 0, 1) == '-') {
return '-$';
}
return '$'; return '$';
} }
+19 -8
View File
@@ -1,16 +1,27 @@
<?php <?php
/**
* Main entry point for the Torn Vault Tracker application.
*
* PHP version 8.1+
*
* @category Main
* @package TornVaultTracker
* @author Keith Solomon <ksolmon@gmail.com>
* @license Unlicense https://unlicense.org/
* @link https://github.com/ksolmon/torn-vault-tracker
*/
require_once __DIR__ . '/config.php'; require_once __DIR__ . '/config.php';
include_once __DIR__ . '/functions.php'; require_once __DIR__ . '/functions.php';
if (dbNew()) { if (dbNew()) {
foreach (USER_KEYS as $key => $value) { foreach (USER_KEYS as $key => $value) {
firstRun($key); firstRun($key);
} }
header('Location: /'); header('Location: /');
} else { } else {
foreach (USER_KEYS as $key => $value) { foreach (USER_KEYS as $key => $value) {
getLog($key); getLog($key);
} }
} }
?> ?>
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0"?>
<ruleset name="Coding Style Checks">
<description>Coding Style Checks</description>
<ini name="error_reporting" value="E_ALL &#38; ~E_DEPRECATED" />
<arg value="sp"/>
<arg name="colors"/>
<arg name="extensions" value="php,html,css"/>
<arg name="parallel" value="2048"/>
<exclude-pattern>vendor/</exclude-pattern>
<exclude-pattern>node_modules/</exclude-pattern>
<rule ref="PEAR">
<exclude name="PEAR.Classes.ClassDeclaration"/>
<exclude name="PEAR.Functions.FunctionDeclaration"/>
<exclude name="Generic.Files.LineLength.TooLong"/>
<exclude name="Generic.WhiteSpace.DisallowSpaceIndent.SpacesUsed"/>
<exclude name="Generic.Functions.CallTimePassByReference"/>
<exclude name="Squiz.Commenting.FileComment.MissingPackageTag"/>
<exclude name="Squiz.Commenting.FileComment.Missing"/>
<exclude name="Squiz.Commenting.FileComment.WrongStyle"/>
<exclude name="Squiz.Commenting.InlineComment.InvalidEndChar"/>
</rule>
<rule ref="Internal.NoCodeFound">
<severity>0</severity>
</rule>
</ruleset>