Wallos v0.9

This commit is contained in:
ellite
2023-10-05 22:39:37 +02:00
commit 63ce5b099a
166 changed files with 6337 additions and 0 deletions
+103
View File
@@ -0,0 +1,103 @@
<?php
require_once '../../includes/connect_endpoint.php';
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
if (isset($_GET['action']) && $_GET['action'] == "add") {
$categoryName = "Category";
$sqlInsert = "INSERT INTO categories (name) VALUES (:name)";
$stmtInsert = $db->prepare($sqlInsert);
$stmtInsert->bindParam(':name', $categoryName, SQLITE3_TEXT);
$resultInsert = $stmtInsert->execute();
if ($resultInsert) {
$categoryId = $db->lastInsertRowID();
$response = [
"success" => true,
"categoryId" => $categoryId
];
echo json_encode($response);
} else {
$response = [
"success" => false,
"errorMessage" => "Failed to add category"
];
echo json_encode($response);
}
} else if (isset($_GET['action']) && $_GET['action'] == "edit") {
if (isset($_GET['categoryId']) && $_GET['categoryId'] != "" && isset($_GET['name']) && $_GET['name'] != "") {
$categoryId = $_GET['categoryId'];
$name = $_GET['name'];
$sql = "UPDATE categories SET name = :name WHERE id = :categoryId";
$stmt = $db->prepare($sql);
$stmt->bindParam(':name', $name, SQLITE3_TEXT);
$stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
$result = $stmt->execute();
if ($result) {
$response = [
"success" => true
];
echo json_encode($response);
} else {
$response = [
"success" => false,
"errorMessage" => "Failed to edit category"
];
echo json_encode($response);
}
} else {
$response = [
"success" => false,
"errorMessage" => "Please fill all the fields"
];
echo json_encode($response);
}
} else if (isset($_GET['action']) && $_GET['action'] == "delete") {
if (isset($_GET['categoryId']) && $_GET['categoryId'] != "" && $_GET['categoryId'] != 1) {
$categoryId = $_GET['categoryId'];
$checkCategory = "SELECT COUNT(*) FROM subscriptions WHERE category_id = :categoryId";
$checkStmt = $db->prepare($checkCategory);
$checkStmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
$checkResult = $checkStmt->execute();
$row = $checkResult->fetchArray();
$count = $row[0];
if ($count > 0) {
$response = [
"success" => false,
"errorMessage" => "Category is in use in subscriptions and can't be removed"
];
echo json_encode($response);
} else {
$sql = "DELETE FROM categories WHERE id = :categoryId";
$stmt = $db->prepare($sql);
$stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
$result = $stmt->execute();
if ($result) {
$response = [
"success" => true
];
echo json_encode($response);
} else {
$response = [
"success" => false,
"errorMessage" => "Failed to remove category"
];
echo json_encode($response);
}
}
} else {
$response = [
"success" => false,
"errorMessage" => "Failed to remove category"
];
echo json_encode($response);
}
} else {
echo "Error";
}
} else {
echo "Error";
}
?>
+225
View File
@@ -0,0 +1,225 @@
<?php
$databaseFile = '/var/www/html/db/wallos.db';
if (!file_exists($databaseFile)) {
echo "Database does not exist. Creating it...";
$db = new SQLite3($databaseFile, SQLITE3_OPEN_CREATE | SQLITE3_OPEN_READWRITE);
$db->busyTimeout(5000);
$db->exec('CREATE TABLE user (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL,
main_currency INTEGER NOT NULL,
avatar TEXT,
FOREIGN KEY(main_currency) REFERENCES currencies(id)
)');
$db->exec('CREATE TABLE payment_methods (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
icon TEXT
)');
$db->exec('CREATE TABLE subscriptions (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
logo TEXT,
price REAL NOT NULL,
currency_id INTEGER,
next_payment DATE,
cycle INTEGER,
frequency INTEGER,
notes TEXT,
payment_method_id INTEGER,
payer_user_id INTEGER,
category_id INTEGER,
FOREIGN KEY(currency_id) REFERENCES currencies(id),
FOREIGN KEY(cycle) REFERENCES cycles(id),
FOREIGN KEY(frequency) REFERENCES frequencies(id),
FOREIGN KEY(payment_method_id) REFERENCES payment_methods(id),
FOREIGN KEY(payer_user_id) REFERENCES user(id)
FOREIGN KEY(category_id) REFERENCES categories(id)
)');
$db->exec('CREATE TABLE categories (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
)');
$db->exec('CREATE TABLE currencies (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
symbol TEXT NOT NULL,
code TEXT NOT NULL,
rate TEXT NOT NULL
)');
$db->exec('CREATE TABLE household (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
)');
$db->exec('CREATE TABLE login_tokens (
user_id INTEGER NOT NULL,
token TEXT NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE CASCADE ON UPDATE CASCADE
)');
$db->exec('CREATE TABLE cycles (
id INTEGER PRIMARY KEY,
days INTEGER NOT NULL,
name TEXT NOT NULL
)');
$db->exec('CREATE TABLE frequencies (
id INTEGER PRIMARY KEY,
name INTEGER NOT NULL
)');
$db->exec('CREATE TABLE fixer (
api_key TEXT NOT NULL
)');
$db->exec('CREATE TABLE last_exchange_update (
date DATE NOT NULL
)');
$db->exec('CREATE TABLE last_update_next_payment_date (
date DATE NOT NULL
)');
$db->exec("INSERT INTO categories (id, name) VALUES
(1, 'No category'),
(2, 'Entertainment'),
(3, 'Music'),
(4, 'Utilities'),
(5, 'Food & Beverages'),
(6, 'Health & Wellbeing'),
(7, 'Productivity'),
(8, 'Banking'),
(9, 'Transport'),
(10, 'Education'),
(11, 'Insurance'),
(12, 'Gaming'),
(13, 'News & Magazines'),
(14, 'Productivity'),
(15, 'Technology'),
(16, 'Cloud Services'),
(17, 'Charity & Donations')");
$db->exec("INSERT INTO cycles (id, days, name) VALUES
(1, 1, 'Daily'),
(2, 7, 'Weekly'),
(3, 30, 'Monthly'),
(4, 365, 'Yearly')");
$db->exec("INSERT INTO frequencies (id, name) VALUES
(1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5),
(6, 6),
(7, 7),
(8, 8),
(9, 9),
(10, 10),
(11, 11),
(12, 12),
(13, 13),
(14, 14),
(15, 15),
(16, 16),
(17, 17),
(18, 18),
(19, 19),
(20, 20),
(21, 21),
(22, 22),
(23, 23),
(24, 24),
(25, 25),
(26, 26),
(27, 27),
(28, 28),
(29, 29),
(30, 30),
(31, 31)");
$db->exec("INSERT INTO currencies (name, symbol, code, rate) VALUES
('Euro', '€', 'EUR', 1),
('US Dollar', '$', 'USD', 1),
('Japanese Yen', '¥', 'JPY', 1),
('Bulgarian Lev', 'лв', 'BGN', 1),
('Czech Republic Koruna', 'Kč', 'CZK', 1),
('Danish Krone', 'kr', 'DKK', 1),
('British Pound Sterling', '£', 'GBP', 1),
('Hungarian Forint', 'Ft', 'HUF', 1),
('Polish Zloty', 'zł', 'PLN', 1),
('Romanian Leu', 'lei', 'RON', 1),
('Swedish Krona', 'kr', 'SEK', 1),
('Swiss Franc', 'Fr', 'CHF', 1),
('Icelandic Króna', 'kr', 'ISK', 1),
('Norwegian Krone', 'kr', 'NOK', 1),
('Croatian Kuna', 'kn', 'HRK', 1),
('Russian Ruble', '₽', 'RUB', 1),
('Turkish Lira', '₺', 'TRY', 1),
('Australian Dollar', '$', 'AUD', 1),
('Brazilian Real', 'R$', 'BRL', 1),
('Canadian Dollar', '$', 'CAD', 1),
('Chinese Yuan', '¥', 'CNY', 1),
('Hong Kong Dollar', 'HK$', 'HKD', 1),
('Indonesian Rupiah', 'Rp', 'IDR', 1),
('Israeli New Sheqel', '₪', 'ILS', 1),
('Indian Rupee', '₹', 'INR', 1),
('South Korean Won', '₩', 'KRW', 1),
('Mexican Peso', 'Mex$', 'MXN', 1),
('Malaysian Ringgit', 'RM', 'MYR', 1),
('New Zealand Dollar', 'NZ$', 'NZD', 1),
('Philippine Peso', '₱', 'PHP', 1),
('Singapore Dollar', 'S$', 'SGD', 1),
('Thai Baht', '฿', 'THB', 1),
('South African Rand', 'R', 'ZAR', 1)");
$db->exec("INSERT INTO payment_methods (id, name, icon) VALUES
(1, 'PayPal', 'paypal.png'),
(2, 'Credit Card', 'creditcard.png'),
(3, 'Bank Transfer', 'banktransfer.png'),
(4, 'Direct Debit', 'directdebit.png'),
(5, 'Money', 'money.png'),
(6, 'Google Pay', 'googlepay.png'),
(7, 'Samsung Pay', 'samsungpay.png'),
(8, 'Apple Pay', 'applepay.png'),
(9, 'Crypto', 'crypto.png'),
(10, 'Klarna', 'klarna.png'),
(11, 'Amazon Pay', 'amazonpay.png'),
(12, 'SEPA', 'sepa.png'),
(13, 'Skrill', 'skrill.png'),
(14, 'Sofort', 'sofort.png'),
(15, 'Stripe', 'stripe.png'),
(16, 'Affirm', 'affirm.png'),
(17, 'AliPay', 'alipay.png'),
(18, 'Elo', 'elo.png'),
(19, 'Facebook Pay', 'facebookpay.png'),
(20, 'GiroPay', 'giropay.png'),
(21, 'iDeal', 'ideal.png'),
(22, 'Union Pay', 'unionpay.png'),
(23, 'Interac', 'interac.png'),
(24, 'WeChat', 'wechat.png'),
(25, 'Paysafe', 'paysafe.png'),
(26, 'Poli', 'poli.png'),
(27, 'Qiwi', 'qiwi.png'),
(28, 'ShopPay', 'shoppay.png'),
(29, 'Venmo', 'venmo.png'),
(30, 'VeriFone', 'verifone.png'),
(31, 'WebMoney', 'webmoney.png')");
} else {
echo "Database already exist. Skipping...";
}
?>
+73
View File
@@ -0,0 +1,73 @@
<?php
require_once '/var/www/html/includes/connect_endpoint_crontabs.php';
$query = "SELECT api_key FROM fixer";
$result = $db->query($query);
if ($result) {
$row = $result->fetchArray(SQLITE3_ASSOC);
if ($row) {
$apiKey = $row['api_key'];
$codes = "";
$query = "SELECT id, name, symbol, code FROM currencies";
$result = $db->query($query);
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$codes .= $row['code'].",";
}
$codes = rtrim($codes, ',');
$query = "SELECT u.main_currency, c.code FROM user u LEFT JOIN currencies c ON u.main_currency = c.id WHERE u.id = 1";
$stmt = $db->prepare($query);
$result = $stmt->execute();
$row = $result->fetchArray(SQLITE3_ASSOC);
$mainCurrencyCode = $row['code'];
$mainCurrencyId = $row['main_currency'];
$api_url = "http://data.fixer.io/api/latest?access_key=". $apiKey . "&base=EUR&symbols=" . $codes;
$response = file_get_contents($api_url);
$apiData = json_decode($response, true);
$mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode];
if ($apiData !== null && isset($apiData['rates'])) {
foreach ($apiData['rates'] as $currencyCode => $rate) {
if ($currencyCode === $mainCurrencyCode) {
$exchangeRate = 1.0;
} else {
$exchangeRate = $rate / $mainCurrencyToEUR;
}
$updateQuery = "UPDATE currencies SET rate = :rate WHERE code = :code";
$updateStmt = $db->prepare($updateQuery);
$updateStmt->bindParam(':rate', $exchangeRate, SQLITE3_TEXT);
$updateStmt->bindParam(':code', $currencyCode, SQLITE3_TEXT);
$updateResult = $updateStmt->execute();
if (!$updateResult) {
echo "Error updating rate for currency: $currencyCode";
}
}
$currentDate = new DateTime();
$formattedDate = $currentDate->format('Y-m-d');
$deleteQuery = "DELETE FROM last_exchange_update";
$deleteStmt = $db->prepare($deleteQuery);
$deleteResult = $deleteStmt->execute();
$query = "INSERT INTO last_exchange_update (date) VALUES (:formattedDate)";
$stmt = $db->prepare($query);
$stmt->bindParam(':formattedDate', $formattedDate, SQLITE3_TEXT);
$result = $stmt->execute();
$db->close();
echo "Rates updated successfully!";
}
} else {
echo "Exchange rates update skipped. No fixer.io api key provided";
$apiKey = null;
}
} else {
echo "Exchange rates update skipped. No fixer.io api key provided";
$apiKey = null;
}
?>
+65
View File
@@ -0,0 +1,65 @@
<?php
require_once '/var/www/html/includes/connect_endpoint_crontabs.php';
$currentDate = new DateTime();
$currentDateString = $currentDate->format('Y-m-d');
$cycles = array();
$query = "SELECT * FROM cycles";
$result = $db->query($query);
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$cycleId = $row['id'];
$cycles[$cycleId] = $row;
}
$query = "SELECT id, next_payment, frequency, cycle FROM subscriptions WHERE next_payment < :currentDate";
$stmt = $db->prepare($query);
$stmt->bindValue(':currentDate', $currentDate->format('Y-m-d'));
$result = $stmt->execute();
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$subscriptionId = $row['id'];
$nextPaymentDate = new DateTime($row['next_payment']);
$frequency = $row['frequency'];
$cycle = $cycles[$row['cycle']]['name'];
// Calculate the interval to add based on the cycle
$intervalSpec = "P";
if ($cycle == 'Daily') {
$intervalSpec .= "{$frequency}D";
} elseif ($cycle === 'Weekly') {
$intervalSpec .= "{$frequency}W";
} elseif ($cycle === 'Monthly') {
$intervalSpec .= "{$frequency}M";
} elseif ($cycle === 'Yearly') {
$intervalSpec .= "{$frequency}Y";
}
$interval = new DateInterval($intervalSpec);
// Add intervals until the next payment date is in the future
while ($nextPaymentDate < $currentDate) {
$nextPaymentDate->add($interval);
}
// Update the subscription's next_payment date
$updateQuery = "UPDATE subscriptions SET next_payment = :nextPaymentDate WHERE id = :subscriptionId";
$updateStmt = $db->prepare($updateQuery);
$updateStmt->bindValue(':nextPaymentDate', $nextPaymentDate->format('Y-m-d'));
$updateStmt->bindValue(':subscriptionId', $subscriptionId);
$updateStmt->execute();
}
$formattedDate = $currentDate->format('Y-m-d');
$deleteQuery = "DELETE FROM last_update_next_payment_date";
$deleteStmt = $db->prepare($deleteQuery);
$deleteResult = $deleteStmt->execute();
$query = "INSERT INTO last_update_next_payment_date (date) VALUES (:formattedDate)";
$stmt = $db->prepare($query);
$stmt->bindParam(':formattedDate', $currentDateString, SQLITE3_TEXT);
$result = $stmt->execute();
echo "Updated next payment dates";
?>
+119
View File
@@ -0,0 +1,119 @@
<?php
require_once '../../includes/connect_endpoint.php';
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
if (isset($_GET['action']) && $_GET['action'] == "add") {
$currencyName = "Currency";
$currencySymbol = "$";
$currencyCode = "CODE";
$currencyRate = 1;
$sqlInsert = "INSERT INTO currencies (name, symbol, code, rate) VALUES (:name, :symbol, :code, :rate)";
$stmtInsert = $db->prepare($sqlInsert);
$stmtInsert->bindParam(':name', $currencyName, SQLITE3_TEXT);
$stmtInsert->bindParam(':symbol', $currencySymbol, SQLITE3_TEXT);
$stmtInsert->bindParam(':code', $currencyCode, SQLITE3_TEXT);
$stmtInsert->bindParam(':rate', $currencyRate, SQLITE3_TEXT);
$resultInsert = $stmtInsert->execute();
if ($resultInsert) {
$currencyId = $db->lastInsertRowID();
echo $currencyId;
} else {
echo "Error adding currency entry.";
}
} else if (isset($_GET['action']) && $_GET['action'] == "edit") {
if (isset($_GET['currencyId']) && $_GET['currencyId'] != "" && isset($_GET['name']) && $_GET['name'] != "" && isset($_GET['symbol']) && $_GET['symbol'] != "") {
$currencyId = $_GET['currencyId'];
$name = $_GET['name'];
$symbol = $_GET['symbol'];
$code = $_GET['code'];
$sql = "UPDATE currencies SET name = :name, symbol = :symbol, code = :code WHERE id = :currencyId";
$stmt = $db->prepare($sql);
$stmt->bindParam(':name', $name, SQLITE3_TEXT);
$stmt->bindParam(':symbol', $symbol, SQLITE3_TEXT);
$stmt->bindParam(':code', $code, SQLITE3_TEXT);
$stmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
$result = $stmt->execute();
if ($result) {
echo json_encode(["success" => true]);
} else {
$response = [
"success" => false,
"message" => "Failed to store Currency on the Database"
];
echo json_encode($response);
}
} else {
$response = [
"success" => false,
"message" => "Some fields are missing"
];
echo json_encode($response);
}
} else if (isset($_GET['action']) && $_GET['action'] == "delete") {
if (isset($_GET['currencyId']) && $_GET['currencyId'] != "") {
$query = "SELECT main_currency FROM user WHERE id = 1";
$stmt = $db->prepare($query);
$result = $stmt->execute();
$row = $result->fetchArray(SQLITE3_ASSOC);
$mainCurrencyId = $row['main_currency'];
$currencyId = $_GET['currencyId'];
$checkQuery = "SELECT COUNT(*) FROM subscriptions WHERE currency_id = :currencyId";
$checkStmt = $db->prepare($checkQuery);
$checkStmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
$checkResult = $checkStmt->execute();
$row = $checkResult->fetchArray();
$count = $row[0];
if ($count > 0) {
$response = [
"success" => false,
"message" => "Currency is in use in subscriptions and can't be deleted."
];
echo json_encode($response);
exit;
} else {
if ($currencyId == $mainCurrencyId) {
$response = [
"success" => false,
"message" => "Currency is set as main currency and can't be deleted."
];
echo json_encode($response);
exit;
} else {
$sql = "DELETE FROM currencies WHERE id = :currencyId";
$stmt = $db->prepare($sql);
$stmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
$result = $stmt->execute();
if ($result) {
echo json_encode(["success" => true]);
} else {
$response = [
"success" => false,
"message" => "Failed to remove currency from the Database"
];
echo json_encode($response);
}
}
}
} else {
$response = [
"success" => false,
"message" => "Some fields are missing."
];
echo json_encode($response);
}
} else {
echo "Error";
}
} else {
$response = [
"success" => false,
"message" => "Your session expired. Please login again"
];
echo json_encode($response);
}
?>
+41
View File
@@ -0,0 +1,41 @@
<?php
require_once '../../includes/connect_endpoint.php';
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$newApiKey = isset($_POST["api_key"]) ? $_POST["api_key"] : "";
$removeOldKey = "DELETE FROM fixer";
$db->exec($removeOldKey);
$testKeyUrl = "http://data.fixer.io/api/latest?access_key=$newApiKey";
$response = file_get_contents($testKeyUrl);
$apiData = json_decode($response, true);
if ($apiData['success'] && $apiData['success'] == 1) {
if (!empty($newApiKey)) {
$insertNewKey = "INSERT INTO fixer (api_key) VALUES (:api_key)";
$stmt = $db->prepare($insertNewKey);
$stmt->bindParam(":api_key", $newApiKey, SQLITE3_TEXT);
$result = $stmt->execute();
if ($result) {
echo json_encode(["success" => true]);
} else {
$response = [
"success" => false,
"message" => "Failed to store API Key on the Database"
];
echo json_encode($response);
}
} else {
echo json_encode(["success" => true]);
}
} else {
$response = [
"success" => false,
"message" => "Invalid API Key"
];
echo json_encode($response);
}
}
}
?>
+90
View File
@@ -0,0 +1,90 @@
<?php
require_once '../../includes/connect_endpoint.php';
$shouldUpdate = true;
$query = "SELECT date FROM last_exchange_update";
$result = $db->querySingle($query);
if ($result) {
$lastUpdateDate = new DateTime($result);
$currentDate = new DateTime();
$lastUpdateDateString = $lastUpdateDate->format('Y-m-d');
$currentDateString = $currentDate->format('Y-m-d');
$shouldUpdate = $lastUpdateDateString < $currentDateString;
}
if (!$shouldUpdate) {
echo "Rates are current, no need to update.";
exit;
}
$query = "SELECT api_key FROM fixer";
$result = $db->query($query);
if ($result) {
$row = $result->fetchArray(SQLITE3_ASSOC);
if ($row) {
$apiKey = $row['api_key'];
$codes = "";
$query = "SELECT id, name, symbol, code FROM currencies";
$result = $db->query($query);
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$codes .= $row['code'].",";
}
$codes = rtrim($codes, ',');
$query = "SELECT u.main_currency, c.code FROM user u LEFT JOIN currencies c ON u.main_currency = c.id WHERE u.id = 1";
$stmt = $db->prepare($query);
$result = $stmt->execute();
$row = $result->fetchArray(SQLITE3_ASSOC);
$mainCurrencyCode = $row['code'];
$mainCurrencyId = $row['main_currency'];
$api_url = "http://data.fixer.io/api/latest?access_key=". $apiKey . "&base=EUR&symbols=" . $codes;
$response = file_get_contents($api_url);
$apiData = json_decode($response, true);
$mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode];
if ($apiData !== null && isset($apiData['rates'])) {
foreach ($apiData['rates'] as $currencyCode => $rate) {
if ($currencyCode === $mainCurrencyCode) {
$exchangeRate = 1.0;
} else {
$exchangeRate = $rate / $mainCurrencyToEUR;
}
$updateQuery = "UPDATE currencies SET rate = :rate WHERE code = :code";
$updateStmt = $db->prepare($updateQuery);
$updateStmt->bindParam(':rate', $exchangeRate, SQLITE3_TEXT);
$updateStmt->bindParam(':code', $currencyCode, SQLITE3_TEXT);
$updateResult = $updateStmt->execute();
if (!$updateResult) {
echo "Error updating rate for currency: $currencyCode";
}
}
$currentDate = new DateTime();
$formattedDate = $currentDate->format('Y-m-d');
$deleteQuery = "DELETE FROM last_exchange_update";
$deleteStmt = $db->prepare($deleteQuery);
$deleteResult = $deleteStmt->execute();
$query = "INSERT INTO last_exchange_update (date) VALUES (:formattedDate)";
$stmt = $db->prepare($query);
$stmt->bindParam(':formattedDate', $formattedDate, SQLITE3_TEXT);
$result = $stmt->execute();
$db->close();
echo "Rates updated successfully!";
}
} else {
echo "Exchange rates update skipped. No fixer.io api key provided";
$apiKey = null;
}
} else {
echo "Exchange rates update skipped. No fixer.io api key provided";
$apiKey = null;
}
?>
+103
View File
@@ -0,0 +1,103 @@
<?php
require_once '../../includes/connect_endpoint.php';
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
if (isset($_GET['action']) && $_GET['action'] == "add") {
$householdName = "Member";
$sqlInsert = "INSERT INTO household (name) VALUES (:name)";
$stmtInsert = $db->prepare($sqlInsert);
$stmtInsert->bindParam(':name', $householdName, SQLITE3_TEXT);
$resultInsert = $stmtInsert->execute();
if ($resultInsert) {
$householdId = $db->lastInsertRowID();
$response = [
"success" => true,
"householdId" => $householdId
];
echo json_encode($response);
} else {
$response = [
"success" => false,
"errorMessage" => "Failed to add household member"
];
echo json_encode($response);
}
} else if (isset($_GET['action']) && $_GET['action'] == "edit") {
if (isset($_GET['memberId']) && $_GET['memberId'] != "" && isset($_GET['name']) && $_GET['name'] != "") {
$memberId = $_GET['memberId'];
$name = $_GET['name'];
$sql = "UPDATE household SET name = :name WHERE id = :memberId";
$stmt = $db->prepare($sql);
$stmt->bindParam(':name', $name, SQLITE3_TEXT);
$stmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);
$result = $stmt->execute();
if ($result) {
$response = [
"success" => true
];
echo json_encode($response);
} else {
$response = [
"success" => false,
"errorMessage" => "Failed to edit household member"
];
echo json_encode($response);
}
} else {
$response = [
"success" => false,
"errorMessage" => "Please fill all the fields"
];
echo json_encode($response);
}
} else if (isset($_GET['action']) && $_GET['action'] == "delete") {
if (isset($_GET['memberId']) && $_GET['memberId'] != "" && $_GET['memberId'] != 1) {
$memberId = $_GET['memberId'];
$checkMember = "SELECT COUNT(*) FROM subscriptions WHERE payer_user_id = :memberId";
$checkStmt = $db->prepare($checkMember);
$checkStmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);
$checkResult = $checkStmt->execute();
$row = $checkResult->fetchArray();
$count = $row[0];
if ($count > 0) {
$response = [
"success" => false,
"errorMessage" => "Household member is in use in subscriptions and can't be removed"
];
echo json_encode($response);
} else {
$sql = "DELETE FROM household WHERE id = :memberId";
$stmt = $db->prepare($sql);
$stmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);
$result = $stmt->execute();
if ($result) {
$response = [
"success" => true
];
echo json_encode($response);
} else {
$response = [
"success" => false,
"errorMessage" => "Failed to remove household member"
];
echo json_encode($response);
}
}
} else {
$response = [
"success" => false,
"errorMessage" => "Failed to remove household member"
];
echo json_encode($response);
}
} else {
echo "Error";
}
} else {
echo "Error";
}
?>
+45
View File
@@ -0,0 +1,45 @@
<?php
if (isset($_GET['search'])) {
$searchTerm = urlencode($_GET['search'] . " logo");
$url = "https://www.google.com/search?q={$searchTerm}&tbm=isch&tbs=iar:xw,ift:png";
// Use cURL to fetch the search results page
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
echo json_encode(['error' => 'Failed to fetch data from Google.']);
} else {
// Parse the HTML response to extract image URLs
$imageUrls = extractImageUrlsFromGoogle($response);
// Pass the image URLs to the client
header('Content-Type: application/json');
echo json_encode(['imageUrls' => $imageUrls]);
}
curl_close($ch);
} else {
echo json_encode(['error' => 'Invalid request.']);
}
function extractImageUrlsFromGoogle($html) {
$imageUrls = [];
$doc = new DOMDocument();
@$doc->loadHTML($html);
$imgTags = $doc->getElementsByTagName('img');
foreach ($imgTags as $imgTag) {
$src = $imgTag->getAttribute('src');
if (filter_var($src, FILTER_VALIDATE_URL)) {
$imageUrls[] = $src;
}
}
return $imageUrls;
}
?>
+202
View File
@@ -0,0 +1,202 @@
<?php
require_once '../../includes/connect_endpoint.php';
session_start();
function sanitizeFilename($filename) {
$filename = preg_replace("/[^a-zA-Z0-9\s]/", "", $filename);
$filename = str_replace(" ", "-", $filename);
return $filename;
}
function getLogoFromUrl($url, $uploadDir, $name) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$imageData = curl_exec($ch);
if ($imageData !== false) {
$timestamp = time();
$fileName = $timestamp . '-' . sanitizeFilename($name) . '.png';
$uploadDir = '../../images/uploads/logos/';
$uploadFile = $uploadDir . $fileName;
if (saveLogo($imageData, $uploadFile, $name)) {
return $fileName;
} else {
echo "Error fetching image: " . curl_error($ch);
return "";
}
curl_close($ch);
} else {
echo "Error fetching image: " . curl_error($ch);
return "";
}
}
function saveLogo($imageData, $uploadFile, $name) {
$image = imagecreatefromstring($imageData);
$removeBackground = isset($_COOKIE['removeBackground']) && $_COOKIE['removeBackground'] === 'true';
if ($image !== false) {
$tempFile = tempnam(sys_get_temp_dir(), 'logo');
imagepng($image, $tempFile);
imagedestroy($image);
$imagick = new Imagick($tempFile);
if ($removeBackground) {
$imagick->transparentPaintImage("rgb(247, 247, 247)", 0, 102, false);
}
$imagick->setImageFormat('png');
$imagick->writeImage($uploadFile);
$imagick->clear();
$imagick->destroy();
unlink($tempFile);
return true;
} else {
return false;
}
}
function resizeAndUploadLogo($uploadedFile, $uploadDir, $name) {
$targetWidth = 135;
$targetHeight = 42;
$timestamp = time();
$originalFileName = $uploadedFile['name'];
$fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION);
$fileName = $timestamp . '-' . sanitizeFilename($name) . '.' . $fileExtension;
$uploadFile = $uploadDir . $fileName;
if (move_uploaded_file($uploadedFile['tmp_name'], $uploadFile)) {
$fileInfo = getimagesize($uploadFile);
if ($fileInfo !== false) {
$width = $fileInfo[0];
$height = $fileInfo[1];
// Load the image based on its format
if ($fileExtension === 'png') {
$image = imagecreatefrompng($uploadFile);
} elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {
$image = imagecreatefromjpeg($uploadFile);
} else {
// Handle other image formats as needed
return "";
}
// Enable alpha channel (transparency) for PNG images
if ($fileExtension === 'png') {
imagesavealpha($image, true);
}
$newWidth = $width;
$newHeight = $height;
if ($width > $targetWidth) {
$newWidth = $targetWidth;
$newHeight = ($targetWidth / $width) * $height;
}
if ($newHeight > $targetHeight) {
$newWidth = ($targetHeight / $newHeight) * $newWidth;
$newHeight = $targetHeight;
}
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);
imagesavealpha($resizedImage, true);
$transparency = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127);
imagefill($resizedImage, 0, 0, $transparency);
imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if ($fileExtension === 'png') {
imagepng($resizedImage, $uploadFile);
} elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {
imagejpeg($resizedImage, $uploadFile);
} else {
return "";
}
imagedestroy($image);
imagedestroy($resizedImage);
return $fileName;
}
}
return "";
}
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$isEdit = isset($_POST['id']) && $_POST['id'] != "";
$name = $_POST["name"];
$price = $_POST['price'];
$currencyId = $_POST["currency_id"];
$frequency = $_POST["frequency"];
$cycle = $_POST["cycle"];
$nextPayment = $_POST["next_payment"];
$paymentMethodId = $_POST["payment_method_id"];
$payerUserId = $_POST["payer_user_id"];
$categoryId = $_POST['category_id'];
$notes = $_POST["notes"];
$logoUrl = $_POST['logo-url'];
$logo = "";
if($logoUrl !== "") {
$logo = getLogoFromUrl($logoUrl, '../../images/uploads/logos/', $name);
} else {
if (!empty($_FILES['logo']['name'])) {
$logo = resizeAndUploadLogo($_FILES['logo'], '../../images/uploads/logos/', $name);
}
}
if (!$isEdit) {
$sql = "INSERT INTO subscriptions (name, logo, price, currency_id, next_payment, cycle, frequency, notes,
payment_method_id, payer_user_id, category_id)
VALUES (:name, :logo, :price, :currencyId, :nextPayment, :cycle, :frequency, :notes,
:paymentMethodId, :payerUserId, :categoryId)";
} else {
$id = $_POST['id'];
if ($logo != "") {
$sql = "UPDATE subscriptions SET name = :name, logo = :logo, price = :price, currency_id = :currencyId, next_payment = :nextPayment, cycle = :cycle, frequency = :frequency, notes = :notes, payment_method_id = :paymentMethodId, payer_user_id = :payerUserId, category_id = :categoryId WHERE id = :id";
} else {
$sql = "UPDATE subscriptions SET name = :name, price = :price, currency_id = :currencyId, next_payment = :nextPayment, cycle = :cycle, frequency = :frequency, notes = :notes, payment_method_id = :paymentMethodId, payer_user_id = :payerUserId, category_id = :categoryId WHERE id = :id";
}
}
$stmt = $db->prepare($sql);
if ($isEdit) {
$stmt->bindParam(':id', $id, SQLITE3_INTEGER);
}
$stmt->bindParam(':name', $name, SQLITE3_TEXT);
if ($logo != "") {
$stmt->bindParam(':logo', $logo, SQLITE3_TEXT);
}
$stmt->bindParam(':price', $price, SQLITE3_FLOAT);
$stmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
$stmt->bindParam(':nextPayment', $nextPayment, SQLITE3_TEXT);
$stmt->bindParam(':cycle', $cycle, SQLITE3_INTEGER);
$stmt->bindParam(':frequency', $frequency, SQLITE3_INTEGER);
$stmt->bindParam(':notes', $notes, SQLITE3_TEXT);
$stmt->bindParam(':paymentMethodId', $paymentMethodId, SQLITE3_INTEGER);
$stmt->bindParam(':payerUserId', $payerUserId, SQLITE3_INTEGER);
$stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
if ($stmt->execute()) {
$success['status'] = "Success";
$text = $isEdit ? "updated" : "added";
$success['message'] = "Subscription " . $text . " successfuly";
$json = json_encode($success);
header('Content-Type: application/json');
echo $json;
exit();
} else {
echo "Error: " . $db->lastErrorMsg();
}
}
}
$db->close();
?>
+23
View File
@@ -0,0 +1,23 @@
<?php
require_once '../../includes/connect_endpoint.php';
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
if ($_SERVER["REQUEST_METHOD"] === "DELETE") {
$subscriptionId = $_GET["id"];
$deleteQuery = "DELETE FROM subscriptions WHERE id = :subscriptionId";
$deleteStmt = $db->prepare($deleteQuery);
$deleteStmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);
if ($deleteStmt->execute()) {
http_response_code(204);
} else {
http_response_code(500);
echo json_encode(array("message" => "Error deleting the subscription."));
}
} else {
http_response_code(405);
echo json_encode(array("message" => "Invalid request method."));
}
}
$db->close();
?>
+39
View File
@@ -0,0 +1,39 @@
<?php
require_once '../../includes/connect_endpoint.php';
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
if (isset($_GET['id']) && $_GET['id'] != "") {
$subscriptionId = intval($_GET['id']);
$query = "SELECT * FROM subscriptions WHERE id = :subscriptionId";
$stmt = $db->prepare($query);
$stmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);
$result = $stmt->execute();
$subscriptionData = array();
if ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$subscriptionData['id'] = $subscriptionId;
$subscriptionData['name'] = $row['name'];
$subscriptionData['logo'] = $row['logo'];
$subscriptionData['price'] = $row['price'];
$subscriptionData['currency_id'] = $row['currency_id'];
$subscriptionData['next_payment'] = $row['next_payment'];
$subscriptionData['frequency'] = $row['frequency'];
$subscriptionData['cycle'] = $row['cycle'];
$subscriptionData['notes'] = $row['notes'];
$subscriptionData['payment_method_id'] = $row['payment_method_id'];
$subscriptionData['payer_user_id'] = $row['payer_user_id'];
$subscriptionData['category_id'] = $row['category_id'];
$subscriptionJson = json_encode($subscriptionData);
header('Content-Type: application/json');
echo $subscriptionJson;
} else {
echo "Error";
}
} else {
echo "Error";
}
}
$db->close();
?>
+89
View File
@@ -0,0 +1,89 @@
<?php
require_once '../../includes/connect_endpoint.php';
session_start();
require_once '../../includes/getdbkeys.php';
include_once '../../includes/list_subscriptions.php';
$theme = "light";
if (isset($_COOKIE['theme'])) {
$theme = $_COOKIE['theme'];
}
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
$sort = "next_payment";
$sql = "SELECT * FROM subscriptions ORDER BY next_payment ASC";
if (isset($_COOKIE['sortOrder']) && $_COOKIE['sortOrder'] != "") {
$sort = $_COOKIE['sortOrder'];
$allowedSortCriteria = ['name', 'id', 'next_payment', 'price', 'payer_user_id', 'category_id'];
$order = "ASC";
if ($sort == "price" || $sort == "id") {
$order = "DESC";
}
if (in_array($sort, $allowedSortCriteria)) {
$sql = "SELECT * FROM subscriptions ORDER BY $sort $order";
}
}
$result = $db->query($sql);
if ($result) {
$subscriptions = array();
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$subscriptions[] = $row;
}
}
$defaultLogo = $theme == "light" ? "images/wallos.png" : "images/walloswhite.png";
foreach ($subscriptions as $subscription) {
$id = $subscription['id'];
$print[$id]['id'] = $id;
$print[$id]['logo'] = $subscription['logo'] != "" ? "images/uploads/logos/".$subscription['logo'] : $defaultLogo;
$print[$id]['name']= $subscription['name'];
$cycle = $subscription['cycle'];
$frequency = $subscription['frequency'];
$print[$id]['billing_cycle'] = getBillingCycle($cycle, $frequency);
$paymentMethodId = $subscription['payment_method_id'];
$print[$id]['currency'] = $currencies[$subscription['currency_id']]['symbol'];
$currencyId = $subscription['currency_id'];
$print[$id]['next_payment'] = date('M d, Y', strtotime($subscription['next_payment']));
$print[$id]['payment_method_icon'] = "images/uploads/icons/" . $payment_methods[$paymentMethodId]['icon'];
$print[$id]['payment_method_name'] = $payment_methods[$paymentMethodId]['name'];
$print[$id]['category_id'] = $subscription['category_id'];
$print[$id]['price'] = $subscription['price'];
if (isset($_COOKIE['convertCurrency']) && $_COOKIE['convertCurrency'] === 'true' && $currencyId != $mainCurrencyId) {
$print[$id]['price'] = getPriceConverted($print[$id]['price'], $currencyId, $db);
$print[$id]['currency'] = $currencies[$mainCurrencyId]['symbol'];
}
if (isset($_COOKIE['showMonthlyPrice']) && $_COOKIE['showMonthlyPrice'] === 'true') {
$print[$id]['price'] = getPricePerMonth($cycle, $frequency, $print[$id]['price']);
}
$print[$id]['price'] = number_format($print[$id]['price'], 2, ".", "");
$print[$id]['hidelogo'] = isset($_COOKIE['hideNameOnMobile']) && $_COOKIE['hideNameOnMobile'] === 'true' && $print[$id]['logo'] === "wallos.png" ? "hideonmobile" : "";
$print[$id]['hidename'] = isset($_COOKIE['hideNameOnMobile']) && $_COOKIE['hideNameOnMobile'] === 'true' && $print[$id]['logo'] != "wallos.png" ? "hideonmobile" : "";
$print[$id]['resizename'] = isset($_COOKIE['hideNameOnMobile']) && $_COOKIE['hideNameOnMobile'] === 'true' && $print[$id]['logo'] === "wallos.png" ? "resize" : "";
}
if (isset($print)) {
printSubscriptons($print, $sort, $categories);
}
if (count($subscriptions) == 0) {
?>
<div class="empty-page">
<img src="images/siteimages/empty.png" alt="Empty page" />
<p>
You don't have any subscriptions yet
</p>
<button class="button" onClick="addSubscription()">
<img class="button-icon" src="images/siteicons/plusicon.png">
Add First Subscription
</button>
</div>
<?
}
}
$db->close();
?>
+158
View File
@@ -0,0 +1,158 @@
<?php
require_once '../../includes/connect_endpoint.php';
session_start();
function update_exchange_rate($db) {
$query = "SELECT api_key FROM fixer";
$result = $db->query($query);
if ($result) {
$row = $result->fetchArray(SQLITE3_ASSOC);
if ($row) {
$apiKey = $row['api_key'];
$codes = "";
$query = "SELECT id, name, symbol, code FROM currencies";
$result = $db->query($query);
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$codes .= $row['code'].",";
}
$codes = rtrim($codes, ',');
$query = "SELECT u.main_currency, c.code FROM user u LEFT JOIN currencies c ON u.main_currency = c.id WHERE u.id = 1";
$stmt = $db->prepare($query);
$result = $stmt->execute();
$row = $result->fetchArray(SQLITE3_ASSOC);
$mainCurrencyCode = $row['code'];
$mainCurrencyId = $row['main_currency'];
$api_url = "http://data.fixer.io/api/latest?access_key=". $apiKey . "&base=" . $mainCurrencyCode . "&symbols=" . $codes;
$response = file_get_contents($api_url);
$apiData = json_decode($response, true);
$mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode];
if ($apiData !== null && isset($apiData['rates'])) {
foreach ($apiData['rates'] as $currencyCode => $rate) {
if ($currencyCode === $mainCurrencyCode) {
$exchangeRate = 1.0;
} else {
$exchangeRate = $rate / $mainCurrencyToEUR;
}
$updateQuery = "UPDATE currencies SET rate = :rate WHERE code = :code";
$updateStmt = $db->prepare($updateQuery);
$updateStmt->bindParam(':rate', $exchangeRate, SQLITE3_TEXT);
$updateStmt->bindParam(':code', $currencyCode, SQLITE3_TEXT);
$updateResult = $updateStmt->execute();
}
$currentDate = new DateTime();
$formattedDate = $currentDate->format('Y-m-d');
$deleteQuery = "DELETE FROM last_exchange_update";
$deleteStmt = $db->prepare($deleteQuery);
$deleteResult = $deleteStmt->execute();
$query = "INSERT INTO last_exchange_update (date) VALUES (:formattedDate)";
$stmt = $db->prepare($query);
$stmt->bindParam(':formattedDate', $formattedDate, SQLITE3_TEXT);
$result = $stmt->execute();
$db->close();
}
}
}
}
$query = "SELECT main_currency FROM user WHERE id = 1";
$stmt = $db->prepare($query);
$result = $stmt->execute();
$row = $result->fetchArray(SQLITE3_ASSOC);
$mainCurrencyId = $row['main_currency'];
if (isset($_SESSION['username']) && isset($_POST['username']) && isset($_POST['email']) && isset($_POST['avatar'])) {
$oldUsername = $_SESSION['username'];
$username = $_POST['username'];
$email = $_POST['email'];
$avatar = $_POST['avatar'];
$main_currency = $_POST['main_currency'];
if (isset($_POST['password']) && $_POST['password'] != "") {
$password = $_POST['password'];
if (isset($_POST['confirm_password'])) {
$confirm = $_POST['confirm_password'];
if ($password != $confirm) {
$response = [
"success" => false,
"errorMessage" => "Passwords do not match"
];
echo json_encode($response);
exit();
}
} else {
$response = [
"success" => false,
"errorMessage" => "Passwords do not match"
];
echo json_encode($response);
exit();
}
}
if (isset($_POST['password']) && $_POST['password'] != "") {
$sql = "UPDATE user SET avatar = :avatar, username = :username, email = :email, password = :password, main_currency = :main_currency WHERE id = 1";
} else {
$sql = "UPDATE user SET avatar = :avatar, username = :username, email = :email, main_currency = :main_currency WHERE id = 1";
}
$stmt = $db->prepare($sql);
$stmt->bindParam(':avatar', $avatar, SQLITE3_TEXT);
$stmt->bindParam(':username', $username, SQLITE3_TEXT);
$stmt->bindParam(':email', $email, SQLITE3_TEXT);
$stmt->bindParam(':main_currency', $main_currency, SQLITE3_INTEGER);
if (isset($_POST['password']) && $_POST['password'] != "") {
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$stmt->bindParam(':password', $hashedPassword, SQLITE3_TEXT);
}
$result = $stmt->execute();
if ($result) {
if ($username != $oldUsername) {
$_SESSION['username'] = $username;
if (isset($_COOKIE['wallos_login'])) {
$cookie = explode('|', $_COOKIE['wallos_login'], 2) ;
$token = $cookie[1];
$cookieExpire = time() + (30 * 24 * 60 * 60);
$cookieValue = $username . "|" . $token . "|" . $main_currency;
}
}
$_SESSION['avatar'] = $avatar;
if ($main_currency != $mainCurrencyId) {
update_exchange_rate($db);
}
$response = [
"success" => true,
];
echo json_encode($response);
} else {
$response = [
"success" => false,
"errorMessage" => "Error updating user data"
];
echo json_encode($response);
}
exit();
} else {
$response = [
"success" => false,
"errorMessage" => "Please fill all fields"
];
echo json_encode($response);
exit();
}
?>