From 248a6fd50cc92a8964567929b83cb1910d349738 Mon Sep 17 00:00:00 2001
From: Jordie <4343468+Jordie0608@users.noreply.github.com>
Date: Mon, 11 May 2020 12:34:51 +1000
Subject: [PATCH] Datum based poll creation and vote handling update (#50843)
An almost complete rework of how creating polls, their data and voting on them is handled.
Instead of repeatedly querying for poll data, running polls are loaded at runtime into poll_question and poll_option datums that stores all the needed variables for both. This datum is then used for creating, editing and accessing poll data. The database is only contacted when saving changes or votes.
Creating polls and options is now done with a html window instead of a series of popups akin to how the banning panel works. The form data is parsed and error-checked before passing to be saved.
This is done in two stages, first time a poll's details are entered and it must be initialized (created as a datum) before options can be added and all of both are saved to the database. Instructions about how this work are shown on the poll creation window.
A new field for polls has been added, subtitles, which is text only shown when a poll is opened by a player instead of on the list of polls. Intended so the actual question text can be kept to only a name and important information about a poll goes in a subtitle.
All polls can now have revoting enabled on them.
Polls can have a starting datetime specified, this can be in the past but why would you do that?
Polls and options can be edited once created, excluding the type of a poll. Doing so will by default clear all existing poll votes. Votes can also be cleared by a button.
The handling of how votes are processed has been adapted for the datum system but is on the whole not functionally that different aside from poll validation not being roughly copypasted across each poll type's vote proc
All poll tables now have a deleted column for retaining 'deleted' data.
poll_question has also gained the columns created_datetime, subtitle, allow_revoting, their function explained above, and a change of idx_pquest_time_admin to idx_pquest_time_deleted_id.
A stored procedure set_poll_deleted has been added. This is called when setting a poll as deleted to avoid needing 4 separate queries from the server or one fairly long 4-way joined
Create Poll verb is renamed to Server Poll Management
---
SQL/database_changelog.txt | 47 +-
SQL/tgstation_schema.sql | 48 +-
SQL/tgstation_schema_prefixed.sql | 48 +-
code/__DEFINES/subsystems.dm | 2 +-
code/_globalvars/misc.dm | 8 +
code/game/world.dm | 1 +
code/modules/admin/admin_verbs.dm | 9 +-
code/modules/admin/create_poll.dm | 150 ---
code/modules/admin/poll_management.dm | 735 +++++++++++
code/modules/admin/sql_ban_system.dm | 3 +-
code/modules/admin/topic.dm | 49 +
.../modules/mob/dead/new_player/new_player.dm | 109 +-
code/modules/mob/dead/new_player/poll.dm | 1080 ++++++++---------
html/admin/admin_panels.css | 42 +
...anpanel_css3.css => admin_panels_css3.css} | 0
html/admin/banpanel.css | 33 -
tgstation.dme | 2 +-
17 files changed, 1460 insertions(+), 906 deletions(-)
delete mode 100644 code/modules/admin/create_poll.dm
create mode 100644 code/modules/admin/poll_management.dm
create mode 100644 html/admin/admin_panels.css
rename html/admin/{banpanel_css3.css => admin_panels_css3.css} (100%)
diff --git a/SQL/database_changelog.txt b/SQL/database_changelog.txt
index 2684cf032a8..c204cbaaf92 100644
--- a/SQL/database_changelog.txt
+++ b/SQL/database_changelog.txt
@@ -1,15 +1,56 @@
Any time you make a change to the schema files, remember to increment the database schema version. Generally increment the minor number, major should be reserved for significant changes to the schema. Both values go up to 255.
-The latest database version is 5.8; The query to update the schema revision table is:
+The latest database version is 5.9; The query to update the schema revision table is:
-INSERT INTO `schema_revision` (`major`, `minor`) VALUES (5, 8);
+INSERT INTO `schema_revision` (`major`, `minor`) VALUES (5, 9);
or
-INSERT INTO `SS13_schema_revision` (`major`, `minor`) VALUES (5, 8);
+INSERT INTO `SS13_schema_revision` (`major`, `minor`) VALUES (5, 9);
In any query remember to add a prefix to the table names if you use one.
-----------------------------------------------------
+Version 5.9, 19 April 2020, by Jordie0608
+Updates and improvements to poll handling.
+Added the `deleted` column to tables 'poll_option', 'poll_textreply' and 'poll_vote' and the columns `created_datetime`, `subtitle`, `allow_revoting` and `deleted` to 'poll_question'.
+Changes table 'poll_question' column `createdby_ckey` to be NOT NULL and index `idx_pquest_time_admin` to be `idx_pquest_time_deleted_id` and 'poll_textreply' column `adminrank` to have no default.
+Added procedure `set_poll_deleted` that's called when deleting a poll to set deleted to true on each poll table where rows matching a poll_id argument.
+
+ALTER TABLE `poll_option`
+ ADD COLUMN `deleted` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0' AFTER `default_percentage_calc`;
+
+ALTER TABLE `poll_question`
+ CHANGE COLUMN `createdby_ckey` `createdby_ckey` VARCHAR(32) NOT NULL AFTER `multiplechoiceoptions`,
+ ADD COLUMN `created_datetime` datetime NOT NULL AFTER `polltype`,
+ ADD COLUMN `subtitle` VARCHAR(255) NULL DEFAULT NULL AFTER `question`,
+ ADD COLUMN `allow_revoting` TINYINT(1) UNSIGNED NOT NULL AFTER `dontshow`,
+ ADD COLUMN `deleted` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0' AFTER `allow_revoting`,
+ DROP INDEX `idx_pquest_time_admin`,
+ ADD INDEX `idx_pquest_time_deleted_id` (`starttime`, `endtime`, `deleted`, `id`);
+
+ALTER TABLE `poll_textreply`
+ CHANGE COLUMN `adminrank` `adminrank` varchar(32) NOT NULL AFTER `replytext`,
+ ADD COLUMN `deleted` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0' AFTER `adminrank`;
+
+ALTER TABLE `poll_vote`
+ ADD COLUMN `deleted` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0' AFTER `rating`;
+
+DELIMITER $$
+CREATE PROCEDURE `set_poll_deleted`(
+ IN `poll_id` INT
+)
+SQL SECURITY INVOKER
+BEGIN
+UPDATE `poll_question` SET deleted = 1 WHERE id = poll_id;
+UPDATE `poll_option` SET deleted = 1 WHERE pollid = poll_id;
+UPDATE `poll_vote` SET deleted = 1 WHERE pollid = poll_id;
+UPDATE `poll_textreply` SET deleted = 1 WHERE pollid = poll_id;
+END
+$$
+DELIMITER ;
+
+-----------------------------------------------------
+
Version 5.8, 7 April 2020, by Jordie0608
Modified table `messages`, adding column `deleted_ckey` to record who deleted a message.
diff --git a/SQL/tgstation_schema.sql b/SQL/tgstation_schema.sql
index f03788e14c4..1f5edef8c57 100644
--- a/SQL/tgstation_schema.sql
+++ b/SQL/tgstation_schema.sql
@@ -346,6 +346,7 @@ CREATE TABLE `poll_option` (
`descmid` varchar(32) DEFAULT NULL,
`descmax` varchar(32) DEFAULT NULL,
`default_percentage_calc` tinyint(1) unsigned NOT NULL DEFAULT '1',
+ `deleted` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_pop_pollid` (`pollid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
@@ -361,17 +362,21 @@ DROP TABLE IF EXISTS `poll_question`;
CREATE TABLE `poll_question` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`polltype` enum('OPTION','TEXT','NUMVAL','MULTICHOICE','IRV') NOT NULL,
+ `created_datetime` datetime NOT NULL,
`starttime` datetime NOT NULL,
`endtime` datetime NOT NULL,
`question` varchar(255) NOT NULL,
+ `subtitle` varchar(255) DEFAULT NULL,
`adminonly` tinyint(1) unsigned NOT NULL,
`multiplechoiceoptions` int(2) DEFAULT NULL,
- `createdby_ckey` varchar(32) DEFAULT NULL,
+ `createdby_ckey` varchar(32) NOT NULL,
`createdby_ip` int(10) unsigned NOT NULL,
`dontshow` tinyint(1) unsigned NOT NULL,
+ `allow_revoting` tinyint(1) unsigned NOT NULL,
+ `deleted` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_pquest_question_time_ckey` (`question`,`starttime`,`endtime`,`createdby_ckey`,`createdby_ip`),
- KEY `idx_pquest_time_admin` (`starttime`,`endtime`,`adminonly`),
+ KEY `idx_pquest_time_deleted_id` (`starttime`,`endtime`, `deleted`, `id`),
KEY `idx_pquest_id_time_type_admin` (`id`,`starttime`,`endtime`,`polltype`,`adminonly`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -390,7 +395,8 @@ CREATE TABLE `poll_textreply` (
`ckey` varchar(32) NOT NULL,
`ip` int(10) unsigned NOT NULL,
`replytext` varchar(2048) NOT NULL,
- `adminrank` varchar(32) NOT NULL DEFAULT 'Player',
+ `adminrank` varchar(32) NOT NULL,
+ `deleted` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_ptext_pollid_ckey` (`pollid`,`ckey`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
@@ -412,6 +418,7 @@ CREATE TABLE `poll_vote` (
`ip` int(10) unsigned NOT NULL,
`adminrank` varchar(32) NOT NULL,
`rating` int(2) DEFAULT NULL,
+ `deleted` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_pvote_pollid_ckey` (`pollid`,`ckey`),
KEY `idx_pvote_optionid_ckey` (`optionid`,`ckey`)
@@ -455,18 +462,6 @@ CREATE TABLE `schema_revision` (
PRIMARY KEY (`major`, `minor`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-DELIMITER $$
-CREATE TRIGGER `role_timeTlogupdate` AFTER UPDATE ON `role_time` FOR EACH ROW BEGIN INSERT into role_time_log (ckey, job, delta) VALUES (NEW.CKEY, NEW.job, NEW.minutes-OLD.minutes);
-END
-$$
-CREATE TRIGGER `role_timeTloginsert` AFTER INSERT ON `role_time` FOR EACH ROW BEGIN INSERT into role_time_log (ckey, job, delta) VALUES (NEW.ckey, NEW.job, NEW.minutes);
-END
-$$
-CREATE TRIGGER `role_timeTlogdelete` AFTER DELETE ON `role_time` FOR EACH ROW BEGIN INSERT into role_time_log (ckey, job, delta) VALUES (OLD.ckey, OLD.job, 0-OLD.minutes);
-END
-$$
-DELIMITER ;
-
--
-- Table structure for table `stickyban`
--
@@ -556,6 +551,29 @@ CREATE TABLE `ticket` (
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+DELIMITER $$
+CREATE PROCEDURE `set_poll_deleted`(
+ IN `poll_id` INT
+)
+SQL SECURITY INVOKER
+BEGIN
+UPDATE `poll_question` SET deleted = 1 WHERE id = poll_id;
+UPDATE `poll_option` SET deleted = 1 WHERE pollid = poll_id;
+UPDATE `poll_vote` SET deleted = 1 WHERE pollid = poll_id;
+UPDATE `poll_textreply` SET deleted = 1 WHERE pollid = poll_id;
+END
+$$
+CREATE TRIGGER `role_timeTlogupdate` AFTER UPDATE ON `role_time` FOR EACH ROW BEGIN INSERT into role_time_log (ckey, job, delta) VALUES (NEW.CKEY, NEW.job, NEW.minutes-OLD.minutes);
+END
+$$
+CREATE TRIGGER `role_timeTloginsert` AFTER INSERT ON `role_time` FOR EACH ROW BEGIN INSERT into role_time_log (ckey, job, delta) VALUES (NEW.ckey, NEW.job, NEW.minutes);
+END
+$$
+CREATE TRIGGER `role_timeTlogdelete` AFTER DELETE ON `role_time` FOR EACH ROW BEGIN INSERT into role_time_log (ckey, job, delta) VALUES (OLD.ckey, OLD.job, 0-OLD.minutes);
+END
+$$
+DELIMITER ;
+
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
diff --git a/SQL/tgstation_schema_prefixed.sql b/SQL/tgstation_schema_prefixed.sql
index 8a4de26c263..cf4818c30c9 100644
--- a/SQL/tgstation_schema_prefixed.sql
+++ b/SQL/tgstation_schema_prefixed.sql
@@ -346,6 +346,7 @@ CREATE TABLE `SS13_poll_option` (
`descmid` varchar(32) DEFAULT NULL,
`descmax` varchar(32) DEFAULT NULL,
`default_percentage_calc` tinyint(1) unsigned NOT NULL DEFAULT '1',
+ `deleted` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_pop_pollid` (`pollid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
@@ -361,17 +362,21 @@ DROP TABLE IF EXISTS `SS13_poll_question`;
CREATE TABLE `SS13_poll_question` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`polltype` enum('OPTION','TEXT','NUMVAL','MULTICHOICE','IRV') NOT NULL,
+ `created_datetime` datetime NOT NULL,
`starttime` datetime NOT NULL,
`endtime` datetime NOT NULL,
`question` varchar(255) NOT NULL,
+ `subtitle` varchar(255) DEFAULT NULL,
`adminonly` tinyint(1) unsigned NOT NULL,
`multiplechoiceoptions` int(2) DEFAULT NULL,
- `createdby_ckey` varchar(32) DEFAULT NULL,
+ `createdby_ckey` varchar(32) NOT NULL,
`createdby_ip` int(10) unsigned NOT NULL,
`dontshow` tinyint(1) unsigned NOT NULL,
+ `allow_revoting` tinyint(1) unsigned NOT NULL,
+ `deleted` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_pquest_question_time_ckey` (`question`,`starttime`,`endtime`,`createdby_ckey`,`createdby_ip`),
- KEY `idx_pquest_time_admin` (`starttime`,`endtime`,`adminonly`),
+ KEY `idx_pquest_time_deleted_id` (`starttime`,`endtime`, `deleted`, `id`),
KEY `idx_pquest_id_time_type_admin` (`id`,`starttime`,`endtime`,`polltype`,`adminonly`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -390,7 +395,8 @@ CREATE TABLE `SS13_poll_textreply` (
`ckey` varchar(32) NOT NULL,
`ip` int(10) unsigned NOT NULL,
`replytext` varchar(2048) NOT NULL,
- `adminrank` varchar(32) NOT NULL DEFAULT 'Player',
+ `adminrank` varchar(32) NOT NULL,
+ `deleted` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_ptext_pollid_ckey` (`pollid`,`ckey`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
@@ -412,6 +418,7 @@ CREATE TABLE `SS13_poll_vote` (
`ip` int(10) unsigned NOT NULL,
`adminrank` varchar(32) NOT NULL,
`rating` int(2) DEFAULT NULL,
+ `deleted` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_pvote_pollid_ckey` (`pollid`,`ckey`),
KEY `idx_pvote_optionid_ckey` (`optionid`,`ckey`)
@@ -455,18 +462,6 @@ CREATE TABLE `SS13_schema_revision` (
PRIMARY KEY (`major`,`minor`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-DELIMITER $$
-CREATE TRIGGER `SS13_role_timeTlogupdate` AFTER UPDATE ON `SS13_role_time` FOR EACH ROW BEGIN INSERT into SS13_role_time_log (ckey, job, delta) VALUES (NEW.CKEY, NEW.job, NEW.minutes-OLD.minutes);
-END
-$$
-CREATE TRIGGER `SS13_role_timeTloginsert` AFTER INSERT ON `SS13_role_time` FOR EACH ROW BEGIN INSERT into SS13_role_time_log (ckey, job, delta) VALUES (NEW.ckey, NEW.job, NEW.minutes);
-END
-$$
-CREATE TRIGGER `SS13_role_timeTlogdelete` AFTER DELETE ON `SS13_role_time` FOR EACH ROW BEGIN INSERT into SS13_role_time_log (ckey, job, delta) VALUES (OLD.ckey, OLD.job, 0-OLD.minutes);
-END
-$$
-DELIMITER ;
-
--
-- Table structure for table `SS13_stickyban`
--
@@ -556,6 +551,29 @@ CREATE TABLE `SS13_ticket` (
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+DELIMITER $$
+CREATE PROCEDURE `set_poll_deleted`(
+ IN `poll_id` INT
+)
+SQL SECURITY INVOKER
+BEGIN
+UPDATE `SS13_poll_question` SET deleted = 1 WHERE id = poll_id;
+UPDATE `SS13_poll_option` SET deleted = 1 WHERE pollid = poll_id;
+UPDATE `SS13_poll_vote` SET deleted = 1 WHERE pollid = poll_id;
+UPDATE `SS13_poll_textreply` SET deleted = 1 WHERE pollid = poll_id;
+END
+$$
+CREATE TRIGGER `SS13_role_timeTlogupdate` AFTER UPDATE ON `SS13_role_time` FOR EACH ROW BEGIN INSERT into SS13_role_time_log (ckey, job, delta) VALUES (NEW.CKEY, NEW.job, NEW.minutes-OLD.minutes);
+END
+$$
+CREATE TRIGGER `SS13_role_timeTloginsert` AFTER INSERT ON `SS13_role_time` FOR EACH ROW BEGIN INSERT into SS13_role_time_log (ckey, job, delta) VALUES (NEW.ckey, NEW.job, NEW.minutes);
+END
+$$
+CREATE TRIGGER `SS13_role_timeTlogdelete` AFTER DELETE ON `SS13_role_time` FOR EACH ROW BEGIN INSERT into SS13_role_time_log (ckey, job, delta) VALUES (OLD.ckey, OLD.job, 0-OLD.minutes);
+END
+$$
+DELIMITER ;
+
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
diff --git a/code/__DEFINES/subsystems.dm b/code/__DEFINES/subsystems.dm
index 6efb38b7785..515f9f485fb 100644
--- a/code/__DEFINES/subsystems.dm
+++ b/code/__DEFINES/subsystems.dm
@@ -20,7 +20,7 @@
*
* make sure you add an update to the schema_version stable in the db changelog
*/
-#define DB_MINOR_VERSION 8
+#define DB_MINOR_VERSION 9
//! ## Timing subsystem
diff --git a/code/_globalvars/misc.dm b/code/_globalvars/misc.dm
index 70ac73929a2..1de2cd22fca 100644
--- a/code/_globalvars/misc.dm
+++ b/code/_globalvars/misc.dm
@@ -17,4 +17,12 @@ GLOBAL_VAR_INIT(bsa_unlock, FALSE) //BSA unlocked by head ID swipes
GLOBAL_LIST_EMPTY(player_details) // ckey -> /datum/player_details
+///All currently running polls held as datums
+GLOBAL_LIST_EMPTY(polls)
+GLOBAL_PROTECT(polls)
+
+///All poll option datums of running polls
+GLOBAL_LIST_EMPTY(poll_options)
+GLOBAL_PROTECT(poll_options)
+
GLOBAL_VAR_INIT(internal_tick_usage, 0.2 * world.tick_lag)
diff --git a/code/game/world.dm b/code/game/world.dm
index 4e290ea9b1f..f7526730771 100644
--- a/code/game/world.dm
+++ b/code/game/world.dm
@@ -50,6 +50,7 @@ GLOBAL_VAR(restart_counter)
SSdbcore.CheckSchemaVersion()
SSdbcore.SetRoundID()
SetupLogs()
+ load_poll_data()
#ifndef USE_CUSTOM_ERROR_HANDLER
world.log = file("[GLOB.log_directory]/dd.log")
diff --git a/code/modules/admin/admin_verbs.dm b/code/modules/admin/admin_verbs.dm
index 3a8730a39af..39973b2f755 100644
--- a/code/modules/admin/admin_verbs.dm
+++ b/code/modules/admin/admin_verbs.dm
@@ -171,7 +171,7 @@ GLOBAL_LIST_INIT(admin_verbs_possess, list(/proc/possess, /proc/release))
GLOBAL_PROTECT(admin_verbs_possess)
GLOBAL_LIST_INIT(admin_verbs_permissions, list(/client/proc/edit_admin_permissions))
GLOBAL_PROTECT(admin_verbs_permissions)
-GLOBAL_LIST_INIT(admin_verbs_poll, list(/client/proc/create_poll))
+GLOBAL_LIST_INIT(admin_verbs_poll, list(/client/proc/poll_panel))
GLOBAL_PROTECT(admin_verbs_poll)
//verbs which can be hidden - needs work
@@ -401,6 +401,13 @@ GLOBAL_PROTECT(admin_verbs_hideable)
holder.Secrets()
SSblackbox.record_feedback("tally", "admin_verb", 1, "Secrets Panel") //If you are copy-pasting this, ensure the 2nd parameter is unique to the new proc!
+/client/proc/poll_panel()
+ set name = "Server Poll Management"
+ set category = "Admin"
+ if(!check_rights(R_POLL))
+ return
+ holder.poll_list_panel()
+ SSblackbox.record_feedback("tally", "admin_verb", 1, "Server Poll Management") //If you are copy-pasting this, ensure the 2nd parameter is unique to the new proc!
/client/proc/findStealthKey(txt)
if(txt)
diff --git a/code/modules/admin/create_poll.dm b/code/modules/admin/create_poll.dm
deleted file mode 100644
index 495ee420bfa..00000000000
--- a/code/modules/admin/create_poll.dm
+++ /dev/null
@@ -1,150 +0,0 @@
-/client/proc/create_poll()
- set name = "Create Poll"
- set category = "Admin"
- if(!check_rights(R_POLL))
- return
- if(!SSdbcore.Connect())
- to_chat(src, "Failed to establish database connection.", confidential = TRUE)
- return
- var/polltype = input("Choose poll type.","Poll Type") as null|anything in list("Single Option","Text Reply","Rating","Multiple Choice", "Instant Runoff Voting")
- var/choice_amount = 0
- switch(polltype)
- if("Single Option")
- polltype = POLLTYPE_OPTION
- if("Text Reply")
- polltype = POLLTYPE_TEXT
- if("Rating")
- polltype = POLLTYPE_RATING
- if("Multiple Choice")
- polltype = POLLTYPE_MULTI
- choice_amount = input("How many choices should be allowed?","Select choice amount") as num|null
- switch(choice_amount)
- if(0)
- to_chat(src, "Multiple choice poll must have at least one choice allowed.", confidential = TRUE)
- return
- if(1)
- polltype = POLLTYPE_OPTION
- if(null)
- return
- if ("Instant Runoff Voting")
- polltype = POLLTYPE_IRV
- else
- return 0
- var/starttime = SQLtime()
- var/endtime = input("Set end time for poll as format YYYY-MM-DD HH:MM:SS. All times in server time. HH:MM:SS is optional and 24-hour. Must be later than starting time for obvious reasons.", "Set end time", SQLtime()) as text|null
- if(!endtime)
- return
- endtime = sanitizeSQL(endtime)
- var/datum/DBQuery/query_validate_time = SSdbcore.NewQuery("SELECT IF(STR_TO_DATE('[endtime]','%Y-%c-%d %T') > NOW(), STR_TO_DATE('[endtime]','%Y-%c-%d %T'), 0)")
- if(!query_validate_time.warn_execute() || QDELETED(usr) || !src)
- qdel(query_validate_time)
- return
- if(query_validate_time.NextRow())
- var/checktime = text2num(query_validate_time.item[1])
- if(!checktime)
- to_chat(src, "Datetime entered is improperly formatted or not later than current server time.", confidential = TRUE)
- qdel(query_validate_time)
- return
- endtime = query_validate_time.item[1]
- qdel(query_validate_time)
- var/adminonly
- switch(alert("Admin only poll?",,"Yes","No","Cancel"))
- if("Yes")
- adminonly = 1
- if("No")
- adminonly = 0
- else
- return
- var/dontshow
- switch(alert("Hide poll results from tracking until completed?",,"Yes","No","Cancel"))
- if("Yes")
- dontshow = 1
- if("No")
- dontshow = 0
- else
- return
- var/sql_ckey = sanitizeSQL(ckey)
- var/question = input("Write your question","Question") as message|null
- if(!question)
- return
- question = sanitizeSQL(question)
- var/list/sql_option_list = list()
- if(polltype != POLLTYPE_TEXT)
- var/add_option = 1
- while(add_option)
- var/option = input("Write your option","Option") as message|null
- if(!option)
- return
- option = sanitizeSQL(option)
- var/default_percentage_calc = 0
- if(polltype != POLLTYPE_IRV)
- switch(alert("Should this option be included by default when poll result percentages are generated?",,"Yes","No","Cancel"))
- if("Yes")
- default_percentage_calc = 1
- if("No")
- default_percentage_calc = 0
- else
- return
- var/minval = 0
- var/maxval = 0
- var/descmin = ""
- var/descmid = ""
- var/descmax = ""
- if(polltype == POLLTYPE_RATING)
- minval = input("Set minimum rating value.","Minimum rating") as num|null
- if(minval)
- minval = sanitizeSQL(minval)
- else if(minval == null)
- return
- maxval = input("Set maximum rating value.","Maximum rating") as num|null
- if(maxval)
- maxval = sanitizeSQL(maxval)
- if(minval >= maxval)
- to_chat(src, "Maximum rating value can't be less than or equal to minimum rating value", confidential = TRUE)
- continue
- else if(maxval == null)
- return
- descmin = input("Optional: Set description for minimum rating","Minimum rating description") as message|null
- if(descmin)
- descmin = sanitizeSQL(descmin)
- else if(descmin == null)
- return
- descmid = input("Optional: Set description for median rating","Median rating description") as message|null
- if(descmid)
- descmid = sanitizeSQL(descmid)
- else if(descmid == null)
- return
- descmax = input("Optional: Set description for maximum rating","Maximum rating description") as message|null
- if(descmax)
- descmax = sanitizeSQL(descmax)
- else if(descmax == null)
- return
- sql_option_list += list(list("text" = "'[option]'", "minval" = "'[minval]'", "maxval" = "'[maxval]'", "descmin" = "'[descmin]'", "descmid" = "'[descmid]'", "descmax" = "'[descmax]'", "default_percentage_calc" = "'[default_percentage_calc]'"))
- switch(alert(" ",,"Add option","Finish", "Cancel"))
- if("Add option")
- add_option = 1
- if("Finish")
- add_option = 0
- else
- return 0
- var/m1 = "[key_name(usr)] has created a new server poll. Poll type: [polltype] - Admin Only: [adminonly ? "Yes" : "No"] - Question: [question]"
- var/m2 = "[key_name_admin(usr)] has created a new server poll. Poll type: [polltype] - Admin Only: [adminonly ? "Yes" : "No"] Question: [question]"
- var/datum/DBQuery/query_polladd_question = SSdbcore.NewQuery("INSERT INTO [format_table_name("poll_question")] (polltype, starttime, endtime, question, adminonly, multiplechoiceoptions, createdby_ckey, createdby_ip, dontshow) VALUES ('[polltype]', '[starttime]', '[endtime]', '[question]', '[adminonly]', '[choice_amount]', '[sql_ckey]', INET_ATON('[address]'), '[dontshow]')")
- if(!query_polladd_question.warn_execute())
- qdel(query_polladd_question)
- return
- qdel(query_polladd_question)
- if(polltype != POLLTYPE_TEXT)
- var/pollid = 0
- var/datum/DBQuery/query_get_id = SSdbcore.NewQuery("SELECT LAST_INSERT_ID()")
- if(!query_get_id.warn_execute())
- qdel(query_get_id)
- return
- if(query_get_id.NextRow())
- pollid = query_get_id.item[1]
- qdel(query_get_id)
- for(var/list/i in sql_option_list)
- i |= list("pollid" = "'[pollid]'")
- SSdbcore.MassInsert(format_table_name("poll_option"), sql_option_list, warn = 1)
- log_admin(m1)
- message_admins(m2)
diff --git a/code/modules/admin/poll_management.dm b/code/modules/admin/poll_management.dm
new file mode 100644
index 00000000000..f7062ad1722
--- /dev/null
+++ b/code/modules/admin/poll_management.dm
@@ -0,0 +1,735 @@
+/**
+ * Datum which holds details of a running poll loaded from the database and supplementary info.
+ *
+ * Used to minimize the need for querying this data every time it's needed.
+ *
+ */
+/datum/poll_question
+ ///Reference list of the options for this poll, not used by text response polls.
+ var/list/options = list()
+ ///Table id of this poll, will be null until poll has been created.
+ var/poll_id
+ ///The type of poll to be created, must be POLLTYPE_OPTION, POLLTYPE_TEXT, POLLTYPE_RATING, POLLTYPE_MULTI or POLLTYPE_IRV.
+ var/poll_type
+ ///Count of how many players have voted or responded to this poll.
+ var/poll_votes
+ ///Ckey of the poll's original author
+ var/created_by
+ ///Date and time the poll opens, timestamp format is YYYY-MM-DD HH:MM:SS.
+ var/start_datetime
+ ///Date and time the poll will run until, timestamp format is YYYY-MM-DD HH:MM:SS.
+ var/end_datetime
+ ///The title text of the poll, shows up on the list of polls.
+ var/question
+ ///Supplementary text displayed only when responding to a poll.
+ var/subtitle
+ ///Hides the poll from any client without a holder datum.
+ var/admin_only
+ ///The number of responses allowed in a multiple-choice poll, more can be selected but won't be recorded.
+ var/options_allowed
+ ///Hint for statbus, not used by the game; Stops the results of a poll from being displayed until the end_datetime is reached.
+ var/dont_show
+ ///Allows a player to change their vote to a poll they've already voted on, off by default.
+ var/allow_revoting
+ ///Indicates if a poll has been submitted or loaded from the DB so the management panel will open with edit functions.
+ var/edit_ready = FALSE
+ ///Holds duration data when creating or editing a poll and refreshing the poll creation window.
+ var/duration
+ ///Holds interval data when creating or editing a poll and refreshing the poll creation window.
+ var/interval
+ ///Indicates a poll is set to not start in the future, still visible for editing but not voting on.
+ var/future_poll
+
+/**
+ * Datum which holds details of a poll option loaded from the database.
+ *
+ * Used to minimize the need for querying this data every time it's needed.
+ *
+ */
+/datum/poll_option
+ ///Reference to the poll this option belongs to
+ var/datum/poll_question/parent_poll
+ ///Table id of this option, will be null until poll has been created.
+ var/option_id
+ ///Description/name of this option
+ var/text
+ ///For rating polls, the minimum selectable value allowed; Supported value range is -2147483648 to 2147483647
+ var/min_val
+ ///For rating polls, the maximum selectable value allowed; Supported value range is -2147483648 to 2147483647
+ var/max_val
+ ///Optional for rating polls, description shown next to the minimum value
+ var/desc_min = ""
+ ///Optional for rating polls, description shown next to the rounded whole middle value
+ var/desc_mid = ""
+ ///Optional for rating polls, description shown next to the maximum value
+ var/desc_max = ""
+ ///Hint for statbus, not used by the game; If this option should be included by default when calculating the resulting percentages of all options for this poll
+ var/default_percentage_calc
+
+/**
+ * Shows a list of all current and future polls and buttons to edit or delete them or create a new poll.
+ *
+ */
+/datum/admins/proc/poll_list_panel()
+ var/list/output = list("Current and future polls Note when editing polls or their options changes are not saved until you press Submit Poll. New PollReload Polls
")
+ for(var/p in GLOB.polls)
+ var/datum/poll_question/poll = p
+ output += {"[poll.question]
+ Edit
+ Delete
+ "}
+ if(poll.subtitle)
+ output += " [poll.subtitle]"
+ output += " [poll.future_poll ? "Starts" : "Started"] at [poll.start_datetime] | Ends at [poll.end_datetime]"
+ if(poll.admin_only)
+ output += " | Admin only"
+ if(poll.dont_show)
+ output += " | Hidden from tracking until complete"
+ output += " | [poll.poll_votes] players have [poll.poll_type == POLLTYPE_TEXT ? "responded" : "voted"]"
+ var/datum/browser/panel = new(usr, "plpanel", "Poll list Panel", 700, 400)
+ panel.set_content(jointext(output, ""))
+ panel.open()
+
+/**
+ * Show the options for creating a poll or editing its parameters along with its linked options.
+ *
+ */
+/datum/admins/proc/poll_management_panel(datum/poll_question/poll)
+ var/list/output = list("
+
+ First enter the poll question details and press Initialize Question.
+
+ Then add poll options and press Submit Poll to save and create the question and options. No options are required for Text Reply polls.
+
+ Which poll type should I use?
+ "}
+ else
+ output += ""
+ if(poll.edit_ready)
+ output += {"
+
+ "}
+ if(poll.poll_type == POLLTYPE_TEXT)
+ output += "Clear poll responses [poll.poll_votes] players have responded"
+ else
+ output += "Clear poll votes [poll.poll_votes] players have voted"
+ if(poll.poll_type == POLLTYPE_TEXT)
+ output += ""
+ else
+ output += "Add Option "
+ if(length(poll.options))
+ for(var/o in poll.options)
+ var/datum/poll_option/option = o
+ option_count++
+ output += {"Option [option_count]
+ Edit
+ Delete
+ [option.text]
+ "}
+ if(poll.poll_type == POLLTYPE_RATING)
+ output += {" Minimum value: [option.min_val] | Maximum value: [option.max_val]
+ Minimum description: [option.desc_min]
+ Middle description: [option.desc_mid]
+ Maximum description: [option.desc_max]
+ "}
+ output += ""
+ var/datum/browser/panel = new(usr, "pmpanel", "Poll Management Panel", 780, 640)
+ panel.add_stylesheet("admin_panelscss", 'html/admin/admin_panels.css')
+ if(usr.client.prefs.tgui_fancy) //some browsers (IE8) have trouble with unsupported css3 elements that break the panel's functionality, so we won't load those if a user is in no frills tgui mode since that's for similar compatability support
+ panel.add_stylesheet("admin_panelscss3", 'html/admin/admin_panels_css3.css')
+ panel.set_content(jointext(output, ""))
+ panel.open()
+
+/**
+ * Processes topic data from poll management panel.
+ *
+ * Reads through returned form data and assigns data to the poll datum, creating a new one if required, before passing it to be saved.
+ * Also does some simple error checking to ensure the poll will be valid before creation.
+ *
+ */
+/datum/admins/proc/poll_parse_href(list/href_list, datum/poll_question/poll)
+ if(!check_rights(R_POLL))
+ return
+ if(!SSdbcore.Connect())
+ to_chat(usr, "Failed to establish database connection.", confidential = TRUE)
+ return
+ var/list/error_state = list()
+ var/new_poll = FALSE
+ var/clear_votes = FALSE
+ var/submit_ready = FALSE
+ if(!poll)
+ poll = new(creator = usr.client.ckey)
+ new_poll = TRUE
+ if(new_poll)
+ poll.poll_type = href_list["polltype"]
+ switch(href_list["radioduration"])
+ if("runfor")
+ poll.duration = text2num(href_list["duration"])
+ poll.interval = href_list["durationtype"]
+ if("rununtil")
+ if(href_list["enddatetimetext"] != "YYYY-MM-DD HH:MM:SS")
+ poll.duration = href_list["enddatetimetext"]
+ if(new_poll)
+ poll.end_datetime = poll.duration
+ if(!poll.duration)
+ error_state += "No duration was provided."
+ switch(href_list["radiostart"])
+ if("startnow")
+ poll.start_datetime = null
+ if("startdatetime")
+ if(href_list["startdatetimetext"] && href_list["startdatetimetext"] != "YYYY-MM-DD HH:MM:SS")
+ poll.start_datetime = href_list["startdatetimetext"]
+ else
+ error_state += "Start datetime was selected but none was provided."
+ if(href_list["question"])
+ poll.question = href_list["question"]
+ else
+ error_state += "No question was provided."
+ poll.subtitle = href_list["subtitle"]
+ if(href_list["adminonly"])
+ poll.admin_only = TRUE
+ else
+ poll.admin_only = FALSE
+ if(href_list["dontshow"])
+ poll.dont_show = TRUE
+ else
+ poll.dont_show = FALSE
+ if(href_list["allowrevoting"])
+ poll.allow_revoting = TRUE
+ else
+ poll.allow_revoting = FALSE
+ if(href_list["clearvotesedit"])
+ clear_votes = TRUE
+ if(href_list["submitpoll"])
+ submit_ready = TRUE
+ if(poll.poll_type == POLLTYPE_MULTI)
+ if(text2num(href_list["optionsallowed"]))
+ poll.options_allowed = text2num(href_list["optionsallowed"])
+ if(poll.options_allowed == 1)
+ error_state += "Multiple choice polls require more than one option allowed, use a standard option poll for singlular voting."
+ if(poll.options_allowed < 0)
+ error_state += "Multiple choice options allowed cannot be negative."
+ else
+ error_state += "Multiple choice poll was selected but no number of allowed options was provided."
+ if(submit_ready && poll.poll_type != POLLTYPE_TEXT && !length(poll.options))
+ error_state += "This poll type requires at least one option."
+ if(error_state.len)
+ if(poll.edit_ready)
+ to_chat(usr, "Not all edits were applied because the following errors were present:\n[error_state.Join("\n")]", confidential = TRUE)
+ else
+ to_chat(usr, "Poll not [new_poll ? "initialized" : "submitted"] because the following errors were present:\n[error_state.Join("\n")]", confidential = TRUE)
+ if(new_poll)
+ qdel(poll)
+ return
+ if(submit_ready)
+ var/db = poll.edit_ready //if the poll is new it will need its options inserted for the first time
+ poll.save_poll_data(clear_votes)
+ if(!db)
+ poll.save_all_options()
+ poll_management_panel(poll)
+
+/datum/poll_question/New(id, polltype, starttime, endtime, question, subtitle, adminonly, multiplechoiceoptions, dontshow, allow_revoting, vote_count, creator, future, dbload = FALSE)
+ poll_id = text2num(id)
+ poll_type = polltype
+ start_datetime = starttime
+ end_datetime = endtime
+ src.question = question
+ src.subtitle = subtitle
+ admin_only = text2num(adminonly)
+ options_allowed = text2num(multiplechoiceoptions)
+ dont_show = text2num(dontshow)
+ src.allow_revoting = text2num(allow_revoting)
+ poll_votes = text2num(vote_count) || 0
+ created_by = creator
+ future_poll = text2num(future)
+ edit_ready = dbload
+ GLOB.polls += src
+
+/datum/poll_question/Destroy()
+ GLOB.polls -= src
+ return ..()
+
+/**
+ * Sets a poll and its associated data as deleted in the database.
+ *
+ * Calls the procedure set_poll_deleted to set the deleted column to 1 for each row in the poll_ tables matching the poll id used.
+ * Then deletes each option datum and finally the poll itself.
+ *
+ */
+/datum/poll_question/proc/delete_poll()
+ if(!check_rights(R_POLL))
+ return
+ if(!SSdbcore.Connect())
+ to_chat(usr, "Failed to establish database connection.", confidential = TRUE)
+ return
+ var/datum/DBQuery/query_delete_poll = SSdbcore.NewQuery("CALL set_poll_deleted('[sanitizeSQL(poll_id)]')")
+ if(!query_delete_poll.warn_execute())
+ qdel(query_delete_poll)
+ return
+ qdel(query_delete_poll)
+ for(var/o in options)
+ var/datum/poll_option/option = o
+ qdel(option)
+ GLOB.polls -= src
+ qdel(src)
+
+/**
+ * Inserts or updates a poll question to the database.
+ *
+ * Uses INSERT ON DUPLICATE KEY UPDATE to handle both inserting and updating at once.
+ * The start and end datetimes and poll id for new polls is then retrieved for the poll datum.
+ * Arguments:
+ * * clear_votes - When true will call clear_poll_votes() to delete all votes matching this poll id.
+ *
+ */
+/datum/poll_question/proc/save_poll_data(clear_votes)
+ if(!check_rights(R_POLL))
+ return
+ if(!SSdbcore.Connect())
+ to_chat(usr, "Failed to establish database connection.", confidential = TRUE)
+ return
+ var/poll_id_sql = "[sanitizeSQL(poll_id)]"
+ var/new_poll = FALSE
+ if(!poll_id_sql)
+ poll_id_sql = "NULL"
+ new_poll = TRUE
+ var/poll_type_sql = sanitizeSQL(poll_type)
+ var/question_sql = sanitizeSQL(question)
+ var/subtitle_sql = sanitizeSQL(subtitle)
+ var/admin_only_sql = sanitizeSQL(admin_only)
+ var/options_allowed_sql = "[sanitizeSQL(options_allowed)]"
+ if(poll_type != POLLTYPE_MULTI)
+ options_allowed_sql = "NULL"
+ var/dont_show_sql = sanitizeSQL(dont_show)
+ var/allow_revoting_sql = sanitizeSQL(allow_revoting)
+ var/admin_ckey = sanitizeSQL(created_by)
+ var/admin_ip = sanitizeSQL(usr.client.address)
+ var/end_datetime_sql
+ if(interval)
+ end_datetime_sql = "NOW() + INTERVAL [sanitizeSQL(duration)] [sanitizeSQL(interval)]"
+ else
+ end_datetime_sql = "'[sanitizeSQL(duration)]'"
+ var/start_datetime_sql
+ if(!start_datetime)
+ start_datetime_sql = "NOW()"
+ else
+ start_datetime_sql = "'[sanitizeSQL(start_datetime)]'"
+ var/kn = key_name(usr)
+ var/kna = key_name_admin(usr)
+ var/datum/DBQuery/query_save_poll = SSdbcore.NewQuery("INSERT INTO [format_table_name("poll_question")] (id, polltype, created_datetime, starttime, endtime, question, subtitle, adminonly, multiplechoiceoptions, createdby_ckey, createdby_ip, dontshow, allow_revoting) VALUES ([poll_id_sql], '[poll_type_sql]', NOW(), [start_datetime_sql], [end_datetime_sql], '[question_sql]', '[subtitle_sql]', '[admin_only_sql]', [options_allowed_sql], '[admin_ckey]', INET_ATON('[admin_ip]'), '[dont_show_sql]', '[allow_revoting_sql]') ON DUPLICATE KEY UPDATE starttime = [start_datetime_sql], endtime = [end_datetime_sql], question = '[question_sql]', subtitle = '[subtitle_sql]', adminonly = '[admin_only_sql]', multiplechoiceoptions = [options_allowed_sql], dontshow = '[dont_show_sql]', allow_revoting = '[allow_revoting_sql]'")
+ if(!query_save_poll.warn_execute())
+ qdel(query_save_poll)
+ return
+ qdel(query_save_poll)
+ if(poll_id_sql == "NULL")
+ poll_id_sql = "LAST_INSERT_ID()"
+ var/datum/DBQuery/query_get_poll_id_start_endtime = SSdbcore.NewQuery("SELECT LAST_INSERT_ID(), starttime, endtime, IF(starttime > NOW(), 1, 0) FROM [format_table_name("poll_question")] WHERE id = [poll_id_sql]")
+ if(!query_get_poll_id_start_endtime.warn_execute())
+ qdel(query_get_poll_id_start_endtime)
+ return
+ if(query_get_poll_id_start_endtime.NextRow())
+ if(!poll_id)
+ poll_id = text2num(query_get_poll_id_start_endtime.item[1])
+ start_datetime = query_get_poll_id_start_endtime.item[2]
+ end_datetime = query_get_poll_id_start_endtime.item[3]
+ future_poll = text2num(query_get_poll_id_start_endtime.item[4])
+ qdel(query_get_poll_id_start_endtime)
+ if(clear_votes)
+ clear_poll_votes()
+ edit_ready = TRUE
+ var/msg = "has [new_poll ? "created a new" : "edited a"][admin_only ? " admin only" : ""] server poll. Question: [question]"
+ if(admin_only)
+ log_admin_private("[kn] [msg]")
+ else
+ log_admin("[kn] [msg]")
+ message_admins("[kna] [msg]")
+
+/**
+ * Saves all options of a poll to the database.
+ *
+ * Saves all the created options for a poll when it's submitted to the DB for the first time and associated an id with the options.
+ * Insertion and id querying for each option is done separately to ensure data integrity; this is less performant, but not significantly.
+ * Using MassInsert() would mean having to query a list of rows by poll_id or matching by fields afterwards, which doesn't guarantee accuracy.
+ *
+ */
+/datum/poll_question/proc/save_all_options()
+ if(!SSdbcore.Connect())
+ to_chat(usr, "Failed to establish database connection.", confidential = TRUE)
+ return
+ for(var/o in options)
+ var/datum/poll_option/option = o
+ option.save_option()
+ var/datum/DBQuery/query_get_option_id = SSdbcore.NewQuery("SELECT LAST_INSERT_ID()")
+ if(!query_get_option_id.warn_execute())
+ qdel(query_get_option_id)
+ return
+ if(query_get_option_id.NextRow())
+ option.option_id = text2num(query_get_option_id.item[1])
+ qdel(query_get_option_id)
+
+/**
+ * Deletes all votes or text replies for this poll, depending on its type.
+ *
+ */
+/datum/poll_question/proc/clear_poll_votes()
+ if(!check_rights(R_POLL))
+ return
+ if(!SSdbcore.Connect())
+ to_chat(usr, "Failed to establish database connection.", confidential = TRUE)
+ return
+ var/table = "poll_vote"
+ if(poll_type == POLLTYPE_TEXT)
+ table = "poll_textreply"
+ var/datum/DBQuery/query_clear_poll_votes = SSdbcore.NewQuery("UPDATE [format_table_name("[table]")] SET deleted = 1 WHERE pollid = [sanitizeSQL(poll_id)]")
+ if(!query_clear_poll_votes.warn_execute())
+ qdel(query_clear_poll_votes)
+ return
+ qdel(query_clear_poll_votes)
+ poll_votes = 0
+ to_chat(usr, "Poll [poll_type == POLLTYPE_TEXT ? "responses" : "votes"] cleared.", confidential = TRUE)
+
+/**
+ * Show the options for creating a poll option or editing its parameters.
+ *
+ */
+/datum/admins/proc/poll_option_panel(datum/poll_question/poll, datum/poll_option/option)
+ var/list/output = list("