-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.example.php
More file actions
359 lines (308 loc) · 11.9 KB
/
config.example.php
File metadata and controls
359 lines (308 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
<?php
/**
* OpenDonate - Konfiguracja
*
* Skopiuj ten plik jako `config.php` i uzupełnij dane.
* Plik `config.php` jest w .gitignore — nigdy nie commituj go z prawdziwymi hasłami!
*
* Copy this file to `config.php` and fill in your credentials.
* The `config.php` file is in .gitignore — never commit it with real passwords!
*/
// === BAZA DANYCH / DATABASE ===
define('DB_HOST', 'localhost');
define('DB_NAME', 'opendonate'); // <-- nazwa Twojej bazy danych
define('DB_USER', 'opendonate_user'); // <-- użytkownik MySQL
define('DB_PASS', 'CHANGE_THIS_PASSWORD'); // <-- HASŁO MySQL — ZMIEŃ!
define('DB_CHARSET', 'utf8mb4');
// === ADRES URL APLIKACJI / APP URL ===
// Pełny URL do katalogu w którym znajduje się projekt, BEZ slasha na końcu
// Full URL to the directory where the project is hosted, WITHOUT trailing slash
define('BASE_URL', 'https://twoja-domena.pl/donate');
// === USTAWIENIA SESJI / SESSION SETTINGS ===
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// === POŁĄCZENIE Z BAZĄ / DB CONNECTION ===
try {
$pdo = new PDO(
"mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
DB_USER,
DB_PASS,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
]
);
} catch (PDOException $e) {
die('Database connection error: ' . $e->getMessage());
}
// === FUNKCJE POMOCNICZE / HELPER FUNCTIONS ===
function getSetting($key, $default = '') {
global $pdo;
try {
$stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
$stmt->execute([$key]);
$result = $stmt->fetch();
return $result ? $result['setting_value'] : $default;
} catch (Exception $e) {
error_log("getSetting error: " . $e->getMessage());
return $default;
}
}
function setSetting($key, $value, $type = 'text') {
global $pdo;
try {
$stmt = $pdo->prepare("
INSERT INTO settings (setting_key, setting_value, setting_type)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE setting_value = ?, setting_type = ?
");
return $stmt->execute([$key, $value, $type, $value, $type]);
} catch (Exception $e) {
error_log("setSetting error: " . $e->getMessage());
return false;
}
}
function checkAuth() {
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
return false;
}
return true;
}
// === STRIPE FUNCTIONS ===
function getStripeConfig() {
return [
'secret_key' => getSetting('stripe_secret_key'),
'publishable_key' => getSetting('stripe_publishable_key'),
'webhook_secret' => getSetting('stripe_webhook_secret'),
'api_url' => 'https://api.stripe.com/v1'
];
}
function stripeRequest($endpoint, $data = [], $method = 'POST') {
$config = getStripeConfig();
$secretKey = $config['secret_key'];
if (empty($secretKey)) {
throw new Exception('Stripe Secret Key nie jest skonfigurowany');
}
$url = $config['api_url'] . '/' . $endpoint;
// Funkcja do flatten array dla Stripe (np. line_items[0][price_data][currency]=pln)
function flattenArray($array, $prefix = '') {
$result = [];
foreach ($array as $key => $value) {
$newKey = $prefix === '' ? $key : $prefix . '[' . $key . ']';
if (is_array($value)) {
$result = array_merge($result, flattenArray($value, $newKey));
} else {
$result[$newKey] = $value;
}
}
return $result;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $secretKey . ':');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded'
]);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
$flatData = flattenArray($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($flatData));
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new Exception('CURL Error: ' . $error);
}
$result = json_decode($response, true);
if ($httpCode !== 200 && $httpCode !== 201) {
$errorMsg = $result['error']['message'] ?? 'Unknown Stripe error';
throw new Exception('Stripe API Error (' . $httpCode . '): ' . $errorMsg);
}
return $result;
}
function createStripeCheckoutSession($donorName, $email, $amount, $controlId, $donationId) {
$successUrl = BASE_URL . '/thank_you.php?donation_id=' . $donationId . '&session_id={CHECKOUT_SESSION_ID}';
$cancelUrl = BASE_URL . '/index.php';
$data = [
'mode' => 'payment',
'success_url' => $successUrl,
'cancel_url' => $cancelUrl,
'payment_method_types' => ['card', 'blik', 'revolut_pay', 'klarna'],
'line_items' => [
[
'price_data' => [
'currency' => 'pln',
'product_data' => [
'name' => 'Donate od ' . $donorName,
],
'unit_amount' => (int)($amount * 100), // Stripe używa groszy
],
'quantity' => 1,
],
],
'metadata' => [
'control_id' => $controlId,
'donation_id' => $donationId,
'donor_name' => $donorName,
],
'customer_email' => $email,
];
return stripeRequest('checkout/sessions', $data);
}
function verifyStripeWebhook($payload, $signature) {
$config = getStripeConfig();
$webhookSecret = $config['webhook_secret'];
if (empty($webhookSecret)) {
throw new Exception('Stripe Webhook Secret nie jest skonfigurowany');
}
// Rozparsuj sygnaturę
$elements = explode(',', $signature);
$signatureData = [];
foreach ($elements as $element) {
list($key, $value) = explode('=', $element, 2);
if ($key === 't') {
$signatureData['timestamp'] = $value;
} elseif ($key === 'v1') {
$signatureData['signature'] = $value;
}
}
if (empty($signatureData['timestamp']) || empty($signatureData['signature'])) {
throw new Exception('Invalid signature format');
}
// Zbuduj signed payload
$signedPayload = $signatureData['timestamp'] . '.' . $payload;
// Oblicz oczekiwaną sygnaturę
$expectedSignature = hash_hmac('sha256', $signedPayload, $webhookSecret);
// Sprawdź czy sygnatury się zgadzają
if (!hash_equals($expectedSignature, $signatureData['signature'])) {
throw new Exception('Invalid signature');
}
// Sprawdź timestamp (ochrona przed replay attacks)
$tolerance = 300; // 5 minut
if (abs(time() - $signatureData['timestamp']) > $tolerance) {
throw new Exception('Timestamp too old');
}
return true;
}
// === FILTROWANIE WIADOMOŚCI / MESSAGE FILTERING ===
function filterMessage($message, $filterUrls = true, $filterSpecialChars = true, $filterWordRepeat = true) {
// URL
if ($filterUrls) {
$message = preg_replace('#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', '[link]', $message);
$message = preg_replace('/www\.[^\s]+/i', '[link]', $message);
}
// Znaki specjalne i emotikony
if ($filterSpecialChars) {
$message = preg_replace('/[\x{1F600}-\x{1F64F}]/u', '', $message); // Emotikony
$message = preg_replace('/[\x{2600}-\x{26FF}]/u', '', $message); // Symbole
$message = preg_replace('/[\x{2700}-\x{27BF}]/u', '', $message); // Dingbats
$message = preg_replace('/[\x{1F300}-\x{1F5FF}]/u', '', $message); // Symbole i piktogramy
$message = preg_replace('/[\x{1F680}-\x{1F6FF}]/u', '', $message); // Transport i symbole
$message = preg_replace('/[☢☣☠]/u', '', $message); // Konkretne znaki
}
// Powtórzenia wyrazów
if ($filterWordRepeat) {
$message = preg_replace('/\b(\w+)(\s+\1\b)+/i', '$1', $message);
}
return trim($message);
}
// === ODLICZNIK DO KOŃCA TRANSMISJI / STREAM COUNTDOWN ===
/**
* Oblicza ile sekund odlicznika dodać za daną kwotę donate'u.
* Uwzględnia konfigurację: PLN per unit, sekundy per unit, min amount.
*
* @param float $amount Kwota donate'u w PLN
* @param bool $checkMin Czy sprawdzać minimum (true dla automatycznego, false dla ręcznego)
* @return int Sekundy do dodania (0 jeśli odlicznik wyłączony / kwota poniżej min)
*/
function calculateCountdownSecondsForAmount($amount, $checkMin = true) {
$enabled = getSetting('countdown_enabled', '0') === '1';
if (!$enabled) return 0;
$minAmount = floatval(getSetting('countdown_min_amount', '0'));
if ($checkMin && $amount < $minAmount) return 0;
$plnPerUnit = floatval(getSetting('countdown_pln_per_unit', '1.00'));
$secondsPerUnit = floatval(getSetting('countdown_seconds_per_unit', '60'));
if ($plnPerUnit <= 0 || $secondsPerUnit <= 0) return 0;
// np. 1 PLN = 60s, donat 5 PLN = 300s
$secondsToAdd = ($amount / $plnPerUnit) * $secondsPerUnit;
return (int)round($secondsToAdd);
}
/**
* Dodaje X sekund do odlicznika. Działa zarówno gdy odlicznik leci, jak i gdy zatrzymany.
* Jeśli leci — przesuwa end_timestamp. Jeśli stoi — zwiększa remaining_seconds.
*
* @param int $seconds Sekundy do dodania
* @return bool Czy się udało
*/
function addTimeToCountdown($seconds) {
if ($seconds <= 0) return false;
$running = getSetting('countdown_running', '0') === '1';
if ($running) {
$endTs = intval(getSetting('countdown_end_timestamp', '0'));
// Jeśli end już minął — zresetuj running
if ($endTs <= time()) {
setSetting('countdown_running', '0', 'boolean');
setSetting('countdown_remaining_seconds', (string)$seconds, 'number');
return true;
}
$endTs += $seconds;
setSetting('countdown_end_timestamp', (string)$endTs, 'number');
setSetting('countdown_remaining_seconds', (string)max(0, $endTs - time()), 'number');
} else {
$current = intval(getSetting('countdown_remaining_seconds', '0'));
$newRemaining = $current + $seconds;
setSetting('countdown_remaining_seconds', (string)$newRemaining, 'number');
}
return true;
}
/**
* Auto-dolicz czas po opłaconym donate (wywoływane z notification_handler).
*
* @param float $amount Kwota brutto donate'u
* @return int Sekundy dodane (0 jeśli warunki nie spełnione)
*/
function addTimeToCountdownFromDonation($amount) {
$seconds = calculateCountdownSecondsForAmount($amount, true);
if ($seconds > 0) {
addTimeToCountdown($seconds);
}
return $seconds;
}
// === CZYSZCZENIE STARYCH WIADOMOŚCI GŁOSOWYCH / VOICE CLEANUP ===
function cleanOldVoiceMessages() {
global $pdo;
$days = intval(getSetting('voice_message_auto_delete_days', 60));
try {
$stmt = $pdo->prepare("
SELECT file_path FROM voice_messages
WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)
AND is_deleted = 0
");
$stmt->execute([$days]);
$oldFiles = $stmt->fetchAll();
foreach ($oldFiles as $file) {
$fullPath = __DIR__ . '/' . $file['file_path'];
if (file_exists($fullPath)) {
unlink($fullPath);
}
}
$stmt = $pdo->prepare("
UPDATE voice_messages
SET is_deleted = 1
WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)
");
$stmt->execute([$days]);
return true;
} catch (Exception $e) {
error_log("cleanOldVoiceMessages error: " . $e->getMessage());
return false;
}
}
?>