diff --git a/.gitignore b/.gitignore
index ee4548c..1261b06 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,3 +3,5 @@ backup/
debug.log
data/*
!data/.gitkeep
+.claude/
+phpcs-results.txt
diff --git a/config.php b/config.php
index 8802734..cdf1b50 100644
--- a/config.php
+++ b/config.php
@@ -1,10 +1,20 @@
+ * @license Unlicense https://unlicense.org/
+ * @link https://github.com/ksolomon/TornVaultTracker
+ */
// Database settings
define('DB_DSN', 'sqlite:data/vault.db'); // Path to your SQLite database
-define('DB_USER', null); // Not needed for SQLite
-define('DB_PASSWORD', null); // Not needed for SQLite
+define('DB_USER', null); // Not needed for SQLite
+define('DB_PASSWORD', null); // Not needed for SQLite
// User-specific keys for accessing logs
const USER_KEYS = [
diff --git a/functions.php b/functions.php
index f0b6468..c5eba8c 100644
--- a/functions.php
+++ b/functions.php
@@ -1,199 +1,226 @@
-setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
-
- $pdo->exec($createTableSQL);
- } catch (PDOException $e) {
- die("Database connection failed: " . $e->getMessage());
- }
- }
-
- return $pdo;
-}
-
-/** 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
- * withdrawals for a specified user. It continues fetching logs until no more
- * entries are available, and stores each entry in the database. Each log entry
- * is uniquely identified by its ID and includes details such as timestamp,
- * description, and amount. The function requires the user's API key to
- * authenticate requests to the Torn API.
- *
- * @param string $user The user whose transaction logs are to be retrieved and stored.
- */
-function firstRun($user) {
- $apiKey = USER_KEYS[$user];
-
- $pdo = getDatabaseConnection();
-
- $to = time();
-
- do {
- $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_setopt($ch, CURLOPT_HTTPHEADER, [
- 'accept: application/json',
- "Authorization: ApiKey $apiKey"
- ]);
-
- $response = curl_exec($ch);
-
- curl_close($ch);
-
- $data = json_decode($response, true);
-
- if (empty($data['log'])) { break; }
-
- foreach ($data['log'] as $key => $entry) {
- $description = $entry['title'];
- $timestamp = $entry['timestamp'];
- $amount = isset($entry['data']['deposited']) ? $entry['data']['deposited'] : -$entry['data']['withdrawn'];
-
- $stmt = $pdo->prepare('INSERT INTO vault (ID, user, timestamp, description, amount) VALUES (:id, :user, :timestamp, :description, :amount)');
-
- $stmt->bindValue(':id', $key);
- $stmt->bindValue(':user', $user);
- $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
- *
- * @param string $user The user to retrieve the log for
- * @param boolean $debug Whether to output debug information (default: false)
- *
- * @throws Exception If the user does not have an API key configured,
- * if the API call fails, or if the log data is invalid
- */
-function getLog($user, $debug = false) {
- $pdo = getDatabaseConnection();
-
- ensureUserHasApiKey($user);
-
- $stmt = $pdo->query("SELECT MAX(timestamp) AS max_timestamp FROM vault WHERE user = '$user'");
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
-
- $from = $row['max_timestamp'];
- $to = time();
-
- $apiKey = USER_KEYS[$user];
- $apiEndpoint = "https://api.torn.com/user/?selections=log&log=5850,5851&to=$to&from=$from&key=$apiKey";
-
- $responseData = executeApiCall($apiEndpoint);
- validateApiResponse($responseData);
-
- $checkStmt = prepareCheckStatement($pdo);
- $insertStmt = prepareInsertStatement($pdo);
-
- processLogEntries($responseData['log'], $user, $checkStmt, $insertStmt, $debug);
-}
-
-/** 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.
- *
- * @return string The balance as a formatted string
- */
-function generateBalance($name=null) {
- $balance = vaultLoop($name);
-
- return number_format($balance, 0); // Format the balance as an integer
-}
-
-/** Calculate the available vault space for a user or all users.
- *
- * 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,
- * the available space is calculated against a limit of 500,000,000.
- * If no user is specified, the available space is calculated against a
- * total vault limit of 1,000,000,000.
- *
- * @param string|null $name (optional) The user to calculate the vault space for.
- * If not provided, calculates for all users.
- *
- * @return string The available vault space as a formatted string.
- */
-
-function getSpace($name=null) {
- $space = vaultLoop($name);
-
- if ($name === null) {
- $space = 1000000000 - $space;
- } else {
- $space = 500000000 - $space;
- }
-
- return number_format($space, 0); // Format the balance as an integer
-}
-
-/** 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,
- * description and amount of each transaction. Amounts are formatted as integers.
- *
- * @return void
- */
-function buildTable () {
- $records = fetchVaultRecords();
-
- foreach ($records as $entry) {
- $user = $entry['user'];
- $timestamp = $entry['timestamp'];
- $description = $entry['description'];
- $amount = $entry['amount'];
- $sign = getSign($amount);
-
- if ($description == 'Vault withdraw') {
- $class = 'debit';
- $amount = substr($amount, 1); // Remove the negative sign
- } else {
- $class = 'credit';
- }
-
- $amount = number_format($amount, 0); // Format the amount as an integer
-
- echo '
';
- echo '
'.$user.'
';
- echo '
'.date("F j, Y / H:i", $timestamp).'
';
- echo '
'.$description.'
';
- echo '
'.$sign.$amount.'
';
- echo '
';
- }
-}
+
+ * @license Unlicense https://unlicense.org/
+ * @link https://github.com/ksolomon/TornVaultTracker
+ */
+
+// Include settings from configuration file
+require_once __DIR__ . '/config.php';
+
+// Include utility functions
+require_once 'includes/exceptions.php';
+require_once 'includes/utilities.php';
+
+/**
+ * Returns a PDO connection to 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.
+ *
+ * @return PDO
+ */
+function getDatabaseConnection() {
+ static $pdo = null;
+
+ // SQL to create the vault table if it doesn't exist
+ $createTableSQL = "CREATE TABLE IF NOT EXISTS vault (
+ id TEXT PRIMARY KEY,
+ user TEXT NOT NULL,
+ timestamp INTEGER NOT NULL,
+ description TEXT NOT NULL,
+ amount REAL NOT NULL
+ );";
+
+ if ($pdo === null) {
+ try {
+ $pdo = new PDO(DB_DSN, DB_USER, DB_PASSWORD);
+ $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+
+ $pdo->exec($createTableSQL);
+ } catch (PDOException $e) {
+ die("Database connection failed: " . $e->getMessage());
+ }
+ }
+
+ return $pdo;
+}
+
+/**
+ * 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
+ * withdrawals for a specified user. It continues fetching logs until no more
+ * entries are available, and stores each entry in the database. Each log entry
+ * is uniquely identified by its ID and includes details such as timestamp,
+ * description, and amount. The function requires the user's API key to
+ * authenticate requests to the Torn API.
+ *
+ * @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) {
+ $apiKey = USER_KEYS[$user];
+ $pdo = getDatabaseConnection();
+ $to = time();
+
+ do {
+ $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_setopt(
+ $ch, CURLOPT_HTTPHEADER, [
+ 'accept: application/json',
+ "Authorization: ApiKey $apiKey"
+ ]
+ );
+
+ $response = curl_exec($ch);
+
+ curl_close($ch);
+
+ $data = json_decode($response, true);
+
+ if (empty($data['log'])) {
+ break;
+ }
+
+ foreach ($data['log'] as $key => $entry) {
+ $description = $entry['title'];
+ $timestamp = $entry['timestamp'];
+ $amount = isset($entry['data']['deposited']) ? $entry['data']['deposited'] : -$entry['data']['withdrawn'];
+
+ $stmt = $pdo->prepare('INSERT INTO vault (ID, user, timestamp, description, amount) VALUES (:id, :user, :timestamp, :description, :amount)');
+
+ $stmt->bindValue(':id', $key);
+ $stmt->bindValue(':user', $user);
+ $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
+ *
+ * @param string $user The user to retrieve the log for
+ * @param boolean $debug Whether to output debug information (default: false)
+ *
+ * @throws Exception If the user does not have an API key configured,
+ * if the API call fails, or if the log data is invalid
+ *
+ * @return void
+ */
+function getLog($user, $debug = false) {
+ $pdo = getDatabaseConnection();
+
+ ensureUserHasApiKey($user);
+
+ $stmt = $pdo->query("SELECT MAX(timestamp) AS max_timestamp FROM vault WHERE user = '$user'");
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+
+ $from = $row['max_timestamp'];
+ $to = time();
+
+ $apiKey = USER_KEYS[$user];
+ $apiEndpoint = "https://api.torn.com/user/?selections=log&log=5850,5851&to=$to&from=$from&key=$apiKey";
+
+ $responseData = executeApiCall($apiEndpoint);
+ validateApiResponse($responseData);
+
+ $checkStmt = prepareCheckStatement($pdo);
+ $insertStmt = prepareInsertStatement($pdo);
+
+ processLogEntries($responseData['log'], $user, $checkStmt, $insertStmt, $debug);
+}
+
+/**
+ * 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.
+ *
+ * @return string The balance as a formatted string
+ */
+function generateBalance($name=null) {
+ $balance = vaultLoop($name);
+
+ return number_format($balance, 0); // Format the balance as an integer
+}
+
+/**
+ * Calculate the available vault space for a user or all users.
+ *
+ * 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,
+ * the available space is calculated against a limit of 500,000,000.
+ * If no user is specified, the available space is calculated against a
+ * total vault limit of 1,000,000,000.
+ *
+ * @param string|null $name (optional) The user to calculate the vault space for.
+ * If not provided, calculates for all users.
+ *
+ * @return string The available vault space as a formatted string.
+ */
+function getSpace($name=null) {
+ $space = vaultLoop($name);
+
+ if ($name === null) {
+ $space = 1000000000 - $space;
+ } else {
+ $space = 500000000 - $space;
+ }
+
+ return number_format($space, 0); // Format the balance as an integer
+}
+
+/**
+ * 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,
+ * description and amount of each transaction. Amounts are formatted as integers.
+ *
+ * @return void
+ */
+function buildTable () {
+ $records = fetchVaultRecords();
+
+ foreach ($records as $entry) {
+ $user = $entry['user'];
+ $timestamp = $entry['timestamp'];
+ $description = $entry['description'];
+ $amount = $entry['amount'];
+ $sign = getSign($amount);
+
+ if ($description == 'Vault withdraw') {
+ $class = 'debit';
+ $amount = substr($amount, 1); // Remove the negative sign
+ } else {
+ $class = 'credit';
+ }
+
+ $amount = number_format($amount, 0); // Format the amount as an integer
+
+ echo '
';
+ echo '
'.$user.'
';
+ echo '
'.date("F j, Y / H:i", $timestamp).'
';
+ echo '
'.$description.'
';
+ echo '
'.$sign.$amount.'
';
+ echo '
';
+ }
+}
diff --git a/includes/exceptions.php b/includes/exceptions.php
index 5f26d40..03844ce 100644
--- a/includes/exceptions.php
+++ b/includes/exceptions.php
@@ -1,24 +1,100 @@
+ * @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
+ * @license Unlicense https://unlicense.org/
+ * @link https://github.com/ksolomon/Torn-Vault-Tracker
+ */
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
+ * @license Unlicense https://unlicense.org/
+ * @link https://github.com/ksolomon/Torn-Vault-Tracker
+ */
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
+ * @license Unlicense https://unlicense.org/
+ * @link https://github.com/ksolomon/Torn-Vault-Tracker
+ */
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
+ * @license Unlicense https://unlicense.org/
+ * @link https://github.com/ksolomon/Torn-Vault-Tracker
+ */
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);
+ }
}
diff --git a/includes/utilities.php b/includes/utilities.php
index 13cb254..0445f6a 100644
--- a/includes/utilities.php
+++ b/includes/utilities.php
@@ -1,5 +1,21 @@
+ * @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.
* 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.
*/
function dbNew() {
- $pdo = getDatabaseConnection();
- $stmt = $pdo->query("SELECT COUNT(*) FROM vault");
+ $pdo = getDatabaseConnection();
+ $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
*
+ * @return void
+ *
* @throws Exception If the user does not have an API key configured
*/
function ensureUserHasApiKey($user) {
- if (!array_key_exists($user, USER_KEYS)) {
- throw new ApiKeyMissingException("User does not have an API key configured.");
- }
+ if (!array_key_exists($user, USER_KEYS)) {
+ 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
*
@@ -35,112 +55,125 @@ function ensureUserHasApiKey($user) {
* @return array The JSON response from the API
*/
function executeApiCall($apiEndpoint) {
- $headers = ["Content-Type: application/json"];
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $apiEndpoint);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+ $headers = ["Content-Type: application/json"];
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_URL, $apiEndpoint);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- $response = curl_exec($ch);
+ $response = curl_exec($ch);
- if (curl_errno($ch)) {
- throw new CurlErrorException("cURL error: " . curl_error($ch));
- }
+ if (curl_errno($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) {
- throw new JsonDataException("Failed to decode JSON response: " . json_last_error_msg());
- }
+ if (json_last_error() !== JSON_ERROR_NONE) {
+ 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.
*
+ * @return void
+ *
* @throws Exception If the log data is missing or not an array.
*/
function validateApiResponse($responseData) {
- if (!isset($responseData['log']) || !is_array($responseData['log'])) {
- throw new ApiValidationException("Invalid log data received from the API.");
- }
+ if (!isset($responseData['log']) || !is_array($responseData['log'])) {
+ 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
*
* @return PDOStatement The prepared statement
*/
function prepareCheckStatement($pdo) {
- $checkQuery = "SELECT COUNT(*) FROM vault WHERE user = :user AND timestamp = :timestamp AND amount = :amount";
- return $pdo->prepare($checkQuery);
+ $checkQuery = "SELECT COUNT(*) FROM vault WHERE user = :user AND timestamp = :timestamp AND amount = :amount";
+ 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
*
* @return PDOStatement The prepared statement
*/
function prepareInsertStatement($pdo) {
- $insertQuery = "INSERT INTO vault (ID, user, timestamp, description, amount) VALUES (:id, :user, :timestamp, :description, :amount)";
- return $pdo->prepare($insertQuery);
+ $insertQuery = "INSERT INTO vault (ID, user, timestamp, description, amount) VALUES (:id, :user, :timestamp, :description, :amount)";
+ 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.
* If it is, it checks if the entry already exists in the database. If it
* doesn't, it inserts the entry into the database.
*
- * @param array $logEntries The array of log entries to process
- * @param string $user The user whose log entries are being processed
- * @param PDOStatement $checkStmt A prepared statement to check if an entry
- * already exists in the database
+ * @param array $logEntries The array of log entries to process
+ * @param string $user The user whose log entries are being processed
+ * @param PDOStatement $checkStmt A prepared statement to check if an entry
+ * already exists in the database
* @param PDOStatement $insertStmt A prepared statement to insert a new entry
- * into the database
- * @param boolean $debug Whether to output debug information (default: false)
+ * into the database
+ * @param boolean $debug Whether to output debug information (default: false)
+ *
+ * @return void
*/
function processLogEntries($logEntries, $user, $checkStmt, $insertStmt, $debug) {
- foreach ($logEntries as $key =>$entry) {
- if ($debug) {
- $logMessage = "Raw entry:\n" . print_r($entry, true);
- file_put_contents(__DIR__ . '/debug.log', $logMessage, FILE_APPEND);
+ foreach ($logEntries as $key =>$entry) {
+ if ($debug) {
+ $logMessage = "Raw entry:\n" . print_r($entry, true);
+ 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
* 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
*/
function fetchVaultRecords($user = null) {
- $pdo = getDatabaseConnection();
+ $pdo = getDatabaseConnection();
- if ($user) {
- $query = "SELECT * FROM vault WHERE user = :user ORDER BY timestamp DESC";
- $params = [':user' => $user];
- } else {
- $query = "SELECT * FROM vault ORDER BY timestamp DESC";
- $params = [];
- }
+ if ($user) {
+ $query = "SELECT * FROM vault WHERE user = :user ORDER BY timestamp DESC";
+ $params = [':user' => $user];
+ } else {
+ $query = "SELECT * FROM vault ORDER BY timestamp DESC";
+ $params = [];
+ }
- try {
- $stmt = $pdo->prepare($query);
- $stmt->execute($params);
+ try {
+ $stmt = $pdo->prepare($query);
+ $stmt->execute($params);
- return $stmt->fetchAll(PDO::FETCH_ASSOC);
- } catch (PDOException $e) {
- echo "Error fetching records: " . $e->getMessage();
+ return $stmt->fetchAll(PDO::FETCH_ASSOC);
+ } catch (PDOException $e) {
+ 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.
* 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).
*/
function vaultLoop ($name=null) {
- $vault = fetchVaultRecords($name);
- $balance = 0;
+ $vault = fetchVaultRecords($name);
+ $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.
*
@@ -195,7 +232,9 @@ function vaultLoop ($name=null) {
* number is negative.
*/
function getSign($number) {
- if (substr($number, 0, 1) == '-') { return '-$'; }
+ if (substr($number, 0, 1) == '-') {
+ return '-$';
+ }
- return '$';
+ return '$';
}
diff --git a/index.php b/index.php
index caf265d..bb66911 100644
--- a/index.php
+++ b/index.php
@@ -1,92 +1,103 @@
- $value) {
- firstRun($key);
- }
- header('Location: /');
-} else {
- foreach (USER_KEYS as $key => $value) {
- getLog($key);
- }
-}
-?>
-
-
-
-
-
-
-
-
- Torn Vault Tracker
-
-
-
-
-
-
-
-
-
-
-