]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/command/vote.qc
Fixed normal readying up
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / command / vote.qc
1 #include "vote.qh"
2
3 #include <common/command/_mod.qh>
4 #include <common/constants.qh>
5 #include <common/gamemodes/_mod.qh>
6 #include <common/items/inventory.qh>
7 #include <common/mapinfo.qh>
8 #include <common/net_linked.qh>
9 #include <common/notifications/all.qh>
10 #include <common/playerstats.qh>
11 #include <common/stats.qh>
12 #include <common/util.qh>
13 #include <common/weapons/_all.qh>
14 #include <server/client.qh>
15 #include <server/command/banning.qh>
16 #include <server/command/common.qh>
17 #include <server/command/vote.qh>
18 #include <server/damage.qh>
19 #include <server/gamelog.qh>
20 #include <server/intermission.qh>
21 #include <server/mutators/_mod.qh>
22 #include <server/race.qh>
23 #include <server/round_handler.qh>
24 #include <server/scores.qh>
25 #include <server/teamplay.qh>
26 #include <server/world.qh>
27
28 // =============================================
29 //  Server side voting code, reworked by Samual
30 //  Last updated: December 27th, 2011
31 // =============================================
32
33 //  Nagger for players to know status of voting
34 bool Nagger_SendEntity(entity this, entity to, float sendflags)
35 {
36         int nags, i, f, b;
37         entity e;
38         WriteHeader(MSG_ENTITY, ENT_CLIENT_NAGGER);
39
40         // bits:
41         //   1 = ready
42         //   2 = player needs to ready up
43         //   4 = vote
44         //   8 = player needs to vote
45         //  16 = warmup
46         // sendflags:
47         //  64 = vote counts
48         // 128 = vote string
49
50         nags = 0;
51         if (readycount)
52         {
53                 nags |= BIT(0);
54                 if (to.ready == 0) nags |= BIT(1);
55         }
56         if (vote_called)
57         {
58                 nags |= BIT(2);
59                 if (to.vote_selection == 0) nags |= BIT(3);
60         }
61         if (warmup_stage) nags |= BIT(4);
62
63         if (sendflags & BIT(6)) nags |= BIT(6);
64
65         if (sendflags & BIT(7)) nags |= BIT(7);
66
67         if (!(nags & 4))  // no vote called? send no string
68                 nags &= ~(BIT(6) | BIT(7));
69
70         WriteByte(MSG_ENTITY, nags);
71
72         if (nags & BIT(6))
73         {
74                 WriteByte(MSG_ENTITY, vote_accept_count);
75                 WriteByte(MSG_ENTITY, vote_reject_count);
76                 WriteByte(MSG_ENTITY, vote_needed_overall);
77                 WriteChar(MSG_ENTITY, to.vote_selection);
78         }
79
80         if (nags & BIT(7)) WriteString(MSG_ENTITY, vote_called_display);
81
82         if (nags & 1)
83         {
84                 for (i = 1; i <= maxclients; i += 8)
85                 {
86                         for (f = 0, e = edict_num(i), b = BIT(0); b < BIT(8); b <<= 1, e = nextent(e))
87                                 if (!IS_REAL_CLIENT(e) || e.ready)
88                                         f |= b;
89                         WriteByte(MSG_ENTITY, f);
90                 }
91         }
92
93         return true;
94 }
95
96 void Nagger_Init()
97 {
98         Net_LinkEntity(nagger = new_pure(nagger), false, 0, Nagger_SendEntity);
99 }
100
101 void Nagger_VoteChanged()
102 {
103         if (nagger) nagger.SendFlags |= BIT(7);
104 }
105
106 void Nagger_VoteCountChanged()
107 {
108         if (nagger) nagger.SendFlags |= BIT(6);
109 }
110
111 void Nagger_ReadyCounted()
112 {
113         if (nagger) nagger.SendFlags |= BIT(0);
114 }
115
116 // If the vote_caller is still here, return their name, otherwise vote_caller_name
117 string OriginalCallerName()
118 {
119         if (IS_REAL_CLIENT(vote_caller)) return playername(vote_caller.netname, vote_caller.team, false);
120         return vote_caller_name;
121 }
122
123 // =======================
124 //  Game logic for voting
125 // =======================
126
127 void VoteReset()
128 {
129         FOREACH_CLIENT(true, { it.vote_selection = 0; });
130
131         if (vote_called)
132         {
133                 strfree(vote_called_command);
134                 strfree(vote_called_display);
135                 strfree(vote_caller_name);
136         }
137
138         vote_called = VOTE_NULL;
139         vote_caller = NULL;
140         vote_endtime = 0;
141
142         vote_parsed_command = string_null;
143         vote_parsed_display = string_null;
144
145         Nagger_VoteChanged();
146 }
147
148 void VoteStop(entity stopper)
149 {
150         bprint("\{1}^2* ^3", GetCallerName(stopper), "^2 stopped ^3", OriginalCallerName(), "^2's vote\n");
151         if (autocvar_sv_eventlog)   GameLogEcho(strcat(":vote:vstop:", ftos(stopper.playerid)));
152         // Don't force them to wait for next vote, this way they can e.g. correct their vote.
153         if ((vote_caller) && (stopper == vote_caller))   vote_caller.vote_waittime = time + autocvar_sv_vote_stop;
154         VoteReset();
155 }
156
157 void VoteAccept()
158 {
159         bprint("\{1}^2* ^3", OriginalCallerName(), "^2's vote for ^1", vote_called_display, "^2 was accepted\n");
160
161         if ((vote_called == VOTE_MASTER) && vote_caller) vote_caller.vote_master = 1;
162         else localcmd(strcat(vote_called_command, "\n"));
163
164         if (vote_caller)   vote_caller.vote_waittime = 0;  // people like your votes, you don't need to wait to vote again
165
166         VoteReset();
167         Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_VOTE_ACCEPT);
168 }
169
170 void VoteReject()
171 {
172         bprint("\{1}^2* ^3", OriginalCallerName(), "^2's vote for ", vote_called_display, "^2 was rejected\n");
173         VoteReset();
174         Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_VOTE_FAIL);
175 }
176
177 void VoteTimeout()
178 {
179         bprint("\{1}^2* ^3", OriginalCallerName(), "^2's vote for ", vote_called_display, "^2 timed out\n");
180         VoteReset();
181         Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_VOTE_FAIL);
182 }
183
184 void VoteSpam(float notvoters, float mincount, string result)
185 {
186         bprint(strcat(
187                 strcat("\{1}^2* vote results: ^1", ftos(vote_accept_count)),
188                 strcat("^2:^1", ftos(vote_reject_count)),
189                 ((mincount >= 0) ? strcat("^2 (^1", ftos(mincount), "^2 needed)") : "^2"),
190                 strcat(", ^1", ftos(vote_abstain_count), "^2 didn't care"),
191                 strcat(", ^1", ftos(notvoters), strcat("^2 didn't ", ((mincount >= 0) ? "" : "have to "), "vote\n"))));
192
193         if (autocvar_sv_eventlog)
194         {
195                 GameLogEcho(strcat(
196                         strcat(":vote:v", result, ":", ftos(vote_accept_count)),
197                         strcat(":", ftos(vote_reject_count)),
198                         strcat(":", ftos(vote_abstain_count)),
199                         strcat(":", ftos(notvoters)),
200                         strcat(":", ftos(mincount))));
201         }
202 }
203
204 #define spectators_allowed (!autocvar_sv_vote_nospectators || (autocvar_sv_vote_nospectators == 1 && (warmup_stage || intermission_running)))
205
206 void VoteCount(float first_count)
207 {
208         // declarations
209         vote_accept_count = vote_reject_count = vote_abstain_count = 0;
210
211         float vote_player_count = 0, notvoters = 0;
212         float vote_real_player_count = 0, vote_real_accept_count = 0;
213         float vote_real_reject_count = 0, vote_real_abstain_count = 0;
214         float vote_needed_of_voted, final_needed_votes;
215         float vote_factor_overall, vote_factor_of_voted;
216
217         Nagger_VoteCountChanged();
218
219         // add up all the votes from each connected client
220         FOREACH_CLIENT(IS_REAL_CLIENT(it) && IS_CLIENT(it), {
221                 ++vote_player_count;
222                 if (IS_PLAYER(it))   ++vote_real_player_count;
223                 switch (it.vote_selection)
224                 {
225                         case VOTE_SELECT_REJECT:
226                         { ++vote_reject_count;
227                           { if (IS_PLAYER(it)) ++vote_real_reject_count; } break;
228                         }
229                         case VOTE_SELECT_ACCEPT:
230                         { ++vote_accept_count;
231                           { if (IS_PLAYER(it)) ++vote_real_accept_count; } break;
232                         }
233                         case VOTE_SELECT_ABSTAIN:
234                         { ++vote_abstain_count;
235                           { if (IS_PLAYER(it)) ++vote_real_abstain_count; } break;
236                         }
237                         default: break;
238                 }
239         });
240
241         // Check to see if there are enough players on the server to allow master voting... otherwise, vote master could be used for evil.
242         if ((vote_called == VOTE_MASTER) && autocvar_sv_vote_master_playerlimit > vote_player_count)
243         {
244                 if (vote_caller)   vote_caller.vote_waittime = 0;
245                 print_to(vote_caller, "^1There are not enough players on this server to allow you to become vote master.");
246                 VoteReset();
247                 return;
248         }
249
250         // if spectators aren't allowed to vote and there are players in a match, then only count the players in the vote and ignore spectators.
251         if (!spectators_allowed && (vote_real_player_count > 0))
252         {
253                 vote_accept_count = vote_real_accept_count;
254                 vote_reject_count = vote_real_reject_count;
255                 vote_abstain_count = vote_real_abstain_count;
256                 vote_player_count = vote_real_player_count;
257         }
258
259         // people who have no opinion in any way :D
260         notvoters = (vote_player_count - vote_accept_count - vote_reject_count - vote_abstain_count);
261
262         // determine the goal for the vote to be passed or rejected normally
263         vote_factor_overall = bound(0.5, autocvar_sv_vote_majority_factor, 0.999);
264         vote_needed_overall = floor((vote_player_count - vote_abstain_count) * vote_factor_overall) + 1;
265
266         // if the vote times out, determine the amount of votes needed of the people who actually already voted
267         vote_factor_of_voted = bound(0.5, autocvar_sv_vote_majority_factor_of_voted, 0.999);
268         vote_needed_of_voted = floor((vote_accept_count + vote_reject_count) * vote_factor_of_voted) + 1;
269
270         // are there any players at all on the server? it could be an admin vote
271         if (vote_player_count == 0 && first_count)
272         {
273                 VoteSpam(0, -1, "yes");  // no players at all, just accept it
274                 VoteAccept();
275                 return;
276         }
277
278         // since there ARE players, finally calculate the result of the vote
279         if (vote_accept_count >= vote_needed_overall)
280         {
281                 VoteSpam(notvoters, -1, "yes");  // there is enough acceptions to pass the vote
282                 VoteAccept();
283                 return;
284         }
285
286         if (vote_reject_count > vote_player_count - vote_abstain_count - vote_needed_overall)
287         {
288                 VoteSpam(notvoters, -1, "no");  // there is enough rejections to deny the vote
289                 VoteReject();
290                 return;
291         }
292
293         // there is not enough votes in either direction, now lets just calculate what the voters have said
294         if (time > vote_endtime)
295         {
296                 final_needed_votes = vote_needed_overall;
297
298                 if (autocvar_sv_vote_majority_factor_of_voted)
299                 {
300                         if (vote_accept_count >= vote_needed_of_voted)
301                         {
302                                 VoteSpam(notvoters, min(vote_needed_overall, vote_needed_of_voted), "yes");
303                                 VoteAccept();
304                                 return;
305                         }
306
307                         if (vote_accept_count + vote_reject_count > 0)
308                         {
309                                 VoteSpam(notvoters, min(vote_needed_overall, vote_needed_of_voted), "no");
310                                 VoteReject();
311                                 return;
312                         }
313
314                         final_needed_votes = min(vote_needed_overall, vote_needed_of_voted);
315                 }
316
317                 // it didn't pass or fail, so not enough votes to even make a decision.
318                 VoteSpam(notvoters, final_needed_votes, "timeout");
319                 VoteTimeout();
320         }
321 }
322
323 void VoteThink()
324 {
325         if (vote_endtime > 0)        // a vote was called
326         {
327                 if (time > vote_endtime) // time is up
328                         VoteCount(false);
329         }
330 }
331
332
333 // =======================
334 //  Game logic for warmup
335 // =======================
336
337 // Resets the state of all clients, items, weapons, waypoints, ... of the map.
338 void reset_map(bool dorespawn)
339 {
340         if (time <= game_starttime)
341         {
342                 if (game_stopped)
343                         return;
344                 if (round_handler_IsActive())
345                         round_handler_Reset(game_starttime);
346         }
347
348         if (shuffleteams_on_reset_map)
349         {
350                 shuffleteams();
351                 shuffleteams_on_reset_map = false;
352         }
353
354         FOREACH_CLIENT(IS_PLAYER(it),
355         {
356                 if (STAT(FROZEN, it))
357                         Unfreeze(it, false);
358                 player_powerups_remove_all(it);
359                 entity store = PS(it);
360                 if (store)
361                 {
362                         Inventory_clear(store.inventory);
363                         Inventory_update(store);
364                 }
365         });
366
367         MUTATOR_CALLHOOK(reset_map_global);
368
369         FOREACH_ENTITY_FLOAT_ORDERED(pure_data, false,
370         {
371                 if(IS_CLIENT(it))
372                         continue;
373                 if (it.reset)
374                 {
375                         it.reset(it);
376                         continue;
377                 }
378                 if (it.team_saved) it.team = it.team_saved;
379                 if (it.flags & FL_PROJECTILE) delete(it);  // remove any projectiles left
380         });
381
382         // Waypoints and assault start come LAST
383         FOREACH_ENTITY_ORDERED(IS_NOT_A_CLIENT(it), {
384                 if (it.reset2) it.reset2(it);
385         });
386
387         // Moving the player reset code here since the player-reset depends
388         // on spawnpoint entities which have to be reset first --blub
389         if (dorespawn)
390         {
391                 if (!MUTATOR_CALLHOOK(reset_map_players))
392                 {
393                         //if (restart_mapalreadyrestarted || (time < game_starttime))
394                         //{
395                                 FOREACH_CLIENT(IS_PLAYER(it),
396                                 {
397                                         /*
398                                         only reset players if a restart countdown is active
399                                         this can either be due to cvar sv_ready_restart_after_countdown having set
400                                         restart_mapalreadyrestarted to 1 after the countdown ended or when
401                                         sv_ready_restart_after_countdown is not used and countdown is still running
402                                         */
403                                         // PlayerScore_Clear(it);
404                                         CS(it).killcount = 0;
405                                         // stop the player from moving so that he stands still once he gets respawned
406                                         it.velocity = '0 0 0';
407                                         it.avelocity = '0 0 0';
408                                         CS(it).movement = '0 0 0';
409                                         PutClientInServer(it);
410                                 });
411                         //}
412                 }
413         }
414 }
415
416 // Restarts the map after the countdown is over (and cvar sv_ready_restart_after_countdown is set)
417 void ReadyRestart_think(entity this)
418 {
419         restart_mapalreadyrestarted = true;
420         reset_map(true);
421         Score_ClearAll();
422         delete(this);
423 }
424
425 // Forces a restart of the game without actually reloading the map // this is a mess...
426 void ReadyRestart_force()
427 {
428         if (time <= game_starttime && game_stopped)
429                 return;
430
431         bprint("^1Server is restarting...\n");
432
433         VoteReset();
434
435         // clear overtime, we have to decrease timelimit to its original value again.
436         if (checkrules_overtimesadded > 0 && g_race_qualifying != 2)
437                 cvar_set("timelimit", ftos(autocvar_timelimit - (checkrules_overtimesadded * autocvar_timelimit_overtime)));
438         checkrules_suddendeathend = checkrules_overtimesadded = checkrules_suddendeathwarning = 0;
439         
440         if(!warmup_stage)
441         {
442                 readyrestart_happened = true;
443                 game_starttime = time + RESTART_COUNTDOWN;
444         }
445         else
446         {
447                 readyrestart_happened = false;
448                 game_starttime = 0;
449         }
450
451         // clear player attributes
452         FOREACH_CLIENT(IS_PLAYER(it), {
453                 it.alivetime = 0;
454                 CS(it).killcount = 0;
455                 float val = PlayerStats_GameReport_Event_Player(it, PLAYERSTATS_ALIVETIME, 0);
456                 PlayerStats_GameReport_Event_Player(it, PLAYERSTATS_ALIVETIME, -val);
457         });
458
459         restart_mapalreadyrestarted = false; // reset this var, needed when cvar sv_ready_restart_repeatable is in use
460
461         // disable the warmup global for the server
462         if(!warmup_stage)
463                 localcmd("\nsv_hook_warmupend\n");
464
465         // reset the .ready status of all players (also spectators)
466         FOREACH_CLIENT(IS_REAL_CLIENT(it), { it.ready = false; });
467         readycount = 0;
468         Nagger_ReadyCounted();  // NOTE: this causes a resend of that entity, and will also turn off warmup state on the client
469
470         // lock teams with lockonrestart
471         if (autocvar_teamplay_lockonrestart && teamplay)
472                 lockteams = !warmup_stage;
473
474         // initiate the restart-countdown-announcer entity
475         if (sv_ready_restart_after_countdown && !warmup_stage)
476         {
477                 entity restart_timer = new_pure(restart_timer);
478                 setthink(restart_timer, ReadyRestart_think);
479                 restart_timer.nextthink = game_starttime;
480         }
481
482         // after a restart every players number of allowed timeouts gets reset, too
483         if (autocvar_sv_timeout)
484         {
485                 FOREACH_CLIENT(IS_PLAYER(it) && IS_REAL_CLIENT(it), { CS(it).allowed_timeouts = autocvar_sv_timeout_number; });
486         }
487
488         if (!sv_ready_restart_after_countdown || warmup_stage) reset_map(true);
489         if (autocvar_sv_eventlog) GameLogEcho(":restart");
490 }
491
492 void ReadyRestart()
493 {
494         if (MUTATOR_CALLHOOK(ReadyRestart_Deny) || intermission_running || race_completing) localcmd("restart\n");
495         else localcmd("\nsv_hook_readyrestart\n");
496
497         // Reset ALL scores, but only do that at the beginning of the countdown if sv_ready_restart_after_countdown is off!
498         // Otherwise scores could be manipulated during the countdown.
499         if (!sv_ready_restart_after_countdown) Score_ClearAll();
500         ReadyRestart_force();
501 }
502
503 // Count the players who are ready and determine whether or not to restart the match
504 void ReadyCount()
505 {
506         float ready_needed_factor, ready_needed_count;
507         float t_ready = 0, t_players = 0;
508
509         FOREACH_CLIENT(IS_REAL_CLIENT(it) && (IS_PLAYER(it) || it.caplayer == 1), {
510                 ++t_players;
511                 if (it.ready) ++t_ready;
512         });
513
514         readycount = t_ready;
515
516         Nagger_ReadyCounted();
517
518         ready_needed_factor = bound(0.5, cvar("g_warmup_majority_factor"), 0.999);
519         ready_needed_count = floor(t_players * ready_needed_factor) + 1;
520
521         if (readycount >= ready_needed_count)
522         {
523                 warmup_stage = 0;
524                 ReadyRestart();
525         }
526 }
527
528
529 // ======================================
530 //  Supporting functions for VoteCommand
531 // ======================================
532
533 float Votecommand_check_assignment(entity caller, float assignment)
534 {
535         float from_server = (!caller);
536
537         if ((assignment == VC_ASGNMNT_BOTH)
538             || ((!from_server && assignment == VC_ASGNMNT_CLIENTONLY)
539             || (from_server && assignment == VC_ASGNMNT_SERVERONLY))) return true;
540
541         return false;
542 }
543
544 string VoteCommand_extractcommand(string input, float startpos, int argc)
545 {
546         string output;
547
548         if ((argc - 1) < startpos) output = "";
549         else output = substring(input, argv_start_index(startpos), argv_end_index(-1) - argv_start_index(startpos));
550
551         return output;
552 }
553
554 float VoteCommand_checknasty(string vote_command)
555 {
556         if ((strstrofs(vote_command, ";", 0) >= 0)
557             || (strstrofs(vote_command, "\n", 0) >= 0)
558             || (strstrofs(vote_command, "\r", 0) >= 0)
559             || (strstrofs(vote_command, "$", 0) >= 0)) return false;
560
561         return true;
562 }
563
564 // NOTE: requires input to be surrounded by spaces
565 string VoteCommand_checkreplacements(string input)
566 {
567         string output = input;
568         // allow gotomap replacements
569         output = strreplace(" map ", " gotomap ", output);
570         output = strreplace(" chmap ", " gotomap ", output);
571         return output;
572 }
573
574 float VoteCommand_checkinlist(string vote_command, string list)
575 {
576         string l = VoteCommand_checkreplacements(strcat(" ", list, " "));
577
578         if (strstrofs(l, VoteCommand_checkreplacements(strcat(" ", vote_command, " ")), 0) >= 0) return true;
579
580         return false;
581 }
582
583 string ValidateMap(string validated_map, entity caller)
584 {
585         validated_map = MapInfo_FixName(validated_map);
586
587         if (!validated_map)
588         {
589                 print_to(caller, "This map is not available on this server.");
590                 return string_null;
591         }
592
593         if (!autocvar_sv_vote_override_mostrecent && caller)
594         {
595                 if (Map_IsRecent(validated_map))
596                 {
597                         print_to(caller, "This server does not allow for recent maps to be played again. Please be patient for some rounds.");
598                         return string_null;
599                 }
600         }
601
602         if (!MapInfo_CheckMap(validated_map))
603         {
604                 print_to(caller, strcat("^1Invalid mapname, \"^3", validated_map, "^1\" does not support the current game mode."));
605                 return string_null;
606         }
607
608         return validated_map;
609 }
610
611 float VoteCommand_checkargs(float startpos, int argc)
612 {
613         float p, q, check, minargs;
614         string cvarname = strcat("sv_vote_command_restriction_", argv(startpos));
615         string cmdrestriction = "";  // No we don't.
616         string charlist, arg;
617         float checkmate;
618
619         if(cvar_type(cvarname) & CVAR_TYPEFLAG_EXISTS)
620                 cmdrestriction = cvar_string(cvarname);
621         else
622                 LOG_INFO("NOTE: ", cvarname, " does not exist, no restrictions will be applied.");
623
624         if (cmdrestriction == "") return true;
625
626         ++startpos;  // skip command name
627
628         // check minimum arg count
629
630         // 0 args: argc == startpos
631         // 1 args: argc == startpos + 1
632         // ...
633
634         minargs = stof(cmdrestriction);
635         if (argc - startpos < minargs) return false;
636
637         p = strstrofs(cmdrestriction, ";", 0);  // find first semicolon
638
639         for ( ; ; )
640         {
641                 // we know that at any time, startpos <= argc - minargs
642                 // so this means: argc-minargs >= startpos >= argc, thus
643                 // argc-minargs >= argc, thus minargs <= 0, thus all minargs
644                 // have been seen already
645
646                 if (startpos >= argc) // all args checked? GOOD
647                         break;
648
649                 if (p < 0)            // no more args? FAIL
650                 {
651                         // exception: exactly minargs left, this one included
652                         if (argc - startpos == minargs) break;
653
654                         // otherwise fail
655                         return false;
656                 }
657
658                 // cut to next semicolon
659                 q = strstrofs(cmdrestriction, ";", p + 1);  // find next semicolon
660                 if (q < 0) charlist = substring(cmdrestriction, p + 1, -1);
661                 else charlist = substring(cmdrestriction, p + 1, q - (p + 1));
662
663                 // in case we ever want to allow semicolons in VoteCommand_checknasty
664                 // charlist = strreplace("^^", ";", charlist);
665
666                 if (charlist != "")
667                 {
668                         // verify the arg only contains allowed chars
669                         arg = argv(startpos);
670                         checkmate = strlen(arg);
671                         for (check = 0; check < checkmate; ++check)
672                                 if (strstrofs(charlist, substring(arg, check, 1), 0) < 0) return false;
673                         // not allowed character
674                         // all characters are allowed. FINE.
675                 }
676
677                 ++startpos;
678                 --minargs;
679                 p = q;
680         }
681
682         return true;
683 }
684
685 int VoteCommand_parse(entity caller, string vote_command, string vote_list, float startpos, int argc)
686 {
687         string first_command = argv(startpos);
688         int missing_chars = argv_start_index(startpos);
689
690         if (autocvar_sv_vote_limit > 0 && strlen(vote_command) > autocvar_sv_vote_limit)
691                 return 0;
692
693         if (!VoteCommand_checkinlist(first_command, vote_list)) return 0;
694
695         if (!VoteCommand_checkargs(startpos, argc)) return 0;
696
697         switch (MUTATOR_CALLHOOK(VoteCommand_Parse, caller, first_command, vote_command, startpos, argc))
698         {
699                 case MUT_VOTEPARSE_CONTINUE: { break; }
700                 case MUT_VOTEPARSE_SUCCESS: { return 1; }
701                 case MUT_VOTEPARSE_INVALID: { return -1; }
702                 case MUT_VOTEPARSE_UNACCEPTABLE: { return 0; }
703         }
704
705         switch (first_command) // now go through and parse the proper commands to adjust as needed.
706         {
707                 case "kick":
708                 case "kickban":    // catch all kick/kickban commands
709                 {
710                         entity victim = GetIndexedEntity(argc, (startpos + 1));
711                         float accepted = VerifyClientEntity(victim, true, false);
712
713                         if (accepted > 0)
714                         {
715                                 string reason = "No reason provided";
716                                 if(argc > next_token)
717                                         reason = substring(vote_command, argv_start_index(next_token) - missing_chars, -1);
718
719                                 string command_arguments = reason;
720                                 if (first_command == "kickban")
721                                         command_arguments = strcat(ftos(autocvar_g_ban_default_bantime), " ", ftos(autocvar_g_ban_default_masksize), " ~");
722
723                                 vote_parsed_command = strcat(first_command, " # ", ftos(etof(victim)), " ", command_arguments);
724                                 vote_parsed_display = sprintf("^1%s #%d ^7%s^1 %s", first_command, etof(victim), victim.netname, reason);
725                         }
726                         else
727                         {
728                                 print_to(caller, strcat("vcall: ", GetClientErrorString(accepted, argv(startpos + 1)), ".\n"));
729                                 return 0;
730                         }
731
732                         break;
733                 }
734
735                 case "map":
736                 case "chmap":
737                 case "gotomap":  // re-direct all map selection commands to gotomap
738                 {
739                         vote_command = ValidateMap(argv(startpos + 1), caller);
740                         if (!vote_command)  return -1;
741                         vote_parsed_command = strcat("gotomap ", vote_command);
742                         vote_parsed_display = strzone(strcat("^1", vote_parsed_command));
743
744                         break;
745                 }
746
747                 // TODO: replicate the old behaviour of being able to vote for maps from different modes on multimode servers (possibly support it in gotomap too)
748                 // maybe fallback instead of aborting if map name is invalid?
749                 case "nextmap":
750                 {
751                         vote_command = ValidateMap(argv(startpos + 1), caller);
752                         if (!vote_command)  return -1;
753                         vote_parsed_command = strcat("nextmap ", vote_command);
754                         vote_parsed_display = strzone(strcat("^1", vote_parsed_command));
755
756                         break;
757                 }
758
759                 case "timelimit": // include restrictions on the maximum votable time limit
760                 {
761                         float timelimit_vote = stof(argv(startpos + 1));
762                         if(timelimit_vote > autocvar_timelimit_max || timelimit_vote < autocvar_timelimit_min)
763                         {
764                                 print_to(caller, strcat("Invalid timelimit vote, accepted values are between ", ftos(autocvar_timelimit_min), " and ", ftos(autocvar_timelimit_max), "."));
765                                 return -1;
766                         }
767                         timelimit_vote = bound(autocvar_timelimit_min, timelimit_vote, autocvar_timelimit_max);
768                         vote_parsed_command = strcat("timelimit ", ftos(timelimit_vote));
769                         vote_parsed_display = strzone(strcat("^1", vote_parsed_command));
770
771                         break;
772                 }
773
774                 case "restart":
775                 {
776                         // add a delay so that vote result can be seen and announcer can be heard
777                         // if the vote is accepted
778                         vote_parsed_command = strcat("defer 1 ", vote_command);
779                         vote_parsed_display = strzone(strcat("^1", vote_command));
780
781                         break;
782                 }
783
784                 default:
785                 {
786                         vote_parsed_command = vote_command;
787                         vote_parsed_display = strzone(strcat("^1", vote_command));
788
789                         break;
790                 }
791         }
792
793         return 1;
794 }
795
796
797 // =======================
798 //  Command Sub-Functions
799 // =======================
800
801 void VoteCommand_abstain(int request, entity caller)  // CLIENT ONLY
802 {
803         switch (request)
804         {
805                 case CMD_REQUEST_COMMAND:
806                 {
807                         if (!vote_called) { print_to(caller, "^1No vote called."); }
808                         else if (caller.vote_selection != VOTE_SELECT_NULL && !autocvar_sv_vote_change)
809                         {
810                                 print_to(caller, "^1You have already voted.");
811                         }
812
813                         else  // everything went okay, continue changing vote
814                         {
815                                 print_to(caller, "^1You abstained from your vote.");
816                                 caller.vote_selection = VOTE_SELECT_ABSTAIN;
817                                 msg_entity = caller;
818                                 if (!autocvar_sv_vote_singlecount)
819                                         VoteCount(false);
820                         }
821
822                         return;
823                 }
824
825                 default:
826                 case CMD_REQUEST_USAGE:
827                 {
828                         print_to(caller, strcat("\nUsage:^3 ", GetCommandPrefix(caller), " vote abstain"));
829                         print_to(caller, "  No arguments required.");
830                         return;
831                 }
832         }
833 }
834
835 void print_available_commands_to(entity caller)
836 {
837         print_to(caller, strcat("You can call a vote for or execute these commands: ^3", autocvar_sv_vote_commands, "^7 and maybe further ^3arguments^7"));
838 }
839
840 void VoteCommand_call(int request, entity caller, int argc, string vote_command)  // BOTH
841 {
842         switch (request)
843         {
844                 case CMD_REQUEST_COMMAND:
845                 {
846                         float tmp_playercount = 0;
847                         int parse_error;
848
849                         vote_command = VoteCommand_extractcommand(vote_command, 2, argc);
850
851                         if (!autocvar_sv_vote_call && caller)
852                         {
853                                 print_to(caller, "^1Vote calling is not allowed.");
854                         }
855                         else if (!autocvar_sv_vote_gamestart && time < game_starttime)
856                         {
857                                 print_to(caller, "^1Vote calling is not allowed before the match has started.");
858                         }
859                         else if (vote_called)
860                         {
861                                 print_to(caller, "^1There is already a vote called.");
862                         }
863                         else if (!spectators_allowed && (caller && !IS_PLAYER(caller)))
864                         {
865                                 print_to(caller, "^1Only players can call a vote.");
866                         }
867                         else if (caller && !IS_CLIENT(caller))
868                         {
869                                 print_to(caller, "^1Only connected clients can vote.");
870                         }
871                         else if (timeout_status && vote_command != "timein")
872                         {
873                                 print_to(caller, "^1You can not call a vote while a timeout is active.");
874                         }
875                         else if (caller && (time < caller.vote_waittime))
876                         {
877                                 print_to(caller, strcat("^1You have to wait ^2", ftos(ceil(caller.vote_waittime - time)), "^1 seconds before you can again call a vote."));
878                         }
879                         else if (!VoteCommand_checknasty(vote_command))
880                         {
881                                 print_to(caller, "^1Syntax error in command.");
882                         }
883                         else if ((parse_error = VoteCommand_parse(caller, vote_command, autocvar_sv_vote_commands, 2, argc)) <= 0)
884                         {
885                                 if(parse_error == 0)
886                                 {
887                                         if (vote_called_command == "")
888                                                 VoteCommand_call(CMD_REQUEST_USAGE, caller, argc, vote_command);
889                                         else
890                                                 print_to(caller, "^1This command is not acceptable or not available.");
891                                 }
892                         }
893                         else  // everything went okay, continue with calling the vote
894                         {
895                                 vote_caller = caller;  // remember who called the vote
896                                 vote_caller_name = strzone(GetCallerName(vote_caller));
897                                 vote_called = VOTE_NORMAL;
898                                 vote_called_command = strzone(vote_parsed_command);
899                                 vote_called_display = strzone(vote_parsed_display);
900                                 vote_endtime = time + autocvar_sv_vote_timeout;
901
902                                 if (caller)
903                                 {
904                                         caller.vote_selection = VOTE_SELECT_ACCEPT;
905                                         caller.vote_waittime = time + autocvar_sv_vote_wait;
906                                         msg_entity = caller;
907                                 }
908
909                                 FOREACH_CLIENT(IS_REAL_CLIENT(it), { ++tmp_playercount; });
910
911                                 bprint("\{1}^2* ^3", OriginalCallerName(), "^2 calls a vote for ", vote_called_display, "\n");
912                                 if (autocvar_sv_eventlog)
913                                         GameLogEcho(strcat(":vote:vcall:", ftos(vote_caller.playerid), ":", vote_called_display));
914                                 Nagger_VoteChanged();
915                                 VoteCount(true);  // needed if you are the only one
916
917                                 if (tmp_playercount > 1 && vote_called != VOTE_NULL)
918                                         Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_VOTE_CALL);
919                         }
920
921                         return;
922                 }
923
924                 default:
925                 case CMD_REQUEST_USAGE:
926                 {
927                         print_to(caller, strcat("\nUsage:^3 ", GetCommandPrefix(caller), " vote call <command>"));
928                         print_to(caller, "  Where <command> is the command to request a vote upon.");
929                         print_to(caller, strcat("Examples: ", GetCommandPrefix(caller), " vote call gotomap dance"));
930                         print_to(caller, strcat("          ", GetCommandPrefix(caller), " vote call endmatch"));
931                         print_available_commands_to(caller);
932                         print_to(caller, "Shortcuts: ^2vcall <command>, vend, vmap, vkick, ...");
933                         return;
934                 }
935         }
936 }
937
938 void VoteCommand_master(int request, entity caller, int argc, string vote_command)  // CLIENT ONLY
939 {
940         switch (request)
941         {
942                 case CMD_REQUEST_COMMAND:
943                 {
944                         if (autocvar_sv_vote_master)
945                         {
946                                 switch (strtolower(argv(2)))
947                                 {
948                                         case "do":
949                                         {
950                                                 int parse_error;
951                                                 vote_command = VoteCommand_extractcommand(vote_command, 3, argc);
952
953                                                 if (!caller.vote_master)
954                                                         print_to(caller, "^1You do not have vote master privileges.");
955                                                 else if (!VoteCommand_checknasty(vote_command))
956                                                 {
957                                                         print_to(caller, "^1Syntax error in command.");
958                                                 }
959                                                 else if ((parse_error = VoteCommand_parse(caller, vote_command, strcat(autocvar_sv_vote_commands, " ", autocvar_sv_vote_master_commands), 3, argc)) <= 0)
960                                                 {
961                                                         if(parse_error == 0)
962                                                         {
963                                                                 if (vote_called_command == "")
964                                                                         VoteCommand_master(CMD_REQUEST_USAGE, caller, argc, vote_command);
965                                                                 else
966                                                                         print_to(caller, "^1This command is not acceptable or not available.");
967                                                         }
968                                                 }
969                                                 else  // everything went okay, proceed with command
970                                                 {
971                                                         localcmd(strcat(vote_parsed_command, "\n"));
972                                                         print_to(caller, strcat("Executing command '", vote_parsed_display, "' on server."));
973                                                         bprint("\{1}^2* ^3", GetCallerName(caller), "^2 used their ^3master^2 status to do \"^2", vote_parsed_display, "^2\".\n");
974                                                         if (autocvar_sv_eventlog)
975                                                                 GameLogEcho(strcat(":vote:vdo:", ftos(caller.playerid), ":", vote_parsed_display));
976                                                 }
977
978                                                 return;
979                                         }
980
981                                         case "login":
982                                         {
983                                                 if (autocvar_sv_vote_master_password == "") { print_to(caller, "^1Login to vote master is not allowed."); }
984                                                 else if (caller.vote_master)
985                                                 {
986                                                         print_to(caller, "^1You are already logged in as vote master.");
987                                                 }
988                                                 else if (autocvar_sv_vote_master_password != argv(3))
989                                                 {
990                                                         print_to(caller, strcat("Rejected vote master login from ", GetCallerName(caller)));
991                                                 }
992                                                 else  // everything went okay, proceed with giving this player master privilages
993                                                 {
994                                                         caller.vote_master = true;
995                                                         print_to(caller, strcat("Accepted vote master login from ", GetCallerName(caller)));
996                                                         bprint("\{1}^2* ^3", GetCallerName(caller), "^2 logged in as ^3master^2\n");
997                                                         if (autocvar_sv_eventlog)
998                                                                 GameLogEcho(strcat(":vote:vlogin:", ftos(caller.playerid)));
999                                                 }
1000
1001                                                 return;
1002                                         }
1003
1004                                         default:  // calling a vote for master
1005                                         {
1006                                                 if (!autocvar_sv_vote_master_callable) { print_to(caller, "^1Vote to become vote master is not allowed."); }
1007                                                 else if (vote_called)
1008                                                 {
1009                                                         print_to(caller, "^1There is already a vote called.");
1010                                                 }
1011                                                 else if (!spectators_allowed && (caller && !IS_PLAYER(caller)))
1012                                                 {
1013                                                         print_to(caller, "^1Only players can call a vote.");
1014                                                 }
1015                                                 else if (timeout_status)
1016                                                 {
1017                                                         print_to(caller, "^1You can not call a vote while a timeout is active.");
1018                                                 }
1019                                                 else  // everything went okay, continue with creating vote
1020                                                 {
1021                                                         vote_caller = caller;
1022                                                         vote_caller_name = strzone(GetCallerName(vote_caller));
1023                                                         vote_called = VOTE_MASTER;
1024                                                         vote_called_command = strzone("XXX");
1025                                                         vote_called_display = strzone("^3master");
1026                                                         vote_endtime = time + autocvar_sv_vote_timeout;
1027
1028                                                         caller.vote_selection = VOTE_SELECT_ACCEPT;
1029                                                         caller.vote_waittime = time + autocvar_sv_vote_wait;
1030
1031                                                         bprint("\{1}^2* ^3", OriginalCallerName(), "^2 calls a vote to become ^3master^2.\n");
1032                                                         if (autocvar_sv_eventlog)
1033                                                                 GameLogEcho(strcat(":vote:vcall:", ftos(vote_caller.playerid), ":", vote_called_display));
1034                                                         Nagger_VoteChanged();
1035                                                         VoteCount(true);  // needed if you are the only one
1036                                                 }
1037
1038                                                 return;
1039                                         }
1040                                 }
1041                         }
1042                         else { print_to(caller, "^1Master control of voting is not allowed."); }
1043
1044                         return;
1045                 }
1046
1047                 default:
1048                 case CMD_REQUEST_USAGE:
1049                 {
1050                         print_to(caller, strcat("\nUsage:^3 ", GetCommandPrefix(caller), " vote master [<action> [<command> | <password>]]"));
1051                         print_to(caller, "  If <action> is left blank, it calls a vote for you to become master.");
1052                         print_to(caller, "  Otherwise it can be either 'do' (to run <command>) or 'login' as master.");
1053                         return;
1054                 }
1055         }
1056 }
1057
1058 void VoteCommand_no(int request, entity caller)  // CLIENT ONLY
1059 {
1060         switch (request)
1061         {
1062                 case CMD_REQUEST_COMMAND:
1063                 {
1064                         if (!vote_called) { print_to(caller, "^1No vote called."); }
1065                         else if (caller.vote_selection != VOTE_SELECT_NULL && !autocvar_sv_vote_change)
1066                         {
1067                                 print_to(caller, "^1You have already voted.");
1068                         }
1069                         else if (((caller == vote_caller) || caller.vote_master) && autocvar_sv_vote_no_stops_vote)
1070                         {
1071                                 VoteStop(caller);
1072                         }
1073
1074                         else  // everything went okay, continue changing vote
1075                         {
1076                                 print_to(caller, "^1You rejected the vote.");
1077                                 caller.vote_selection = VOTE_SELECT_REJECT;
1078                                 msg_entity = caller;
1079                                 if (!autocvar_sv_vote_singlecount)
1080                                         VoteCount(false);
1081                         }
1082
1083                         return;
1084                 }
1085
1086                 default:
1087                 case CMD_REQUEST_USAGE:
1088                 {
1089                         print_to(caller, strcat("\nUsage:^3 ", GetCommandPrefix(caller), " vote no"));
1090                         print_to(caller, "  No arguments required.");
1091                         return;
1092                 }
1093         }
1094 }
1095
1096 void VoteCommand_status(int request, entity caller)  // BOTH
1097 {
1098         switch (request)
1099         {
1100                 case CMD_REQUEST_COMMAND:
1101                 {
1102                         if (vote_called) print_to(caller, strcat("^7Vote for ", vote_called_display, "^7 called by ^7", OriginalCallerName(), "^7."));
1103                         else print_to(caller, "^1No vote called.");
1104
1105                         return;
1106                 }
1107
1108                 default:
1109                 case CMD_REQUEST_USAGE:
1110                 {
1111                         print_to(caller, strcat("\nUsage:^3 ", GetCommandPrefix(caller), " vote status"));
1112                         print_to(caller, "  No arguments required.");
1113                         return;
1114                 }
1115         }
1116 }
1117
1118 void VoteCommand_stop(int request, entity caller)  // BOTH
1119 {
1120         switch (request)
1121         {
1122                 case CMD_REQUEST_COMMAND:
1123                 {
1124                         if (!vote_called)   print_to(caller, "^1No vote called.");
1125                         else if ((caller == vote_caller) || !caller || caller.vote_master)   VoteStop(caller);
1126                         else   print_to(caller, "^1You are not allowed to stop that vote.");
1127                         return;
1128                 }
1129
1130                 default:
1131                 case CMD_REQUEST_USAGE:
1132                 {
1133                         print_to(caller, strcat("\nUsage:^3 ", GetCommandPrefix(caller), " vote stop"));
1134                         print_to(caller, "  No arguments required.");
1135                         return;
1136                 }
1137         }
1138 }
1139
1140 void VoteCommand_yes(int request, entity caller)  // CLIENT ONLY
1141 {
1142         switch (request)
1143         {
1144                 case CMD_REQUEST_COMMAND:
1145                 {
1146                         if (!vote_called) { print_to(caller, "^1No vote called."); }
1147                         else if (caller.vote_selection != VOTE_SELECT_NULL && !autocvar_sv_vote_change)
1148                         {
1149                                 print_to(caller, "^1You have already voted.");
1150                         }
1151                         else  // everything went okay, continue changing vote
1152                         {
1153                                 print_to(caller, "^1You accepted the vote.");
1154                                 caller.vote_selection = VOTE_SELECT_ACCEPT;
1155                                 msg_entity = caller;
1156                                 if (!autocvar_sv_vote_singlecount)
1157                                         VoteCount(false);
1158                         }
1159
1160                         return;
1161                 }
1162
1163                 default:
1164                 case CMD_REQUEST_USAGE:
1165                 {
1166                         print_to(caller, strcat("\nUsage:^3 ", GetCommandPrefix(caller), " vote yes"));
1167                         print_to(caller, "  No arguments required.");
1168                         return;
1169                 }
1170         }
1171 }
1172
1173 /* use this when creating a new command, making sure to place it in alphabetical order... also,
1174 ** ADD ALL NEW COMMANDS TO commands.cfg WITH PROPER ALIASES IN THE SAME FASHION!
1175 void VoteCommand_(int request)
1176 {
1177     switch(request)
1178     {
1179         case CMD_REQUEST_COMMAND:
1180         {
1181
1182             return;
1183         }
1184
1185         default:
1186         case CMD_REQUEST_USAGE:
1187         {
1188             print_to(caller, strcat("\nUsage:^3 ", GetCommandPrefix(caller), " vote ");
1189             print_to(caller, "  No arguments required.");
1190             return;
1191         }
1192     }
1193 }
1194 */
1195
1196
1197 // ================================
1198 //  Macro system for vote commands
1199 // ================================
1200
1201 // Do not hard code aliases for these, instead create them in commands.cfg... also: keep in alphabetical order, please ;)
1202 #define VOTE_COMMANDS(request, caller, arguments, command) \
1203         VOTE_COMMAND("abstain", VoteCommand_abstain(request, caller), "Abstain your vote in current vote", VC_ASGNMNT_CLIENTONLY) \
1204         VOTE_COMMAND("call", VoteCommand_call(request, caller, arguments, command), "Create a new vote for players to decide on", VC_ASGNMNT_BOTH) \
1205         VOTE_COMMAND("help", VoteCommand_macro_help(caller, arguments), "Shows this information", VC_ASGNMNT_BOTH) \
1206         VOTE_COMMAND("master", VoteCommand_master(request, caller, arguments, command), "Full control over all voting and vote commands", VC_ASGNMNT_CLIENTONLY) \
1207         VOTE_COMMAND("no", VoteCommand_no(request, caller), "Select no in current vote", VC_ASGNMNT_CLIENTONLY) \
1208         VOTE_COMMAND("status", VoteCommand_status(request, caller), "Prints information about current vote", VC_ASGNMNT_BOTH) \
1209         VOTE_COMMAND("stop", VoteCommand_stop(request, caller), "Immediately end a vote", VC_ASGNMNT_BOTH) \
1210         VOTE_COMMAND("yes", VoteCommand_yes(request, caller), "Select yes in current vote", VC_ASGNMNT_CLIENTONLY) \
1211         /* nothing */
1212
1213 void VoteCommand_macro_help(entity caller, int argc)
1214 {
1215         string command_origin = GetCommandPrefix(caller);
1216
1217         if (argc == 2 || argv(2) == "help")  // help display listing all commands
1218         {
1219                 print_to(caller, "\nVoting commands:\n");
1220                 #define VOTE_COMMAND(name, function, description, assignment) \
1221                         { if (Votecommand_check_assignment(caller, assignment)) { print_to(caller, strcat("  ^2", name, "^7: ", description)); } }
1222
1223                 VOTE_COMMANDS(0, caller, 0, "");
1224                 #undef VOTE_COMMAND
1225
1226                 print_to(caller, strcat("\nUsage:^3 ", command_origin, " vote <command>^7, where possible commands are listed above.\n"));
1227                 print_to(caller, strcat("For help about a specific command, type ", command_origin, " vote help <command>"));
1228                 print_available_commands_to(caller);
1229         }
1230         else  // usage for individual command
1231         {
1232                 #define VOTE_COMMAND(name, function, description, assignment) \
1233                         { if (Votecommand_check_assignment(caller, assignment)) { if (name == strtolower(argv(2))) { function; return; } } }
1234
1235                 VOTE_COMMANDS(CMD_REQUEST_USAGE, caller, argc, "");
1236                 #undef VOTE_COMMAND
1237
1238                 string cvarname = strcat("sv_vote_command_help_", argv(2));
1239                 if(cvar_type(cvarname) & CVAR_TYPEFLAG_EXISTS)
1240                         wordwrap_sprint(caller, cvar_string(cvarname), 1000);
1241                 else if (argv(2) != "")
1242                         print_to(caller, "No documentation exists for this vote");
1243         }
1244 }
1245
1246 float VoteCommand_macro_command(entity caller, int argc, string vote_command)
1247 {
1248         #define VOTE_COMMAND(name, function, description, assignment) \
1249                 { if (Votecommand_check_assignment(caller, assignment)) { if (name == strtolower(argv(1))) { function; return true; } } }
1250
1251         VOTE_COMMANDS(CMD_REQUEST_COMMAND, caller, argc, vote_command);
1252         #undef VOTE_COMMAND
1253
1254         return false;
1255 }
1256
1257
1258 // ======================================
1259 //  Main function handling vote commands
1260 // ======================================
1261
1262 void VoteCommand(int request, entity caller, int argc, string vote_command)
1263 {
1264         // Guide for working with argc arguments by example:
1265         // argc:   1    - 2      - 3     - 4
1266         // argv:   0    - 1      - 2     - 3
1267         // cmd     vote - master - login - password
1268
1269         switch (request)
1270         {
1271                 case CMD_REQUEST_COMMAND:
1272                 {
1273                         if (VoteCommand_macro_command(caller, argc, vote_command)) return;
1274                 }
1275
1276                 default:
1277                         print_to(caller, strcat(((argv(1) != "") ? strcat("Unknown vote command \"", argv(1), "\"") : "No command provided"), ". For a list of supported commands, try ", GetCommandPrefix(caller), " vote help.\n"));
1278                 case CMD_REQUEST_USAGE:
1279                 {
1280                         VoteCommand_macro_help(caller, argc);
1281                         return;
1282                 }
1283         }
1284 }