-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfunctions.php
More file actions
1248 lines (994 loc) · 29.6 KB
/
functions.php
File metadata and controls
1248 lines (994 loc) · 29.6 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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
require_once './data.php';
require_once './database.php';
require_once './logging.php';
date_default_timezone_set($site_timezone);
function reauthuser()
{
if(!isSet($_SESSION['userid']))
{
// Attempt to find persistent session cookie
if(isSet($_COOKIE['agoraSession']))
{
$findSession = json_decode($_COOKIE['agoraSession']);
if($findSession === false)
return;
$idCheck = intval($findSession -> id);
$tokenCheck = sanitizeSQL($findSession -> token);
$sql = "SELECT * FROM sessions WHERE userID=$idCheck AND token='$tokenCheck';";
$result = querySQL($sql);
if($result -> num_rows > 0)
{
$session = $result -> fetch_assoc();
if($findSession -> token == $session['token'])
{
if($session['lastSeenTime'] + 60*60*24*30*12 < time())
{
setcookie("agoraSession", "");
warn("Your session has expired.");
return;
}
$userData = findUserbyID($idCheck);
$_SESSION['loggedin'] = true;
$_SESSION['name'] = $userData['username'];
$_SESSION['banned'] = $userData['banned'];
$_SESSION['userid'] = $userData['id'];
$_SESSION['lastpostdata'] = "";
$_SESSION['actionSecret'] = mt_rand(10000, 99999);
$_SESSION['token'] = $session['token'];
// Refresh client's cookie
$newSession = new StdClass();
$newSession -> token = $session['token'];
$newSession -> id = $userData['id'];
setcookie("agoraSession", json_encode($newSession), time()+60*60*24*30*12);
// Update the last seen time and IP in session table
$time = time();
$sql = "UPDATE sessions SET lastSeenIP='{$_SERVER['REMOTE_ADDR']}', lastSeenTime={$time} WHERE id={$session['id']};";
querySQL($sql);
// info("Your session has been restored.", "Session restored");
}
if(!isSet($_SESSION['loggedin']))
return;
else if($_SESSION['loggedin'] == false)
return;
// User is now logged in if those checks passed. The rest of the function will handle group stuff and check if they're banned, etc.
}
else
return;
}
else
return;
}
$userData = findUserByID($_SESSION['userid']);
$_SESSION['loggedin'] = true;
$_SESSION['name'] = $userData['username'];
switch($userData['usergroup'])
{
case "superuser":
$_SESSION['superuser'] = true;
$_SESSION['admin'] = true;
$_SESSION['moderator'] = true;
$_SESSION['member'] = true;
break;
case "admin":
$_SESSION['superuser'] = false;
$_SESSION['admin'] = true;
$_SESSION['moderator'] = true;
$_SESSION['member'] = true;
break;
case "moderator":
$_SESSION['superuser'] = false;
$_SESSION['admin'] = false;
$_SESSION['moderator'] = true;
$_SESSION['member'] = true;
break;
case "member":
$_SESSION['superuser'] = false;
$_SESSION['admin'] = false;
$_SESSION['moderator'] = false;
$_SESSION['member'] = true;
break;
case "unverified":
$_SESSION['superuser'] = false;
$_SESSION['admin'] = false;
$_SESSION['moderator'] = false;
$_SESSION['member'] = false;
break;
}
$_SESSION['banned'] = $userData['banned'];
$sql = "SELECT COUNT(*) FROM privateMessages WHERE `recipientID` = {$_SESSION['userid']} AND `read` = 0;";
$result = querySQL($sql);
$result = $result -> fetch_assoc();
$_SESSION['unreadMessages'] = $result['COUNT(*)'];
if($_SESSION['banned'] == true)
{
error("You have been banned.");
setcookie("agoraSession", "");
session_destroy();
finishPage();
}
}
function sendMail($toAddress, $subject, $contents)
{
global $site_name;
$fromName = "$site_name Agora <donotreply@" . $_SERVER['SERVER_NAME'] . ">";
$headers = "From: " . $fromName . "\r\n" .
"Reply-To:" . $fromName . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$message = wordwrap($contents, 70, "\r\n");
$success = mail($toAddress, $subject, $contents, $headers);
}
function getVerificationByID($ID)
{
$ID = intval($ID);
$sql = "SELECT verification FROM users WHERE id='{$ID}';";
$result = querySQL($sql);
$result = $result -> fetch_assoc();
return $result['verification'];
}
function clearVerificationByID($ID)
{
$ID = intval($ID);
$sql = "UPDATE users SET verification='0' WHERE id='{$ID}';";
$result = querySQL($sql);
return true;
}
function verifyAccount($code)
{
if(strlen($code) != 64)
{
error("Invalid verification code.");
return false;
}
$code = sanitizeSQL($code);
$sql = "SELECT id FROM users WHERE verification='{$code}'";
$result = querySQL($sql);
$result = $result -> fetch_assoc();
if(!isSet($result['id']))
return false;
$ID = intval($result['id']);
$sql = "UPDATE users SET verified=1, verification=0 WHERE id='{$ID}'";
$result = querySQL($sql);
addLogMessage("User verified their email.", 'info', $ID);
return true;
}
function sendResetEmail($email)
{
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
error("That's not a valid email address.");
return false;
}
$realEmail = $email;
$email = sanitizeSQL($email);
$sql = "SELECT id, verified FROM users WHERE email='{$email}'";
$result = querySQL($sql);
$result = $result -> fetch_assoc();
if(!isSet($result['id']))
{
return true; // Don't let the user know that the email wasn't on file.
}
if($result['verified'] == 0)
{
error("This account is not yet verified. You cannot reset the password until the account is verified. If you have not seen your verification email, please check your spam folder and/or wait a few minutes for it to arrive. If the email does not arrive, try registering again or contact the administrator for manual verification.");
return -1;
}
$verification = bin2hex(openssl_random_pseudo_bytes(32));
$domain = $_SERVER['SERVER_NAME']; // Just hope their webserver is configured correctly...
if(!isSet($_SERVER['REQUEST_URI']))
$uri = "/";
else
{
$uri = $_SERVER['REQUEST_URI'];
$uri = substr($uri, 0, strrpos($uri, '/') + 1);
if(strlen($uri) == 0)
$uri = "/";
}
global $force_ssl;
$url = ($force_ssl ? "https://" : "http://") . $domain . $uri . "index.php?action=resetpassword&code=" . $verification . "&id=" . $result['id'];
$message = <<<EOF
This email was sent to you because a password reset was initiated on your account. If you intended to do this, please click the link below:<br />
<br />
<a href="{$url}">{$url}</a><br />
<br />
If you did not initiate this reset, you may safely disregard this email.<br />
EOF;
$verificationCode = sanitizeSQL($verification);
$sql = "UPDATE users SET verification='{$verificationCode}' WHERE id='{$result['id']}'";
$result = querySQL($sql);
global $site_name;
$error = mail($realEmail, "$site_name password reset", $message, "MIME-Version: 1.0\r\nContent-type: text/html; charset=iso-utf-8\r\nFrom: donotreply@{$domain}\r\nX-Mailer: PHP/" . phpversion());
if($error === false)
{
error("Failed to send verification email. Please try again later.");
addLogMessage("Failed to send password reset email.", 'error', $result['id']);
return false;
}
addLogMessage("Password reset email sent for user.", 'security', $result['id']);
return true;
}
function findTopicbyID()
{
$numArgs = func_num_args();
if($numArgs < 1 || $numArgs > 2)
return;
$ID = func_get_arg(0);
$nocache = false;
if($numArgs > 1)
$nocache = boolval(func_get_arg(1));
static $topic = Array();
if(isSet($topic[$ID]) && !$nocache)
return $topic[$ID];
$ID = intval($ID);
$sql = "SELECT * FROM topics WHERE topicID = {$ID}";
$result = querySQL($sql);
if($numResults = $result -> num_rows > 0)
{
while($row = $result -> fetch_assoc())
{
$topic[$ID] = $row;
return $row;
}
return false;
}
else
return false;
}
function banUserByID($id)
{
$id = intval($id);
$sql = "UPDATE users SET banned=1, tagline='Banned user' WHERE id={$id}";
$result = querySQL($sql);
$user = findUserByID($id);
adminLog("Banned user \$USERID:{$id}");
return true;
}
function unbanUserByID($id)
{
$id = intval($id);
$sql = "UPDATE users SET banned=0, tagline='' WHERE id='{$id}'";
$result = querySQL($sql);
$user = findUserByID($id);
adminLog("Unbanned user \$USERID:{$id}");
return true;
}
function toggleBanUserByID($id)
{
$user = findUserByID($id);
if($user === false)
{
error("No user exists by that id.");
return;
}
if($user['banned'])
{
unbanUserByID($id);
return false;
}
else
{
banUserByID($id);
return true;
}
}
function promoteUserByID($id)
{
$id = intval($id);
$sql = "UPDATE users SET usergroup='admin', tagline='Administrator' WHERE id={$id}";
$result = querySQL($sql);
$user = findUserByID($id);
adminLog("Promoted user \$USERID:{$id} to admin.");
return true;
}
function demoteUserByID($id)
{
$id = intval($id);
$user = findUserByID($id);
if($id == 1)
{
error("You cannot demote the superuser.");
return false;
}
else if($user['usergroup'] != 'admin')
{
error("That user isn't an administrator.");
return false;
}
$sql = "UPDATE users SET usergroup='member', tagline='' WHERE id='{$id}'";
$result = querySQL($sql);
adminLog("Demoted user \$USERID:{$id} from admin.");
return true;
}
function togglePromoteUserByID($id)
{
$user = findUserByID($id);
if($user === false)
{
error("No user exists by that id.");
return;
}
if($user['usergroup'] == 'admin')
{
demoteUserByID($id);
return false;
}
else
{
promoteUserByID($id);
return true;
}
}
function findUserbyName($name)
{
// Speed up many requests by avoiding duplicate mysql queries
static $user = array();
$name = htmlentities(html_entity_decode(trim($name)));
if(isSet($user[$name]))
return $user[$name];
$name = sanitizeSQL(strToLower($name));
$sql = "SELECT * FROM users WHERE lower(username) = '{$name}'";
$result = querySQL($sql);
if($numResults = $result -> num_rows > 0)
{
while($row = $result -> fetch_assoc())
{
$user[$name] = $row;
return $row;
}
return false;
}
else
return false;
}
function findUserbyID($ID)
{
static $user = array();
if(isSet($user[$ID]))
return $user[$ID];
$ID = intval($ID);
$sql = "SELECT * FROM users WHERE id = {$ID}";
$result = querySQL($sql);
if($numResults = $result -> num_rows > 0)
{
while($row = $result -> fetch_assoc())
{
$user[$ID] = $row;
return $row;
}
return false;
}
else
return false;
}
function findUserbyID_nocache($ID)
{
$ID = intval($ID);
$sql = "SELECT * FROM users WHERE id = {$ID}";
$result = querySQL($sql);
if($numResults = $result -> num_rows > 0)
{
while($row = $result -> fetch_assoc())
{
$user[$ID] = $row;
return $row;
}
return false;
}
else
return false;
}
function getUserNameByID($id)
{
$id = intval($id);
$sql = "SELECT username FROM users WHERE id = '{$id}'";
$result = querySQL($sql);
if($numResults = $result -> num_rows > 0)
{
while($row = $result -> fetch_assoc())
{
return $row['username'];
}
return false;
}
else
return false;
}
function getUserPostcountByID($id)
{
$id = intval($id);
$sql = "SELECT postCount FROM users WHERE id = '{$id}'";
$result = querySQL($sql);
if($numResults = $result -> num_rows > 0)
{
while($row = $result -> fetch_assoc())
return $row['postCount'];
return false;
}
else
return false;
}
function getAvatarByID($id)
{
$id = intval($id);
$sql = "SELECT avatar FROM users WHERE id={$id};";
$result = querySQL($sql);
$result = $result -> fetch_assoc();
if(isSet($result['avatar']))
return $result['avatar'];
return false;
}
function updateAvatarByID($id, $imagePath)
{
if(move_uploaded_file($_FILES['avatar']['tmp_name'], $imagePath))
{
$imgInfo = getimagesize($imagePath);
$width = $imgInfo[0];
$height = $imgInfo[1];
$imgType = $imgInfo['mime'];
$keepOriginal = false;
$scaled = false;
if($imgType == "image/png")
{
$image = imagecreatefrompng($imagePath);
if(filesize($imagePath) < 65000)
$keepOriginal = true;
}
else if($imgType == "image/jpeg")
$image = imagecreatefromjpeg($imagePath);
else if($imgType == "image/gif")
{
$image = imagecreatefromgif($imagePath);
if(filesize($imagePath) < 65000)
$keepOriginal = true;
}
else if($imgType == "image/bmp")
$image = imagecreatefrombmp($imagePath);
else if($imgType == "image/webp")
$image = imagecreatefromwebp($imagePath);
else
{
unlink($imagePath);
error("Avatar is in an unsupported image format. Please make your avatar a png, jpeg, bmp, webp, or gif type image.");
return false;
}
// Delete the raw uploaded image so it isn't left there if we exit from an error.
if(!$keepOriginal)
unlink($imagePath);
if($image === false)
{
error("Failed to load image.");
return false;
}
if($height > 100 || $width > 100)
{
if($height > $width)
{
$newHeight = 100;
$newWidth = round($width * ($newHeight / $height));
}
else
{
$newWidth = 100;
$newHeight = round($height * ($newWidth / $width));
}
$newImage = imagecreatetruecolor($newWidth, $newHeight);
// Make sure transparency is spared.
imagesavealpha($image, true);
imagesavealpha($newImage, true);
imagesetinterpolation($newImage, IMG_BICUBIC);
$error = imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if($error === false)
{
error("Unable to scale image.");
return false;
}
imagedestroy($image);
$image = $newImage;
$scaled = true;
warn("Your image was scaled because it was too big. Some quality may have been lost.");
}
// Save the converted image.
if(!$keepOriginal || $scaled)
{
$error = imagepng($image, $imagePath, 9, PNG_NO_FILTER);
if($error === false)
{
error("Unable to save converted image.");
return false;
}
if(!$scaled)
warn("Your image was converted to PNG format.");
}
imagedestroy($image);
//Upload the avatar to the MySQL database
$id = intval($id);
$inputData = sanitizeSQL(fread(fopen($imagePath, "rb"), filesize($imagePath)));
unlink($imagePath);
$time = time();
$sql = "UPDATE users SET avatar='{$inputData}', avatarUpdated='{$time}' WHERE id={$id};";
querySQL($sql);
}
else
{
error("Uploaded file could not be validated.");
return false;
}
return true;
}
function getPasswordHashByID($ID)
{
$ID = intval($ID);
$sql = "SELECT passkey FROM users WHERE id={$ID};";
$result = querySQL($sql);
return $result -> fetch_assoc()['passkey'];
}
function updatePasswordByID($ID, $newHash)
{
$ID = intval($ID);
$newHash = sanitizeSQL($newHash);
$sql = "UPDATE users SET passkey='{$newHash}' WHERE id={$ID};";
querySQL($sql);
}
function getEmailByID($ID)
{
$ID = intval($ID);
$sql = "SELECT email FROM users WHERE id={$ID};";
$result = querySQL($sql);
return $result -> fetch_assoc()['email'];
}
function updateEmailByID($ID, $newEmail)
{
if(filter_var($newEmail, FILTER_VALIDATE_EMAIL) === false)
return false;
global $require_email_verification;
if($require_email_verification)
{
$verification = bin2hex(openssl_random_pseudo_bytes(32));
$domain = $_SERVER['SERVER_NAME']; // Just hope their webserver is configured correctly...
$uri = $_SERVER['REQUEST_URI'];
$uripos = strrchr($uri, '/');
if($uripos === false)
$uri = "/";
else
$uri = substr($uri, 0, $uripos + 1);
global $force_ssl;
$url = ($force_ssl ? "https://" : "http://") . $domain . $uri . "index.php?action=emailchange&code=" . $verification . "&id=" . $ID;
$user = getUserNameByID($ID);
$message = <<<EOF
This email was sent to you because an email change was initiated on your account, {$user}. If you intended to do this, please click the link below to confirm the new email:<br />
<br />
<a href="{$url}">{$url}</a><br />
<br />
If you are not the owner of the account, pleae disregard this email.<br />
EOF;
$verificationCode = sanitizeSQL($verification);
$newEmail = sanitizeSQL($newEmail);
$ID = intval($ID);
$sql = "UPDATE users SET emailVerification='{$verificationCode}', newEmail='{$newEmail}' WHERE id='{$ID}';";
querySQL($sql);
global $site_name;
$error = mail($newEmail, "$site_name email change", $message, "MIME-Version: 1.0\r\nContent-type: text/html; charset=iso-utf-8\r\nFrom: donotreply@{$domain}\r\nX-Mailer: PHP/" . phpversion());
if($error === false)
{
error("Failed to send verification email. Please try again later.");
return false;
}
return true;
}
else
{
$ID = intval($ID);
$newEmail = sanitizeSQL(trim($newEmail));
$sql = "UPDATE users SET email='{$newEmail}' WHERE id={$ID};";
querySQL($sql);
return true;
}
}
function verifyEmailChange($ID, $verification)
{
$ID = intval($ID);
$user = findUserByID($ID);
if($verification !== $user['emailVerification'])
{
error("Invalid verification code.");
return false;
}
$sql = "UPDATE users SET email='{$user['newEmail']}', newEmail='', emailVerification=0 WHERE id='{$ID}';";
$result = querySQL($sql);
return true;
}
function checkUserExists($username, $email)
{
$username = sanitizeSQL(strToLower($username));
$email = sanitizeSQL(strToLower($email));
$sql = "SELECT * FROM users WHERE lower(username) = '{$username}' OR lower(email) = '{$email}';";
$result = querySQL($sql);
if($result -> num_rows > 0)
{
while($row = $result -> fetch_assoc())
return true;
return false;
}
else
return false;
}
function displayUserProfile($id)
{
global $_userData, $_id;
$_userData = findUserByID_nocache($id);
$_id = $id;
if($_userData == false)
{
error("No user by this user id exists.");
return;
}
loadThemePart("profile");
}
function updateUserProfileText($id, $text, $tagLine, $website)
{
if(strlen($text) > 1001)
{
error("Your profile info text cannot exceed 1000 characters. (" . strlen($text) . ")");
return false;
}
// verify website and tagline are OK and then sql escape them
if(!filter_var($website, FILTER_VALIDATE_URL) || strlen($website) > 200)
{
if(strToLower($website) != "http://" && strlen($website) > 1)
{
$website = findUserByID($id)['website'];
error("Your website url is invalid or too long.");
}
else if(strToLower($website) == "http://")
$website = findUserByID($id)['website'];
else
$website = "";
}
if(strlen($tagLine) > 30)
{
error("Your tagline is too long.");
$tagLine = findUserByID($id)['tagline'];
}
$id = intval($id);
$rawText = sanitizeSQL(htmlentities(html_entity_decode($text), ENT_SUBSTITUTE | ENT_QUOTES, "UTF-8"));
$text = sanitizeSQL(bb_parse($text));
$website = sanitizeSQL(trim($website));
$tagLine = sanitizeSQL(htmlentities(html_entity_decode(trim($tagLine)), ENT_SUBSTITUTE | ENT_QUOTES, "UTF-8"));
if(strlen($text) > 2000)
{
error("Your bbcode formatting exceeded storage parameters. Use fewer tags that expand into lots of html.");
return false;
}
$sql = "UPDATE users SET profiletext='{$rawText}', profiletextPreparsed='{$text}', tagline='{$tagLine}', website='{$website}' WHERE id={$id}";
$result = querySQL($sql);
return true;
}
function fetchSinglePost($postID)
{
static $post = array();
if(isSet($post[$postID]))
return $post[$postID];
$postID = intval($postID);
$sql = "SELECT * FROM posts WHERE postID={$postID};";
$result = querySQL($sql);
if($result === false)
return false;
$row = $result -> fetch_assoc();
$post[$postID] = $row;
return $row;
}
function getPostLink($postID)
{
global $items_per_page;
$postID = intval($postID);
$post = fetchSinglePost($postID);
if($post === false)
return false;
$topicPage = floor($post['threadIndex'] / $items_per_page);
$link = "./?topic={$post['topicID']}&page={$topicPage}#{$post['postID']}";
return $link;
}
function createThread($userID, $topic, $postData)
{
$userID = intval($userID);
$topic = sanitizeSQL(htmlentities(html_entity_decode($topic), ENT_SUBSTITUTE | ENT_QUOTES, "UTF-8"));
$sql = "INSERT INTO topics (creatorUserID, topicName) VALUES ({$userID}, '{$topic}');";
$result = querySQL($sql);
$topicID = getLastInsertID();
createPost($userID, $topicID, $postData);
addLogMessage('User started a new topic $TOPICID:' . $topicID);
return $topicID;
}
function lockTopic($topicID)
{
$topicID = intval($topicID);
$topic = findTopicbyID($topicID);
if($topic === false)
{
error("That topic does not exist.");
return -1;
}
if($_SESSION['userid'] != $topic['creatorUserID'] && !$_SESSION['admin'])
{
error("You do not have permission to do this action.");
return -1;
}
$newValue = !$topic['locked'];
$sql = "UPDATE topics SET locked='{$newValue}' WHERE topicID='{$topicID}';";
querySQL($sql);
adminLog(($newValue ? "Locked" : "Unlocked") . " topic \$TOPICID:{$topicID}");
return $newValue;
}
function stickyTopic($topicID)
{
$topicID = intval($topicID);
$topic = findTopicbyID($topicID);
if($topic === false)
{
error("That topic does not exist.");
return -1;
}
if(!$_SESSION['admin'])
{
error("You do not have permission to do this action.");
return -1;
}
$newValue = !$topic['sticky'];
$sql = "UPDATE topics SET sticky='{$newValue}' WHERE topicID='{$topicID}';";
querySQL($sql);
adminLog("Topic \$TOPICID:{$topicID} is " . ($newValue ? "now sticky" : "no longer sticky") . ".");
return $newValue;
}
function createPost($userID, $topicID, $postData)
{
$userID = intval($userID);
$topicID = intval($topicID);
$row = findTopicbyID($topicID);
if($row === false)
{
error("Could not find thread data.");
return;
}
if($row['locked'] == true)
{
error("This thread is locked. No further posts are permitted.");
return false;
}
// Cleanse post data
$parsedPost = sanitizeSQL(bb_parse($postData));
$postData = sanitizeSQL(htmlentities(html_entity_decode($postData), ENT_SUBSTITUTE | ENT_QUOTES, "UTF-8"));
$date = time();
// Make entry in posts table
$mysqli = getSQLConnection();
$sql = "INSERT INTO posts (userID, topicID, postDate, postData, postPreparsed, threadIndex) VALUES ({$userID}, {$topicID}, '{$date}', '{$postData}', '{$parsedPost}', '{$row['numposts']}');";
querySQL($sql);
$postID = getLastInsertID();
// Make new data for thread entry
$numPosts = $row['numposts'] + 1;
// Update thread entry
$sql = "UPDATE topics SET lastposttime='{$date}', lastpostid='{$postID}', numposts='{$numPosts}' WHERE topicID={$topicID}";
querySQL($sql);
// Update user post count
$postCount = getUserPostcountByID($userID) + 1;
$sql = "UPDATE users SET postCount='{$postCount}' WHERE id={$userID}";
querySQL($sql);
addLogMessage('User created a post $POSTID:' . $postID . ' in $TOPICID:' . $topicID, 'info', $userID);
return $postID;
}
function editPost($userID, $postID, $newPostData)
{
if($_SESSION['userid'] !== $userID && !$_SESSION['admin'])
{
error("You do not have permission to edit this post.");
return;
}
if(!$post = fetchSinglePost($postID))
{
error("This post does not exist.");
return;
}
if(boolval(findTopicbyID($post['topicID'])['locked']))
{
error("You can't edit posts in a locked thread.");
return;
}
$changeTime = time();
$postID = intval($postID);
$changeID = (int) $post['changeID'];