Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
feat: add openai compatible host for ai recommendations
Miguel Ribeiro99c30e70c801
diff --git a/README.md b/README.mdindex 51a69a7..6072954 100644--- a/README.md+++ b/README.md@@ -114,6 +114,8 @@ See instructions to run Wallos below.*/2 * * * * php /var/www/html/endpoints/cronjobs/sendresetpasswordemails.php >> /var/log/cron/sendresetpasswordemails.log 2>&10 */6 * * * php /var/www/html/endpoints/cronjobs/checkforupdates.php >> /var/log/cron/checkforupdates.log 2>&130 1 * * 1 php /var/www/html/endpoints/cronjobs/storetotalyearlycost.php >> /var/log/cron/storetotalyearlycost.log 2>&1+30 3 * * 1 php /var/www/html/endpoints/cronjobs/generaterecommendations.php weekly >> /var/log/cron/generaterecommendations.log 2>&1+0 4 1 * * php /var/www/html/endpoints/cronjobs/generaterecommendations.php monthly >> /var/log/cron/generaterecommendations.log 2>&1```5. If your web root is not `/var/www/html/` adjust the cronjobs above accordingly.diff --git a/admin.php b/admin.phpindex 6cea995..d443514 100644--- a/admin.php+++ b/admin.php@@ -502,6 +502,8 @@ $loginDisabledAllowed = $userCount == 1 && $settings['registrations_open'] == 0;onclick="executeCronJob('updatenextpayment')"><input type="button" value="Store Total Yearly Cost" class="button tiny mobile-grow"onclick="executeCronJob('storetotalyearlycost')">+ <input type="button" value="Generate AI Recommendations" class="button tiny mobile-grow"+ onclick="executeCronJob('generaterecommendations')"></div><div class="inline-row"><textarea id="cronjobResult" class="thin" readonly></textarea>diff --git a/cronjobs b/cronjobsindex ee85017..084edee 100644--- a/cronjobs+++ b/cronjobs@@ -7,4 +7,6 @@*/2 * * * * /usr/local/bin/php /var/www/html/endpoints/cronjobs/sendresetpasswordemails.php >> /var/log/cron/sendresetpasswordemails.log 2>&10 */6 * * * /usr/local/bin/php /var/www/html/endpoints/cronjobs/checkforupdates.php >> /var/log/cron/checkforupdates.log 2>&130 1 * * 1 /usr/local/bin/php /var/www/html/endpoints/cronjobs/storetotalyearlycost.php >> /var/log/cron/storetotalyearlycost.log 2>&1-0 3 * * * /usr/local/bin/php /var/www/html/endpoints/cronjobs/cleanupresettokens.php >> /var/log/cron/cleanupresettokens.log 2>&1\ No newline at end of file+0 3 * * * /usr/local/bin/php /var/www/html/endpoints/cronjobs/cleanupresettokens.php >> /var/log/cron/cleanupresettokens.log 2>&1+30 3 * * 1 /usr/local/bin/php /var/www/html/endpoints/cronjobs/generaterecommendations.php weekly >> /var/log/cron/generaterecommendations.log 2>&1+0 4 1 * * /usr/local/bin/php /var/www/html/endpoints/cronjobs/generaterecommendations.php monthly >> /var/log/cron/generaterecommendations.log 2>&1\ No newline at end of filediff --git a/endpoints/ai/fetch_models.php b/endpoints/ai/fetch_models.phpindex 1bbe72d..8debff2 100644--- a/endpoints/ai/fetch_models.php+++ b/endpoints/ai/fetch_models.php@@ -10,37 +10,28 @@ $openrouterModelsApiUrl = 'https://openrouter.ai/api/v1/models';$input = file_get_contents('php://input');$data = json_decode($input, true);-// Check if ai-type and ai-api-key are set+$aiType = isset($data["type"]) ? trim($data["type"]) : '';$aiApiKey = isset($data["api_key"]) ? trim($data["api_key"]) : '';$aiOllamaHost = isset($data["ollama_host"]) ? trim($data["ollama_host"]) : '';// Validate ai-type-if (!in_array($aiType, ['chatgpt', 'gemini', 'openrouter', 'ollama'])) {- $response = [- "success" => false,- "message" => translate('error', $i18n)- ];- echo json_encode($response);+if (!in_array($aiType, ['chatgpt', 'gemini', 'openrouter', 'ollama', 'openai-compatible'])) {+ echo json_encode(["success" => false, "message" => translate('error', $i18n)]);exit;}-// Validate ai-api-key and fetch models if ai-type is chatgpt, gemini or openrouter-if ($aiType === 'chatgpt' || $aiType === 'gemini' || $aiType === 'openrouter') {+// Validate API key for providers that require it+if (in_array($aiType, ['chatgpt', 'gemini', 'openrouter'])) {if (empty($aiApiKey)) {- $response = [- "success" => false,- "message" => translate('invalid_api_key', $i18n)- ];- echo json_encode($response);+ echo json_encode(["success" => false, "message" => translate('invalid_api_key', $i18n)]);exit;}}-// Prepare the request headers-$headers = [- 'Content-Type: application/json',-];+// Prepare the request headers and URL+$headers = ['Content-Type: application/json'];+if ($aiType === 'chatgpt') {$headers[] = 'Authorization: Bearer ' . $aiApiKey;$apiUrl = $chatgptModelsApiUrl;@@ -49,19 +40,38 @@ if ($aiType === 'chatgpt') {} elseif ($aiType === 'openrouter') {$headers[] = 'Authorization: Bearer ' . $aiApiKey;$apiUrl = $openrouterModelsApiUrl;+} elseif ($aiType === 'openai-compatible') {+ if (empty($aiOllamaHost)) {+ echo json_encode(["success" => false, "message" => translate('invalid_host', $i18n)]);+ exit;+ }++ $parsedUrl = parse_url($aiOllamaHost);+ if (+ !isset($parsedUrl['scheme']) ||+ !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||+ !filter_var($aiOllamaHost, FILTER_VALIDATE_URL)+ ) {+ echo json_encode(["success" => false, "message" => translate('invalid_host', $i18n)]);+ exit;+ }++ $ssrf = validate_webhook_url_for_ssrf($aiOllamaHost, $db, $i18n);++ // API key is optional — local instances don't need one+ if (!empty($aiApiKey)) {+ $headers[] = 'Authorization: Bearer ' . $aiApiKey;+ }++ $apiUrl = rtrim($aiOllamaHost, '/') . '/models';+} else {- // For ollama, no API key is needed- // Check for ollama host+ // Ollama — no API key neededif (empty($aiOllamaHost)) {- $response = [- "success" => false,- "message" => translate('invalid_host', $i18n)- ];- echo json_encode($response);+ echo json_encode(["success" => false, "message" => translate('invalid_host', $i18n)]);exit;}- // Scheme check$parsedUrl = parse_url($aiOllamaHost);if (!isset($parsedUrl['scheme']) ||@@ -72,75 +82,67 @@ if ($aiType === 'chatgpt') {exit;}- // SSRF check — dies automatically if private IP not in allowlist$ssrf = validate_webhook_url_for_ssrf($aiOllamaHost, $db, $i18n);- $apiUrl = $aiOllamaHost . '/api/tags';+ $apiUrl = rtrim($aiOllamaHost, '/') . '/api/tags';}-// Initialize cURL++// Execute cURL request$ch = curl_init($apiUrl);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);-curl_setopt($ch, CURLOPT_TIMEOUT, 60); // Set a timeout for the request-// Execute the request+curl_setopt($ch, CURLOPT_TIMEOUT, 60);$response = curl_exec($ch);-// Check for cURL errors+if (curl_errno($ch)) {$response = ["success" => false,- "message" => ($aiType === 'ollama')+ "message" => in_array($aiType, ['ollama', 'openai-compatible'])? translate('invalid_host', $i18n): translate('error', $i18n)];} else {- // Decode the response$modelsData = json_decode($response, true);+if ($aiType === 'gemini' && isset($modelsData['models']) && is_array($modelsData['models'])) {// Normalize Gemini response$models = array_map(function ($model) {return [- 'id' => str_replace('models/', '', $model['name']),+ 'id' => str_replace('models/', '', $model['name']),'name' => $model['displayName'] ?? $model['name'],];}, $modelsData['models']);- $response = [- "success" => true,- "models" => $models- ];+ $response = ["success" => true, "models" => $models];+} elseif (isset($modelsData['data']) && is_array($modelsData['data'])) {- // OpenAI format+ // OpenAI format (ChatGPT, OpenRouter, OpenAI Compatible)$models = array_map(function ($model) {return [- 'id' => $model['id'],+ 'id' => $model['id'],'name' => $model['name'] ?? $model['id'],];}, $modelsData['data']);- $response = [- "success" => true,- "models" => $models- ];- } elseif ($aiType === 'ollama' && isset($modelsData['models']) && is_array($modelsData['models'])) {- // Normalize Ollama response+ $response = ["success" => true, "models" => $models];++ } elseif (in_array($aiType, ['ollama', 'openai-compatible']) && isset($modelsData['models']) && is_array($modelsData['models'])) {+ // Ollama native format — also a fallback for openai-compatible servers that return this shape$models = array_map(function ($model) {return [- 'id' => $model['name'],+ 'id' => $model['name'],'name' => $model['name'],];}, $modelsData['models']);- $response = [- "success" => true,- "models" => $models- ];+ $response = ["success" => true, "models" => $models];+} else {$response = ["success" => false,- "message" => ($aiType === 'ollama')+ "message" => in_array($aiType, ['ollama', 'openai-compatible'])? translate('invalid_host', $i18n): translate('invalid_api_key', $i18n)];}}-// Close cURL session-curl_close($ch);-// Return the response as JSON-echo json_encode($response);\ No newline at end of file++unset($ch);+echo json_encode($response);diff --git a/endpoints/ai/generate_recommendations.php b/endpoints/ai/generate_recommendations.phpindex 2cfbb37..3a3d283 100644--- a/endpoints/ai/generate_recommendations.php+++ b/endpoints/ai/generate_recommendations.php@@ -7,16 +7,11 @@ require_once '../../includes/ssrf_helper.php';function getPricePerMonth($cycle, $frequency, $price){switch ($cycle) {- case 1:- return $price * (30 / $frequency); // daily- case 2:- return $price * (4.35 / $frequency); // weekly- case 3:- return $price / $frequency; // monthly- case 4:- return $price / (12 * $frequency); // yearly- default:- return $price;+ case 1: return $price * (30 / $frequency); // daily+ case 2: return $price * (4.35 / $frequency); // weekly+ case 3: return $price / $frequency; // monthly+ case 4: return $price / (12 * $frequency); // yearly+ default: return $price;}}@@ -30,11 +25,7 @@ function describeFrequency($cycle, $frequency)default => 'unit'};- if ($frequency == 1) {- return "Every $unit";- } else {- return "Every $frequency {$unit}s";- }+ return $frequency == 1 ? "Every $unit" : "Every $frequency {$unit}s";}function describeCurrency($currencyId, $currencies)@@ -42,45 +33,38 @@ function describeCurrency($currencyId, $currencies)return $currencies[$currencyId]['code'] ?? '';}-// Get AI settings for the user from the database+// Load AI settings$stmt = $db->prepare("SELECT * FROM ai_settings WHERE user_id = ?");$stmt->bindValue(1, $userId, SQLITE3_INTEGER);$result = $stmt->execute();$aiSettings = $result->fetchArray(SQLITE3_ASSOC);$stmt->close();+if (!$aiSettings) {- $response = [- "success" => false,- "message" => translate('error', $i18n)- ];- echo json_encode($response);+ echo json_encode(["success" => false, "message" => translate('error', $i18n)]);exit;}-$type = isset($aiSettings['type']) ? $aiSettings['type'] : '';-$enabled = isset($aiSettings['enabled']) ? (bool) $aiSettings['enabled'] : false;-$model = isset($aiSettings['model']) ? $aiSettings['model'] : '';-$host = "";-$apiKey = "";-if (!in_array($type, ['chatgpt', 'gemini', 'openrouter', 'ollama']) || !$enabled || empty($model)) {- $response = [- "success" => false,- "message" => translate('error', $i18n)- ];- echo json_encode($response);+$type = $aiSettings['type'] ?? '';+$enabled = !empty($aiSettings['enabled']);+$model = $aiSettings['model'] ?? '';+$host = $aiSettings['url'] ?? '';+$apiKey = $aiSettings['api_key'] ?? '';++if (!in_array($type, ['chatgpt', 'gemini', 'openrouter', 'ollama', 'openai-compatible']) || !$enabled || empty($model)) {+ echo json_encode(["success" => false, "message" => translate('error', $i18n)]);exit;}-if ($type == 'ollama') {- $host = isset($aiSettings['url']) ? $aiSettings['url'] : '';+$ssrf = null;++// Host-based providers+if (in_array($type, ['ollama', 'openai-compatible'])) {if (empty($host)) {- $response = [- "success" => false,- "message" => translate('invalid_host', $i18n)- ];- echo json_encode($response);+ echo json_encode(["success" => false, "message" => translate('invalid_host', $i18n)]);exit;}+$parsedUrl = parse_url($host);if (!isset($parsedUrl['scheme']) ||@@ -92,21 +76,18 @@ if ($type == 'ollama') {}$ssrf = validate_webhook_url_for_ssrf($host, $db, $i18n);++ if ($type === 'ollama') {+ $apiKey = '';+ }} else {- $ssrf = null;- $apiKey = isset($aiSettings['api_key']) ? $aiSettings['api_key'] : '';if (empty($apiKey)) {- $response = [- "success" => false,- "message" => translate('invalid_api_key', $i18n)- ];- echo json_encode($response);+ echo json_encode(["success" => false, "message" => translate('invalid_api_key', $i18n)]);exit;}}-// We have everything we need, fetch information from the dabase to send to the AI API-// Get the categories from the database for user with ID 1+// Categories$stmt = $db->prepare("SELECT * FROM categories WHERE user_id = :user_id");$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);$result = $stmt->execute();@@ -115,7 +96,7 @@ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {$categories[$row['id']] = $row;}-// Get the currencies from the database for user with ID 1+// Currencies$stmt = $db->prepare("SELECT * FROM currencies WHERE user_id = :user_id");$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);$result = $stmt->execute();@@ -124,7 +105,7 @@ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {$currencies[$row['id']] = $row;}-// Get houswhold members from the database for user with ID 1+// Household members$stmt = $db->prepare("SELECT * FROM household WHERE user_id = :user_id");$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);$result = $stmt->execute();@@ -133,17 +114,17 @@ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {$members[$row['id']] = $row;}-// Get language from the user table+// User language$stmt = $db->prepare("SELECT language FROM user WHERE id = :user_id");$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);$result = $stmt->execute();$userLanguage = $result->fetchArray(SQLITE3_ASSOC)['language'] ?? 'en';-// Get name from includes/i18n/languages.php+// Language namerequire_once '../../includes/i18n/languages.php';$userLanguageName = $languages[$userLanguage]['name'] ?? 'English';-// Get subscriptions from the database for user with ID 1+// Subscriptions$stmt = $db->prepare("SELECT * FROM subscriptions WHERE user_id = :user_id AND inactive = 0");$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);$result = $stmt->execute();@@ -153,85 +134,100 @@ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {$subscriptions[] = $row;}-if (!empty($subscriptions)) {- $subscriptionsForAI = [];+if (empty($subscriptions)) {+ echo json_encode(["success" => false, "message" => translate('error', $i18n)]);+ exit;+}- foreach ($subscriptions as $row) {- if ($row['inactive'])- continue;+$subscriptionsForAI = [];- $price = round($row['price'], 2);- $currencyCode = $currencies[$row['currency_id']]['code'] ?? '';- $priceFormatted = $currencyCode ? "$price $currencyCode" : "$price";+foreach ($subscriptions as $row) {+ if ($row['inactive']) {+ continue;+ }- $payerName = $members[$row['payer_user_id']]['name'] ?? 'Unknown';+ $price = round($row['price'], 2);+ $currencyCode = $currencies[$row['currency_id']]['code'] ?? '';+ $priceFormatted = $currencyCode ? "$price $currencyCode" : "$price";- $subscriptionsForAI[] = [- 'name' => $row['name'],- 'price' => $priceFormatted,- 'frequency' => describeFrequency($row['cycle'], $row['frequency']),- 'category' => $categories[$row['category_id']]['name'] ?? 'Uncategorized',- 'payer' => $payerName- ];- }+ $payerName = $members[$row['payer_user_id']]['name'] ?? 'Unknown';- // encode- $aiDataJson = json_encode($subscriptionsForAI, JSON_PRETTY_PRINT);-} else {- $response = [- "success" => false,- "message" => translate('error', $i18n)+ $subscriptionsForAI[] = [+ 'name' => $row['name'],+ 'price' => $priceFormatted,+ 'frequency' => describeFrequency($row['cycle'], $row['frequency']),+ 'category' => $categories[$row['category_id']]['name'] ?? 'Uncategorized',+ 'payer' => $payerName,];- echo json_encode($response);- exit;}$prompt = <<<PROMPT- You are a helpful assistant designed to help users save money on digital subscriptions.+You are a helpful assistant designed to help users save money on digital subscriptions.- The user has shared a list of their active subscriptions across household members. For each subscription, you are given:- - Name of the service- - Price (in original currency)- - Payment frequency (e.g., every month, every year, etc.)- - Category- - Payer (which household member pays for it)+The user has shared a list of their active subscriptions across household members. For each subscription, you are given:+- Name of the service+- Price (in original currency)+- Payment frequency (e.g., every month, every year, etc.)+- Category+- Payer (which household member pays for it)- Analyze the data and give 3 to 7 smart and specific recommendations to reduce subscription costs. If possible, include estimated savings for each suggestion.+Analyze the data and give 3 to 7 smart and specific recommendations to reduce subscription costs. If possible, include estimated savings for each suggestion.- Follow these guidelines:- - Do NOT suggest switching to family or group plans unless two or more different household members are paying for the same or similar service.- - Recognize known feature overlaps, such as:- • YouTube Premium includes YouTube Music.- • Amazon Prime includes Prime Video.- • Google One, iCloud+, and Proton all offer cloud storage.- • Real Debrid, All Debrid, and Premiumize offer similar download capabilities.- - Suggest rotating or cancelling subscriptions that serve similar purposes (e.g. multiple streaming or IPTV services).- - Recommend switching from monthly to yearly plans only if it provides clear savings and the user is likely to keep the service long-term.- - Suggest looking for promo or new customer deals if a service appears overpriced.- - Only recommend cancelling rarely used services if they do not provide unique value.+Follow these guidelines:+- Do NOT suggest switching to family or group plans unless two or more different household members are paying for the same or similar service.+- Recognize known feature overlaps, such as:+• YouTube Premium includes YouTube Music.+• Amazon Prime includes Prime Video.+• Google One, iCloud+, and Proton all offer cloud storage.+• Real Debrid, All Debrid, and Premiumize offer similar download capabilities.+- Suggest rotating or cancelling subscriptions that serve similar purposes (e.g. multiple streaming or IPTV services).+- Recommend switching from monthly to yearly plans only if it provides clear savings and the user is likely to keep the service long-term.+- Suggest looking for promo or new customer deals if a service appears overpriced.+- Only recommend cancelling rarely used services if they do not provide unique value.- Return the result as a JSON array. Each item in the array should have:- - "title": a short summary of the suggestion- - "description": a longer explanation with reasoning- - "savings": a rough estimate like "10 EUR/month" or "60 EUR/year" (if possible)+Return the result as a JSON array. Each item in the array should have:+- "title": a short summary of the suggestion+- "description": a longer explanation with reasoning+- "savings": a rough estimate like "10 EUR/month" or "60 EUR/year" (if possible)- If possible, all text should be in the user's language: {$userLanguageName}. Otherwise, use English.+If possible, all text should be in the user's language: {$userLanguageName}. Otherwise, use English.- Do not include any other text, just the JSON output. Absolutely no additional comments or explanations.+Do not include any other text, just the JSON output. Absolutely no additional comments or explanations.- Here is the user’s data:- PROMPT;+Here is the user’s data:+PROMPT;$prompt .= "\n\n" . json_encode($subscriptionsForAI, JSON_PRETTY_PRINT);-// Prepare the cURL request+// cURL request$ch = curl_init();if ($type === 'ollama') {- curl_setopt($ch, CURLOPT_URL, $host . '/api/generate');+ curl_setopt($ch, CURLOPT_URL, rtrim($host, '/') . '/api/generate');curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);curl_setopt($ch, CURLOPT_POST, true);- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['model' => $model, 'prompt' => $prompt, 'stream' => false]));+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([+ 'model' => $model,+ 'prompt' => $prompt,+ 'stream' => false,+ ]));+} elseif ($type === 'openai-compatible') {+ $headers = ['Content-Type: application/json'];+ if (!empty($apiKey)) {+ $headers[] = 'Authorization: Bearer ' . $apiKey;+ }++ curl_setopt($ch, CURLOPT_URL, rtrim($host, '/') . '/chat/completions');+ curl_setopt($ch, CURLOPT_POST, true);+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([+ 'model' => $model,+ 'messages' => [['role' => 'user', 'content' => $prompt]],+ ]));+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);++ if ($ssrf) {+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);+ }} else {$headers = ['Content-Type: application/json'];@@ -239,29 +235,27 @@ if ($type === 'ollama') {$headers[] = 'Authorization: Bearer ' . $apiKey;curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([- 'model' => $model,- 'messages' => [['role' => 'user', 'content' => $prompt]]+ 'model' => $model,+ 'messages' => [['role' => 'user', 'content' => $prompt]],]));} elseif ($type === 'gemini') {curl_setopt($ch,CURLOPT_URL,- 'https://generativelanguage.googleapis.com/v1beta/models/' . urlencode($model) .- ':generateContent?key=' . urlencode($apiKey)+ 'https://generativelanguage.googleapis.com/v1beta/models/' .+ urlencode($model) . ':generateContent?key=' . urlencode($apiKey));curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([- 'contents' => [- [- 'parts' => [['text' => $prompt]]- ]- ]+ 'contents' => [[+ 'parts' => [['text' => $prompt]],+ ]],]));} elseif ($type === 'openrouter') {$headers[] = 'Authorization: Bearer ' . $apiKey;curl_setopt($ch, CURLOPT_URL, 'https://openrouter.ai/api/v1/chat/completions');curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([- 'model' => $model,- 'messages' => [['role' => 'user', 'content' => $prompt]]+ 'model' => $model,+ 'messages' => [['role' => 'user', 'content' => $prompt]],]));}@@ -271,71 +265,76 @@ if ($type === 'ollama') {curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_TIMEOUT, 300);-// Execute the cURL request$reply = curl_exec($ch);-// Check for errorsif (curl_errno($ch)) {- $response = [- "success" => false,- "message" => curl_error($ch)- ];- echo json_encode($response);+ echo json_encode(["success" => false, "message" => curl_error($ch)]);exit;}-// Close the cURL session-curl_close($ch);+unset($ch);++// Decode AI reply+$replyData = json_decode($reply, true);+$recommendations = null;++if (in_array($type, ['chatgpt', 'openrouter', 'openai-compatible'])+ && isset($replyData['choices'][0]['message']['content'])) {-// Try to decode the AI's JSON reply-$replyData = json_decode($reply, true); // decode into array-if (($type === 'chatgpt' || $type === 'openrouter') && isset($replyData['choices'][0]['message']['content'])) {$recommendationsJson = $replyData['choices'][0]['message']['content'];+ // Strip ```json or ``` fences if present+ $recommendationsJson = preg_replace('/^```json\s*|\s*```$/m', '', $recommendationsJson);+ $recommendationsJson = preg_replace('/^```\s*|\s*```$/m', '', $recommendationsJson);+ $recommendationsJson = trim($recommendationsJson);+$recommendations = json_decode($recommendationsJson, true);-} elseif ($type === 'gemini' && isset($replyData['candidates'][0]['content']['parts'][0]['text'])) {++} elseif ($type === 'gemini'+ && isset($replyData['candidates'][0]['content']['parts'][0]['text'])) {+$recommendationsJson = $replyData['candidates'][0]['content']['parts'][0]['text'];- // Gemini has a habit of returning the JSON wrapped in markdown syntax, no matter the prompting, strip before parsing.$recommendationsJson = preg_replace('/^```json\s*|\s*```$/m', '', $recommendationsJson);+ $recommendationsJson = preg_replace('/^```\s*|\s*```$/m', '', $recommendationsJson);$recommendationsJson = trim($recommendationsJson);+$recommendations = json_decode($recommendationsJson, true);-} else {- $recommendations = json_decode($replyData['response'], true);++} elseif ($type === 'ollama') {+ $recommendations = json_decode($replyData['response'] ?? '', true);}if (json_last_error() === JSON_ERROR_NONE && is_array($recommendations)) {- // Remove old recommendations for this user+ // Clear old recommendations$stmt = $db->prepare("DELETE FROM ai_recommendations WHERE user_id = :user_id");$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);$stmt->execute();- // Insert each new recommendation+ // Insert new recommendations$insert = $db->prepare("- INSERT INTO ai_recommendations (user_id, type, title, description, savings)- VALUES (:user_id, :type, :title, :description, :savings)- ");+ INSERT INTO ai_recommendations (user_id, type, title, description, savings)+ VALUES (:user_id, :type, :title, :description, :savings)+ ");foreach ($recommendations as $rec) {$insert->bindValue(':user_id', $userId, SQLITE3_INTEGER);- $insert->bindValue(':type', 'subscription', SQLITE3_TEXT); // or any category you want+ $insert->bindValue(':type', 'subscription', SQLITE3_TEXT);$insert->bindValue(':title', $rec['title'] ?? '', SQLITE3_TEXT);$insert->bindValue(':description', $rec['description'] ?? '', SQLITE3_TEXT);$insert->bindValue(':savings', $rec['savings'] ?? '', SQLITE3_TEXT);$insert->execute();}- $response = [- "success" => true,- "message" => translate('success', $i18n),- "recommendations" => $recommendations- ];- echo json_encode($response);+ echo json_encode([+ "success" => true,+ "message" => translate('success', $i18n),+ "recommendations" => $recommendations,+ ]);exit;-} else {- $response = [- "success" => false,- "message" => translate('error', $i18n),- "json_error" => json_last_error_msg()- ];- echo json_encode($response);- exit;-}\ No newline at end of file+}++echo json_encode([+ "success" => false,+ "message" => translate('error', $i18n),+ "json_error" => json_last_error_msg(),+]);+exit;diff --git a/endpoints/ai/save_settings.php b/endpoints/ai/save_settings.phpindex 27d1aa8..0165367 100644--- a/endpoints/ai/save_settings.php+++ b/endpoints/ai/save_settings.php@@ -6,50 +6,39 @@ require_once '../../includes/ssrf_helper.php';$input = file_get_contents('php://input');$data = json_decode($input, true);-$aiEnabled = isset($data['ai_enabled']) ? (bool) $data['ai_enabled'] : false;-$aiType = isset($data['ai_type']) ? trim($data['ai_type']) : '';-$aiApiKey = isset($data['api_key']) ? trim($data['api_key']) : '';+$aiEnabled = isset($data['ai_enabled']) ? (bool) $data['ai_enabled'] : false;+$aiType = isset($data['ai_type']) ? trim($data['ai_type']) : '';+$aiApiKey = isset($data['api_key']) ? trim($data['api_key']) : '';$aiOllamaHost = isset($data['ollama_host']) ? trim($data['ollama_host']) : '';-$aiModel = isset($data['model']) ? trim($data['model']) : '';+$aiModel = isset($data['model']) ? trim($data['model']) : '';+$aiSchedule = isset($data['ai_run_schedule']) ? $data['ai_run_schedule'] : "manual";-if (empty($aiType) || !in_array($aiType, ['chatgpt', 'gemini', 'openrouter', 'ollama'])) {- $response = [- "success" => false,- "message" => translate('error', $i18n)- ];- echo json_encode($response);+// Validate type+if (empty($aiType) || !in_array($aiType, ['chatgpt', 'gemini', 'openrouter', 'ollama', 'openai-compatible'])) {+ echo json_encode(["success" => false, "message" => translate('error', $i18n)]);exit;}-if (($aiType === 'chatgpt' || $aiType === 'gemini' || $aiType === 'openrouter') && empty($aiApiKey)) {- $response = [- "success" => false,- "message" => translate('invalid_api_key', $i18n)- ];- echo json_encode($response);+// API key required only for these+if (in_array($aiType, ['chatgpt', 'gemini', 'openrouter']) && empty($aiApiKey)) {+ echo json_encode(["success" => false, "message" => translate('invalid_api_key', $i18n)]);exit;}-if ($aiType === 'ollama' && empty($aiOllamaHost)) {- $response = [- "success" => false,- "message" => translate('invalid_host', $i18n)- ];- echo json_encode($response);+// URL required when using a host+if (in_array($aiType, ['ollama', 'openai-compatible']) && empty($aiOllamaHost)) {+ echo json_encode(["success" => false, "message" => translate('invalid_host', $i18n)]);exit;}+// Model is always requiredif (empty($aiModel)) {- $response = [- "success" => false,- "message" => translate('fill_mandatory_fields', $i18n)- ];- echo json_encode($response);+ echo json_encode(["success" => false, "message" => translate('fill_mandatory_fields', $i18n)]);exit;}-if ($aiType === 'ollama') {- $aiApiKey = ''; // Ollama does not require an API key+// URL validation + SSRF for host-based providers+if (in_array($aiType, ['ollama', 'openai-compatible'])) {$parsedUrl = parse_url($aiOllamaHost);if (!isset($parsedUrl['scheme']) ||@@ -60,38 +49,47 @@ if ($aiType === 'ollama') {exit;}- // SSRF check — dies automatically if private IP not in allowlistvalidate_webhook_url_for_ssrf($aiOllamaHost, $db, $i18n);++ if ($aiType === 'ollama') {+ // Ollama never uses an API key+ $aiApiKey = '';+ }} else {- $aiOllamaHost = ''; // Clear Ollama host if not using Ollama+ // Non-host providers do not store a URL+ $aiOllamaHost = '';}-// Remove existing AI settings for the user+// Save settings$stmt = $db->prepare("DELETE FROM ai_settings WHERE user_id = ?");$stmt->bindValue(1, $userId, SQLITE3_INTEGER);$stmt->execute();$stmt->close();-// Insert new AI settings-$stmt = $db->prepare("INSERT INTO ai_settings (user_id, type, enabled, api_key, model, url) VALUES (:user_id, :type, :enabled, :api_key, :model, :url)");-$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);-$stmt->bindValue(':type', $aiType, SQLITE3_TEXT);-$stmt->bindValue(':enabled', $aiEnabled, SQLITE3_INTEGER);-$stmt->bindValue(':api_key', $aiApiKey, SQLITE3_TEXT);-$stmt->bindValue(':model', $aiModel, SQLITE3_TEXT);-$stmt->bindValue(':url', $aiOllamaHost, SQLITE3_TEXT);+$stmt = $db->prepare("+ INSERT INTO ai_settings (user_id, type, enabled, api_key, model, url, run_schedule)+ VALUES (:user_id, :type, :enabled, :api_key, :model, :url, :run_schedule)+");+$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);+$stmt->bindValue(':type', $aiType, SQLITE3_TEXT);+$stmt->bindValue(':enabled', $aiEnabled, SQLITE3_INTEGER);+$stmt->bindValue(':api_key', $aiApiKey, SQLITE3_TEXT);+$stmt->bindValue(':model', $aiModel, SQLITE3_TEXT);+$stmt->bindValue(':url', $aiOllamaHost,SQLITE3_TEXT);+$stmt->bindValue(':run_schedule', $aiSchedule, SQLITE3_TEXT);$result = $stmt->execute();if ($result) {$response = ["success" => true,"message" => translate('success', $i18n),- "enabled" => $aiEnabled+ "enabled" => $aiEnabled,];} else {$response = ["success" => false,- "message" => translate('error', $i18n)+ "message" => translate('error', $i18n),];}+echo json_encode($response);diff --git a/endpoints/cronjobs/generaterecommendations.php b/endpoints/cronjobs/generaterecommendations.phpnew file mode 100644index 0000000..977c7d6--- /dev/null+++ b/endpoints/cronjobs/generaterecommendations.php@@ -0,0 +1,333 @@+<?php+set_time_limit(300);+require_once 'validate.php';+require_once __DIR__ . '/../../includes/connect_endpoint_crontabs.php';+require_once __DIR__ . '/../../includes/ssrf_helper.php';++if (php_sapi_name() === 'cli') {+ $runType = $argv[1] ?? 'weekly';+} else {+ $runType = $_GET['run'] ?? 'weekly';+}++if (!in_array($runType, ['weekly', 'monthly'])) {+ $runType = 'weekly';+}++echo "Running " . $runType . " AI Recommendations generation.\n";++$stmt = $db->prepare("+ SELECT user_id, type, api_key, model, url+ FROM ai_settings+ WHERE enabled = 1+ AND model != ''+ AND run_schedule = ?+");+$stmt->bindValue(1, $runType, SQLITE3_TEXT);+$queryResult = $stmt->execute();++// Fetch all into array first so the connection is free for inner queries+$allAiSettings = [];+while ($row = $queryResult->fetchArray(SQLITE3_ASSOC)) {+ $allAiSettings[] = $row;+}+$stmt->close();++function getPricePerMonth($cycle, $frequency, $price)+{+ switch ($cycle) {+ case 1: return $price * (30 / $frequency);+ case 2: return $price * (4.35 / $frequency);+ case 3: return $price / $frequency;+ case 4: return $price / (12 * $frequency);+ default: return $price;+ }+}++function describeFrequency($cycle, $frequency)+{+ $unit = match ($cycle) {+ 1 => 'day',+ 2 => 'week',+ 3 => 'month',+ 4 => 'year',+ default => 'unit'+ };+ return $frequency == 1 ? "Every $unit" : "Every $frequency {$unit}s";+}++require_once __DIR__ . '/../../includes/i18n/languages.php';++$processed = 0;+$successes = 0;+$failures = [];++foreach ($allAiSettings as $aiSettings) {+ $processed++;+ $tempUserId = $aiSettings['user_id'];++ $type = $aiSettings['type'] ?? '';+ $model = $aiSettings['model'] ?? '';+ $host = $aiSettings['url'] ?? '';+ $apiKey = $aiSettings['api_key'] ?? '';+ $ssrf = null;++ // Validate provider+ if (!in_array($type, ['chatgpt', 'gemini', 'openrouter', 'ollama', 'openai-compatible']) || empty($model)) {+ $failures[] = ['user_id' => $tempUserId, 'reason' => 'invalid type or model'];+ continue;+ }++ // Validate host/key+ if (in_array($type, ['ollama', 'openai-compatible'])) {+ if (empty($host)) {+ $failures[] = ['user_id' => $tempUserId, 'reason' => 'missing host'];+ continue;+ }+ $parsedUrl = parse_url($host);+ if (+ !isset($parsedUrl['scheme']) ||+ !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||+ !filter_var($host, FILTER_VALIDATE_URL)+ ) {+ $failures[] = ['user_id' => $tempUserId, 'reason' => 'invalid host URL'];+ continue;+ }+ $ssrf = validate_webhook_url_for_ssrf($host, $db, []);+ if ($type === 'ollama') {+ $apiKey = '';+ }+ } else {+ if (empty($apiKey)) {+ $failures[] = ['user_id' => $tempUserId, 'reason' => 'missing api key'];+ continue;+ }+ }++ // Categories+ $catStmt = $db->prepare("SELECT * FROM categories WHERE user_id = :user_id");+ $catStmt->bindValue(':user_id', $tempUserId, SQLITE3_INTEGER);+ $catResult = $catStmt->execute();+ $categories = [];+ while ($row = $catResult->fetchArray(SQLITE3_ASSOC)) {+ $categories[$row['id']] = $row;+ }++ // Currencies+ $curStmt = $db->prepare("SELECT * FROM currencies WHERE user_id = :user_id");+ $curStmt->bindValue(':user_id', $tempUserId, SQLITE3_INTEGER);+ $curResult = $curStmt->execute();+ $currencies = [];+ while ($row = $curResult->fetchArray(SQLITE3_ASSOC)) {+ $currencies[$row['id']] = $row;+ }++ // Household members+ $memStmt = $db->prepare("SELECT * FROM household WHERE user_id = :user_id");+ $memStmt->bindValue(':user_id', $tempUserId, SQLITE3_INTEGER);+ $memResult = $memStmt->execute();+ $members = [];+ while ($row = $memResult->fetchArray(SQLITE3_ASSOC)) {+ $members[$row['id']] = $row;+ }++ // User language+ $langStmt = $db->prepare("SELECT language FROM user WHERE id = :user_id");+ $langStmt->bindValue(':user_id', $tempUserId, SQLITE3_INTEGER);+ $langResult = $langStmt->execute();+ $userLanguage = $langResult->fetchArray(SQLITE3_ASSOC)['language'] ?? 'en';+ $userLanguageName = $languages[$userLanguage]['name'] ?? 'English';++ // Subscriptions+ $subStmt = $db->prepare("SELECT * FROM subscriptions WHERE user_id = :user_id AND inactive = 0");+ $subStmt->bindValue(':user_id', $tempUserId, SQLITE3_INTEGER);+ $subResult = $subStmt->execute();+ $subscriptions = [];+ while ($row = $subResult->fetchArray(SQLITE3_ASSOC)) {+ $subscriptions[] = $row;+ }++ if (empty($subscriptions)) {+ $failures[] = ['user_id' => $tempUserId, 'reason' => 'no active subscriptions'];+ continue;+ }++ $subscriptionsForAI = [];+ foreach ($subscriptions as $row) {+ if ($row['inactive']) continue;+ $price = round($row['price'], 2);+ $currencyCode = $currencies[$row['currency_id']]['code'] ?? '';+ $priceFormatted = $currencyCode ? "$price $currencyCode" : "$price";+ $payerName = $members[$row['payer_user_id']]['name'] ?? 'Unknown';+ $subscriptionsForAI[] = [+ 'name' => $row['name'],+ 'price' => $priceFormatted,+ 'frequency' => describeFrequency($row['cycle'], $row['frequency']),+ 'category' => $categories[$row['category_id']]['name'] ?? 'Uncategorized',+ 'payer' => $payerName,+ ];+ }++ $prompt = <<<PROMPT+You are a helpful assistant designed to help users save money on digital subscriptions.++The user has shared a list of their active subscriptions across household members. For each subscription, you are given:+- Name of the service+- Price (in original currency)+- Payment frequency (e.g., every month, every year, etc.)+- Category+- Payer (which household member pays for it)++Analyze the data and give 3 to 7 smart and specific recommendations to reduce subscription costs. If possible, include estimated savings for each suggestion.++Follow these guidelines:+- Do NOT suggest switching to family or group plans unless two or more different household members are paying for the same or similar service.+- Recognize known feature overlaps, such as:+• YouTube Premium includes YouTube Music.+• Amazon Prime includes Prime Video.+• Google One, iCloud+, and Proton all offer cloud storage.+• Real Debrid, All Debrid, and Premiumize offer similar download capabilities.+- Suggest rotating or cancelling subscriptions that serve similar purposes (e.g. multiple streaming or IPTV services).+- Recommend switching from monthly to yearly plans only if it provides clear savings and the user is likely to keep the service long-term.+- Suggest looking for promo or new customer deals if a service appears overpriced.+- Only recommend cancelling rarely used services if they do not provide unique value.++Return the result as a JSON array. Each item in the array should have:+- "title": a short summary of the suggestion+- "description": a longer explanation with reasoning+- "savings": a rough estimate like "10 EUR/month" or "60 EUR/year" (if possible)++If possible, all text should be in the user's language: {$userLanguageName}. Otherwise, use English.++Do not include any other text, just the JSON output. Absolutely no additional comments or explanations.++Here is the user's data:+PROMPT;++ $prompt .= "\n\n" . json_encode($subscriptionsForAI, JSON_PRETTY_PRINT);++ // cURL request+ $ch = curl_init();++ if ($type === 'ollama') {+ curl_setopt($ch, CURLOPT_URL, rtrim($host, '/') . '/api/generate');+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);+ curl_setopt($ch, CURLOPT_POST, true);+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([+ 'model' => $model,+ 'prompt' => $prompt,+ 'stream' => false,+ ]));+ } elseif ($type === 'openai-compatible') {+ $headers = ['Content-Type: application/json'];+ if (!empty($apiKey)) {+ $headers[] = 'Authorization: Bearer ' . $apiKey;+ }+ curl_setopt($ch, CURLOPT_URL, rtrim($host, '/') . '/chat/completions');+ curl_setopt($ch, CURLOPT_POST, true);+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([+ 'model' => $model,+ 'messages' => [['role' => 'user', 'content' => $prompt]],+ ]));+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);+ if ($ssrf) {+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);+ }+ } else {+ $headers = ['Content-Type: application/json'];+ if ($type === 'chatgpt') {+ $headers[] = 'Authorization: Bearer ' . $apiKey;+ curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([+ 'model' => $model,+ 'messages' => [['role' => 'user', 'content' => $prompt]],+ ]));+ } elseif ($type === 'gemini') {+ curl_setopt($ch, CURLOPT_URL,+ 'https://generativelanguage.googleapis.com/v1beta/models/' .+ urlencode($model) . ':generateContent?key=' . urlencode($apiKey)+ );+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([+ 'contents' => [['parts' => [['text' => $prompt]]]],+ ]));+ } elseif ($type === 'openrouter') {+ $headers[] = 'Authorization: Bearer ' . $apiKey;+ curl_setopt($ch, CURLOPT_URL, 'https://openrouter.ai/api/v1/chat/completions');+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([+ 'model' => $model,+ 'messages' => [['role' => 'user', 'content' => $prompt]],+ ]));+ }+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);+ }++ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_TIMEOUT, 300);++ $reply = curl_exec($ch);++ if (curl_errno($ch)) {+ $failures[] = ['user_id' => $tempUserId, 'reason' => curl_error($ch)];+ unset($ch);+ continue;+ }+ unset($ch);++ // Parse response+ $replyData = json_decode($reply, true);+ $recommendations = null;++ if (in_array($type, ['chatgpt', 'openrouter', 'openai-compatible'])+ && isset($replyData['choices'][0]['message']['content'])) {+ $recommendationsJson = $replyData['choices'][0]['message']['content'];+ $recommendationsJson = preg_replace('/^```json\s*|\s*```$/m', '', $recommendationsJson);+ $recommendationsJson = preg_replace('/^```\s*|\s*```$/m', '', $recommendationsJson);+ $recommendations = json_decode(trim($recommendationsJson), true);+ } elseif ($type === 'gemini'+ && isset($replyData['candidates'][0]['content']['parts'][0]['text'])) {+ $recommendationsJson = $replyData['candidates'][0]['content']['parts'][0]['text'];+ $recommendationsJson = preg_replace('/^```json\s*|\s*```$/m', '', $recommendationsJson);+ $recommendationsJson = preg_replace('/^```\s*|\s*```$/m', '', $recommendationsJson);+ $recommendations = json_decode(trim($recommendationsJson), true);+ } elseif ($type === 'ollama') {+ $recommendations = json_decode($replyData['response'] ?? '', true);+ }++ if (json_last_error() !== JSON_ERROR_NONE || !is_array($recommendations)) {+ $failures[] = ['user_id' => $tempUserId, 'reason' => 'invalid AI response: ' . json_last_error_msg()];+ continue;+ }++ // Save recommendations+ $delStmt = $db->prepare("DELETE FROM ai_recommendations WHERE user_id = :user_id");+ $delStmt->bindValue(':user_id', $tempUserId, SQLITE3_INTEGER);+ $delStmt->execute();++ $insert = $db->prepare("+ INSERT INTO ai_recommendations (user_id, type, title, description, savings)+ VALUES (:user_id, :type, :title, :description, :savings)+ ");+ foreach ($recommendations as $rec) {+ $insert->bindValue(':user_id', $tempUserId, SQLITE3_INTEGER);+ $insert->bindValue(':type', 'subscription', SQLITE3_TEXT);+ $insert->bindValue(':title', $rec['title'] ?? '', SQLITE3_TEXT);+ $insert->bindValue(':description', $rec['description'] ?? '', SQLITE3_TEXT);+ $insert->bindValue(':savings', $rec['savings'] ?? '', SQLITE3_TEXT);+ $insert->execute();+ }++ // Update last_successful_run+ $updateStmt = $db->prepare("UPDATE ai_settings SET last_successful_run = CURRENT_TIMESTAMP WHERE user_id = ?");+ $updateStmt->bindValue(1, $tempUserId, SQLITE3_INTEGER);+ $updateStmt->execute();++ $successes++;+}++echo json_encode([+ "success" => true,+ "run_type" => $runType,+ "processed" => $processed,+ "successes" => $successes,+ "failures" => $failures,+]);diff --git a/endpoints/cronjobs/sendcancellationnotifications.php b/endpoints/cronjobs/sendcancellationnotifications.phpindex 27de8fd..01d25c6 100644--- a/endpoints/cronjobs/sendcancellationnotifications.php+++ b/endpoints/cronjobs/sendcancellationnotifications.php@@ -320,13 +320,14 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);$response = curl_exec($ch);- curl_close($ch);-+if ($response === false) {echo "Error sending notifications: " . curl_error($ch) . "<br />";} else {echo "Discord Notifications sent<br />";}++ unset($ch);}}}@@ -468,13 +469,13 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {$result = curl_exec($ch);- curl_close($ch);-if ($result === false) {echo "Error sending notifications: " . curl_error($ch) . "<br />";} else {echo "Pushover Notifications sent<br />";}++ unset($ch);}}@@ -523,13 +524,14 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {}$response = curl_exec($ch);- curl_close($ch);-+if ($response === false) {echo "Error sending notifications: " . curl_error($ch) . "<br />";} else {echo "Ntfy Notifications sent<br />";}++ unset($ch);}}}@@ -586,13 +588,14 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {// Execute the cURL request$response = curl_exec($ch);$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);- curl_close($ch);if ($response === false || $httpCode >= 400) {echo "Error sending cancellation notifications: " . curl_error($ch) . "<br />";} else {echo "Webhook Cancellation Notification sent for subscription: " . $subscription['name'] . "<br />";}++ unset($ch);usleep(1000000); // 1s delay between requests}diff --git a/endpoints/cronjobs/sendnotifications.php b/endpoints/cronjobs/sendnotifications.phpindex 0614eb2..c26450f 100644--- a/endpoints/cronjobs/sendnotifications.php+++ b/endpoints/cronjobs/sendnotifications.php@@ -424,13 +424,14 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);$response = curl_exec($ch);- curl_close($ch);if ($result === false) {echo "Error sending notifications: " . curl_error($ch) . "<br />";} else {echo "Discord Notifications sent<br />";}++ unset($ch);}}}@@ -602,7 +603,7 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {echo "PushPlus API error: " . $errorMsg . "<br />";}}- curl_close($ch);+ unset($ch);}}@@ -669,7 +670,7 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {echo "Mattermost API error: " . $errorMsg . "<br />";}}- curl_close($ch);+ unset($ch);}}}@@ -706,13 +707,13 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {$result = curl_exec($ch);- curl_close($ch);-if ($result === false) {echo "Error sending notifications: " . curl_error($ch) . "<br />";} else {echo "Pushover Notifications sent<br />";}++ unset($ch);}}@@ -766,13 +767,14 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {}$response = curl_exec($ch);- curl_close($ch);if ($response === false) {echo "Error sending notifications: " . curl_error($ch) . "<br />";} else {echo "Ntfy Notifications sent<br />";}++ unset($ch);}}}@@ -831,13 +833,14 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {// Execute the cURL request$response = curl_exec($ch);$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);- curl_close($ch);if ($response === false || $httpCode >= 400) {echo "Error sending notifications: " . curl_error($ch) . "<br />";} else {echo "Webhook Notification sent for subscription: " . $subscription['name'] . "<br />";}++ unset($ch);usleep(1000000); // 1s delay between requests}@@ -892,10 +895,10 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {if ($response === false || $httpCode >= 400) {$errorMessage = $response === false ? curl_error($ch) : $httpCode;- curl_close($ch);+ unset($ch);echo "Error sending Serverchan notifications: " . $errorMessage . "<br />";} else {- curl_close($ch);+ unset($ch);echo "Serverchan Notifications sent<br />";}}diff --git a/endpoints/logos/search.php b/endpoints/logos/search.phpindex a966f5d..1a1ae08 100644--- a/endpoints/logos/search.php+++ b/endpoints/logos/search.php@@ -33,7 +33,7 @@ if (isset($_GET['search'])) {if (!empty($headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);applyProxy($ch);$response = curl_exec($ch);- curl_close($ch);+ unset($ch);return $response ?: null;}diff --git a/endpoints/notifications/testdiscordnotifications.php b/endpoints/notifications/testdiscordnotifications.phpindex f4ac12b..b0905f4 100644--- a/endpoints/notifications/testdiscordnotifications.php+++ b/endpoints/notifications/testdiscordnotifications.php@@ -76,7 +76,7 @@ if ($response = curl_exec($ch);// Close the cURL session- curl_close($ch);+ unset($ch);// Check if the message was sent successfullyif ($response === false) {diff --git a/endpoints/notifications/testgotifynotifications.php b/endpoints/notifications/testgotifynotifications.phpindex e3d05a8..c745328 100644--- a/endpoints/notifications/testgotifynotifications.php+++ b/endpoints/notifications/testgotifynotifications.php@@ -65,7 +65,7 @@ if ($httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);// Close the cURL session- curl_close($ch);+ unset($ch);// Check if the message was sent successfullyif ($response === false || $httpCode < 200 || $httpCode >= 300) {diff --git a/endpoints/notifications/testmattermostnotifications.php b/endpoints/notifications/testmattermostnotifications.phpindex 63a99cb..5527024 100755--- a/endpoints/notifications/testmattermostnotifications.php+++ b/endpoints/notifications/testmattermostnotifications.php@@ -70,7 +70,7 @@ if ($response = curl_exec($ch);// Close the cURL session- curl_close($ch);+ unset($ch);// Check if the message was sent successfullyif ($response === false) {diff --git a/endpoints/notifications/testntfynotifications.php b/endpoints/notifications/testntfynotifications.phpindex 97b1bfd..77ce582 100644--- a/endpoints/notifications/testntfynotifications.php+++ b/endpoints/notifications/testntfynotifications.php@@ -68,7 +68,7 @@ if ($response = curl_exec($ch);// Close the cURL session- curl_close($ch);+ unset($ch);// Check if the message was sent successfullyif ($response === false) {diff --git a/endpoints/notifications/testpushovernotifications.php b/endpoints/notifications/testpushovernotifications.phpindex 3bdaeb9..714edc9 100644--- a/endpoints/notifications/testpushovernotifications.php+++ b/endpoints/notifications/testpushovernotifications.php@@ -38,7 +38,7 @@ if ($response = curl_exec($ch);// Close the cURL session- curl_close($ch);+ unset($ch);// Check if the message was sent successfullyif ($response === false) {diff --git a/endpoints/notifications/testpushplusnotifications.php b/endpoints/notifications/testpushplusnotifications.phpindex 653e641..110649c 100644--- a/endpoints/notifications/testpushplusnotifications.php+++ b/endpoints/notifications/testpushplusnotifications.php@@ -45,7 +45,7 @@ if (!isset($data["token"]) || $data["token"] == "") {$curlError = curl_error($ch);// Close the cURL session- curl_close($ch);+ unset($ch);// Check if the message was sent successfullyif ($response === false) {diff --git a/endpoints/notifications/testtelegramnotifications.php b/endpoints/notifications/testtelegramnotifications.phpindex 4e594db..29460a8 100644--- a/endpoints/notifications/testtelegramnotifications.php+++ b/endpoints/notifications/testtelegramnotifications.php@@ -37,7 +37,7 @@ if ($response = curl_exec($ch);// Close the cURL session- curl_close($ch);+ unset($ch);// Check if the message was sent successfullyif ($response === false) {diff --git a/endpoints/notifications/testwebhooknotifications.php b/endpoints/notifications/testwebhooknotifications.phpindex 14b9eed..c1ab1c2 100644--- a/endpoints/notifications/testwebhooknotifications.php+++ b/endpoints/notifications/testwebhooknotifications.php@@ -81,16 +81,17 @@ if (// Execute the request$response = curl_exec($ch);$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);+ $curlError = curl_error($ch);// Close the cURL session- curl_close($ch);+ unset($ch);// Check if the message was sent successfullyif ($response === false || $httpCode >= 400) {die(json_encode(["success" => false,"message" => translate('notification_failed', $i18n),- "response" => curl_error($ch)+ "response" => $curlError ? $curlError : $response]));} else {die(json_encode([diff --git a/endpoints/payments/add.php b/endpoints/payments/add.phpindex c9fe488..36ab5c6 100644--- a/endpoints/payments/add.php+++ b/endpoints/payments/add.php@@ -61,15 +61,16 @@ function getLogoFromUrl($url, $uploadDir, $name, $i18n, $settings)$uploadFile = $uploadDir . $fileName;if (saveLogo($imageData, $uploadFile, $name, $settings)) {- curl_close($ch);+ unset($ch);return $fileName;} else {- curl_close($ch);echo translate('error_fetching_image', $i18n) . ": " . curl_error($ch);+ unset($ch);return "";}} else {echo translate('error_fetching_image', $i18n) . ": " . curl_error($ch);+ unset($ch);return "";}}diff --git a/endpoints/payments/search.php b/endpoints/payments/search.phpindex ff68846..7d82438 100644--- a/endpoints/payments/search.php+++ b/endpoints/payments/search.php@@ -33,7 +33,7 @@ if (isset($_GET['search'])) {applyProxy($ch);$response = curl_exec($ch);- curl_close($ch);+ unset($ch);return $response ?: null;}diff --git a/endpoints/subscription/add.php b/endpoints/subscription/add.phpindex 800d184..e4fc603 100644--- a/endpoints/subscription/add.php+++ b/endpoints/subscription/add.php@@ -54,7 +54,7 @@ function getLogoFromUrl($url, $uploadDir, $name, $settings, $i18n)if ($httpCode >= 300 && $httpCode < 400) {$redirectUrl = curl_getinfo($ch, CURLINFO_REDIRECT_URL);- curl_close($ch);+ unset($ch);if (!$redirectUrl) {break;@@ -70,13 +70,13 @@ function getLogoFromUrl($url, $uploadDir, $name, $settings, $i18n)$uploadFile = '../../images/uploads/logos/' . $fileName;if (saveLogo($imageData, $uploadFile, $name, $settings)) {- curl_close($ch);+ unset($ch);return ['success' => true, 'filename' => $fileName];}}$error = curl_error($ch);- curl_close($ch);+ unset($ch);return ['success' => false, 'message' => translate('error_fetching_image', $i18n) . ': ' . $error];}diff --git a/includes/oidc/handle_oidc_callback.php b/includes/oidc/handle_oidc_callback.phpindex c22fb3d..4811148 100644--- a/includes/oidc/handle_oidc_callback.php+++ b/includes/oidc/handle_oidc_callback.php@@ -32,7 +32,7 @@ curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);$response = curl_exec($ch);-curl_close($ch);+unset($ch);$tokenData = json_decode($response, true);if (!$tokenData || !isset($tokenData['access_token'])) {@@ -47,7 +47,7 @@ curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $tokenData['access_token']]);$response = curl_exec($ch);-curl_close($ch);+unset($ch);$userInfo = json_decode($response, true);if (!$userInfo || !isset($userInfo[$oidcSettings['user_identifier_field']])) {diff --git a/includes/version.php b/includes/version.phpindex fea4171..d00d351 100644--- a/includes/version.php+++ b/includes/version.php@@ -1,3 +1,3 @@<?php-$version = "v4.7.3";+$version = "v4.8.0";?>\ No newline at end of filediff --git a/index.php b/index.phpindex 1eb2d82..43d643a 100644--- a/index.php+++ b/index.php@@ -93,6 +93,32 @@ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {?><section class="contain dashboard">+ <?php+ if ($isAdmin && $settings['update_notification']) {+ if (!is_null($settings['latest_version'])) {+ $latestVersion = $settings['latest_version'];+ if (version_compare($version, $latestVersion) == -1) {+ ?>+ <div class="update-banner">+ <?= translate('new_version_available', $i18n) ?>:+ <span><a href="https://github.com/ellite/Wallos/releases/tag/<?= htmlspecialchars($latestVersion) ?>"+ target="_blank" rel="noreferer">+ <?= htmlspecialchars($latestVersion) ?>+ </a></span>+ </div>+ <?php+ }+ }+ }+ if ($demoMode) {+ ?>+ <div class="demo-banner">+ Running in <b>Demo Mode</b>, certain actions and settings are disabled.<br>+ The database will be reset every 120 minutes.+ </div>+ <?php+ }+ ?><h1><?= translate('hello', $i18n) ?> <?= htmlspecialchars($first_name) ?></h1><?phpdiff --git a/scripts/settings.js b/scripts/settings.jsindex 9beab1e..ad5307d 100644--- a/scripts/settings.js+++ b/scripts/settings.js@@ -1081,34 +1081,39 @@ function fetch_ai_models() {}function toggleAiInputs() {- const aiTypeSelect = document.getElementById("ai_type");+ const type = document.getElementById("ai_type").value;const apiKeyInput = document.getElementById("ai_api_key");const apiKeyToggleButton = document.getElementById("toggleAiApiKey");- const apiKeyToggleIcon = apiKeyToggleButton ? apiKeyToggleButton.querySelector("i") : null;- const ollamaHostInput = document.getElementById("ai_ollama_host");- const type = aiTypeSelect.value;+ const apiKeyToggleIcon = apiKeyToggleButton?.querySelector("i");+ const urlGroup = document.getElementById("ai_url_group");+ const urlInput = document.getElementById("ai_ollama_host");+ const testButtonUrl = document.getElementById("fetchModelsButton2");+ const testButtonKey = document.getElementById("fetchModelsButton");++ // Reset key visibility+ apiKeyInput.type = "password";+ apiKeyToggleIcon?.classList.replace("fa-eye-slash", "fa-eye");+if (type === "ollama") {apiKeyInput.classList.add("hidden");- if (apiKeyToggleButton) {- apiKeyToggleButton.classList.add("hidden");- }- apiKeyInput.type = "password";- if (apiKeyToggleIcon) {- apiKeyToggleIcon.classList.remove("fa-eye-slash");- apiKeyToggleIcon.classList.add("fa-eye");- }- ollamaHostInput.classList.remove("hidden");+ apiKeyToggleButton?.classList.add("hidden");+ testButtonKey.classList.add("hidden"); // hide key-row Test+ urlGroup.style.display = "";+ urlInput.placeholder = "http://localhost:11434";+ testButtonUrl.classList.remove("hidden"); // show url-row Test+ } else if (type === "openai-compatible") {+ apiKeyInput.classList.remove("hidden");+ apiKeyToggleButton?.classList.remove("hidden");+ testButtonKey.classList.remove("hidden"); // show key-row Test+ urlGroup.style.display = "";+ urlInput.placeholder = "http://localhost:11434/v1";+ testButtonUrl.classList.add("hidden"); // hide url-row Test} else {apiKeyInput.classList.remove("hidden");- if (apiKeyToggleButton) {- apiKeyToggleButton.classList.remove("hidden");- }- apiKeyInput.type = "password";- if (apiKeyToggleIcon) {- apiKeyToggleIcon.classList.remove("fa-eye-slash");- apiKeyToggleIcon.classList.add("fa-eye");- }- ollamaHostInput.classList.add("hidden");+ apiKeyToggleButton?.classList.remove("hidden");+ testButtonKey.classList.remove("hidden"); // show key-row Test+ urlGroup.style.display = "none";+ testButtonUrl.classList.add("hidden"); // hidden anyway (group hidden)}}@@ -1135,6 +1140,7 @@ function saveAiSettingsButton() {const aiApiKey = document.querySelector("#ai_api_key").value.trim();const aiOllamaHost = document.querySelector("#ai_ollama_host").value.trim();const aiModel = document.querySelector("#ai_model").value;+ const aiRunSchedule = document.querySelector("#ai_run_schedule").value;fetch('endpoints/ai/save_settings.php', {method: 'POST',@@ -1142,7 +1148,7 @@ function saveAiSettingsButton() {'Content-Type': 'application/json','X-CSRF-Token': window.csrfToken,},- body: JSON.stringify({ ai_enabled: aiEnabled, ai_type: aiType, api_key: aiApiKey, ollama_host: aiOllamaHost, model: aiModel })+ body: JSON.stringify({ ai_enabled: aiEnabled, ai_type: aiType, api_key: aiApiKey, ollama_host: aiOllamaHost, model: aiModel, ai_run_schedule: aiRunSchedule })}).then(response => response.json()).then(data => {diff --git a/settings.php b/settings.phpindex b28054c..4c001ff 100644--- a/settings.php+++ b/settings.php@@ -1090,17 +1090,25 @@ $userData['currency_symbol'] = $currencies[$main_currency]['symbol'];<option value="gemini" <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'gemini') ? 'selected' : '' ?>>Gemini</option><option value="openrouter" <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'openrouter') ? 'selected' : '' ?>>OpenRouter</option><option value="ollama" <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'ollama') ? 'selected' : '' ?>>Local Ollama</option>+ <option value="openai-compatible" <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'openai-compatible') ? 'selected' : '' ?>>OpenAI Compatible</option></select></div>+ <div class="form-group-inline" id="ai_url_group"+ <?= (!isset($aiSettings['type']) || !in_array($aiSettings['type'], ['ollama', 'openai-compatible'])) ? 'style="display:none"' : '' ?>>+ <input type="text" id="ai_ollama_host" name="ai_ollama_host" autocomplete="off"+ placeholder="<?= (isset($aiSettings['type']) && $aiSettings['type'] == 'openai-compatible') ? 'http://localhost:11434/v1' : 'http://localhost:11434' ?>"+ value="<?= isset($aiSettings['url']) ? htmlspecialchars($aiSettings['url']) : '' ?>" />+ <button type="button" id="fetchModelsButton2"+ class="button thin <?= (!isset($aiSettings['type']) || $aiSettings['type'] != 'ollama') ? 'hidden' : '' ?>"+ onclick="fetch_ai_models()">+ <?= translate('test', $i18n) ?>+ </button>+ </div><div class="form-group-inline"><input type="password" id="ai_api_key" name="ai_api_key" autocomplete="off"class="<?= (isset($aiSettings['type']) && $aiSettings['type'] == 'ollama') ? 'hidden' : '' ?>"placeholder="<?= translate('api_key', $i18n) ?>"value="<?= isset($aiSettings['api_key']) ? htmlspecialchars($aiSettings['api_key']) : '' ?>" />- <input type="text" id="ai_ollama_host" name="ai_ollama_host" autocomplete="off"- class="<?= (!isset($aiSettings['type']) || $aiSettings['type'] != 'ollama') ? 'hidden' : '' ?>"- placeholder="<?= translate('host', $i18n) ?>"- value="<?= isset($aiSettings['url']) ? htmlspecialchars($aiSettings['url']) : '' ?>" /><button type="button" id="toggleAiApiKey" class="button secondary-button icon-button <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'ollama') ? 'hidden' : '' ?>" onclick="toggleAiApiKeyVisibility()" aria-label="Toggle API key visibility"><i class="fa-solid fa-eye"></i></button>@@ -1120,9 +1128,8 @@ $userData['currency_symbol'] = $currencies[$main_currency]['symbol'];</select></div><div class="form-group">- <label for="ai_run_schedule" class="flex"><?= translate('run_schedule', $i18n) ?>: <span- class="info-badge"><?= translate("coming_soon", $i18n) ?></span></span></label>- <select id="ai_run_schedule" name="ai_run_schedule" disabled>+ <label for="ai_run_schedule" class="flex"><?= translate('run_schedule', $i18n) ?>:</label>+ <select id="ai_run_schedule" name="ai_run_schedule"><option value="manual" <?= (isset($aiSettings['run_schedule']) && $aiSettings['run_schedule'] == 'manual') ? 'selected' : '' ?>><?= translate('manually', $i18n) ?></option><option value="weekly" <?= (isset($aiSettings['run_schedule']) && $aiSettings['run_schedule'] == 'weekly') ? 'selected' : '' ?>><?= translate('Weekly', $i18n) ?>diff --git a/subscriptions.php b/subscriptions.phpindex ff76f97..88c6d69 100644--- a/subscriptions.php+++ b/subscriptions.php@@ -154,34 +154,6 @@ $headerClass = count($subscriptions) > 0 ? "main-actions" : "main-actions hidden</style><section class="contain">- <?php- if ($isAdmin && $settings['update_notification']) {- if (!is_null($settings['latest_version'])) {- $latestVersion = $settings['latest_version'];- if (version_compare($version, $latestVersion) == -1) {- ?>- <div class="update-banner">- <?= translate('new_version_available', $i18n) ?>:- <span><a href="https://github.com/ellite/Wallos/releases/tag/<?= htmlspecialchars($latestVersion) ?>"- target="_blank" rel="noreferer">- <?= htmlspecialchars($latestVersion) ?>- </a></span>- </div>- <?php- }- }- }-- if ($demoMode) {- ?>- <div class="demo-banner">- Running in <b>Demo Mode</b>, certain actions and settings are disabled.<br>- The database will be reset every 120 minutes.- </div>- <?php- }- ?>-<header class="<?= $headerClass ?>" id="main-actions"><button class="button" onClick="addSubscription()"><i class="fa-solid fa-circle-plus"></i>