Subversion Repositories SvarDOS

Rev

Rev 1233 | Rev 1645 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1223 mateusz.vi 1
<?php
2
//
1242 mateusz.vi 3
// mateuszbb - minimalist bulletin board forum. MIT license.
4
//
5
// VERSION 20230523
6
//
1223 mateusz.vi 7
// Copyright (C) 2021-2023 Mateusz Viste
8
//
1242 mateusz.vi 9
// Permission is hereby granted, free of charge, to any person obtaining a copy
10
// of this software and associated documentation files (the “Software”), to
11
// deal in the Software without restriction, including without limitation the
12
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
13
// sell copies of the Software, and to permit persons to whom the Software is
14
// furnished to do so, subject to the following conditions:
15
//
16
//The above copyright notice and this permission notice shall be included in
17
// all copies or substantial portions of the Software.
18
//
19
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
25
// IN THE SOFTWARE.
1223 mateusz.vi 26
 
27
global $TRIP_SALT;
28
global $INITYEAR;
29
global $DATADIR;
30
global $NICE_URLS;
31
global $STR;
32
global $LANG;
1242 mateusz.vi 33
global $TZ;
34
global $DATE_FORMAT;
35
global $MAINPAGE_MAXTHREADS;
36
global $MAINPAGE_MAXINACT;
37
global $LOCK_DELAY;
38
global $EDIT_ALLOWED_MINUTES;
39
global $MAXDAILYPOSTS;
1223 mateusz.vi 40
 
41
include 'mateuszbb-config.php';
42
 
43
 
44
// *** TRANSLATION STRINGS *****************************************
45
 
46
$STR = array();
47
$STR['en']['opnewthread'] = 'open a new thread';
48
$STR['en']['newthread']   = 'New thread';
49
$STR['en']['latestentry'] = 'latest entry:';
50
$STR['en']['searchterm']  = 'searched term:';
51
$STR['en']['noresults']   = 'No results';
52
$STR['en']['reply']       = 'reply';
53
$STR['en']['jumptoend']   = 'jump to end';
54
$STR['en']['listthreads'] = 'list of threads';
55
$STR['en']['author']      = 'author:';
56
$STR['en']['address']     = 'address:';
57
$STR['en']['date']        = 'date:';
58
$STR['en']['nameornick']  = 'your name or nick';
59
$STR['en']['threadsubj']  = 'subject';
60
$STR['en']['yourmsg']     = 'Your message';
61
$STR['en']['cancel']      = 'cancel';
62
$STR['en']['send']        = 'send';
63
$STR['en']['archives']    = 'archives';
64
$STR['en']['backtocur']   = 'go back to current threads';
65
$STR['en']['search']      = 'search';
66
$STR['en']['password']    = 'password';
67
$STR['en']['optional']    = 'optional';
68
$STR['en']['passhelp']    = 'Providing a password here will generate a unique digital signature on your message.';
1242 mateusz.vi 69
$STR['en']['locked']      = "Thread locked due to inactivity since over {$LOCK_DELAY} days.";
1223 mateusz.vi 70
$STR['en']['captcha'][1]  = 'check the FIRST box';
71
$STR['en']['captcha'][2]  = 'check the MIDDLE box';
72
$STR['en']['captcha'][3]  = 'check the LAST box';
73
$STR['en']['captcha'][4]  = 'check the FIRST and LAST boxes';
74
$STR['en']['captcha'][5]  = 'check the TWO LAST boxes';
75
 
1230 mateusz.vi 76
// PL translations by Mateusz Viste
1223 mateusz.vi 77
$STR['pl']['opnewthread'] = 'stwórz nowy wątek';
78
$STR['pl']['newthread']   = 'Nowy wątek';
79
$STR['pl']['latestentry'] = 'ostatni wpis:';
80
$STR['pl']['searchterm']  = 'szukane wyrażenie:';
81
$STR['pl']['noresults']   = 'Brak wyników';
82
$STR['pl']['reply']       = 'odpowiedz';
83
$STR['pl']['jumptoend']   = 'skocz do końca';
84
$STR['pl']['listthreads'] = 'lista wątków';
85
$STR['pl']['author']      = 'autor:';
86
$STR['pl']['address']     = 'adres:';
87
$STR['pl']['date']        = 'data:';
88
$STR['pl']['nameornick']  = 'imię, nazwisko lub pseudonim';
89
$STR['pl']['threadsubj']  = 'tytuł wątku';
90
$STR['pl']['yourmsg']     = 'Twoja wiadomość';
91
$STR['pl']['cancel']      = 'anuluj';
92
$STR['pl']['send']        = 'wyślij';
93
$STR['pl']['archives']    = 'archiwum';
94
$STR['pl']['backtocur']   = 'powrót do bieżących wątków';
95
$STR['pl']['search']      = 'szukaj';
96
$STR['pl']['password']    = 'hasło';
1242 mateusz.vi 97
$STR['pl']['optional']    = 'opcjonalne';
1223 mateusz.vi 98
$STR['pl']['passhelp']    = 'Podanie hasła pozwoli wygenerować unikalny podpis elektroniczny przy twojej wiadomości.';
1242 mateusz.vi 99
$STR['pl']['locked']      = "Wątek zamknięty z powodu braku aktywności od ponad {$LOCK_DELAY} dni.";
1223 mateusz.vi 100
$STR['pl']['captcha'][1]  = 'zaznacz PIERWSZE pole';
101
$STR['pl']['captcha'][2]  = 'zaznacz ŚRODKOWE pole';
102
$STR['pl']['captcha'][3]  = 'zaznacz OSTATNIE pole';
103
$STR['pl']['captcha'][4]  = 'zaznacz PIERWSZE i OSTATNIE pole';
104
$STR['pl']['captcha'][5]  = 'zaznacz DWA OSTATNIE pola';
105
 
1230 mateusz.vi 106
// pt-BR translations courtesty of Luzemário Dantas
107
$STR['pt']['opnewthread'] = 'abrir novo tópico';
108
$STR['pt']['newthread']   = 'Novo tópico';
109
$STR['pt']['latestentry'] = 'entrada mais recente:';
110
$STR['pt']['searchterm']  = 'termo pesquisado:';
111
$STR['pt']['noresults']   = 'Sem resultados';
112
$STR['pt']['reply']       = 'responder';
113
$STR['pt']['jumptoend']   = 'ir para o final';
114
$STR['pt']['listthreads'] = 'lista de tópicos';
115
$STR['pt']['author']      = 'autor:';
116
$STR['pt']['address']     = 'endereço:';
117
$STR['pt']['date']        = 'data:';
118
$STR['pt']['nameornick']  = 'seu nome ou apelido';
119
$STR['pt']['threadsubj']  = 'assunto';
120
$STR['pt']['yourmsg']     = 'Sua mensagem';
121
$STR['pt']['cancel']      = 'cancelar';
122
$STR['pt']['send']        = 'enviar';
123
$STR['pt']['archives']    = 'arquivos';
124
$STR['pt']['backtocur']   = 'voltar ao tópico atuai';
125
$STR['pt']['search']      = 'pesquisar';
126
$STR['pt']['password']    = 'senha';
127
$STR['pt']['optional']    = 'opcional';
128
$STR['pt']['passhelp']    = 'Fornecer uma senha aqui vai gerar uma assinatura digital única na sua mensagem.';
1242 mateusz.vi 129
$STR['pt']['locked']      = "Este tópico está bloqueado porque está inativo há mais de {$LOCK_DELAY} dias."; // translated by google translate, wording might be poor
1230 mateusz.vi 130
$STR['pt']['captcha'][1]  = 'marque a PRIMEIRA caixa';
131
$STR['pt']['captcha'][2]  = 'marque a caixa do MEIO';
132
$STR['pt']['captcha'][3]  = 'marque a ÚLTIMA caixa';
133
$STR['pt']['captcha'][4]  = 'marque a PRIMEIRA e ÚLTIMA caixas';
134
$STR['pt']['captcha'][5]  = 'marque as DUAS ÚLTIMAS caixas';
135
 
1223 mateusz.vi 136
// *****************************************************************
137
 
138
 
139
function data_dluga($timestamp) {
1242 mateusz.vi 140
  global $DATE_FORMAT;
141
  return(date($DATE_FORMAT, $timestamp));
1223 mateusz.vi 142
}
143
 
144
 
1231 mateusz.vi 145
function selfurl($params = '') {
146
  global $SELFURL;
147
  $r = $SELFURL;
148
  if (!empty($params)) {
149
    if (strrchr($SELFURL, '?')) {
150
      $r .= '&';
151
    } else {
152
      $r .= '?';
153
    }
154
    $r .= $params;
155
  }
156
  return($r);
157
}
158
 
159
 
1223 mateusz.vi 160
// returns an array with the list of languages requested by the browser, in
161
// the order of preference
162
function getpreflang() {
163
  $res = array();
164
  if (! isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) return($res);
165
  $langlist = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
166
  foreach ($langlist as $lang) {
167
    $res[] = strtolower(substr($lang, 0, 2));
168
  }
169
  return(array_unique($res));
170
}
171
 
172
 
173
function mateuszbb_rss() {
174
  global $DATADIR;
1229 mateusz.vi 175
  global $RSS_TITLE;
1242 mateusz.vi 176
  global $NICE_URLS;
1229 mateusz.vi 177
 
1223 mateusz.vi 178
  $db = new SQLite3($DATADIR . 'mateuszbb.sqlite3', SQLITE3_OPEN_READONLY);
179
  if (! $db) {
180
    echo "SQL ERROR: ACCESS DENIED\n";
181
    return false;
182
  }
183
  $sqlres = $db->query('SELECT thread, msgid, author FROM rss ORDER BY msgid DESC, thread DESC LIMIT 100;');
184
  if (! $sqlres) {
185
    echo "SQL ERROR: QUERY FAILED\n";
186
    return false;
187
  }
188
 
189
  header('content-type: application/rss+xml');
190
 
191
  echo '<?xml version="1.0" encoding="utf-8" ?>' . "\n";
192
  echo '<rss version="2.0">' . "\n";
193
  echo "<channel>\n";
1229 mateusz.vi 194
  echo "<title>" . htmlspecialchars($RSS_TITLE, ENT_XML1) . "</title>\n";
195
  echo "<link>" . selfurl(). "</link>\n";
1223 mateusz.vi 196
 
197
  while ($row = $sqlres->fetchArray()) {
198
    $rawtitle = file_get_contents($DATADIR . 'threads/' . $row['thread'] . '/title.txt');
199
    if (empty($rawtitle)) continue;
200
    $title = htmlspecialchars($rawtitle, ENT_XML1, 'UTF-8');
201
    $author = htmlspecialchars($row['author'], ENT_XML1, 'UTF-8');
1229 mateusz.vi 202
    if ($NICE_URLS) {
203
      $link = selfurl();
204
      if (substr($link, -1) !== '/') $link .= '/';
205
      $link .= "{$row['thread']}";
206
    } else {
207
      $link = selfurl('thread=' . $row['thread']);
208
    }
209
    $link .= '#' . $row['msgid'];
1223 mateusz.vi 210
    echo "<item>\n";
1229 mateusz.vi 211
    echo "<title>{$author} @ '{$title}'</title>\n";
212
    echo "<link>" . htmlspecialchars($link, ENT_XML1) . "</link>\n";
213
    echo "<description>{$author} @ '{$title}'</description>\n";
1223 mateusz.vi 214
    echo "<pubDate>" . date('r', $row['msgid']) . "</pubDate>\n";
1229 mateusz.vi 215
    echo "<guid>" . htmlspecialchars($link, ENT_XML1) . "</guid>\n";
1223 mateusz.vi 216
    echo "</item>\n";
217
  }
218
  $db->close();
219
 
220
  echo "</channel>\n";
221
  echo "</rss>\n";
222
  return true;
223
}
224
 
225
 
1242 mateusz.vi 226
function formularz($thread = 0, $postid = 0, $msg = '') {
1223 mateusz.vi 227
  global $STR;
228
  global $LANG;
1242 mateusz.vi 229
  global $NICE_URLS;
1223 mateusz.vi 230
 
1242 mateusz.vi 231
  if ($thread == 0) {
1223 mateusz.vi 232
    echo '<form class="minibb" method="POST" action="' . selfurl() . '#title" id="formularz">' . "\n";
233
    echo '<input type="hidden" name="action" value="createthread">' . "\n";
234
  } else {
235
    echo '<form class="minibb" method="POST" action="' . selfurl() . '" id="formularz">' . "\n";
236
    echo '<input type="hidden" name="thread" value="' . $thread . '">' . "\n";
1242 mateusz.vi 237
    if ($postid > 0) {
238
      echo '<input type="hidden" name="action" value="editpost">' . "\n";
239
      echo '<input type="hidden" name="postid" value="' . $postid . '">' . "\n";
240
    } else {
241
      echo '<input type="hidden" name="action" value="newpost">' . "\n";
242
    }
1223 mateusz.vi 243
  }
244
 
245
  echo '<div class="minibb-formfields">' . "\n";
1242 mateusz.vi 246
  echo '<div class="minibb-formlabelgroup"><p>' . $STR[$LANG]['nameornick'] . '</p><input type="text" name="username" pattern=".*[^\s].*" minlength="1" maxlength="40" autofill="username" title="' . $STR[$LANG]['nameornick'];
247
  if (!empty($msg)) echo '" value="' . htmlspecialchars($msg['author']) . '"';
248
  echo '" required></div><div class="minibb-formlabelgroup"><p>' . $STR[$LANG]['password'] . ' (<span title="' . $STR[$LANG]['passhelp'] . '" style="text-decoration-line: underline; text-decoration-style: dotted;">' . $STR[$LANG]['optional'] . '</span>)</p><input type="password" name="password" maxlength="40" autofill="current-password"></div>' . "\n";
249
  if ($thread == 0) {
1223 mateusz.vi 250
    echo '<div class="minibb-formlabelgroup" style="width: 100%;">' . "\n";
251
    echo "<p>" . $STR[$LANG]['threadsubj'] . "</p>\n";
252
    echo '<input type="text" name="title" title="' . $STR[$LANG]['threadsubj'] . '" maxlength="64" pattern=".*[^\s].*" required>' . "\n";
253
    echo "</div>\n";
254
  }
255
  echo '<textarea name="msg" placeholder="' . $STR[$LANG]['yourmsg'] . '">' . "\n";
1242 mateusz.vi 256
  if (!empty($msg)) echo htmlspecialchars($msg['msg']);
257
  echo "</textarea><br>\n";
258
  echo "</div>\n";
1223 mateusz.vi 259
  // --- CAPTCHA ---
260
  $capid = rand(1, 5);
1242 mateusz.vi 261
  echo '<div class="minibb-formcaptcha">' . $STR[$LANG]['captcha'][$capid] . ': <span class="minibb-cboxgroup"><input type="checkbox" name=c1><input type="checkbox" name=c2><input type="checkbox" name=c3></span>' . "\n";
1223 mateusz.vi 262
  echo '<input type="hidden" name="capid" value="' . $capid . '">';
263
  // ---------------
1242 mateusz.vi 264
  echo '<div class="minibb-formbtns">' . "\n";
265
  $link = selfurl();
266
  if ($postid > 0) {
267
    $link = selfurl("thread=" . $thread);
268
    if ($NICE_URLS) $link = $thread;
269
    $link .= '#' . $postid;
270
  }
271
  echo '<a href="' . $link . '">' . $STR[$LANG]['cancel'] . '</a> <input type="submit" value="' . $STR[$LANG]['send'] . '">' . "\n";
272
  echo "</div>\n";
273
  echo "</div>\n";
1223 mateusz.vi 274
  echo '</form>';
275
}
276
 
277
function wyswietl_watek_w_liscie($threadid, $tytul, $lastauthor, $lastupdate) {
278
  global $NICE_URLS;
279
  global $STR;
280
  global $LANG;
281
 
282
  echo '<a href="';
283
  if (!$NICE_URLS) {
284
    echo selfurl("thread=$threadid");
285
  } else {
286
    echo $threadid;
287
  }
288
  echo '" class="minibb-threaditem">' . "\n";
289
  echo '<h2>' . htmlspecialchars($tytul) . "</h2>\n";
290
  echo '<p>' . $STR[$LANG]['latestentry'] . ' ' . htmlspecialchars($lastauthor) . ', ' . htmlspecialchars(data_dluga($lastupdate)) . "</p>\n";
291
  echo "</a>\n";
292
}
293
 
294
function sprawdz_captcha($CAPARR) {
295
  //echo "<!-- capid={$CAPARR['capid']} c1={$CAPARR['c1']} c2={$CAPARR['c2']} c3={$CAPARR['c3']}-->\n";
296
  switch ($CAPARR['capid']) {
297
    case 1:
298
      if (($CAPARR['c1']) && (!$CAPARR['c2']) && (!$CAPARR['c3'])) return(true);
299
      break;
300
    case 2:
301
      if ((!$CAPARR['c1']) && ($CAPARR['c2']) && (!$CAPARR['c3'])) return(true);
302
      break;
303
    case 3:
304
      if ((!$CAPARR['c1']) && (!$CAPARR['c2']) && ($CAPARR['c3'])) return(true);
305
      break;
306
    case 4:
307
      if (($CAPARR['c1']) && (!$CAPARR['c2']) && ($CAPARR['c3'])) return(true);
308
      break;
309
    case 5:
310
      if ((!$CAPARR['c1']) && ($CAPARR['c2']) && ($CAPARR['c3'])) return(true);
311
      break;
312
  }
313
  return(false);
314
}
315
 
316
 
317
// zwraca akcję na podstawie globalnych POST lub GET
318
function getvar_action() {
319
  if (!empty($_POST['action'])) return $_POST['action'];
320
  if (!empty($_GET['action'])) return $_GET['action'];
321
  return('');
322
}
323
 
324
function getvar_thread() {
325
  if (!empty($_POST['thread'])) return intval($_POST['thread']);
326
  if (!empty($_GET['thread'])) return intval($_GET['thread']);
327
  return(-1);
328
}
329
 
330
function getvar_archiveyear() {
331
  if (!empty($_POST['arch'])) return intval($_POST['arch']);
332
  if (!empty($_GET['arch'])) return intval($_GET['arch']);
333
  return(-1);
334
}
335
 
336
 
337
// funkcja która zapisuje nowe wiadomości
338
function mateuszbb_preprocess() {
339
global $TRIP_SALT;
340
global $DATADIR;
341
global $NICE_URLS;
342
global $ERRSTR; // zmienna zawierająca komunikat błędu (jeśli jakiś wystąpił)
343
global $STR;
344
global $LANG;
1242 mateusz.vi 345
global $MAXDAILYPOSTS;
346
global $EDIT_ALLOWED_MINUTES;
1223 mateusz.vi 347
 
348
$action = getvar_action();
349
$thread = getvar_thread();
350
$archiveyear = getvar_archiveyear();
351
 
1242 mateusz.vi 352
// negotiate language, unless forced by configuration
353
if (empty($LANG)) {
354
  $LANG = 'en'; // preselect english as default language
355
  foreach (getpreflang() as $l) {
356
    if (!empty($STR[$l])) {
357
      $LANG = $l;
358
      break;
359
    }
1223 mateusz.vi 360
  }
1242 mateusz.vi 361
} else { // if language forced by configuration then make sure it is supported
362
  if (empty($STR[$LANG])) $LANG = 'en'; // fall back to 'en' on error
1223 mateusz.vi 363
}
364
 
365
// write access: check how many messages the user posted during last 24h
366
if (($action === 'createthread') || ($action === 'newpost')) {
1242 mateusz.vi 367
  $db = new SQLite3($DATADIR . 'mateuszbb.sqlite3');
368
  if ($db) {
369
    $db->exec('DELETE FROM ip_msg_counters24h WHERE msgid < strftime(\'%s\', \'now\') - 24*3600;');
370
    $count24h = intval($db->querySingle("SELECT count(*) FROM ip_msg_counters24h WHERE ipaddr = '{$_SERVER['REMOTE_ADDR']}'"));
371
    $db->close();
372
    if ($count24h >= $MAXDAILYPOSTS) {
373
      $ERRSTR = "BŁĄD: Z TWOJEGO ADRESU NAPISANO JUŻ {$count24h} WIADOMOŚCI W PRZECIĄGU OSTATNICH 24H. SPRÓBUJ PONOWNIE ZA JAKIŚ CZAS.";
374
      $action = '';
375
    }
376
  }
1223 mateusz.vi 377
}
378
 
1242 mateusz.vi 379
// edit post becomes newpost, it was different just to avoid 24h counters
380
if ($action === 'editpost') $action = 'newpost';
381
 
1223 mateusz.vi 382
// new thread creation (+switch to read thread)
383
if ($action === 'createthread') {
384
  // captcha check
385
  if (!sprawdz_captcha($_POST)) {
386
    echo "<p>BŁĄD: NIEPRAWIDŁOWE CAPTCHA</p>\n";
387
    goto DONE;
388
  }
389
  //
390
  $thread = time();
1242 mateusz.vi 391
  if (empty($_POST['username']) || (empty($_POST['msg'])) || (empty($_POST['title']))) {
1223 mateusz.vi 392
    echo '<p>BŁĄD: pusty nick, wiadomość lub tytuł</p>' . "\n";
393
    goto DONE;
394
  }
395
  if (!mkdir($DATADIR . 'threads/' . $thread, 0755, true)) {
396
    echo '<p>BŁĄD: nie zdołano utworzyć wątku nr ' . $thread . "</p>\n";
397
    goto DONE;
398
  }
399
  // zapisz tytuł
400
  file_put_contents($DATADIR . 'threads/' . $thread . '/title.txt', trim($_POST['title']));
401
  // ustaw co trzeba żeby zapisać wiadomość
402
  $action = 'newpost';
403
}
404
 
405
// nowy post do istniejącego wątku
1242 mateusz.vi 406
if (($action === 'newpost') && ($thread >= 0) && (!empty($_POST['msg'])) && (!empty($_POST['username']))) {
407
  // is it really about a NEW post or about EDITING an existing one?
408
  if (empty($_POST['postid'])) {
409
    $postid = time();
410
  } else { // editing an existing post
411
    $msg = loadmsg($_POST['thread'], $_POST['postid']);
412
    if (!is_art_edition_allowed($_POST['postid'], $msg)) {
413
      $action = '';
414
      $ERRSTR = "NOT ALLOWED";
415
      goto DONE;
416
    }
417
    $postid = $_POST['postid'];
418
  }
419
 
1223 mateusz.vi 420
  if (!sprawdz_captcha($_POST)) {
421
    $ERRSTR = "BŁĄD: NIEPRAWIDŁOWE CAPTCHA";
422
    goto DONE;
423
  }
424
  // nadpisz lastauthor i lastupdate
1242 mateusz.vi 425
  $lastupdate = array('lastupdate' => $postid, 'lastauthor' => trim($_POST['username']));
1223 mateusz.vi 426
  file_put_contents($DATADIR . 'threads/' . $thread . '/lastupdate', serialize($lastupdate));
427
  // oblicz tripkod, jeśli hasło zostało ustawione
428
  $tripsig = '';
1242 mateusz.vi 429
  if (!empty(trim($_POST['password']))) {
430
    $tripsig = hash('whirlpool', trim($_POST['username']) . '#' . trim($_POST['password']) . $TRIP_SALT);
1223 mateusz.vi 431
  }
1242 mateusz.vi 432
  // wygeneruj klucz do edycji postu i prześlij go przeglądarce przez ciasteczko (chyba że przeglądarka już ma klucz)
433
  if (!empty($EDIT_ALLOWED_MINUTES)) {
434
    if (!empty($_COOKIE['mateuszbbkey'])) {
435
      $artkey = $_COOKIE['mateuszbbkey'];
436
    } else {
437
      $artkey = bin2hex(random_bytes(128));
438
      setcookie('mateuszbbkey', $artkey, array('secure' => true, 'httponly' => true, 'samesite' => 'Lax'));
439
    }
440
  }
1223 mateusz.vi 441
  // zapisz wiadomość
1242 mateusz.vi 442
  $msg = array('author' => trim($_POST['username']), 'ip' => $_SERVER['REMOTE_ADDR'], 'trip' => $tripsig, 'msg' => trim($_POST['msg']), 'key' => password_hash($artkey, PASSWORD_DEFAULT));
1223 mateusz.vi 443
  file_put_contents($DATADIR . 'threads/' . $thread . '/' . $postid, serialize($msg));
1242 mateusz.vi 444
  // zaktualizuj metadane dot. ostatniego wpisu, ostatniego autora i ilości wpisów dla tego IP w ciągu ostatniej godziny, ale tylko dla nowych wpisów (nie dla edycji)
445
  if (empty($_POST['postid'])) {
446
    $db = new SQLite3($DATADIR . 'mateuszbb.sqlite3');
447
    if ($db) {
448
      $db->exec('CREATE TABLE IF NOT EXISTS newest (thread INTEGER PRIMARY KEY, lastupdate INTEGER NOT NULL, lastauthor TEXT NOT NULL);');
449
      $db->exec('CREATE INDEX IF NOT EXISTS lastupdated ON newest (lastupdate);');
450
      $db->exec('CREATE TABLE IF NOT EXISTS ip_msg_counters24h (threadid INTEGER NOT NULL, msgid INTEGER NOT NULL, ipaddr TEXT NOT NULL);');
451
      $db->exec('CREATE TABLE IF NOT EXISTS rss (thread INTEGER NOT NULL, msgid INTEGER NOT NULL, author TEXT NOT NULL);');
452
      $db->exec('CREATE INDEX IF NOT EXISTS rss_msgid ON rss (msgid);');
453
      $login_escaped = $db->escapeString(trim($_POST['username']));
454
      $db->exec("INSERT OR REPLACE INTO newest (thread, lastupdate, lastauthor) VALUES ({$thread}, {$postid}, '{$login_escaped}');");
455
      $db->exec("INSERT INTO rss (thread, msgid, author) VALUES ({$thread}, {$postid}, '{$login_escaped}');");
456
      $db->exec("INSERT INTO ip_msg_counters24h (threadid, msgid, ipaddr) VALUES ({$thread}, {$postid}, '{$_SERVER['REMOTE_ADDR']}');");
457
      $db->close();
458
    } else {
459
      echo "SQL ERROR WHILE WRITING STATS\n";
460
    }
1223 mateusz.vi 461
  }
462
  // przekieruj
463
  if ($NICE_URLS) {
464
    $newurl = "{$thread}#{$postid}";
465
  } else {
466
    $newurl = selfurl("thread={$thread}") . "#{$postid}";
467
  }
468
  header("Location: {$newurl}");
469
  echo "<html><head></head><body><a href=\"{$newurl}\">KLIKNIJ TUTAJ</a></body></html>\n";
470
  exit();
471
}
472
 
473
DONE:
474
 
475
}
476
 
477
 
478
function mateuszbb_tytulwatku($id) {
479
  global $DATADIR;
480
  return file_get_contents($DATADIR . 'threads/' . $id . '/title.txt');
481
}
482
 
483
 
1242 mateusz.vi 484
// returns an array of last n threads with most recent activity that had activity
485
// in last maxinact days. returns false on error or empty set.
486
// the returned result, when not false, is an array of arrays, where each
487
// leaf array represents one thread
488
function mateuszbb_getactivethreads($n, $maxinact = -1) {
489
  global $DATADIR;
490
  $result = array();
491
 
492
  $db = new SQLite3($DATADIR . 'mateuszbb.sqlite3', SQLITE3_OPEN_READONLY);
493
  if (! $db) return(false);
494
 
495
  $minupdatedate = 0;
496
  if ($maxinact >= 0) $minupdatedate = time() - (intval($maxinact) * 86400);
497
 
498
  $sqlquery = 'SELECT thread, lastupdate, lastauthor FROM newest WHERE lastupdate > ' . $minupdatedate . ' ORDER BY lastupdate DESC LIMIT ' . intval($n) . ';';
499
 
500
  $sqlres = $db->query($sqlquery);
501
  if (! $sqlres) {
502
    $db->close();
503
    return(false);
504
  }
505
 
506
  // kopiuj wpisy do nowej tablicy
507
  while ($row = $sqlres->fetchArray()) {
508
    $result[] = $row;
509
  }
510
 
511
  $db->close();
512
  return($result);
513
}
514
 
515
 
516
// returns true if post can be edited by current user
517
function is_art_edition_allowed($timestamp, $msg) {
518
  global $EDIT_ALLOWED_MINUTES;
519
  if ($EDIT_ALLOWED_MINUTES >= 0) {
520
    if (((time() - $timestamp) / 60) >= $EDIT_ALLOWED_MINUTES) return(false); // only posts from last x minutes can be edited
521
  }
522
  if (empty($_COOKIE['mateuszbbkey'])) return(false);
523
  if (empty($msg['key'])) return(false);
524
  return(password_verify($_COOKIE['mateuszbbkey'], $msg['key']));
525
}
526
 
527
 
528
function loadmsg($threadid, $postid) {
529
  global $DATADIR;
530
  $fname = $DATADIR . 'threads/' . $threadid . '/' . $postid;
531
  if (!file_exists($fname)) return(false);
532
  return(unserialize(file_get_contents($fname)));
533
}
534
 
535
 
1223 mateusz.vi 536
// wyświetlanie UI itd
537
function mateuszbb_start() {
538
global $TRIP_SALT;
539
global $ERRSTR;
540
global $DATADIR;
541
global $INITYEAR;
542
global $LANG;
543
global $STR;
544
global $NICE_URLS;
545
global $SEARCH_API_URL;
1242 mateusz.vi 546
global $TZ;
547
global $LOCK_DELAY;
548
global $MAINPAGE_MAXTHREADS;
549
global $MAINPAGE_MAXINACT;
1223 mateusz.vi 550
 
551
// read global variables
552
$action = getvar_action();
553
$thread = getvar_thread();
554
$archiveyear = getvar_archiveyear();
555
 
1242 mateusz.vi 556
// ustaw strefę czasową, jeśli jakaś jest skonfigurowana
557
if (!empty($TZ)) date_default_timezone_set($TZ);
558
 
1223 mateusz.vi 559
// wyświetl błąd, jeśli jakiś wystąpił w mateuszbb_preprocess()
560
if (!empty($ERRSTR)) {
561
  echo "<p class=\"minibb-errstr\">{$ERRSTR}</p>\n";
562
  $action = '';
563
  echo '<p><a href="./">Wróć do głównej strony</a></p>' . "\n";
564
  goto DONE;
565
}
566
 
567
// szukanie
568
if (isset($_POST['szukaj']) && (!empty(trim($_POST['szukaj'])))) {
569
  $q = trim($_POST['szukaj']);
570
  $query = $SEARCH_API_URL . urlencode($q);
571
  echo '<p>' . $STR[$LANG]['searchterm'] . ' ' . htmlentities($q) . '</p>';
572
  $results = file_get_contents($query);
573
  $resarr = json_decode($results, true)['items'];
574
 
575
  $licznik = 0;
576
  foreach ($resarr as $r) {
577
    if (mb_substr($r['link'], -1) === '/') continue;
578
    echo '<a href=' . $r['link'] . ' class="minibb-searchresult">';
579
    echo "<div><h1>{$r['title']}</h1><p>{$r['htmlSnippet']}</p></div></a>\n";
580
    $licznik++;
581
  }
582
 
583
  if ($licznik == 0) echo "<p>" . $STR[$LANG]['noresults'] . "</p>\n";
584
 
585
  goto DONE;
586
}
587
 
1242 mateusz.vi 588
// edit post
589
if ($action === 'editpostform') {
590
  $msg = loadmsg($_POST['thread'], $_POST['post']);
591
  if (is_art_edition_allowed($_POST['post'], $msg)) {
592
    formularz(intval($_POST['thread']), intval($_POST['post']), $msg);
593
  } else {
594
    echo "<p>Link expired</p>\n";
595
  }
596
  GOTO DONE;
597
}
598
 
1223 mateusz.vi 599
// new thread form
600
if ($action === 'newthread') {
601
  echo '<h2 class="minibb-threadtitle">' . $STR[$LANG]['newthread'] . '</h2>' . "\n";
602
  formularz();
603
  goto DONE;
604
}
605
 
1242 mateusz.vi 606
// zobacz listę wątków (main page)
1223 mateusz.vi 607
if ((empty($action)) && ($thread < 0) && ($archiveyear <= 0)) {
1242 mateusz.vi 608
  // display the main page header if any is defined
609
  if (file_exists($DATADIR . 'mateuszbb-main-head.html')) {
610
    readfile($DATADIR . 'mateuszbb-main-head.html');
611
  }
612
  // list wątków
1223 mateusz.vi 613
  echo '<div class="minibb-toolbar" style="justify-content: space-between;">';
614
  echo '<form action="' . selfurl() . '" method="POST"><input type="text" name="szukaj" placeholder="' . $STR[$LANG]['search'] . '"></form>';
615
  echo '<a href="' . selfurl('action=newthread') . '#formularz">' . $STR[$LANG]['opnewthread'] . '</a>';
616
  echo "</div>\n";
1242 mateusz.vi 617
 
618
  $lista_watkow = mateuszbb_getactivethreads($MAINPAGE_MAXTHREADS, $MAINPAGE_MAXINACT);
619
  if ($lista_watkow === false) {
620
    echo "<p>NO ENTRIES FOUND</p>";
621
  } else {
622
    foreach ($lista_watkow as $row) {
623
      $title = mateuszbb_tytulwatku($row['thread']);
624
      if (empty($title)) {
625
        echo "<!-- BŁĄD: nie zdołano załadować wątku nr {$row['thread']} -->\n";
626
        continue;
1223 mateusz.vi 627
      }
1242 mateusz.vi 628
      wyswietl_watek_w_liscie($row['thread'], $title, $row['lastauthor'], $row['lastupdate']);
1223 mateusz.vi 629
    }
630
  }
631
 
632
  echo '<div style="display: flex; justify-content: space-between; font-size: 0.9em; opacity: 0.8; margin: 0.6em 0.5em 0 0.5em;">' . "\n";
633
  echo '<div>' . $STR[$LANG]['archives'] . ':';
634
  for ($y = $INITYEAR; $y <= intval(gmdate('Y')); $y++) {
635
    if ($NICE_URLS) {
636
      echo " <a href=\"{$y}\">{$y}</a>";
637
    } else {
638
      echo ' <a href="' . selfurl("arch={$y}") . '">' . $y . '</a>';
639
    }
640
  }
641
  echo "</div>\n";
1242 mateusz.vi 642
  echo '<a href="rss.php"><img style="height: 1em;" src="mateuszbb_rss.svg" alt="RSS"></a>' . "\n";
1223 mateusz.vi 643
  echo "</div>\n";
644
 
645
  // display the main page footer if any is defined
1242 mateusz.vi 646
  if (file_exists($DATADIR . 'mateuszbb-main-foot.html')) {
647
    readfile($DATADIR . 'mateuszbb-main-foot.html');
1223 mateusz.vi 648
  }
649
 
650
  goto DONE;
651
}
652
 
653
// wyświetl archiwum
654
if ($archiveyear > 0) {
655
  echo '<div class="minibb-toolbar" id="title"><a href="' . selfurl() . '">' . $STR[$LANG]['backtocur'] . '</a></div>' . "\n";
1233 mateusz.vi 656
  echo '<h2 class="minibb-threadtitle">' . $STR[$LANG]['archives'] . " {$archiveyear}</h2>\n";
1223 mateusz.vi 657
  $threads = scandir($DATADIR . 'threads/', SCANDIR_SORT_ASCENDING);
658
  foreach ($threads as $t) {
659
    if (!preg_match('/^[0-9][0-9]*$/', $t)) continue; // skip anything that is not a thread id
660
    if (intval(gmdate('Y', $t)) != $archiveyear) continue; // skip threads out of the targeted year
661
    $title = file_get_contents($DATADIR . 'threads/' . $t . '/title.txt');
662
    $link = $t;
663
    if (! $NICE_URLS) $link = selfurl("thread={$t}");
664
    echo '<span style="font-family: monospace;">[' . gmdate("Y-m-d", $t) . "]</span> <a href=\"{$link}\">{$title}</a><br>\n";
665
  }
666
  goto DONE;
667
}
668
 
669
// zobacz wątek
670
if ((empty($action)) && ($thread >= 0)) {
671
  // załaduj listę postów (i zapamiętaj ostatnią pozycję)
672
  $listapostow = scandir($DATADIR . 'threads/' . $thread . '/');
673
  // usuń pozycje które nie są żadnym msgid (np. title.txt) i zapamiętaj ostatni msgid
674
  $posty = array();
675
  foreach ($listapostow as $p) {
676
    if (!preg_match('/^[0-9][0-9]*$/', $p)) continue; // skip anything that is not a messageid
677
    $posty[] = $p;
678
    $ostatnipost = $p;
679
  }
1242 mateusz.vi 680
  // is this thread locked?
681
  $islocked = false;
682
  if (($LOCK_DELAY >= 0) && ((time() - intval($ostatnipost)) / 86400 >= $LOCK_DELAY)) $islocked = true;
1223 mateusz.vi 683
  // toolbar (ostatni wątek / odpowiedz / powrót do forum)
684
  echo '<div class="minibb-toolbar" id="title">';
1242 mateusz.vi 685
  echo '<a href="#' . $ostatnipost . '">' . $STR[$LANG]['jumptoend'] . '</a>';
686
  if (! $islocked) echo ' <a href="#formularz">' . $STR[$LANG]['reply'] . '</a>';
687
  echo ' <a href="' . selfurl() . '">' . $STR[$LANG]['listthreads'] . '</a></div>' . "\n";
1223 mateusz.vi 688
  // wyświetl tytuł wątku
689
  echo '<h2 class="minibb-threadtitle">' . htmlspecialchars(file_get_contents($DATADIR . 'threads/' . $thread . '/title.txt')) . "</h2>\n";
1242 mateusz.vi 690
  // "thread is locked"
691
  if ($islocked) echo '<p class="minibb-islockedmsg">' . $STR[$LANG]['locked'] . "</p>\n";
692
  // wyświetl listę postów
1223 mateusz.vi 693
  foreach ($posty as $p) {
1242 mateusz.vi 694
    $msg = loadmsg($thread, $p);
1223 mateusz.vi 695
    echo '<div class="minibb-post" id="' . $p . '">' . "\n";
696
    echo '<div class="minibb-postheader"><a href="#' . $p . '" style="text-decoration: inherit; color: inherit;"><div class="minibb-postauthor">' . "\n";
697
    echo $STR[$LANG]['author'] . ' ' . htmlspecialchars($msg['author']) . "<br>\n";
698
    echo $STR[$LANG]['address'] . ' ' . htmlspecialchars($msg['ip']) . "<br>\n";
699
    echo $STR[$LANG]['date'] . ' ' . htmlspecialchars(data_dluga($p)) . "</div></a>\n";
700
    if (!empty($msg['trip'])) {
701
      echo '<div class="minibb-trip">';
702
      echo chunk_split($msg['trip'], 16, "\n");
703
      echo "</div>\n";
704
    }
705
    echo "</div>\n";
706
 
707
    // symbole html
708
    $bodyprocessed = htmlspecialchars($msg['msg']);
709
 
1242 mateusz.vi 710
    // ludzie czasem dodają znaczniki [img] do obrazków, usuń je (ale tylko jeśli są na początku linii)
711
    $bodyprocessed = preg_replace('~^(\[img\])(.*)(\[/img\])~m', '$2', $bodyprocessed);
712
 
1223 mateusz.vi 713
    // dodaj podgląd pod linki do obrazków, ale tylko jeśli link jest sam w linijce
1242 mateusz.vi 714
    $bodyprocessed = preg_replace('~^(http[s]?://[^<>[:space:]]+[[:alnum:]/]\.(jpg|png))($|[\r\n]{1,2})~m', "$1\n<img src=\"$1\">\n", $bodyprocessed);
1223 mateusz.vi 715
 
716
    // olinkuj linki
1242 mateusz.vi 717
    $bodyprocessed = preg_replace("~([^\"]|^)(http[s]?://[^<>[:space:]]+[[:alnum:]/=])~", "$1<a href=\"$2\">$2</a>", $bodyprocessed);
1223 mateusz.vi 718
 
719
    // oflaguj cytaty (linijki zaczynające się od ">")
1242 mateusz.vi 720
    $bodyprocessed = preg_replace('/^(&gt;.*)[\r]?\n/m', '<blockquote>$1</blockquote>', $bodyprocessed);
1223 mateusz.vi 721
 
1242 mateusz.vi 722
    echo '<div class="minibb-postbody">';
723
    // czy mogę edytować?
724
    if (is_art_edition_allowed($p, $msg)) {
725
      echo '<form class="editbtn" method="POST" action="' . selfurl() . '"><input type="hidden" name="action" value="editpostform"><input type="hidden" name="post" value="' . $p . '"><input type="hidden" name="thread" value="' . $thread . '"><input type="submit" value="EDIT"></form>';
726
    }
727
    echo $bodyprocessed . "</div>\n";
1223 mateusz.vi 728
    echo "</div>\n";
729
  }
1242 mateusz.vi 730
  // formularz odpowiedzi albo komunikat o zamknięciu
731
  if ($islocked) {
732
    echo '<p class="minibb-islockedmsg">' . $STR[$LANG]['locked'] . "</p>\n";
733
  } else {
734
    formularz($thread);
735
  }
1223 mateusz.vi 736
  goto DONE;
737
}
738
 
739
DONE:
740
}
741
?>