This repository has been archived by the owner on Feb 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
utils.php
4078 lines (3424 loc) · 132 KB
/
utils.php
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 // vim:set ts=4 sw=4 sts=4 et:
require_once "config.php";
require_once "db-func.php";
require_once "session.php";
use Aws\S3\S3Client;
// Return an HTMLPurifier object ready for use.
function getHtmlPurifier() {
$config = HTMLPurifier_Config::createDefault();
$config->set('Cache.SerializerPath', HTMLPURIFIER_CACHE_PATH);
return new HTMLPurifier($config);
}
// If the session contains a flag reporting an error adding a puzzle to an
// editing queue, return the HTML describing that error, then clear the
// session flag.
//
// (It's like a single-purpose Rails 'flash'!)
function addEditFailureHtml() {
$html = '';
if (isset($_SESSION['failedToAddEdit'])) {
$html = "<div class='errormsg'>\n";
$html .= "Failed to add puzzle to your editing queue<br/>\n";
$html .= "Perhaps you are an author, are testsolving it, or are already editing it?\n";
$html .= "</div>\n";
unset($_SESSION['failedToAddEdit']);
}
return $html;
}
// Check that the user is logged in.
// If so, update the session (to provent timing out) and return the uid;
// If not, redirect to login page. Preserve POST data if redirecting.
function isLoggedIn() {
if (isset($_SESSION['uid']) && ($_SESSION['SITEURL'] == URL)) {
$_SESSION['time'] = time();
if (isset($_SESSION['postdata'])) {
$_POST = $_SESSION['postdata'];
unset($_SESSION['postdata']);
}
return $_SESSION['uid'];
} else {
unset($_SESSION['uid']);
$_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
$_SESSION['postdata'] = $_POST;
header("Location: " . URL . "/login.php");
exit(0);
}
}
function validUserId($uid) {
$sql = sprintf("SELECT 1 FROM users WHERE uid='%s'", mysql_real_escape_string($uid));
return has_result($sql);
}
function validPuzzleId($uid) {
$sql = sprintf("SELECT 1 FROM puzzles WHERE id='%s'", mysql_real_escape_string($uid));
return has_result($sql);
}
function validRoundId($rid) {
$sql = sprintf("SELECT 1 FROM rounds WHERE rid='%s'", mysql_real_escape_string($rid));
return has_result($sql);
}
function isValidPuzzleFilter() {
if (isset($_GET['filterkey']) && isset($_GET['filtervalue'])) {
$key = $_GET['filterkey'];
if ($key != "status" && $key != "author" &&
$key != "editor" && $key != "approver" &&
$key != "tag" && $key != "round") {
echo "<div class='errormsg'>Invalid sort key. What did you even do?</div>";
foot();
exit(1);
}
$val = $_GET['filtervalue'];
if ($key == "status" && !validPuzzleStatus($val)) {
echo "<div class='errormsg'>Invalid puzzle status ID.</div>";
foot();
exit(1);
}
if (($key == "author" || $key == "editor" || $key == "approver") && !validUserId($val)) {
echo "<div class='errormsg'>Invalid user ID.</div>";
foot();
exit(1);
}
if (($key == "tag") && !validTag($val)) {
echo "<div class='errormsg'>Invalid tag ID.</div>";
foot();
exit(1);
}
if (($key == "round") && !validRoundId($val)) {
echo "<div class='errormsg'>Invalid round ID.</div>";
foot();
exit(1);
}
return array($key, $val);
}
return array();
}
// Check that a valid puzzle is given in the URL.
function isValidPuzzleURL() {
if (!isset($_GET['pid'])) {
echo "<div class='errormsg'>Puzzle ID not found. Please try again.</div>";
foot();
exit(1);
}
$pid = $_GET['pid'];
$sql = sprintf("SELECT 1 FROM puzzles WHERE id='%s'",
mysql_real_escape_string($pid));
if (!has_result($sql)) {
echo "<div class='errormsg'>Puzzle ID not valid. Please try again.</div>";
foot();
exit(1);
}
return $pid;
}
// convert puzzle names to canonical form used on post-prod site
function postprodCanon($s) {
$s = strtolower(trim($s));
$s = preg_replace('/[\']([st])\b/', '$1', $s);
$s = preg_replace('/[^a-z0-9]+/', '_', $s);
return trim($s, "_");
}
function nl2br2($s) {
// builtin nl2br inserts <br />s before newlines instead of replacing
// which makes line breaks in <pre> tags get doubled
return str_replace("\n", '<br />', $s);
}
function postprodCanonRound($s) {
return postprodCanon($s);
}
function postprodAll($uid) {
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
@ob_end_clean();
set_time_limit(0);
header( 'Content-type: text/plain; charset=utf-8' );
print "Postprodding all...\n\n";
ob_flush();
flush();
$allofem = getPuzzlesInPostprodAndLater();
foreach ($allofem as $puz) {
print "$puz ... ";
ob_flush();
flush();
$status = pushToPostProdHelper($uid, $puz, $output);
if ($status == 0) {
print "OK\n\n$output\n\n";
} else {
print "FAILED\n\n$output\n\n";
}
ob_flush();
flush();
}
print "Done!\n";
exit(1);
}
function pushToPostProd($uid, $pid) {
$status = pushToPostProdHelper($uid, $pid, $output);
if ($status == 0) {
print "<pre>OK\n\n$output</pre>";
} else {
utilsError($output);
}
exit(0);
}
function pushToPostProdHelper($uid, $pid, &$output) {
$round_rows = getRoundDictForPuzzle($pid);
$rinfo = $round_rows[0];
$answer_dict = getAnswersAndDeepForPuzzle($pid);
$aid = $answer_dict['aid'];
$deep = $answer_dict['deep'];
$answer = $answer_dict['answer'];
#$runscript = "/usr/bin/env | grep ^CATTLEPROD";
#$runscript = "/srv/veil/venv/bin/cattleprod 2>&1";
# $runscript = "/nfs/sages/deploy/mh2013/present/bin/cattleprod 2>&1";
$runscript = "/home/puzzletron/cattleprod.py 2>&1";
$roundname = $rinfo['name'];
$roundslug = postprodCanonRound($roundname);
$title = getTitle($pid);
$titleslug = postprodCanon($title);
$fileList = getFileListForPuzzle($pid, 'postprod');
$file = $fileList[0];
$credits = getCreditsWithDefault($pid);
$filename = $file['filename'];
if (empty($filename)) {
return "Nothing in the postproduction slot of this puzzle: Nothing to push!";
}
$username = getUserUsername($uid);
# ???
putenv("CATTLEPROD_PUZZLE_SLUG=" . $titleslug);
putenv("CATTLEPROD_ROUND_SLUG=" . $roundslug);
putenv("CATTLEPROD_ROUND_NAME=" . $roundname);
putenv("CATTLEPROD_TITLE=" . $title);
putenv("CATTLEPROD_MEDIA=" . "$filename");
putenv("CATTLEPROD_ANSWER_ID=" . $aid);
putenv("CATTLEPROD_PUZZLE_ID=" . $pid);
putenv("CATTLEPROD_ANSWER=" . $answer);
putenv("CATTLEPROD_DEEP=" . $deep);
putenv("CATTLEPROD_CREDITS=" . $credits);
putenv("CATTLEPROD_PUSHER=" . $username);
# putenv("CATTLEPROD_ASSET_PATH=/nfs/enigma/mh2013/chazelle/assets");
exec($runscript, $output, $exit_status);
$output = implode("\n", $output);
return $exit_status;
}
function isStatusInPostProd($sid) {
$sql = sprintf("SELECT postprod FROM pstatus WHERE id='%s'", mysql_real_escape_string($sid));
return get_element($sql) == 1;
}
function getCodename($pid) {
if (USING_CODENAMES) {
$sql = sprintf("SELECT name from codenames where id = '%s';", mysql_real_escape_string($pid));
return get_element($sql);
}
return getTitle($pid);
}
// Does user have permission to add themselves as a Discussion Editor?
function hasEditorPermission($uid) {
return hasPermission($uid, 'becomeEditor');
}
// Does user have permission to add themselves as an Approval Editor?
function hasApproverPermission($uid) {
return hasPermission($uid, 'becomeApprover');
}
// Will user be auto-subscribed to emails for puzzles they edit?
function hasEditorAutosubscribe($uid) {
return hasPermission($uid, 'autoSubWhenEditing');
}
function hasRoundCaptainPermission($uid) {
return hasPermission($uid, 'becomeRoundCaptain');
}
function hasTestAdminPermission($uid) {
return hasPermission($uid, 'beTestAdmin');
}
function hasLurkerPermission($uid) {
//return hasPermission($uid, 'beLurker');
return TRUE;
}
function hasFactCheckerPermission($uid) {
return hasPermission($uid, 'factcheck');
}
function isBlind($uid) {
return hasPermission($uid, 'beBlind');
}
function hasServerAdminPermission($uid) {
return hasPermission($uid, 'administerServer');
}
function isDirector($uid) {
return isRole($uid, 3);
}
function isEditorChief($uid) {
return isRole($uid, 9);
}
function isApprovalEditor($uid) {
return isRole($uid, 14);
}
function isCohesion($uid) {
return isRole($uid, 15);
}
function canChangeStatus($uid) {
return hasPermission($uid, 'changePuzzleStatus');
}
function canRequestTestsolve($uid, $pid) {
return isPuzzleInTesting($pid) &&
canViewPuzzle($uid, $pid);
// Should maybe be stricter than 'can view', but 'is editor on puzzle'
// is too strict because it excludes the testsolve admins / chief
// editors / chief producers / etc.
}
function hasPermission($uid, $permission) {
$sql = sprintf("SELECT 1 FROM user_role LEFT JOIN roles ON user_role.role_id = roles.id
WHERE uid='%s' AND %s='1'",
mysql_real_escape_string($uid), mysql_real_escape_string($permission));
return has_result($sql);
}
function isRole($uid, $role_id) {
$sql = sprintf("SELECT 1 FROM user_role WHERE uid='%s' AND role_id='%d'",
mysql_real_escape_string($uid), mysql_real_escape_string($role_id));
return has_result($sql);
}
function isRelatedBy($table, $uid, $pid) {
$sql = sprintf("SELECT 1 FROM $table WHERE uid='%s' AND pid='%s'",
mysql_real_escape_string($uid), mysql_real_escape_string($pid));
return has_result($sql);
}
function isAuthorOnPuzzle($uid, $pid) {
return isRelatedBy("author_links", $uid, $pid);
}
function isRoundCaptainOnPuzzle($uid, $pid) {
return isRelatedBy("round_captain_links", $uid, $pid);
}
function isEditorOnPuzzle($uid, $pid) {
return isRelatedBy("editor_links", $uid, $pid);
}
function isApproverOnPuzzle($uid, $pid) {
return isRelatedBy("approval_editor_links", $uid, $pid);
}
function isTesterOnPuzzle($uid, $pid) {
return isRelatedBy("tester_links", $uid, $pid);
}
function isFactcheckerOnPuzzle($uid, $pid) {
return isRelatedBy("factchecker_links", $uid, $pid);
}
function isFormerTesterOnPuzzle($uid, $pid) {
return isRelatedBy("former_tester_links", $uid, $pid);
}
function isSpoiledOnPuzzle($uid, $pid) {
return isRelatedBy("spoiled_user_links", $uid, $pid);
}
function isTestingAdminOnPuzzle($uid, $pid) {
return isRelatedBy("test_admin_links", $uid, $pid);
}
function setFlag($uid, $pid, $value) {
$sql = sprintf("INSERT INTO flagger_links (pid, uid, flag) VALUES ('%s', '%s', '%s')
ON DUPLICATE KEY UPDATE flag='%s'", mysql_real_escape_string($pid),
mysql_real_escape_string($uid),
mysql_real_escape_string($value),
mysql_real_escape_string($value));
query_db($sql);
}
function getFlag($uid, $pid) {
$sql = sprintf("SELECT flag FROM flagger_links WHERE pid='%s' AND uid='%s'",
mysql_real_escape_string($pid), mysql_real_escape_string($uid));
return get_element_null($sql);
}
function getFlaggedPuzzles($uid) {
$sql = sprintf("SELECT pid FROM flagger_links WHERE uid='%s' AND flag",
mysql_real_escape_string($uid));
return get_elements($sql);
}
function updateLastVisit($uid, $pid) {
// Get previous visit time
$lastVisit = getLastVisit($uid, $pid);
// Store this visit in visitor_links table
$sql = sprintf("INSERT INTO visitor_links (pid, uid, date) VALUES ('%s', '%s', NOW())
ON DUPLICATE KEY UPDATE date=NOW()", mysql_real_escape_string($pid),
mysql_real_escape_string($uid));
query_db($sql);
return $lastVisit;
}
function getLastVisit($uid, $pid) {
$sql = sprintf("SELECT date FROM visitor_links WHERE pid='%s' AND uid='%s'",
mysql_real_escape_string($pid), mysql_real_escape_string($uid));
return get_element_null($sql);
}
function getUserUsername($uid) {
$sql = sprintf("SELECT username FROM users WHERE uid='%s'", mysql_real_escape_string($uid));
return get_element($sql);
}
function getUserName($uid) {
$sql = sprintf("SELECT fullname FROM users WHERE uid='%s'", mysql_real_escape_string($uid));
return get_element($sql);
}
function getEmail($uid) {
$sql = sprintf("SELECT email FROM users WHERE uid='%s'",
mysql_real_escape_string($uid));
return get_element($sql);
}
function getEmailLevel($uid) {
$sql = sprintf("SELECT email_level FROM users WHERE uid='%s'",
mysql_real_escape_string($uid));
return get_element($sql);
}
// Get associative array of users' uid and name
function getUsersForPuzzle($table, $pid) {
// This is only called from the below functions, where $table is a hardcoded string
$sql = sprintf("SELECT users.uid, users.fullname FROM users INNER JOIN %s ON users.uid=%s.uid WHERE %s.pid='%s'",
$table, $table, $table, mysql_real_escape_string($pid));
return get_assoc_array($sql, "uid", "fullname");
}
function getAuthorsForPuzzle($pid) {
return getUsersForPuzzle("author_links", $pid);
}
function getRoundCaptainsForPuzzle($pid) {
return getUsersForPuzzle("round_captain_links", $pid);
}
function getEditorsForPuzzle($pid) {
return getUsersForPuzzle("editor_links", $pid);
}
function getApproversForPuzzle($pid) {
return getUsersForPuzzle("approval_editor_links", $pid);
}
function validTag($id) {
$sql = sprintf("SELECT 1 FROM tags WHERE id='%s'", mysql_real_escape_string($id));
return has_result($sql);
}
function getTagsAsList($pid) {
// This is only called from the below functions, where $table is a hardcoded string
$sql = sprintf("SELECT tags.name FROM tags INNER JOIN puzzle_tag ON tags.id=puzzle_tag.tid WHERE puzzle_tag.pid='%s'", mysql_real_escape_string($pid));
$tags = get_elements($sql);
return ($tags ? implode(", ", $tags) : "<span class='emptylist'>(none)</span>" );
}
function getTagsForPuzzle($pid) {
$sql = sprintf("SELECT tags.id, tags.name FROM tags INNER JOIN puzzle_tag ON tags.id=puzzle_tag.tid WHERE puzzle_tag.pid='%s'", mysql_real_escape_string($pid));
return get_assoc_array($sql, "id", "name");
}
function isTagOnPuzzle($tid, $pid) {
$sql = sprintf("SELECT 1 FROM puzzle_tag WHERE pid='%s' AND tid='%s'",
mysql_real_escape_string($pid), mysql_real_escape_string($tid));
return has_result($sql);
}
function getAvailableTagsForPuzzle($pid) {
// Get all tags
$sql = 'SELECT id, name FROM tags';
$all_tags = get_assoc_array($sql, "id", "name");
$tags = array();
foreach ($all_tags as $tid => $name) {
if (!isTagOnPuzzle($tid, $pid)) {
$tags[$tid] = $name;
}
}
return $tags;
}
function getAllTags() {
$sql = 'SELECT id, name FROM tags';
return get_assoc_array($sql, "id", "name");
}
function addTags($uid, $pid, $add) {
if (!$add) {
return;
}
if (!canViewPuzzle($uid, $pid)) {
utilsError("You do not have permission to modify puzzle $pid.");
}
foreach ($add as $tag) {
if (isTagOnPuzzle($tag, $pid)) {
utilsError('Tag is not available.');
}
$sql = sprintf("INSERT INTO puzzle_tag (pid, tid) VALUES ('%s', '%s')",
mysql_real_escape_string($pid), mysql_real_escape_string($tag));
query_db($sql);
}
}
function removeTags($uid, $pid, $remove) {
if (!$remove) {
return;
}
if (!canViewPuzzle($uid, $pid)) {
utilsError("You do not have permission to modify puzzle $pid.");
}
foreach ($remove as $tag) {
if (!isTagOnPuzzle($tag, $pid)) {
utilsError('Tag is not available.');
}
$sql = sprintf("DELETE FROM puzzle_tag WHERE pid='%s' AND tid='%s'",
mysql_real_escape_string($pid), mysql_real_escape_string($tag));
query_db($sql);
}
}
function changeTags($uid, $pid, $add, $remove) {
mysql_query('START TRANSACTION');
addTags($uid, $pid, $add);
removeTags($uid, $pid, $remove);
mysql_query('COMMIT');
}
function getSpoiledUsersForPuzzle($pid) {
return getUsersForPuzzle("spoiled_user_links", $pid);
}
function getFactcheckersForPuzzle($pid) {
return getUsersForPuzzle("factchecker_links", $pid);
}
function getTestAdminsToNotify($pid) {
$table = 'test_admin_links';
$sql = sprintf("SELECT users.uid FROM users INNER JOIN %s ON users.uid=%s.uid WHERE %s.pid='%s'",
$table, $table, $table, mysql_real_escape_string($pid));
$testadmins_for_puzzle = get_elements($sql);
$sql = "select users.uid from users, user_role where users.uid=user_role.uid and (user_role.role_id=6 or user_role.role_id=13);";
$all_testadmins = get_elements($sql);
// If a puzzle has testadmins, they will be auto-subscribed to
// comments. Prevent them from getting notified twice.
return ($testadmins_for_puzzle ? array() : $all_testadmins);
}
// Get comma-separated list of users' names
function getUserNamesAsList($table, $pid) {
// This is only called from the below functions, where $table is a hardcoded string
$sql = sprintf("SELECT users.fullname FROM users INNER JOIN %s ON users.uid=%s.uid WHERE %s.pid='%s'",
$table, $table, $table, mysql_real_escape_string($pid));
$users = get_elements($sql);
if (count($users) == 0) {
return "<span class='emptylist'>(none)</span>";
} elseif (count($users) == 1) {
return $users[0];
} elseif (count($users) == 2) {
return implode(" and ", $users);
} else {
$last_element = array_pop($users);
array_push($users, 'and '.$last_element);
return implode(", ", $users);
}
}
function getAuthorsAsList($pid) {
return getUserNamesAsList("author_links", $pid);
}
function getRoundCaptainsAsList($pid) {
return getUserNamesAsList("round_captain_links", $pid);
}
function getEditorsAsList($pid) {
return getUserNamesAsList("editor_links", $pid);
}
function getNeededEditors($pid) {
$sql = sprintf("SELECT needed_editors FROM puzzles WHERE id='%s'", mysql_real_escape_string($pid));
return get_element($sql);
}
function getPriorityWord($priority) {
if ($priority == 1) { return "1 - Very high"; }
if ($priority == 2) { return "2 - High"; }
if ($priority == 3) { return "3 - Normal"; }
if ($priority == 4) { return "4 - Low"; }
if ($priority == 5) { return "5 - Very low"; }
return $priority;
}
function getPriority($pid) {
$sql = sprintf("SELECT priority FROM puzzles WHERE id='%s'", mysql_real_escape_string($pid));
return get_element($sql);
}
function getEditorStatus($pid) {
$sql = sprintf("SELECT users.fullname FROM users INNER JOIN editor_links ON users.uid=editor_links.uid WHERE editor_links.pid='%s'", mysql_real_escape_string($pid));
$eds = get_elements($sql);
$need = getNeededEditors($pid); // warning: total needed, not additional
$edc = count($eds);
$count = $edc;
if (MIN_EDITORS >= 0) {
$count .= "/$need";
}
if ($eds) {
return array("$count: " . implode(", ", $eds), $need - $edc);
} else {
return array("<span class='emptylist'>$count</span>", $need - $edc);
}
}
function getApproversAsList($pid) {
return getUserNamesAsList("approval_editor_links", $pid);
}
function getTestingAdminsForPuzzleAsList($pid) {
return getUserNamesAsList("test_admin_links", $pid);
}
function getCurrentTestersAsList($pid) {
return getUserNamesAsList("tester_links", $pid);
}
function getSpoiledAsList($pid) {
return getUserNamesAsList("spoiled_user_links", $pid);
}
function getFactcheckersAsList($pid) {
return getUserNamesAsList("factchecker_links", $pid);
}
function getFinishedTestersAsList($pid) {
return getUserNamesAsList("former_tester_links", $pid);
}
// Get comma-separated list of users' names, with email addresses
function getUserNamesAndEmailsAsList($users) {
if (!$users) {
return '(none)';
}
$list = '';
foreach ($users as $uid) {
if ($list != '') {
$list .= ', ';
}
$name = getUserName($uid);
$email = getEmail($uid);
$list .= "<a href='mailto:$email'>$name</a>";
}
return $list;
}
function getNonAdminRoles() {
return get_row_dicts("SELECT roles.* FROM roles WHERE roles.administerServer = 0 OR roles.administerServer is null");
}
function getAllUsersAndNonAdminRoles() {
$sql = sprintf("SELECT u.uid, u.username, u.fullname, r.role_id " .
"FROM users u " .
"LEFT JOIN " .
"(SELECT ur.uid, ur.role_id " .
"FROM user_role ur ".
"LEFT JOIN roles ON ur.role_id = roles.id ".
"WHERE roles.administerServer = 0 OR roles.administerServer is null) r " .
"ON u.uid = r.uid " .
"ORDER BY u.username");
return get_row_dicts($sql);
}
function getUserRolesAsList($uid) {
$sql = sprintf("SELECT roles.name FROM user_role, roles WHERE user_role.uid='%s' AND user_role.role_id=roles.id",
mysql_real_escape_string($uid));
$result = get_elements($sql);
if ($result) {
return implode(', ', $result);
} else {
return '';
}
}
function isAnyAuthorBlind($pid) {
$authors = getAuthorsForPuzzle($pid);
foreach ($authors as $author) {
if (isBlind($author)) {
return TRUE;
}
}
return FALSE;
}
function getPuzzleInfo($pid) {
$sql = sprintf("SELECT * FROM puzzles WHERE id='%s'", mysql_real_escape_string($pid));
return get_row($sql);
}
function getTitle($pid) {
$sql = sprintf("SELECT title FROM puzzles WHERE id='%s'", mysql_real_escape_string($pid));
return get_element($sql);
}
function getCreditsWithDefault($pid) {
$credit = getCredits($pid);
if ($credit == NULL) {
$credit = "by " . getAuthorsAsList($pid);
}
return $credit;
}
function getCredits($pid) {
$sql = sprintf("SELECT credits FROM puzzles WHERE id='%s'", mysql_real_escape_string($pid));
return get_element($sql);
}
function getNotes($pid) {
$sql = sprintf("SELECT notes FROM puzzles WHERE id='%s'", mysql_real_escape_string($pid));
return get_element($sql);
}
function getEditorNotes($pid) {
$sql = sprintf("SELECT editor_notes FROM puzzles WHERE id='%s'", mysql_real_escape_string($pid));
return get_element($sql);
}
function getRuntime($pid) {
$sql = sprintf("SELECT runtime_info FROM puzzles WHERE id='%s'", mysql_real_escape_string($pid));
return get_element($sql);
}
function getCurMotd() {
$sql = sprintf("SELECT * FROM motds ORDER BY time DESC LIMIT 1");
return get_row_null($sql);
}
function getAllMotd() {
$sql = sprintf("SELECT * FROM motds ORDER BY time DESC");
return get_rows($sql);
}
// Update the title, summary, and description of the puzzle (from form on puzzle page)
function changeTitleSummaryDescription($uid, $pid, $title, $summary, $description) {
// Check that user can view the puzzle
if (!canViewPuzzle($uid, $pid)) {
utilsError("You do not have permission to modify this puzzle.");
}
// Get the old title, summary, and description
$puzzleInfo = getPuzzleInfo($pid);
$oldTitle = $puzzleInfo["title"];
$oldSummary = $puzzleInfo["summary"];
$oldDescription = $puzzleInfo["description"];
$purifier = getHtmlPurifier();
mysql_query('START TRANSACTION');
// If title has changed, update it
$cleanTitle = htmlspecialchars($title);
if ($oldTitle !== $cleanTitle) {
updateTitle($uid, $pid, $oldTitle, $cleanTitle);
}
// If summary has changed, update it
$cleanSummary = $purifier->purify($summary);
if ($oldSummary !== $cleanSummary) {
updateSummary($uid, $pid, $oldSummary, $cleanSummary);
}
// If description has changed, update it
$cleanDescription = $purifier->purify($description);
if ($oldDescription !== $cleanDescription) {
updateDescription($uid, $pid, $oldDescription, $cleanDescription);
}
// Assuming all went well, commit the changes to the database
mysql_query('COMMIT');
}
function updateTitle($uid = 0, $pid, $oldTitle, $cleanTitle) {
$sql = sprintf("UPDATE puzzles SET title='%s' WHERE id='%s'",
mysql_real_escape_string($cleanTitle), mysql_real_escape_string($pid));
query_db($sql);
$comment = "Changed title from \"$oldTitle\" to \"$cleanTitle\"";
addComment($uid, $pid, $comment, TRUE);
}
function updateSummary($uid = 0, $pid, $oldSummary, $cleanSummary) {
$sql = sprintf("UPDATE puzzles SET summary='%s' WHERE id='%s'",
mysql_real_escape_string($cleanSummary), mysql_real_escape_string($pid));
query_db($sql);
$comment = "<p><strong>Changed summary from:</strong></p>\"$oldSummary\"";
addComment($uid, $pid, $comment, TRUE);
}
function updateDescription($uid = 0, $pid, $oldDescription, $cleanDescription) {
$sql = sprintf("UPDATE puzzles SET description='%s' WHERE id='%s'",
mysql_real_escape_string($cleanDescription), mysql_real_escape_string($pid));
query_db($sql);
$id = time();
$comment = "<p><strong>Changed description</strong></p>";
$comment .= "<p><a class='description' href='#'>[View Old Description]</a></p>";
$comment .= "<div>$oldDescription</div>";
addComment($uid, $pid, $comment, TRUE);
}
function updateCredits($uid = 0, $pid, $oldCredits, $cleanCredits) {
$sql = sprintf("UPDATE puzzles SET credits='%s' WHERE id='%s'",
mysql_real_escape_string($cleanCredits), mysql_real_escape_string($pid));
query_db($sql);
$comment = "Changed credits from \"$oldCredits\" to \"$cleanCredits\"";
addComment($uid, $pid, $comment, TRUE);
}
function updateNotes($uid = 0, $pid, $oldNotes, $cleanNotes) {
$sql = sprintf("UPDATE puzzles SET notes='%s' WHERE id='%s'",
mysql_real_escape_string($cleanNotes), mysql_real_escape_string($pid));
query_db($sql);
$comment = "Changed status notes from \"$oldNotes\" to \"$cleanNotes\"";
addComment($uid, $pid, $comment, TRUE);
}
function updateEditorNotes($uid = 0, $pid, $oldNotes, $cleanNotes) {
$sql = sprintf("UPDATE puzzles SET editor_notes='%s' WHERE id='%s'",
mysql_real_escape_string($cleanNotes), mysql_real_escape_string($pid));
query_db($sql);
$comment = "Changed editor notes from \"$oldNotes\" to \"$cleanNotes\"";
addComment($uid, $pid, $comment, TRUE);
}
function updateRuntime($uid = 0, $pid, $oldRuntime, $cleanRuntime) {
$sql = sprintf("UPDATE puzzles SET runtime_info='%s' WHERE id='%s'",
mysql_real_escape_string($cleanRuntime), mysql_real_escape_string($pid));
query_db($sql);
$comment = "Changed runtime notes from \"$oldRuntime\" to \"$cleanRuntime\"";
addComment($uid, $pid, $comment, TRUE);
}
function updateWikiPage($uid = 0, $pid, $oldWikiPage, $cleanWikiPage) {
$sql = sprintf("UPDATE puzzles SET wikipage ='%s' WHERE id='%s'",
mysql_real_escape_string($cleanWikiPage), mysql_real_escape_string($pid));
query_db($sql);
$comment = "Changed testsolve wiki page from \"$oldWikiPage\" to \"$cleanWikiPage\"";
addComment($uid, $pid, $comment, TRUE);
}
// Get the current answers (including answer id) for a puzzle
// Return an assoc array of type [aid] => [answer]
function getAnswersForPuzzle($pid) {
$sql = sprintf("SELECT aid, answer FROM answers WHERE pid='%s'",
mysql_real_escape_string($pid));
return get_assoc_array($sql, "aid", "answer");
}
function getAnswersAndDeepForPuzzle($pid) {
$sql = sprintf("SELECT aid, answer, deep FROM answers WHERE pid='%s'",
mysql_real_escape_string($pid));
$arr = get_row($sql);
$ret = array();
$ret["aid"] = $arr[0];
$ret["answer"] = $arr[1];
$ret["deep"] = $arr[2];
return $ret;
}
// Get the current answers for a puzzle as a comma separated list
function getAnswersForPuzzleAsList($pid) {
$sql = sprintf("SELECT answer FROM answers WHERE pid='%s'",
mysql_real_escape_string($pid));
$answers = get_elements($sql);
if ($answers) {
return implode(', ', $answers);
} else {
return '';
}
}
// Get available answers
// Return an assoc array of type [aid] => [answer]
function getAvailableAnswers() {
$answers = get_assoc_array("SELECT aid, answer FROM answers WHERE pid IS NULL", "aid", "answer");
natcasesort($answers);
return $answers;
}
function getAvailableAnswersForRound($rid) {
$answers = get_elements(sprintf("SELECT answer FROM answer_round JOIN answers ON answers.aid=answer_round.aid WHERE answer_round.rid='%s'", mysql_real_escape_string($rid)));
natcasesort($answers);
return $answers;
}
function getAvailableAnswersNotForRound($rid) {
$answers = get_elements(sprintf("SELECT answer FROM answer_round JOIN answers ON answers.aid=answer_round.aid WHERE answer_round.rid!='%s'", mysql_real_escape_string($rid)));
natcasesort($answers);
return $answers;
}
// Get count of total answers
function numAnswers() {
$sql = sprintf("SELECT count(*) FROM answers");
return get_element($sql);
}
// Get count of answers that have been assigned
function answersAssigned() {
$sql = sprintf("SELECT count(*) FROM answers WHERE pid IS NOT NULL");
return get_element($sql);
}
// Add and remove puzzle answers
function changeAnswers($uid, $pid, $add, $remove) {
mysql_query('START TRANSACTION');
addAnswers($uid, $pid, $add);
removeAnswers($uid, $pid, $remove);
mysql_query('COMMIT');
}
function addAnswers($uid, $pid, $add) {
if (!$add) {
return;
}
if (!canChangeAnswers($uid)) {
utilsError("You do not have permission to add answers.");
}
foreach ($add as $ans) {
// Check that this answer is available for assignment
if (!isAnswerAvailable($ans)) {
utilsError(getAnswerWord($ans) . ' is not available.');
}
// Add answer to puzzle
$sql = sprintf("UPDATE answers SET pid='%s' WHERE aid='%s'",
mysql_real_escape_string($pid), mysql_real_escape_string($ans));
query_db($sql);
}
$comment = "Assigned answer";
if (count($add) > 1) {
$comment .= "s";
}
addComment($uid, $pid, $comment, TRUE);
}
function removeAnswerKill($uid, $pid, $ans) {
//echo "called: removeAnswerKill with ansid= $ans<br>";
// Check that this answer is assigned to this puzzle
if (!isAnswerOnPuzzle($pid, $ans)) {
utilsError(getAnswerWord($ans) . " is not assigned to puzzle $pid");
}
// Remove answer from puzzle
$sql = sprintf("UPDATE answers SET pid=NULL WHERE aid='%s'",
mysql_real_escape_string($ans));
query_db($sql);
$comment = "Unassigned answer";
addComment($uid, $pid, $comment, TRUE);
}
function removeAnswers($uid, $pid, $remove) {
if (!$remove) {
return;
}
if (!isAuthorOnPuzzle($uid, $pid) && !canChangeAnswers($uid)) {
utilsError("You do not have permission to remove answers.");
}
foreach ($remove as $ans) {
// Check that this answer is assigned to this puzzle
if (!isAnswerOnPuzzle($pid, $ans)) {
utilsError(getAnswerWord($ans) . " is not assigned to puzzle $pid");
}
// Remove answer from puzzle
$sql = sprintf("UPDATE answers SET pid=NULL WHERE aid='%s'",
mysql_real_escape_string($ans));
query_db($sql);
}