Enhance Torn Vault Tracker: Add documentation, improve exception handling, and update styles
Deploy website via FTP / Deploy (push) Skipped
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:
+226
-199
@@ -1,199 +1,226 @@
|
||||
<?php
|
||||
// Include settings from a separate 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.
|
||||
*/
|
||||
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 '<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>';
|
||||
}
|
||||
}
|
||||
<?php
|
||||
/**
|
||||
* 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';
|
||||
|
||||
// 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 '<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>';
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user