Forward messages sent to helpserv after pickup to the helper.
[srvx.git] / src / mod-helpserv.c
1 /* mod-helpserv.c - Support Helper assistant service
2  * Copyright 2002-2003, 2006 srvx Development Team
3  *
4  * This file is part of srvx.
5  *
6  * srvx is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with srvx; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
19  */
20
21 /* Wishlist for helpserv.c
22  * - Make HelpServ send unassigned request count to helpers as they join the
23  *   channel
24  * - FAQ responses
25  * - Get cmd_statsreport to sort by time and show requests closed
26  * - .. then make statsreport show weighted combination of time and requests closed :)
27  * - Something for users to use a subset of commands... like closing their
28  *   own request(s), viewing what they've sent so far, and finding their
29  *   helper's nick.
30  * - It would be nice to have some variable expansions for the custom
31  *   request open/close/etc messages. ${request/id}, etc
32  * - Allow manipulation of the persist types on a per-request basis... so
33  *   if it's normally set to close requests after a user quits, but there
34  *   is a long-term issue, then that single request can remain
35  * - Bot suspension
36  */
37
38 #include "conf.h"
39 #include "global.h"
40 #include "modcmd.h"
41 #include "nickserv.h"
42 #include "opserv.h"
43 #include "saxdb.h"
44 #include "timeq.h"
45
46 #define HELPSERV_CONF_NAME "modules/helpserv"
47 #define HELPSERV_HELPFILE_NAME "mod-helpserv.help"
48 const char *helpserv_module_deps[] = { NULL };
49
50 /* db entries */
51 #define KEY_BOTS "bots"
52 #define KEY_LAST_STATS_UPDATE "last_stats_update"
53 #define KEY_NICK "nick"
54 #define KEY_DB_BADCHANS "badchans"
55 #define KEY_HELP_CHANNEL "help_channel"
56 #define KEY_PAGE_DEST "page_dest"
57 #define KEY_CMDWORD "cmdword"
58 #define KEY_PERSIST_LENGTH "persist_length"
59 #define KEY_REGISTERED "registered"
60 #define KEY_REGISTRAR "registrar"
61 #define KEY_IDWRAP "id_wrap"
62 #define KEY_REQ_MAXLEN "req_maxlen"
63 #define KEY_LAST_REQUESTID "last_requestid"
64 #define KEY_HELPERS "users"
65 #define KEY_HELPER_LEVEL "level"
66 #define KEY_HELPER_HELPMODE "helpmode"
67 #define KEY_HELPER_WEEKSTART "weekstart"
68 #define KEY_HELPER_STATS "stats"
69 #define KEY_HELPER_STATS_TIME "time"
70 #define KEY_HELPER_STATS_PICKUP "picked_up"
71 #define KEY_HELPER_STATS_CLOSE "closed"
72 #define KEY_HELPER_STATS_REASSIGNFROM "reassign_from"
73 #define KEY_HELPER_STATS_REASSIGNTO "reassign_to"
74 #define KEY_REQUESTS "requests"
75 #define KEY_REQUEST_HELPER "helper"
76 #define KEY_REQUEST_ASSIGNED "assigned"
77 #define KEY_REQUEST_HANDLE "handle"
78 #define KEY_REQUEST_TEXT "text"
79 #define KEY_REQUEST_OPENED "opened"
80 #define KEY_REQUEST_NICK "nick"
81 #define KEY_REQUEST_USERHOST "userhost"
82 #define KEY_REQUEST_CLOSED "closed"
83 #define KEY_REQUEST_CLOSEREASON "closereason"
84 #define KEY_NOTIFICATION "notification"
85 #define KEY_PRIVMSG_ONLY "privmsg_only"
86 #define KEY_REQ_ON_JOIN "req_on_join"
87 #define KEY_AUTO_VOICE "auto_voice"
88 #define KEY_AUTO_DEVOICE "auto_devoice"
89 #define KEY_LAST_ACTIVE "last_active"
90
91 /* General */
92 #define HSFMT_TIME               "%a, %d %b %Y %H:%M:%S %Z"
93 static const struct message_entry msgtab[] = {
94     { "HSMSG_READHELP_SUCCESS", "Read HelpServ help database in %lu.%03lu seconds." },
95     { "HSMSG_INVALID_BOT", "This command requires a valid HelpServ bot name." },
96     { "HSMSG_ILLEGAL_CHANNEL", "$b%s$b is an illegal channel; cannot use it." },
97     { "HSMSG_INTERNAL_COMMAND", "$b%s$b appears to be an internal HelpServ command, sorry." },
98     { "HSMSG_NOT_IN_USERLIST", "%s lacks access to $b%s$b." },
99     { "HSMSG_LEVEL_TOO_LOW", "You lack access to this command." },
100     { "HSMSG_OPER_CMD", "This command can only be executed via $O." },
101     { "HSMSG_WTF_WHO_ARE_YOU", "$bUnable to find you on the %s userlist.$b This is a bug. Please report it." },
102     { "HSMSG_NO_USE_OPSERV", "This command cannot be used via $O. If you really need to use it, add yourself to the userlist." },
103     { "HSMSG_OPSERV_NEED_USER", "To use this command via $O, you must supply a user to target." },
104     { "HSMSG_PAGE_REQUEST", "Page from $b%s$b: $b%s$b" },
105     { "HSMSG_BAD_REQ_TYPE", "I don't know how to list $b%s$b requests." },
106
107 /* Greetings */
108     { "HSMSG_GREET_EXISTING_REQ", "Welcome back to %s. You have already opened request ID#%lu. Any messages you send to $S will be appended to that request." },
109     { "HSMSG_GREET_PRIVMSG_EXISTREQ", "Hello again. Your account has a previously opened request ID#%lu. This message and any further messages you send to $S will be appended to that request." },
110
111 /* User Management */
112     { "HSMSG_CANNOT_ADD", "You do not have permission to add users." },
113     { "HSMSG_CANNOT_DEL", "You do not have permission to delete users." },
114     { "HSMSG_CANNOT_CLVL", "You do not have permission to modify users' access." },
115     { "HSMSG_NO_SELF_CLVL", "You cannot change your own access." },
116     { "HSMSG_NO_BUMP_ACCESS", "You cannot give users the same or more access than yourself." },
117     { "HSMSG_NO_TRANSFER_SELF", "You cannot give ownership to your own account." },
118     { "HSMSG_ADDED_USER", "Added new $b%s$b %s to the user list." },
119     { "HSMSG_DELETED_USER", "Deleted $b%s$b %s from the user list." },
120     { "HSMSG_USER_EXISTS", "$b%s$b is already on the user list." },
121     { "HSMSG_INVALID_ACCESS", "$b%s$b is an invalid access level." },
122     { "HSMSG_CHANGED_ACCESS", "%s now has $b%s$b access." },
123     { "HSMSG_EXPIRATION_DONE", "%d eligible HelpServ bots have retired." },
124     { "HSMSG_BAD_WEEKDAY", "I do not know which day of the week $b%s$b is." },
125     { "HSMSG_WEEK_STARTS", "$b%s$b's weeks start on $b%s$b." },
126
127 /* Registration */
128     { "HSMSG_ILLEGAL_NICK", "$b%s$b is an illegal nick; cannot use it." },
129     { "HSMSG_NICK_EXISTS", "The nick %s is in use by someone else." },
130     { "HSMSG_REG_SUCCESS", "%s now has ownership of bot %s." },
131     { "HSMSG_NEED_UNREG_CONFIRM", "To unregister this bot, you must /msg $S unregister CONFIRM" },
132     { "HSMSG_ERROR_ADDING_SERVICE", "Error creating new user $b%s$b." },
133
134 /* Rename */
135     { "HSMSG_RENAMED", "%s has been renamed to $b%s$b." },
136     { "HSMSG_MOVE_SAME_CHANNEL", "You cannot move %s to the same channel it is on." },
137     { "HSMSG_INVALID_MOVE", "$b%s$b is not a valid nick or channel name." },
138     { "HSMSG_NEED_GIVEOWNERSHIP_CONFIRM", "To transfer ownership of this bot, you must /msg $S giveownership newowner CONFIRM" },
139     { "HSMSG_MULTIPLE_OWNERS", "There is more than one owner of %s; please use other commands to change ownership." },
140     { "HSMSG_NO_TRANSFER_SELF", "You cannot give ownership to your own account." },
141     { "HSMSG_OWNERSHIP_GIVEN", "Ownership of $b%s$b has been transferred to account $b%s$b." },
142
143 /* Queue settings */
144     { "HSMSG_INVALID_OPTION", "$b%s$b is not a valid option." },
145     { "HSMSG_QUEUE_OPTIONS", "HelpServ Queue Options:" },
146     { "HSMSG_SET_COMMAND_TYPE",   "$bPageType        $b %s" },
147     { "HSMSG_SET_ALERT_TYPE",     "$bAlertPageType   $b %s" },
148     { "HSMSG_SET_STATUS_TYPE",    "$bStatusPageType  $b %s" },
149     { "HSMSG_SET_COMMAND_TARGET", "$bPageTarget      $b %s" },
150     { "HSMSG_SET_ALERT_TARGET",   "$bAlertPageTarget $b %s" },
151     { "HSMSG_SET_STATUS_TARGET",  "$bStatusPageTarget$b %s" },
152     { "HSMSG_SET_GREETING",       "$bGreeting        $b %s" },
153     { "HSMSG_SET_REQOPENED",      "$bReqOpened       $b %s" },
154     { "HSMSG_SET_REQASSIGNED",    "$bReqAssigned     $b %s" },
155     { "HSMSG_SET_REQCLOSED",      "$bReqClosed       $b %s" },
156     { "HSMSG_SET_IDLEDELAY",      "$bIdleDelay       $b %s" },
157     { "HSMSG_SET_WHINEDELAY",     "$bWhineDelay      $b %s" },
158     { "HSMSG_SET_WHINEINTERVAL",  "$bWhineInterval   $b %s" },
159     { "HSMSG_SET_EMPTYINTERVAL",  "$bEmptyInterval   $b %s" },
160     { "HSMSG_SET_STALEDELAY",     "$bStaleDelay      $b %s" },
161     { "HSMSG_SET_REQPERSIST",     "$bReqPersist      $b %s" },
162     { "HSMSG_SET_HELPERPERSIST",  "$bHelperPersist   $b %s" },
163     { "HSMSG_SET_NOTIFICATION",   "$bNotification    $b %s" },
164     { "HSMSG_SET_IDWRAP",         "$bIDWrap          $b %d" },
165     { "HSMSG_SET_REQMAXLEN",      "$bReqMaxLen       $b %d" },
166     { "HSMSG_SET_PRIVMSGONLY",    "$bPrivmsgOnly     $b %s" },
167     { "HSMSG_SET_REQONJOIN",      "$bReqOnJoin       $b %s" },
168     { "HSMSG_SET_AUTOVOICE",      "$bAutoVoice       $b %s" },
169     { "HSMSG_SET_AUTODEVOICE",    "$bAutoDevoice     $b %s" },
170     { "HSMSG_PAGE_NOTICE", "notice" },
171     { "HSMSG_PAGE_PRIVMSG", "privmsg" },
172     { "HSMSG_PAGE_ONOTICE", "onotice" },
173     { "HSMSG_LENGTH_PART", "part" },
174     { "HSMSG_LENGTH_QUIT", "quit" },
175     { "HSMSG_LENGTH_CLOSE", "close" },
176     { "HSMSG_NOTIFY_DROP", "ReqDrop" },
177     { "HSMSG_NOTIFY_USERCHANGES", "UserChanges" },
178     { "HSMSG_NOTIFY_ACCOUNTCHANGES", "AccountChanges" },
179     { "HSMSG_INVALID_INTERVAL", "Sorry, %s must be at least %s." },
180     { "HSMSG_0_DISABLED", "0 (Disabled)" },
181     { "HSMSG_NEED_MANAGER", "Only managers or higher can do this." },
182     { "HSMSG_SET_NEED_OPER", "This option can only be set by an oper." },
183
184 /* Requests */
185     { "HSMSG_REQ_INVALID", "$b%s$b is not a valid request ID, or there are no requests for that nick or account." },
186     { "HSMSG_REQ_NOT_YOURS_ASSIGNED_TO", "Request $b%lu$b is not assigned to you; it is currently assigned to %s." },
187     { "HSMSG_REQ_NOT_YOURS_UNASSIGNED", "Request $b%lu$b is not assigned to you; it is currently unassigned." },
188     { "HSMSG_REQ_FOUNDMANY", "The user you entered had multiple requests. The oldest one is being used." },
189     { "HSMSG_REQ_CLOSED", "Request $b%lu$b has been closed." },
190     { "HSMSG_REQ_NO_UNASSIGNED", "There are no unassigned requests." },
191     { "HSMSG_USERCMD_NO_REQUEST", "You must have an open request to use a user command." },
192     { "HSMSG_USERCMD_UNKNOWN", "I do not know the user command $b%s$b." },
193     { "HSMSG_REQ_YOU_NOT_IN_HELPCHAN_OPEN", "You cannot open this request as you are not in %s." },
194     { "HSMSG_REQ_YOU_NOT_IN_HELPCHAN", "You cannot be assigned this request as you are not in %s." },
195     { "HSMSG_REQ_HIM_NOT_IN_HELPCHAN", "%s cannot be assigned this request as they are not in %s." },
196     { "HSMSG_REQ_SELF_NOT_IN_OVERRIDE", "You are being assigned this request even though you are not in %s, because the restriction was overridden (you are a manager or owner). If you join and then part, this request will be marked unassigned." },
197     { "HSMSG_REQ_YOU_NOT_IN_OVERRIDE", "Note: You are being assigned this request even though you are not in %s, because the restriction was overridden by a manager or owner. If you join and then part, this request will be marked unassigned." },
198     { "HSMSG_REQ_HIM_NOT_IN_OVERRIDE", "Note: %s is being assigned this request even though they are not in %s, because the restriction was overridden (you are a manager or owner). If they join and then part, this request will be marked unassigned." },
199     { "HSMSG_REQ_ASSIGNED_YOU", "You have been assigned request ID#%lu:" },
200     { "HSMSG_REQ_REASSIGNED", "You have been assigned request ID#%lu (reassigned from %s):" },
201     { "HSMSG_REQ_INFO_1", "Request ID#%lu:" },
202     { "HSMSG_REQ_INFO_2a", " - Nick %s / Account %s" },
203     { "HSMSG_REQ_INFO_2b", " - Nick %s / Not authed" },
204     { "HSMSG_REQ_INFO_2c", " - Online somewhere / Account %s" },
205     { "HSMSG_REQ_INFO_2d", " - Not online / Account %s" },
206     { "HSMSG_REQ_INFO_2e", " - Not online / No account" },
207     { "HSMSG_REQ_INFO_3", " - Opened at %s (%s ago)" },
208     { "HSMSG_REQ_INFO_4", " - Message:" },
209     { "HSMSG_REQ_INFO_MESSAGE", "   %s" },
210     { "HSMSG_REQ_ASSIGNED", "Your helper for request ID#%lu is %s (Current nick: %s)" },
211     { "HSMSG_REQ_ASSIGNED_AGAIN", "Your helper for request ID#%lu has been changed to %s (Current nick: %s)" },
212     { "HSMSG_REQ_UNASSIGNED", "Your helper for request ID#%lu has %s, so your request is no longer being handled by them. It has been placed near the front of the unhandled request queue, based on how long ago your request was opened." },
213     { "HSMSG_REQ_NEW", "Your message has been recorded and assigned request ID#%lu. A helper should contact you shortly." },
214     { "HSMSG_REQ_NEWONJOIN", "Welcome to %s. You have been assigned request ID#%lu. A helper should contact you shortly." },
215     { "HSMSG_REQ_UNHANDLED_TIME", "The oldest unhandled request has been waiting for %s." },
216     { "HSMSG_REQ_NO_UNHANDLED", "There are no other unhandled requests." },
217     { "HSMSG_REQ_PERSIST_QUIT", "Everything you tell me until you are helped (or you quit) will be recorded. If you disconnect, your request will be lost." },
218     { "HSMSG_REQ_PERSIST_PART", "Everything you tell me until you are helped (or you leave %s) will be recorded. If you part %s, your request will be lost." },
219     { "HSMSG_REQ_PERSIST_HANDLE", "Everything you tell me until you are helped will be recorded." },
220     { "HSMSG_REQ_MAXLEN", "Sorry, but your request has reached the maximum number of lines. Please wait to be assigned to a helper and continue explaining your request to them." },
221     { "HSMSQ_REQ_TEXT_ADDED", "Message from $b%s:$b %s" },
222     { "HSMSG_REQ_FOUND_ANOTHER", "Request ID#%lu has been closed. $S detected that you also have request ID#%lu open. If you send $S a message, it will be associated with that request." },
223
224 /* Messages that are inserted into request text */
225     { "HSMSG_REQMSG_NOTE_ADDED", "Your note for request ID#%lu has been recorded." },
226
227 /* Automatically generated page messages */
228     { "HSMSG_PAGE_NEW_REQUEST_AUTHED", "New request (ID#%lu) from $b%s$b (Account %s)" },
229     { "HSMSG_PAGE_NEW_REQUEST_UNAUTHED", "New request (ID#%lu) from $b%s$b (Not logged in)" },
230     { "HSMSG_PAGE_UPD_REQUEST_AUTHED", "Request ID#%lu has been updated by $b%s$b (Account %s). Request was initially opened at %s, and was last updated %s ago." },
231     { "HSMSG_PAGE_UPD_REQUEST_NOT_AUTHED", "Request ID#%lu has been updated by $b%s$b (not authed). Request was initially opened at %s, and was last updated %s ago." },
232     { "HSMSG_PAGE_CLOSE_REQUEST_1", "Request ID#%lu from $b%s$b (Account %s) has been closed by %s." },
233     { "HSMSG_PAGE_CLOSE_REQUEST_2", "Request ID#%lu from $b%s$b (Not authed) has been closed by %s." },
234     { "HSMSG_PAGE_CLOSE_REQUEST_3", "Request ID#%lu from an offline user (Account %s) has been closed by %s." },
235     { "HSMSG_PAGE_CLOSE_REQUEST_4", "Request ID#%lu from an offline user (no account) has been closed by %s." },
236     { "HSMSG_PAGE_ASSIGN_REQUEST_1", "Request ID#%lu from $b%s$b (Account %s) has been assigned to %s." },
237     { "HSMSG_PAGE_ASSIGN_REQUEST_2", "Request ID#%lu from $b%s$b (Not authed) has been assigned to %s." },
238     { "HSMSG_PAGE_ASSIGN_REQUEST_3", "Request ID#%lu from an offline user (Account %s) has been assigned to %s." },
239     { "HSMSG_PAGE_ASSIGN_REQUEST_4", "Request ID#%lu from an offline user (no account) has been assigned to %s." },
240     /* The last %s is still an I18N lose.  Blame whoever decided to overload it so much. */
241     { "HSMSG_PAGE_HELPER_GONE_1", "Request ID#%lu from $b%s$b (Account %s) $bhas been unassigned$b, as its helper, %s has %s." },
242     { "HSMSG_PAGE_HELPER_GONE_2", "Request ID#%lu from $b%s$b (Not authed) $bhas been unassigned$b, as its helper, %s has %s." },
243     { "HSMSG_PAGE_HELPER_GONE_3", "Request ID#%lu from an offline user (Account %s) $bhas been unassigned$b, as its helper, %s has %s." },
244     { "HSMSG_PAGE_HELPER_GONE_4", "Request ID#%lu from an offline user (No account) $bhas been unassigned$b, as its helper, %s has %s." },
245     { "HSMSG_PAGE_WHINE_HEADER", "$b%u unhandled request(s)$b waiting at least $b%s$b (%u unhandled, %u total)" },
246     { "HSMSG_PAGE_IDLE_HEADER", "$b%u users$b in %s $bidle at least %s$b:" },
247     { "HSMSG_PAGE_EMPTYALERT", "$b%s has no helpers present (%u unhandled request(s))$b" },
248     { "HSMSG_PAGE_ONLYTRIALALERT", "$b%s has no full helpers present (%d trial(s) present; %u unhandled request(s))$b" },
249     { "HSMSG_PAGE_FIRSTEMPTYALERT", "$b%s has no helpers present because %s has left (%u unhandled request(s))$b" },
250     { "HSMSG_PAGE_FIRSTONLYTRIALALERT", "$b%s has no full helpers present because %s has left (%d trial(s) present; %u unhandled request(s))$b" },
251     { "HSMSG_PAGE_EMPTYNOMORE", "%s has joined %s; cancelling the \"no helpers present\" alert" },
252
253 /* Notification messages */
254     { "HSMSG_NOTIFY_USER_QUIT", "The user for request ID#%lu, $b%s$b, has disconnected." },
255     { "HSMSG_NOTIFY_USER_MOVE", "The account for request ID#%lu, $b%s$b has been unregistered. It has been associated with user $b%s$b." },
256     { "HSMSG_NOTIFY_USER_NICK", "The user for request ID#%lu has changed their nick from $b%s$b to $b%s$b." },
257     { "HSMSG_NOTIFY_USER_FOUND", "The user for request ID#%lu is now online using nick $b%s$b." },
258     { "HSMSG_NOTIFY_HAND_RENAME", "The account for request ID#%lu has been renamed from $b%s$b to $b%s$b." },
259     { "HSMSG_NOTIFY_HAND_MOVE", "The account for request ID#%lu has been changed to $b%s$b from $b%s$b." },
260     { "HSMSG_NOTIFY_HAND_STUCK", "The user for request ID#%lu, $b%s$b, has re-authenticated to account $b%s$b from $b%s$b, and the request remained associated with the old handle." },
261     { "HSMSG_NOTIFY_HAND_AUTH", "The user for request ID#%lu, $b%s$b, has authenticated to account $b%s$b." },
262     { "HSMSG_NOTIFY_HAND_UNREG", "The account for request ID#%lu, $b%s$b, has been unregistered by $b%s$b." },
263     { "HSMSG_NOTIFY_HAND_MERGE", "The account for request ID#%lu, $b%s$b, has been merged with $b%s$b by %s." },
264     { "HSMSG_NOTIFY_ALLOWAUTH", "The user for request ID#%lu, $b%s$b, has been permitted by %s to authenticate to account $b%s$b without hostmask checking." },
265     { "HSMSG_NOTIFY_UNALLOWAUTH", "The user for request ID#%lu, $b%s$b, has had their ability to authenticate without hostmask checking revoked by %s." },
266     { "HSMSG_NOTIFY_FAILPW", "The user for request ID#%lu, $b%s$b, has attempted to authenticate to account $b%s$b, but used an incorrect password." },
267     { "HSMSG_NOTIFY_REQ_DROP_PART", "Request ID#%lu has been $bdropped$b because %s left the help channel." },
268     { "HSMSG_NOTIFY_REQ_DROP_QUIT", "Request ID#%lu has been $bdropped$b because %s quit IRC." },
269     { "HSMSG_NOTIFY_REQ_DROP_UNREGGED", "Request ID#%lu (account %s) has been $bdropped$b because the account was unregistered." },
270
271 /* Presence and request-related messages */
272     { "HSMSG_REQ_DROPPED_PART", "You have left $b%s$b. Your help request (ID#%lu) has been deleted." },
273     { "HSMSG_REQ_WARN_UNREG", "The account you were authenticated to ($b%s$b) has been unregistered. Therefore unless you register a new handle, or authenticate to another one, if you disconnect, your HelpServ $S (%s) request ID#%lu will be lost." },
274     { "HSMSG_REQ_DROPPED_UNREG", "By unregistering the account $b%s$b, HelpServ $S (%s) request ID#%lu was dropped, as there was nobody online to associate the request with." },
275     { "HSMSG_REQ_ASSIGNED_UNREG", "As the account $b%s$b was unregistered, HelpServ $S (%s) request ID#%lu was associated with you, as you were authenticated to that account. If you disconnect, then this request will be lost forever." },
276     { "HSMSG_REQ_AUTH_STUCK", "By authenticating to account $b%s$b, HelpServ $S (%s) request ID#%lu remained with the previous account $b%s$b (because the request will remain until closed). This means that if you send $S a message, it $uwill not$u be associated with this request." },
277     { "HSMSG_REQ_AUTH_MOVED", "By authenticating to account $b%s$b, HelpServ $S (%s) request ID#%lu ceased to be associated with your previously authenticated account ($b%s$b), and was transferred to your new account (because the request will only remain until you %s). This means that if you send $S a message, it $uwill$u be associated with this request." },
278
279 /* Lists */
280     { "HSMSG_BOTLIST_HEADER", "$bCurrent HelpServ bots:$b" },
281     { "HSMSG_USERLIST_HEADER", "$b%s users:$b" },
282     { "HSMSG_USERLIST_ZOOT_LVL", "%s $b%ss$b:" },
283     { "HSMSG_REQLIST_AUTH", "You are currently assigned these requests:" },
284     { "HSMSG_REQ_LIST_TOP_UNASSIGNED", "Listing $ball unassigned$b requests (%d in list)." },
285     { "HSMSG_REQ_LIST_TOP_ASSIGNED", "Listing $ball assigned$b requests (%d in list)." },
286     { "HSMSG_REQ_LIST_TOP_YOUR", "Listing $byour$b requests (%d in list)." },
287     { "HSMSG_REQ_LIST_TOP_ALL", "Listing $ball$b requests (%d in list)." },
288     { "HSMSG_REQ_LIST_NONE", "There are no matching requests." },
289     { "HSMSG_STATS_TOP", "Stats for %s user $b%s$b (week starts %s):" },
290     { "HSMSG_STATS_TIME", "$uTime spent helping in %s:$u" },
291     { "HSMSG_STATS_REQS", "$uRequest activity statistics:$u" },
292
293 /* Status report headers */
294     { "HSMSG_STATS_REPORT_0", "Stats report for current week" },
295     { "HSMSG_STATS_REPORT_1", "Stats report for one week ago" },
296     { "HSMSG_STATS_REPORT_2", "Stats report for two weeks ago" },
297     { "HSMSG_STATS_REPORT_3", "Stats report for three weeks ago" },
298
299 /* Responses to user commands */
300     { "HSMSG_YOU_BEING_HELPED", "You are already being helped." },
301     { "HSMSG_YOU_BEING_HELPED_BY", "You are already being helped by $b%s$b." },
302     { "HSMSG_WAIT_STATUS", "You are %d of %d in line; the first person has waited %s." },
303     { NULL, NULL }
304 };
305
306 enum helpserv_level {
307     HlNone,
308     HlTrial,
309     HlHelper,
310     HlManager,
311     HlOwner,
312     HlOper,
313     HlCount
314 };
315
316 static const char *helpserv_level_names[] = {
317     "None",
318     "Trial",
319     "Helper",
320     "Manager",
321     "Owner",
322     "Oper",
323     NULL
324 };
325
326 enum page_type {
327     PAGE_NONE,
328     PAGE_NOTICE,
329     PAGE_PRIVMSG,
330     PAGE_ONOTICE,
331     PAGE_COUNT
332 };
333
334 static const struct {
335     char *db_name;
336     char *print_name;
337     irc_send_func func;
338 } page_types[] = {
339     { "none", "MSG_NONE", NULL },
340     { "notice", "HSMSG_PAGE_NOTICE", irc_notice },
341     { "privmsg", "HSMSG_PAGE_PRIVMSG", irc_privmsg },
342     { "onotice", "HSMSG_PAGE_ONOTICE", irc_wallchops },
343     { NULL, NULL, NULL }
344 };
345
346 enum page_source {
347     PGSRC_COMMAND,
348     PGSRC_ALERT,
349     PGSRC_STATUS,
350     PGSRC_COUNT
351 };
352
353 static const struct {
354     char *db_name;
355     char *print_target;
356     char *print_type;
357 } page_sources[] = {
358     { "command", "HSMSG_SET_COMMAND_TARGET", "HSMSG_SET_COMMAND_TYPE" },
359     { "alert", "HSMSG_SET_ALERT_TARGET", "HSMSG_SET_ALERT_TYPE" },
360     { "status", "HSMSG_SET_STATUS_TARGET", "HSMSG_SET_STATUS_TYPE" },
361     { NULL, NULL, NULL }
362 };
363
364 enum message_type {
365     MSGTYPE_GREETING,
366     MSGTYPE_REQ_OPENED,
367     MSGTYPE_REQ_ASSIGNED,
368     MSGTYPE_REQ_CLOSED,
369     MSGTYPE_REQ_DROPPED,
370     MSGTYPE_COUNT
371 };
372
373 static const struct {
374     char *db_name;
375     char *print_name;
376 } message_types[] = {
377     { "greeting", "HSMSG_SET_GREETING" },
378     { "reqopened", "HSMSG_SET_REQOPENED" },
379     { "reqassigned", "HSMSG_SET_REQASSIGNED" },
380     { "reqclosed", "HSMSG_SET_REQCLOSED" },
381     { "reqdropped", "HSMSG_SET_REQDROPPED" },
382     { NULL, NULL }
383 };
384
385 enum interval_type {
386     INTERVAL_IDLE_DELAY,
387     INTERVAL_WHINE_DELAY,
388     INTERVAL_WHINE_INTERVAL,
389     INTERVAL_EMPTY_INTERVAL,
390     INTERVAL_STALE_DELAY,
391     INTERVAL_COUNT
392 };
393
394 static const struct {
395     char *db_name;
396     char *print_name;
397 } interval_types[] = {
398     { "idledelay", "HSMSG_SET_IDLEDELAY" },
399     { "whinedelay", "HSMSG_SET_WHINEDELAY" },
400     { "whineinterval", "HSMSG_SET_WHINEINTERVAL" },
401     { "emptyinterval", "HSMSG_SET_EMPTYINTERVAL" },
402     { "staledelay", "HSMSG_SET_STALEDELAY" },
403     { NULL, NULL }
404 };
405
406 enum persistence_type {
407     PERSIST_T_REQUEST,
408     PERSIST_T_HELPER,
409     PERSIST_T_COUNT
410 };
411
412 static const struct {
413     char *db_name;
414     char *print_name;
415 } persistence_types[] = {
416     { "reqpersist", "HSMSG_SET_REQPERSIST" },
417     { "helperpersist", "HSMSG_SET_HELPERPERSIST" },
418     { NULL, NULL }
419 };
420
421 enum persistence_length {
422     PERSIST_PART,
423     PERSIST_QUIT,
424     PERSIST_CLOSE,
425     PERSIST_COUNT
426 };
427
428 static const struct {
429     char *db_name;
430     char *print_name;
431 } persistence_lengths[] = {
432     { "part", "HSMSG_LENGTH_PART" },
433     { "quit", "HSMSG_LENGTH_QUIT" },
434     { "close", "HSMSG_LENGTH_CLOSE" },
435     { NULL, NULL }
436 };
437
438 enum notification_type {
439     NOTIFY_NONE,
440     NOTIFY_DROP,
441     NOTIFY_USER,
442     NOTIFY_HANDLE,
443     NOTIFY_COUNT
444 };
445
446 static const struct {
447     char *db_name;
448     char *print_name;
449 } notification_types[] = {
450     { "none", "MSG_NONE" },
451     { "reqdrop", "HSMSG_NOTIFY_DROP" },
452     { "userchanges", "HSMSG_NOTIFY_USERCHANGES" },
453     { "accountchanges", "HSMSG_NOTIFY_ACCOUNTCHANGES" },
454     { NULL, NULL }
455 };
456
457 static const char *weekday_names[] = {
458     "Sunday",
459     "Monday",
460     "Tuesday",
461     "Wednesday",
462     "Thursday",
463     "Friday",
464     "Saturday",
465     NULL
466 };
467
468 static const char *statsreport_week[] = {
469     "HSMSG_STATS_REPORT_0",
470     "HSMSG_STATS_REPORT_1",
471     "HSMSG_STATS_REPORT_2",
472     "HSMSG_STATS_REPORT_3"
473 };
474
475 static struct {
476     const char *description;
477     const char *reqlogfile;
478     unsigned long db_backup_frequency;
479     unsigned int expire_age;
480     char user_escape;
481 } helpserv_conf;
482
483 static unsigned long last_stats_update;
484 static int shutting_down;
485 static FILE *reqlog_f;
486 static struct log_type *HS_LOG;
487
488 #define CMD_NEED_BOT            0x001
489 #define CMD_NOT_OVERRIDE        0x002
490 #define CMD_FROM_OPSERV_ONLY    0x004
491 #define CMD_IGNORE_EVENT        0x008
492 #define CMD_NEVER_FROM_OPSERV   0x010
493
494 struct helpserv_bot {
495     struct userNode *helpserv;
496
497     struct chanNode *helpchan;
498
499     struct chanNode *page_targets[PGSRC_COUNT];
500     enum page_type page_types[PGSRC_COUNT];
501     char *messages[MSGTYPE_COUNT];
502     unsigned long intervals[INTERVAL_COUNT];
503     enum notification_type notify;
504
505     /* This is a default; it can be changed on a per-request basis */
506     enum persistence_type persist_types[PERSIST_T_COUNT];
507
508     dict_t users; /* indexed by handle */
509
510     struct helpserv_request *unhandled; /* linked list of unhandled requests */
511     dict_t requests; /* indexed by request id */
512     unsigned long last_requestid;
513     unsigned long id_wrap;
514     unsigned long req_maxlen; /* Maxmimum request length in lines */
515
516     unsigned int privmsg_only : 1;
517     unsigned int req_on_join : 1;
518     unsigned int auto_voice : 1;
519     unsigned int auto_devoice : 1;
520
521     unsigned int helpchan_empty : 1;
522
523     unsigned long registered;
524     unsigned long last_active;
525     char *registrar;
526 };
527
528 struct helpserv_user {
529     struct handle_info *handle;
530     struct helpserv_bot *hs;
531     unsigned int help_mode : 1;
532     unsigned int week_start : 3;
533     enum helpserv_level level;
534     /* statistics */
535     unsigned long join_time; /* when they joined, or 0 if not in channel */
536     /* [0] through [3] are n weeks ago, [4] is the total of everything before that */
537     unsigned int time_per_week[5]; /* how long they've were in the channel the past 4 weeks */
538     unsigned int picked_up[5]; /* how many requests they have picked up */
539     unsigned int closed[5]; /* how many requests they have closed */
540     unsigned int reassigned_from[5]; /* how many requests reassigned from them to others */
541     unsigned int reassigned_to[5]; /* how many requests reassigned from others to them */
542 };
543
544 struct helpserv_request {
545     struct helpserv_user *helper;
546     struct helpserv_bot *hs;
547     struct string_list *text;
548     struct helpserv_request *next_unhandled;
549
550     struct helpserv_reqlist *parent_nick_list;
551     struct helpserv_reqlist *parent_hand_list;
552
553     /* One, but not both, of "user" and "handle" may be NULL,
554      * depending on what we know about the user.
555      *
556      * If persist == PERSIST_CLOSE when the user quits, then it
557      * switches to handle instead of user... and stays that way (it's
558      * possible to have >1 nick per handle, so you can't really decide
559      * to reassign a userNode to it unless they send another message
560      * to HelpServ).
561      */
562     struct userNode *user;
563     struct handle_info *handle;
564
565     unsigned long id;
566     unsigned long opened;
567     unsigned long assigned;
568     unsigned long updated;
569 };
570
571 #define DEFINE_LIST_ALLOC(STRUCTNAME) \
572 struct STRUCTNAME * STRUCTNAME##_alloc() {\
573     struct STRUCTNAME *newlist; \
574     newlist = malloc(sizeof(struct STRUCTNAME)); \
575     STRUCTNAME##_init(newlist); \
576     return newlist; \
577 }\
578 void STRUCTNAME##_free(void *data) {\
579     struct STRUCTNAME *list = data; /* void * to let dict_set_free_data use it */ \
580     STRUCTNAME##_clean(list); \
581     free(list); \
582 }
583
584 DECLARE_LIST(helpserv_botlist, struct helpserv_bot *);
585 DEFINE_LIST(helpserv_botlist, struct helpserv_bot *)
586 DEFINE_LIST_ALLOC(helpserv_botlist)
587
588 DECLARE_LIST(helpserv_reqlist, struct helpserv_request *);
589 DEFINE_LIST(helpserv_reqlist, struct helpserv_request *)
590 DEFINE_LIST_ALLOC(helpserv_reqlist)
591
592 DECLARE_LIST(helpserv_userlist, struct helpserv_user *);
593 DEFINE_LIST(helpserv_userlist, struct helpserv_user *)
594 DEFINE_LIST_ALLOC(helpserv_userlist)
595
596 struct helpfile *helpserv_helpfile;
597 static struct module *helpserv_module;
598 static dict_t helpserv_func_dict;
599 static dict_t helpserv_usercmd_dict; /* contains helpserv_usercmd_t */
600 static dict_t helpserv_option_dict;
601 static dict_t helpserv_bots_dict; /* indexed by nick */
602 static dict_t helpserv_bots_bychan_dict; /* indexed by chan, holds a struct helpserv_botlist */
603 /* QUESTION: why are these outside of any helpserv_bot struct? */
604 static dict_t helpserv_reqs_bynick_dict; /* indexed by nick, holds a struct helpserv_reqlist */
605 static dict_t helpserv_reqs_byhand_dict; /* indexed by handle, holds a struct helpserv_reqlist */
606 static dict_t helpserv_users_byhand_dict; /* indexed by handle, holds a struct helpserv_userlist */
607
608 /* This is so that overrides can "speak" from opserv */
609 extern struct userNode *opserv;
610
611 #define HELPSERV_SYNTAX() helpserv_help(hs, from_opserv, user, argv[0])
612 #define HELPSERV_FUNC(NAME) int NAME(struct userNode *user, UNUSED_ARG(struct helpserv_bot *hs), int from_opserv, UNUSED_ARG(unsigned int argc), UNUSED_ARG(char *argv[]))
613 typedef HELPSERV_FUNC(helpserv_func_t);
614 #define HELPSERV_USERCMD(NAME) void NAME(struct helpserv_request *req, UNUSED_ARG(struct userNode *likely_helper), UNUSED_ARG(char *args))
615 typedef HELPSERV_USERCMD(helpserv_usercmd_t);
616 #define HELPSERV_OPTION(NAME) HELPSERV_FUNC(NAME)
617 typedef HELPSERV_OPTION(helpserv_option_func_t);
618
619 static HELPSERV_FUNC(cmd_help);
620
621 #define REQUIRE_PARMS(N) if (argc < N) { \
622         helpserv_notice(user, "MSG_MISSING_PARAMS", argv[0]); \
623         HELPSERV_SYNTAX(); \
624         return 0; }
625
626 /* For messages going to users being helped */
627 #if defined(GCC_VARMACROS)
628 # define helpserv_msguser(target, ARGS...) send_message_type((from_opserv ? 0 : hs->privmsg_only), (target), (from_opserv ? opserv : hs->helpserv), ARGS)
629 # define helpserv_user_reply(ARGS...) send_message_type(req->hs->privmsg_only, req->user, req->hs->helpserv, ARGS)
630 /* For messages going to helpers */
631 # define helpserv_notice(target, ARGS...) send_message((target), (from_opserv ? opserv : hs->helpserv), ARGS)
632 # define helpserv_notify(helper, ARGS...) do { struct userNode *_target; for (_target = (helper)->handle->users; _target; _target = _target->next_authed) { \
633         send_message(_target, (helper)->hs->helpserv, ARGS); \
634     } } while (0)
635 # define helpserv_page(TYPE, ARGS...) do { \
636     int msg_type=0; struct chanNode *target=helpserv_get_page_type(hs, (TYPE), &msg_type); \
637     if (target) send_target_message(msg_type, target->name, hs->helpserv, ARGS); \
638     } while (0)
639 #elif defined(C99_VARMACROS)
640 # define helpserv_msguser(target, ...) send_message_type((from_opserv ? 0 : hs->privmsg_only), (target), (from_opserv ? opserv : hs->helpserv), __VA_ARGS__)
641 # define helpserv_user_reply(...) send_message_type(req->hs->privmsg_only, req->user, req->hs->helpserv, __VA_ARGS__)
642 /* For messages going to helpers */
643 # define helpserv_notice(target, ...) send_message((target), (from_opserv ? opserv : hs->helpserv), __VA_ARGS__)
644 # define helpserv_notify(helper, ...) do { struct userNode *_target; for (_target = (helper)->handle->users; _target; _target = _target->next_authed) { \
645         send_message(_target, (helper)->hs->helpserv, __VA_ARGS__); \
646     } } while (0)
647 # define helpserv_page(TYPE, ...) do { \
648     int msg_type=0; struct chanNode *target=helpserv_get_page_type(hs, (TYPE), &msg_type); \
649     if (target) send_target_message(msg_type, target->name, hs->helpserv, __VA_ARGS__); \
650     } while (0)
651 #endif
652 #define helpserv_message(hs, target, id) do { if ((hs)->messages[id]) { \
653     if (from_opserv) \
654         send_message_type(4, (target), opserv, "%s", (hs)->messages[id]); \
655     else \
656         send_message_type(4 | hs->privmsg_only, (target), hs->helpserv, "%s", (hs)->messages[id]); \
657     } } while (0)
658 #define helpserv_get_handle_info(user, text) smart_get_handle_info((from_opserv ? opserv : hs->helpserv) , (user), (text))
659
660 struct helpserv_cmd {
661     enum helpserv_level access;
662     helpserv_func_t *func;
663     double weight;
664     long flags;
665 };
666
667 static void run_empty_interval(void *data);
668
669 static void helpserv_interval(char *output, unsigned long interval) {
670     int num_hours = interval / 3600;
671     int num_minutes = (interval % 3600) / 60;
672     sprintf(output, "%u hour%s, %u minute%s", num_hours, num_hours == 1 ? "" : "s", num_minutes, num_minutes == 1 ? "" : "s");
673 }
674
675 static const char * helpserv_level2str(enum helpserv_level level) {
676     if (level <= HlOper) {
677         return helpserv_level_names[level];
678     } else {
679         log_module(HS_LOG, LOG_ERROR, "helpserv_level2str receieved invalid level %d.", level);
680         return "Error";
681     }
682 }
683
684 static enum helpserv_level helpserv_str2level(const char *msg) {
685     enum helpserv_level nn;
686     for (nn=HlNone; nn<=HlOper; nn++) {
687         if (!irccasecmp(msg, helpserv_level_names[nn]))
688             return nn;
689     }
690     log_module(HS_LOG, LOG_ERROR, "helpserv_str2level received invalid level %s.", msg);
691     return HlNone; /* Error */
692 }
693
694 static struct helpserv_user *GetHSUser(struct helpserv_bot *hs, struct handle_info *hi) {
695     return dict_find(hs->users, hi->handle, NULL);
696 }
697
698 static void helpserv_log_request(struct helpserv_request *req, const char *reason) {
699     char key[27+NICKLEN];
700     char userhost[USERLEN+HOSTLEN+2];
701     struct saxdb_context *ctx;
702     int res;
703
704     assert(req != NULL);
705     assert(reason != NULL);
706     if (!reqlog_f || !(ctx = saxdb_open_context(reqlog_f)))
707         return;
708     sprintf(key, "%s-%lu-%lu", req->hs->helpserv->nick, (unsigned long)req->opened, req->id);
709     if ((res = setjmp(*saxdb_jmp_buf(ctx))) != 0) {
710         log_module(HS_LOG, LOG_ERROR, "Unable to log helpserv request: %s.", strerror(res));
711     } else {
712         saxdb_start_record(ctx, key, 1);
713         if (req->helper) {
714             saxdb_write_string(ctx, KEY_REQUEST_HELPER, req->helper->handle->handle);
715             saxdb_write_int(ctx, KEY_REQUEST_ASSIGNED, req->assigned);
716         }
717         if (req->handle) {
718             saxdb_write_string(ctx, KEY_REQUEST_HANDLE, req->handle->handle);
719         }
720         if (req->user) {
721             saxdb_write_string(ctx, KEY_REQUEST_NICK, req->user->nick);
722             sprintf(userhost, "%s@%s", req->user->ident, req->user->hostname);
723             saxdb_write_string(ctx, KEY_REQUEST_USERHOST, userhost);
724         }
725         saxdb_write_int(ctx, KEY_REQUEST_OPENED, req->opened);
726         saxdb_write_int(ctx, KEY_REQUEST_CLOSED, now);
727         saxdb_write_string(ctx, KEY_REQUEST_CLOSEREASON, reason);
728         saxdb_write_string_list(ctx, KEY_REQUEST_TEXT, req->text);
729         saxdb_end_record(ctx);
730         saxdb_close_context(ctx, 0);
731     }
732 }
733
734 static struct chanNode *helpserv_get_page_type(struct helpserv_bot *hs, enum page_source type, int *msg_type)
735 {
736     switch (hs->page_types[type]) {
737         case PAGE_NOTICE:
738             *msg_type = 0;
739             break;
740         case PAGE_PRIVMSG:
741             *msg_type = 1;
742             break;
743         case PAGE_ONOTICE:
744             *msg_type = 2;
745             break;
746         default:
747             log_module(HS_LOG, LOG_ERROR, "helpserv_page() called but %s has an invalid page type %d.", hs->helpserv->nick, type);
748             /* and fall through */
749         case PAGE_NONE:
750             return NULL;
751     }
752     return hs->page_targets[type];
753 }
754
755 /* Searches for a request by number, nick, or account (num|nick|*account).
756  * As there can potentially be >1 match, it takes a reqlist. The return
757  * value is the "best" request found (explained in the comment block below).
758  *
759  * If num_results is not NULL, it is set to the number of potentially matching
760  * requests.
761  * If hs_user is not NULL, requests assigned to this helper will be given
762  * preference (oldest assigned, falling back to oldest if there are none).
763  */
764 static struct helpserv_request * smart_get_request(struct helpserv_bot *hs, struct helpserv_user *hs_user, const char *needle, int *num_results) {
765     struct helpserv_reqlist *reqlist, resultlist;
766     struct helpserv_request *req, *oldest=NULL, *oldest_assigned=NULL;
767     struct userNode *user;
768     unsigned int i;
769
770     if (num_results)
771         *num_results = 0;
772
773     if (*needle == '*') {
774         /* This test (handle) requires the least processing, so it's first */
775         if (!(reqlist = dict_find(helpserv_reqs_byhand_dict, needle+1, NULL)))
776             return NULL;
777         helpserv_reqlist_init(&resultlist);
778         for (i=0; i < reqlist->used; i++) {
779             req = reqlist->list[i];
780             if (req->hs == hs) {
781                 helpserv_reqlist_append(&resultlist, req);
782                 if (num_results)
783                     (*num_results)++;
784             }
785         }
786     } else if (!needle[strspn(needle, "0123456789")]) {
787         /* The string is 100% numeric - a request id */
788         if (!(req = dict_find(hs->requests, needle, NULL)))
789             return NULL;
790         if (num_results)
791             *num_results = 1;
792         return req;
793     } else if ((user = GetUserH(needle))) {
794         /* And finally, search by nick */
795         if (!(reqlist = dict_find(helpserv_reqs_bynick_dict, needle, NULL)))
796             return NULL;
797         helpserv_reqlist_init(&resultlist);
798
799         for (i=0; i < reqlist->used; i++) {
800             req = reqlist->list[i];
801             if (req->hs == hs) {
802                 helpserv_reqlist_append(&resultlist, req);
803                 if (num_results)
804                     (*num_results)++;
805             }
806         }
807         /* If the nick didn't have anything, try their handle */
808         if (!resultlist.used && user->handle_info) {
809             char star_handle[NICKSERV_HANDLE_LEN+2];
810
811             helpserv_reqlist_clean(&resultlist);
812             sprintf(star_handle, "*%s", user->handle_info->handle);
813
814             return smart_get_request(hs, hs_user, star_handle, num_results);
815         }
816     } else {
817         return NULL;
818     }
819
820     if (resultlist.used == 0) {
821         helpserv_reqlist_clean(&resultlist);
822         return NULL;
823     } else if (resultlist.used == 1) {
824         req = resultlist.list[0];
825         helpserv_reqlist_clean(&resultlist);
826         return req;
827     }
828
829     /* In case there is >1 request returned, use the oldest one assigned to
830      * the helper executing the command. Otherwise, use the oldest request.
831      * This may not be the intended result for cmd_pickup (first unhandled
832      * request may be better), or cmd_reassign (first handled request), but
833      * it's close enough, and there really aren't supposed to be multiple
834      * requests per person anyway; they're just side effects of authing. */
835
836     for (i=0; i < resultlist.used; i++) {
837         req = resultlist.list[i];
838         if (!oldest || req->opened < oldest->opened)
839             oldest = req;
840         if (hs_user && (!oldest_assigned || (req->helper == hs_user && req->opened < oldest_assigned->opened)))
841             oldest_assigned = req;
842     }
843
844     helpserv_reqlist_clean(&resultlist);
845
846     return oldest_assigned ? oldest_assigned : oldest;
847 }
848
849 static struct helpserv_request * create_request(struct userNode *user, struct helpserv_bot *hs, int from_join) {
850     struct helpserv_request *req = calloc(1, sizeof(struct helpserv_request));
851     char lbuf[3][MAX_LINE_SIZE], unh[INTERVALLEN];
852     struct helpserv_reqlist *reqlist, *hand_reqlist;
853     const unsigned int from_opserv = 0;
854     const char *fmt;
855
856     assert(req);
857
858     req->id = ++hs->last_requestid;
859     sprintf(unh, "%lu", req->id);
860     dict_insert(hs->requests, strdup(unh), req);
861
862     if (hs->id_wrap) {
863         unsigned long i;
864         char buf[12];
865         if (hs->last_requestid < hs->id_wrap) {
866             for (i=hs->last_requestid; i < hs->id_wrap; i++) {
867                 sprintf(buf, "%lu", i);
868                 if (!dict_find(hs->requests, buf, NULL)) {
869                     hs->last_requestid = i-1;
870                     break;
871                 }
872             }
873         }
874         if (hs->last_requestid >= hs->id_wrap) {
875             for (i=1; i < hs->id_wrap; i++) {
876                 sprintf(buf, "%lu", i);
877                 if (!dict_find(hs->requests, buf, NULL)) {
878                     hs->last_requestid = i-1;
879                     break;
880                 }
881             }
882             if (i >= hs->id_wrap) {
883                 log_module(HS_LOG, LOG_INFO, "%s has more requests than its id_wrap.", hs->helpserv->nick);
884             }
885         }
886     }
887
888     req->hs = hs;
889     req->helper = NULL;
890     req->text = alloc_string_list(4);
891     req->user = user;
892     req->handle = user->handle_info;
893     if (from_join && self->burst) {
894         extern unsigned long burst_begin;
895         /* We need to keep all the requests during a burst join together,
896          * even if the burst takes more than 1 second. ircu seems to burst
897          * in reverse-join order. */
898         req->opened = burst_begin;
899     } else {
900         req->opened = now;
901     }
902     req->updated = now;
903
904     if (!hs->unhandled) {
905         hs->unhandled = req;
906         req->next_unhandled = NULL;
907     } else if (self->burst && hs->unhandled->opened >= req->opened) {
908         req->next_unhandled = hs->unhandled;
909         hs->unhandled = req;
910     } else if (self->burst) {
911         struct helpserv_request *unh;
912         /* Add the request to the beginning of the set of requests with
913          * req->opened having the same value. This makes reqonjoin create
914          * requests in the correct order while bursting. Note that this
915          * does not correct request ids, so they will be in reverse order
916          * though "/msg botname next" will work properly. */
917         for (unh = hs->unhandled; unh->next_unhandled && unh->next_unhandled->opened < req->opened; unh = unh->next_unhandled) ;
918         req->next_unhandled = unh->next_unhandled;
919         unh->next_unhandled = req;
920     } else {
921         struct helpserv_request *unh;
922         /* Add to the end */
923         for (unh = hs->unhandled; unh->next_unhandled; unh = unh->next_unhandled) ;
924         req->next_unhandled = NULL;
925         unh->next_unhandled = req;
926     }
927
928     if (!(reqlist = dict_find(helpserv_reqs_bynick_dict, user->nick, NULL))) {
929         reqlist = helpserv_reqlist_alloc();
930         dict_insert(helpserv_reqs_bynick_dict, user->nick, reqlist);
931     }
932     req->parent_nick_list = reqlist;
933     helpserv_reqlist_append(reqlist, req);
934
935     if (user->handle_info) {
936         if (!(hand_reqlist = dict_find(helpserv_reqs_byhand_dict, user->handle_info->handle, NULL))) {
937             hand_reqlist = helpserv_reqlist_alloc();
938             dict_insert(helpserv_reqs_byhand_dict, user->handle_info->handle, hand_reqlist);
939         }
940         req->parent_hand_list = hand_reqlist;
941         helpserv_reqlist_append(hand_reqlist, req);
942     } else {
943         req->parent_hand_list = NULL;
944     }
945
946     if (from_join) {
947         fmt = user_find_message(user, "HSMSG_REQ_NEWONJOIN");
948         sprintf(lbuf[0], fmt, hs->helpchan->name, req->id);
949     } else {
950         fmt = user_find_message(user, "HSMSG_REQ_NEW");
951         sprintf(lbuf[0], fmt, req->id);
952     }
953     if (req != hs->unhandled) {
954         intervalString(unh, now - hs->unhandled->opened, user->handle_info);
955         fmt = user_find_message(user, "HSMSG_REQ_UNHANDLED_TIME");
956         sprintf(lbuf[1], fmt, unh);
957     } else {
958         fmt = user_find_message(user, "HSMSG_REQ_NO_UNHANDLED");
959         sprintf(lbuf[1], "%s", fmt);
960     }
961     switch (hs->persist_types[PERSIST_T_REQUEST]) {
962         case PERSIST_PART:
963             fmt = user_find_message(user, "HSMSG_REQ_PERSIST_PART");
964             sprintf(lbuf[2], fmt, hs->helpchan->name, hs->helpchan->name);
965             break;
966         case PERSIST_QUIT:
967             fmt = user_find_message(user, "HSMSG_REQ_PERSIST_QUIT");
968             sprintf(lbuf[2], "%s", fmt);
969             break;
970         default:
971             log_module(HS_LOG, LOG_ERROR, "%s has an invalid req_persist.", hs->helpserv->nick);
972         case PERSIST_CLOSE:
973             if (user->handle_info) {
974                 fmt = user_find_message(user, "HSMSG_REQ_PERSIST_HANDLE");
975             } else {
976                 fmt = user_find_message(user, "HSMSG_REQ_PERSIST_QUIT");
977             }
978             sprintf(lbuf[2], "%s", fmt);
979             break;
980     }
981     helpserv_message(hs, user, MSGTYPE_REQ_OPENED);
982     if (from_opserv)
983         send_message_type(4, user, opserv, "%s %s %s", lbuf[0], lbuf[1], lbuf[2]);
984     else
985         send_message_type(4, user, hs->helpserv, "%s %s %s", lbuf[0], lbuf[1], lbuf[2]);
986
987     if (hs->req_on_join && req == hs->unhandled && hs->helpchan_empty && !user->uplink->burst) {
988         timeq_del(0, run_empty_interval, hs, TIMEQ_IGNORE_WHEN);
989         run_empty_interval(hs);
990     }
991
992     return req;
993 }
994
995 /* Handle a message from a user to a HelpServ bot. */
996 static void helpserv_usermsg(struct userNode *user, struct helpserv_bot *hs, const char *text) {
997     const int from_opserv = 0; /* for helpserv_notice */
998     struct helpserv_request *req=NULL, *newest=NULL;
999     struct helpserv_reqlist *reqlist, *hand_reqlist;
1000     unsigned int i;
1001
1002     if ((reqlist = dict_find(helpserv_reqs_bynick_dict, user->nick, NULL))) {
1003         for (i=0; i < reqlist->used; i++) {
1004             req = reqlist->list[i];
1005             if (req->hs != hs)
1006                 continue;
1007             if (!newest || (newest->opened < req->opened))
1008                 newest = req;
1009         }
1010
1011         /* If nothing was found, this will set req to NULL */
1012         req = newest;
1013     }
1014
1015     if (user->handle_info) {
1016         hand_reqlist = dict_find(helpserv_reqs_byhand_dict, user->handle_info->handle, NULL);
1017         if (!req && hand_reqlist) {
1018             /* Most recent first again */
1019             for (i=0; i < hand_reqlist->used; i++) {
1020                 req = hand_reqlist->list[i];
1021                 if ((req->hs != hs) || req->user)
1022                     continue;
1023                 if (!newest || (newest->opened < req->opened))
1024                     newest = req;
1025             }
1026             req = newest;
1027
1028             if (req) {
1029                 req->user = user;
1030                 if (!reqlist) {
1031                     reqlist = helpserv_reqlist_alloc();
1032                     dict_insert(helpserv_reqs_bynick_dict, user->nick, reqlist);
1033                 }
1034                 req->parent_nick_list = reqlist;
1035                 helpserv_reqlist_append(reqlist, req);
1036
1037                 if (req->helper && (hs->notify >= NOTIFY_USER))
1038                     helpserv_notify(req->helper, "HSMSG_NOTIFY_USER_FOUND", req->id, user->nick);
1039
1040                 helpserv_msguser(user, "HSMSG_GREET_PRIVMSG_EXISTREQ", req->id);
1041             }
1042         }
1043     } else {
1044         hand_reqlist = NULL;
1045     }
1046
1047     if (!req) {
1048         if (text[0] == helpserv_conf.user_escape) {
1049             helpserv_msguser(user, "HSMSG_USERCMD_NO_REQUEST");
1050             return;
1051         }
1052         if ((hs->persist_types[PERSIST_T_REQUEST] == PERSIST_PART) && !GetUserMode(hs->helpchan, user)) {
1053             helpserv_msguser(user, "HSMSG_REQ_YOU_NOT_IN_HELPCHAN_OPEN", hs->helpchan->name);
1054             return;
1055         }
1056
1057         req = create_request(user, hs, 0);
1058         if (user->handle_info)
1059             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_NEW_REQUEST_AUTHED", req->id, user->nick, user->handle_info->handle);
1060         else
1061             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_NEW_REQUEST_UNAUTHED", req->id, user->nick);
1062     } else if (text[0] == helpserv_conf.user_escape) {
1063         char cmdname[MAXLEN], *space;
1064         helpserv_usercmd_t *usercmd;
1065         struct userNode *likely_helper;
1066
1067         /* Find somebody likely to be the helper */
1068         if (!req->helper)
1069             likely_helper = NULL;
1070         else if ((likely_helper = req->helper->handle->users) && !likely_helper->next_authed) {
1071             /* only one user it could be :> */
1072         } else for (likely_helper = req->helper->handle->users; likely_helper; likely_helper = likely_helper->next_authed)
1073             if (GetUserMode(hs->helpchan, likely_helper))
1074                 break;
1075
1076         /* Parse out command name */
1077         space = strchr(text+1, ' ');
1078         if (space)
1079             strncpy(cmdname, text+1, space-text-1);
1080         else
1081             strcpy(cmdname, text+1);
1082
1083         /* Call the user command function */
1084         usercmd = dict_find(helpserv_usercmd_dict, cmdname, NULL);
1085         if (usercmd)
1086             usercmd(req, likely_helper, space+1);
1087         else
1088             helpserv_msguser(user, "HSMSG_USERCMD_UNKNOWN", cmdname);
1089         return;
1090     } else if (hs->intervals[INTERVAL_STALE_DELAY]
1091                && (req->updated < now - hs->intervals[INTERVAL_STALE_DELAY])
1092                && (!hs->req_maxlen || req->text->used < hs->req_maxlen)) {
1093         char buf[MAX_LINE_SIZE], updatestr[INTERVALLEN], timestr[MAX_LINE_SIZE];
1094         time_t feh;
1095
1096         feh = req->opened;
1097         strftime(timestr, MAX_LINE_SIZE, HSFMT_TIME, localtime(&feh));
1098         intervalString(updatestr, now - req->updated, user->handle_info);
1099         if (req->helper && (hs->notify >= NOTIFY_USER))
1100             if (user->handle_info)
1101                 helpserv_notify(req->helper, "HSMSG_PAGE_UPD_REQUEST_AUTHED", req->id, user->nick, user->handle_info->handle, timestr, updatestr);
1102             else
1103                 helpserv_notify(req->helper, "HSMSG_PAGE_UPD_REQUEST_NOT_AUTHED", req->id, user->nick, timestr, updatestr);
1104         else
1105             if (user->handle_info)
1106                 helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_UPD_REQUEST_AUTHED", req->id, user->nick, user->handle_info->handle, timestr, updatestr);
1107             else
1108                 helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_UPD_REQUEST_NOT_AUTHED", req->id, user->nick, timestr, updatestr);
1109         feh = now;
1110         strftime(timestr, MAX_LINE_SIZE, HSFMT_TIME, localtime(&feh));
1111         snprintf(buf, MAX_LINE_SIZE, "[Stale request updated at %s]", timestr);
1112         string_list_append(req->text, strdup(buf));
1113     }
1114
1115     req->updated = now;
1116     if (!hs->req_maxlen || req->text->used < hs->req_maxlen) {
1117         struct userNode *likely_helper;
1118
1119         string_list_append(req->text, strdup(text));
1120         /* Find somebody likely to be the helper */
1121         if (!req->helper)
1122             likely_helper = NULL;
1123         else if ((likely_helper = req->helper->handle->users) && !likely_helper->next_authed) {
1124             /* only one user it could be :> */
1125         } else for (likely_helper = req->helper->handle->users; likely_helper; likely_helper = likely_helper->next_authed)
1126             if (GetUserMode(hs->helpchan, likely_helper))
1127                 break;
1128
1129         if(likely_helper)
1130             send_target_message(1, likely_helper->nick, hs->helpserv, "HSMSQ_REQ_TEXT_ADDED", user->nick, text);
1131
1132     } else
1133         helpserv_msguser(user, "HSMSG_REQ_MAXLEN");
1134 }
1135
1136 /* Handle messages direct to a HelpServ bot. */
1137 static void helpserv_botmsg(struct userNode *user, struct userNode *target, const char *text, UNUSED_ARG(int server_qualified)) {
1138     struct helpserv_bot *hs;
1139     struct helpserv_cmd *cmd;
1140     struct helpserv_user *hs_user;
1141     char *argv[MAXNUMPARAMS];
1142     char tmpline[MAXLEN];
1143     int argc, argv_shift;
1144     const int from_opserv = 0; /* for helpserv_notice */
1145
1146     /* Ignore things consisting of empty lines or from ourselves */
1147     if (!*text || IsLocal(user))
1148         return;
1149
1150     hs = dict_find(helpserv_bots_dict, target->nick, NULL);
1151
1152     /* See if we should listen to their message as a command (helper)
1153      * or a help request (user) */
1154     if (!user->handle_info || !(hs_user = dict_find(hs->users, user->handle_info->handle, NULL))) {
1155         helpserv_usermsg(user, hs, text);
1156         return;
1157     }
1158
1159     argv_shift = 1;
1160     safestrncpy(tmpline, text, sizeof(tmpline));
1161     argc = split_line(tmpline, false, ArrayLength(argv)-argv_shift, argv+argv_shift);
1162     if (!argc)
1163         return;
1164
1165     cmd = dict_find(helpserv_func_dict, argv[argv_shift], NULL);
1166     if (!cmd) {
1167         helpserv_notice(user, "MSG_COMMAND_UNKNOWN", argv[argv_shift]);
1168         return;
1169     }
1170     if (cmd->flags & CMD_FROM_OPSERV_ONLY) {
1171         helpserv_notice(user, "HSMSG_OPER_CMD");
1172         return;
1173     }
1174     if (cmd->access > hs_user->level) {
1175         helpserv_notice(user, "HSMSG_LEVEL_TOO_LOW");
1176         return;
1177     }
1178     if (!cmd->func) {
1179         helpserv_notice(user, "HSMSG_INTERNAL_COMMAND", argv[argv_shift]);
1180     } else if (cmd->func(user, hs, 0, argc, argv+argv_shift)) {
1181         unsplit_string(argv+argv_shift, argc, tmpline);
1182         log_audit(HS_LOG, LOG_COMMAND, user, hs->helpserv, hs->helpchan->name, 0, tmpline);
1183     }
1184 }
1185
1186 /* Handle a control command from an IRC operator */
1187 static MODCMD_FUNC(cmd_helpserv) {
1188     struct helpserv_bot *hs = NULL;
1189     struct helpserv_cmd *subcmd;
1190     const int from_opserv = 1; /* for helpserv_notice */
1191     char botnick[NICKLEN+1]; /* in case command is unregister */
1192     int retval;
1193
1194     if (argc < 2) {
1195         send_help(user, opserv, helpserv_helpfile, NULL);
1196         return 0;
1197     }
1198
1199     if (!(subcmd = dict_find(helpserv_func_dict, argv[1], NULL))) {
1200         helpserv_notice(user, "MSG_COMMAND_UNKNOWN", argv[1]);
1201         return 0;
1202     }
1203
1204     if (!subcmd->func) {
1205         helpserv_notice(user, "HSMSG_INTERNAL_COMMAND", argv[1]);
1206         return 0;
1207     }
1208
1209     if ((subcmd->flags & CMD_NEED_BOT) && ((argc < 3) || !(hs = dict_find(helpserv_bots_dict, argv[2], NULL)))) {
1210         helpserv_notice(user, "HSMSG_INVALID_BOT");
1211         return 0;
1212     }
1213
1214     if (subcmd->flags & CMD_NEVER_FROM_OPSERV) {
1215         helpserv_notice(user, "HSMSG_NO_USE_OPSERV");
1216         return 0;
1217     }
1218
1219     if (hs) {
1220         argv[2] = argv[1];
1221         strcpy(botnick, hs->helpserv->nick);
1222         retval = subcmd->func(user, hs, 1, argc-2, argv+2);
1223     } else {
1224         strcpy(botnick, "No bot");
1225         retval = subcmd->func(user, hs, 1, argc-1, argv+1);
1226     }
1227
1228     return retval;
1229 }
1230
1231 static void helpserv_help(struct helpserv_bot *hs, int from_opserv, struct userNode *user, const char *topic) {
1232     send_help(user, (from_opserv ? opserv : hs->helpserv), helpserv_helpfile, topic);
1233 }
1234
1235 static int append_entry(const char *key, UNUSED_ARG(void *data), void *extra) {
1236     struct helpfile_expansion *exp = extra;
1237     int row;
1238
1239     row = exp->value.table.length++;
1240     exp->value.table.contents[row] = calloc(1, sizeof(char*));
1241     exp->value.table.contents[row][0] = key;
1242     return 0;
1243 }
1244
1245 static struct helpfile_expansion helpserv_expand_variable(const char *variable) {
1246     struct helpfile_expansion exp;
1247
1248     if (!irccasecmp(variable, "index")) {
1249         exp.type = HF_TABLE;
1250         exp.value.table.length = 1;
1251         exp.value.table.width = 1;
1252         exp.value.table.flags = TABLE_REPEAT_ROWS;
1253         exp.value.table.contents = calloc(dict_size(helpserv_func_dict)+1, sizeof(char**));
1254         exp.value.table.contents[0] = calloc(1, sizeof(char*));
1255         exp.value.table.contents[0][0] = "Commands:";
1256         dict_foreach(helpserv_func_dict, append_entry, &exp);
1257         return exp;
1258     }
1259
1260     exp.type = HF_STRING;
1261     exp.value.str = NULL;
1262     return exp;
1263 }
1264
1265 static void helpserv_helpfile_read(void) {
1266     helpserv_helpfile = open_helpfile(HELPSERV_HELPFILE_NAME, helpserv_expand_variable);
1267 }
1268
1269 static HELPSERV_USERCMD(usercmd_wait) {
1270     struct helpserv_request *other;
1271     int pos, count;
1272     char buf[INTERVALLEN];
1273
1274     if (req->helper) {
1275         if (likely_helper)
1276             helpserv_user_reply("HSMSG_YOU_BEING_HELPED_BY", likely_helper->nick);
1277         else
1278             helpserv_user_reply("HSMSG_YOU_BEING_HELPED");
1279         return;
1280     }
1281
1282     for (other = req->hs->unhandled, pos = -1, count = 0;
1283          other;
1284          other = other->next_unhandled, ++count) {
1285         if (other == req)
1286             pos = count;
1287     }
1288     assert(pos >= 0);
1289     intervalString(buf, now - req->hs->unhandled->opened, req->user->handle_info);
1290     helpserv_user_reply("HSMSG_WAIT_STATUS", pos+1, count, buf);
1291 }
1292
1293 static HELPSERV_FUNC(cmd_help) {
1294     const char *topic;
1295
1296     if (argc < 2)
1297         topic = NULL;
1298     else
1299         topic = unsplit_string(argv+1, argc-1, NULL);
1300     helpserv_help(hs, from_opserv, user, topic);
1301
1302     return 1;
1303 }
1304
1305 static HELPSERV_FUNC(cmd_readhelp) {
1306     struct timeval start, stop;
1307     struct helpfile *old_helpfile = helpserv_helpfile;
1308
1309     gettimeofday(&start, NULL);
1310     helpserv_helpfile_read();
1311     if (helpserv_helpfile) {
1312         close_helpfile(old_helpfile);
1313     } else {
1314         helpserv_helpfile = old_helpfile;
1315     }
1316     gettimeofday(&stop, NULL);
1317     stop.tv_sec -= start.tv_sec;
1318     stop.tv_usec -= start.tv_usec;
1319     if (stop.tv_usec < 0) {
1320         stop.tv_sec -= 1;
1321         stop.tv_usec += 1000000;
1322     }
1323     helpserv_notice(user, "HSMSG_READHELP_SUCCESS", (unsigned long)stop.tv_sec, (unsigned long)stop.tv_usec/1000);
1324
1325     return 1;
1326 }
1327
1328 static struct helpserv_user * helpserv_add_user(struct helpserv_bot *hs, struct handle_info *handle, enum helpserv_level level) {
1329     struct helpserv_user *hs_user;
1330     struct helpserv_userlist *userlist;
1331
1332     hs_user = calloc(1, sizeof(struct helpserv_user));
1333     hs_user->handle = handle;
1334     hs_user->hs = hs;
1335     hs_user->help_mode = 0;
1336     hs_user->level = level;
1337     hs_user->join_time = find_handle_in_channel(hs->helpchan, handle, NULL) ? now : 0;
1338     dict_insert(hs->users, handle->handle, hs_user);
1339
1340     if (!(userlist = dict_find(helpserv_users_byhand_dict, handle->handle, NULL))) {
1341         userlist = helpserv_userlist_alloc();
1342         dict_insert(helpserv_users_byhand_dict, handle->handle, userlist);
1343     }
1344     helpserv_userlist_append(userlist, hs_user);
1345
1346     return hs_user;
1347 }
1348
1349 static void helpserv_del_user(struct helpserv_bot *hs, struct helpserv_user *hs_user) {
1350     dict_remove(hs->users, hs_user->handle->handle);
1351 }
1352
1353 static int cmd_add_user(struct helpserv_bot *hs, int from_opserv, struct userNode *user, enum helpserv_level level, int argc, char *argv[]) {
1354     struct helpserv_user *actor, *new_user;
1355     struct handle_info *handle;
1356
1357     REQUIRE_PARMS(2);
1358
1359     if (!from_opserv) {
1360         actor = GetHSUser(hs, user->handle_info);
1361         if (actor->level < HlManager) {
1362             helpserv_notice(user, "HSMSG_CANNOT_ADD");
1363             return 0;
1364         }
1365     } else {
1366         actor = NULL;
1367     }
1368
1369     if (!(handle = helpserv_get_handle_info(user, argv[1])))
1370         return 0;
1371
1372     if (GetHSUser(hs, handle)) {
1373         helpserv_notice(user, "HSMSG_USER_EXISTS", handle->handle);
1374         return 0;
1375     }
1376
1377     if (!(from_opserv) && actor && (actor->level <= level)) {
1378         helpserv_notice(user, "HSMSG_NO_BUMP_ACCESS");
1379         return 0;
1380     }
1381
1382     new_user = helpserv_add_user(hs, handle, level);
1383
1384     helpserv_notice(user, "HSMSG_ADDED_USER", helpserv_level2str(level), handle->handle);
1385     return 1;
1386 }
1387
1388 static HELPSERV_FUNC(cmd_deluser) {
1389     struct helpserv_user *actor=NULL, *victim;
1390     struct handle_info *handle;
1391     enum helpserv_level level;
1392
1393     REQUIRE_PARMS(2);
1394
1395     if (!from_opserv) {
1396         actor = GetHSUser(hs, user->handle_info);
1397         if (actor->level < HlManager) {
1398             helpserv_notice(user, "HSMSG_CANNOT_DEL");
1399             return 0;
1400         }
1401     }
1402
1403     if (!(handle = helpserv_get_handle_info(user, argv[1])))
1404         return 0;
1405
1406     if (!(victim = GetHSUser(hs, handle))) {
1407         helpserv_notice(user, "HSMSG_NOT_IN_USERLIST", handle->handle, hs->helpserv->nick);
1408         return 0;
1409     }
1410
1411     if (!from_opserv && actor && (actor->level <= victim->level)) {
1412         helpserv_notice(user, "MSG_USER_OUTRANKED", victim->handle->handle);
1413         return 0;
1414     }
1415
1416     level = victim->level;
1417     helpserv_del_user(hs, victim);
1418     helpserv_notice(user, "HSMSG_DELETED_USER", helpserv_level2str(level), handle->handle);
1419     return 1;
1420 }
1421
1422 static int
1423 helpserv_user_comp(const void *arg_a, const void *arg_b)
1424 {
1425     const struct helpserv_user *a = *(struct helpserv_user**)arg_a;
1426     const struct helpserv_user *b = *(struct helpserv_user**)arg_b;
1427     int res;
1428     if (a->level != b->level)
1429         res = b->level - a->level;
1430     else
1431         res = irccasecmp(a->handle->handle, b->handle->handle);
1432     return res;
1433 }
1434
1435 static int show_helper_range(struct userNode *user, struct helpserv_bot *hs, int from_opserv, enum helpserv_level min_lvl, enum helpserv_level max_lvl) {
1436     struct helpserv_userlist users;
1437     struct helpfile_table tbl;
1438     struct helpserv_user *hs_user;
1439     dict_iterator_t it;
1440     enum helpserv_level last_level;
1441     unsigned int ii;
1442
1443     users.used = 0;
1444     users.size = dict_size(hs->users);
1445     users.list = alloca(users.size*sizeof(hs->users[0]));
1446     helpserv_notice(user, "HSMSG_USERLIST_HEADER", hs->helpserv->nick);
1447     for (it = dict_first(hs->users); it; it = iter_next(it)) {
1448         hs_user = iter_data(it);
1449         if (hs_user->level < min_lvl)
1450             continue;
1451         if (hs_user->level > max_lvl)
1452             continue;
1453         users.list[users.used++] = hs_user;
1454     }
1455     if (!users.used) {
1456         helpserv_notice(user, "MSG_NONE");
1457         return 1;
1458     }
1459     qsort(users.list, users.used, sizeof(users.list[0]), helpserv_user_comp);
1460     switch (user->handle_info->userlist_style) {
1461     case HI_STYLE_DEF:
1462         tbl.length = users.used + 1;
1463         tbl.width = 3;
1464         tbl.flags = TABLE_NO_FREE;
1465         tbl.contents = alloca(tbl.length * sizeof(tbl.contents[0]));
1466         tbl.contents[0] = alloca(tbl.width * sizeof(tbl.contents[0][0]));
1467         tbl.contents[0][0] = "Level";
1468         tbl.contents[0][1] = "Handle";
1469         tbl.contents[0][2] = "WeekStart";
1470         for (ii = 0; ii < users.used; ) {
1471             hs_user = users.list[ii++];
1472             tbl.contents[ii] = alloca(tbl.width * sizeof(tbl.contents[0][0]));
1473             tbl.contents[ii][0] = helpserv_level_names[hs_user->level];
1474             tbl.contents[ii][1] = hs_user->handle->handle;
1475             tbl.contents[ii][2] = weekday_names[hs_user->week_start];
1476         }
1477         table_send((from_opserv ? opserv : hs->helpserv), user->nick, 0, NULL, tbl);
1478         break;
1479     case HI_STYLE_ZOOT: default:
1480         last_level = HlNone;
1481         tbl.length = 0;
1482         tbl.width = 1;
1483         tbl.flags = TABLE_NO_FREE | TABLE_REPEAT_ROWS | TABLE_NO_HEADERS;
1484         tbl.contents = alloca(users.used * sizeof(tbl.contents[0]));
1485         for (ii = 0; ii < users.used; ) {
1486             hs_user = users.list[ii++];
1487             if (hs_user->level != last_level) {
1488                 if (tbl.length) {
1489                     helpserv_notice(user, "HSMSG_USERLIST_ZOOT_LVL", hs->helpserv->nick, helpserv_level_names[last_level]);
1490                     table_send((from_opserv ? opserv : hs->helpserv), user->nick, 0, NULL, tbl);
1491                     tbl.length = 0;
1492                 }
1493                 last_level = hs_user->level;
1494             }
1495             tbl.contents[tbl.length] = alloca(tbl.width * sizeof(tbl.contents[0][0]));
1496             tbl.contents[tbl.length++][0] = hs_user->handle->handle;
1497         }
1498         if (tbl.length) {
1499             helpserv_notice(user, "HSMSG_USERLIST_ZOOT_LVL", hs->helpserv->nick, helpserv_level_names[last_level]);
1500             table_send((from_opserv ? opserv : hs->helpserv), user->nick, 0, NULL, tbl);
1501         }
1502     }
1503     return 1;
1504 }
1505
1506 static HELPSERV_FUNC(cmd_helpers) {
1507     return show_helper_range(user, hs, from_opserv, HlTrial, HlOwner);
1508 }
1509
1510 static HELPSERV_FUNC(cmd_wlist) {
1511     return show_helper_range(user, hs, from_opserv, HlOwner, HlOwner);
1512 }
1513
1514 static HELPSERV_FUNC(cmd_mlist) {
1515     return show_helper_range(user, hs, from_opserv, HlManager, HlManager);
1516 }
1517
1518 static HELPSERV_FUNC(cmd_hlist) {
1519     return show_helper_range(user, hs, from_opserv, HlHelper, HlHelper);
1520 }
1521
1522 static HELPSERV_FUNC(cmd_tlist) {
1523     return show_helper_range(user, hs, from_opserv, HlTrial, HlTrial);
1524 }
1525
1526 static HELPSERV_FUNC(cmd_addowner) {
1527     return cmd_add_user(hs, from_opserv, user, HlOwner, argc, argv);
1528 }
1529
1530 static HELPSERV_FUNC(cmd_addmanager) {
1531     return cmd_add_user(hs, from_opserv, user, HlManager, argc, argv);
1532 }
1533
1534 static HELPSERV_FUNC(cmd_addhelper) {
1535     return cmd_add_user(hs, from_opserv, user, HlHelper, argc, argv);
1536 }
1537
1538 static HELPSERV_FUNC(cmd_addtrial) {
1539     return cmd_add_user(hs, from_opserv, user, HlTrial, argc, argv);
1540 }
1541
1542 static HELPSERV_FUNC(cmd_clvl) {
1543     struct helpserv_user *actor=NULL, *victim;
1544     struct handle_info *handle;
1545     enum helpserv_level level;
1546
1547     REQUIRE_PARMS(3);
1548
1549     if (!from_opserv) {
1550         actor = GetHSUser(hs, user->handle_info);
1551         if (actor->level < HlManager) {
1552             helpserv_notice(user, "HSMSG_CANNOT_CLVL");
1553             return 0;
1554         }
1555     }
1556
1557     if (!(handle = helpserv_get_handle_info(user, argv[1])))
1558         return 0;
1559
1560     if (!(victim = GetHSUser(hs, handle))) {
1561         helpserv_notice(user, "HSMSG_NOT_IN_USERLIST", handle->handle, hs->helpserv->nick);
1562         return 0;
1563     }
1564
1565     if (((level = helpserv_str2level(argv[2])) == HlNone) || level == HlOper) {
1566         helpserv_notice(user, "HSMSG_INVALID_ACCESS", argv[2]);
1567         return 0;
1568     }
1569
1570     if (!(from_opserv) && actor) {
1571         if (actor == victim) {
1572             helpserv_notice(user, "HSMSG_NO_SELF_CLVL");
1573             return 0;
1574         }
1575
1576         if (actor->level <= victim->level) {
1577             helpserv_notice(user, "MSG_USER_OUTRANKED", victim->handle->handle);
1578             return 0;
1579         }
1580
1581         if (level >= actor->level) {
1582             helpserv_notice(user, "HSMSG_NO_BUMP_ACCESS");
1583             return 0;
1584         }
1585     }
1586
1587     victim->level = level;
1588     helpserv_notice(user, "HSMSG_CHANGED_ACCESS", handle->handle, helpserv_level2str(level));
1589
1590     return 1;
1591 }
1592
1593 static void free_request(void *data) {
1594     struct helpserv_request *req = data;
1595
1596     /* Logging */
1597     if (shutting_down && (req->hs->persist_types[PERSIST_T_REQUEST] != PERSIST_CLOSE || !req->handle)) {
1598         helpserv_log_request(req, "srvx shutdown");
1599     }
1600
1601     /* Clean up from the unhandled queue */
1602     if (req->hs->unhandled) {
1603         if (req->hs->unhandled == req) {
1604             req->hs->unhandled = req->next_unhandled;
1605         } else {
1606             struct helpserv_request *uh;
1607             for (uh=req->hs->unhandled; uh->next_unhandled && (uh->next_unhandled != req); uh = uh->next_unhandled);
1608             if (uh->next_unhandled) {
1609                 uh->next_unhandled = req->next_unhandled;
1610             }
1611         }
1612     }
1613
1614     /* Clean up the lists */
1615     if (req->parent_nick_list) {
1616         if (req->parent_nick_list->used == 1) {
1617             dict_remove(helpserv_reqs_bynick_dict, req->user->nick);
1618         } else {
1619             helpserv_reqlist_remove(req->parent_nick_list, req);
1620         }
1621     }
1622     if (req->parent_hand_list) {
1623         if (req->parent_hand_list->used == 1) {
1624             dict_remove(helpserv_reqs_byhand_dict, req->handle->handle);
1625         } else {
1626             helpserv_reqlist_remove(req->parent_hand_list, req);
1627         }
1628     }
1629
1630     free_string_list(req->text);
1631     free(req);
1632 }
1633
1634 static HELPSERV_FUNC(cmd_close) {
1635     struct helpserv_request *req, *newest=NULL;
1636     struct helpserv_reqlist *nick_list, *hand_list;
1637     struct helpserv_user *hs_user=GetHSUser(hs, user->handle_info);
1638     struct userNode *req_user=NULL;
1639     char close_reason[MAXLEN], reqnum[12];
1640     unsigned long old_req;
1641     unsigned int i;
1642     int num_requests=0;
1643
1644     REQUIRE_PARMS(2);
1645
1646     assert(hs_user);
1647
1648     if (!(req = smart_get_request(hs, hs_user, argv[1], &num_requests))) {
1649         helpserv_notice(user, "HSMSG_REQ_INVALID", argv[1]);
1650         return 0;
1651     }
1652
1653     sprintf(reqnum, "%lu", req->id);
1654
1655     if (num_requests > 1)
1656         helpserv_notice(user, "HSMSG_REQ_FOUNDMANY");
1657
1658     if (hs_user->level < HlManager && req->helper != hs_user) {
1659         if (req->helper)
1660             helpserv_notice(user, "HSMSG_REQ_NOT_YOURS_ASSIGNED_TO", req->id, req->helper->handle->handle);
1661         else
1662             helpserv_notice(user, "HSMSG_REQ_NOT_YOURS_UNASSIGNED", req->id);
1663         return 0;
1664     }
1665
1666     helpserv_notice(user, "HSMSG_REQ_CLOSED", req->id);
1667     if (req->user) {
1668         req_user = req->user;
1669         helpserv_message(hs, req->user, MSGTYPE_REQ_CLOSED);
1670         if (req->handle)
1671             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_CLOSE_REQUEST_1", req->id, req->user->nick, req->handle->handle, user->nick);
1672         else
1673             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_CLOSE_REQUEST_2", req->id, req->user->nick, user->nick);
1674     } else {
1675         if (req->handle)
1676             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_CLOSE_REQUEST_3", req->id, req->handle->handle, user->nick);
1677         else
1678             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_CLOSE_REQUEST_4", req->id, user->nick);
1679     }
1680
1681     hs_user->closed[0]++;
1682     hs_user->closed[4]++;
1683
1684     /* Set these to keep track of the lists after the request is gone, but
1685      * not if free_request() will helpserv_reqlist_free() them. */
1686     nick_list = req->parent_nick_list;
1687     if (nick_list && (nick_list->used == 1))
1688         nick_list = NULL;
1689     hand_list = req->parent_hand_list;
1690     if (hand_list && (hand_list->used == 1))
1691         hand_list = NULL;
1692     old_req = req->id;
1693
1694     if (argc >= 3) {
1695         snprintf(close_reason, MAXLEN, "Closed by %s: %s", user->handle_info->handle, unsplit_string(argv+2, argc-2, NULL));
1696     } else {
1697         sprintf(close_reason, "Closed by %s", user->handle_info->handle);
1698     }
1699     helpserv_log_request(req, close_reason);
1700     dict_remove(hs->requests, reqnum);
1701
1702     /* Look for other requests associated with them */
1703     if (nick_list) {
1704         for (i=0; i < nick_list->used; i++) {
1705             req = nick_list->list[i];
1706
1707             if (req->hs != hs)
1708                 continue;
1709             if (!newest || (newest->opened < req->opened))
1710                 newest = req;
1711         }
1712
1713         if (newest)
1714             helpserv_msguser(newest->user, "HSMSG_REQ_FOUND_ANOTHER", old_req, newest->id);
1715     }
1716
1717     if (req_user && hs->auto_devoice) {
1718         struct modeNode *mn = GetUserMode(hs->helpchan, req_user);
1719         if ((!newest || !newest->helper) && mn && (mn->modes & MODE_VOICE)) {
1720             struct mod_chanmode change;
1721             mod_chanmode_init(&change);
1722             change.argc = 1;
1723             change.args[0].mode = MODE_REMOVE | MODE_VOICE;
1724             change.args[0].u.member = mn;
1725             mod_chanmode_announce(hs->helpserv, hs->helpchan, &change);
1726         }
1727     }
1728
1729     return 1;
1730 }
1731
1732 static HELPSERV_FUNC(cmd_list) {
1733     dict_iterator_t it;
1734     int searchtype;
1735     struct helpfile_table tbl;
1736     unsigned int line, total;
1737     struct helpserv_request *req;
1738
1739     if ((argc < 2) || !irccasecmp(argv[1], "unassigned")) {
1740         for (req = hs->unhandled, total=0; req; req = req->next_unhandled, total++) ;
1741         helpserv_notice(user, "HSMSG_REQ_LIST_TOP_UNASSIGNED", total);
1742         searchtype = 1; /* Unassigned */
1743     } else if (!irccasecmp(argv[1], "assigned")) {
1744         for (req = hs->unhandled, total=dict_size(hs->requests); req; req = req->next_unhandled, total--) ;
1745         helpserv_notice(user, "HSMSG_REQ_LIST_TOP_ASSIGNED", total);
1746         searchtype = 2; /* Assigned */
1747     } else if (!irccasecmp(argv[1], "me")) {
1748         for (total = 0, it = dict_first(hs->requests); it; it = iter_next(it)) {
1749             req = iter_data(it);
1750             if (req->helper && (req->helper->handle == user->handle_info))
1751                 total++;
1752         }
1753         helpserv_notice(user, "HSMSG_REQ_LIST_TOP_YOUR", total);
1754         searchtype = 4;
1755     } else if (!irccasecmp(argv[1], "all")) {
1756         total = dict_size(hs->requests);
1757         helpserv_notice(user, "HSMSG_REQ_LIST_TOP_ALL", total);
1758         searchtype = 3; /* All */
1759     } else {
1760         helpserv_notice(user, "HSMSG_BAD_REQ_TYPE", argv[1]);
1761         return 0;
1762     }
1763
1764     if (!total) {
1765         helpserv_notice(user, "HSMSG_REQ_LIST_NONE");
1766         return 1;
1767     }
1768
1769     tbl.length = total+1;
1770     tbl.width = 5;
1771     tbl.flags = TABLE_NO_FREE;
1772     tbl.contents = alloca(tbl.length * sizeof(*tbl.contents));
1773     tbl.contents[0] = alloca(tbl.width * sizeof(**tbl.contents));
1774     tbl.contents[0][0] = "ID#";
1775     tbl.contents[0][1] = "User";
1776     tbl.contents[0][2] = "Helper";
1777     tbl.contents[0][3] = "Time open";
1778     tbl.contents[0][4] = "User status";
1779
1780     for (it=dict_first(hs->requests), line=0; it; it=iter_next(it)) {
1781         char opentime[INTERVALLEN], reqid[12], username[NICKLEN+2];
1782
1783         req = iter_data(it);
1784
1785         switch (searchtype) {
1786         case 1:
1787             if (req->helper)
1788                 continue;
1789             break;
1790         case 2:
1791             if (!req->helper)
1792                 continue;
1793             break;
1794         case 3:
1795         default:
1796             break;
1797         case 4:
1798             if (!req->helper || (req->helper->handle != user->handle_info))
1799                 continue;
1800             break;
1801         }
1802
1803         line++;
1804
1805         tbl.contents[line] = alloca(tbl.width * sizeof(**tbl.contents));
1806         sprintf(reqid, "%lu", req->id);
1807         tbl.contents[line][0] = strdup(reqid);
1808         if (req->user) {
1809             strcpy(username, req->user->nick);
1810         } else {
1811             username[0] = '*';
1812             strcpy(username+1, req->handle->handle);
1813         }
1814         tbl.contents[line][1] = strdup(username);
1815         tbl.contents[line][2] = req->helper ? req->helper->handle->handle : "(Unassigned)";
1816         intervalString(opentime, now - req->opened, user->handle_info);
1817         tbl.contents[line][3] = strdup(opentime);
1818         tbl.contents[line][4] = ((req->user || req->handle->users) ? "Online" : "Offline");
1819     }
1820
1821     table_send((from_opserv ? opserv : hs->helpserv), user->nick, 0, NULL, tbl);
1822
1823     for (; line > 0; line--) {
1824         free((char *)tbl.contents[line][0]);
1825         free((char *)tbl.contents[line][1]);
1826         free((char *)tbl.contents[line][3]);
1827     }
1828
1829     return 1;
1830 }
1831
1832 static void helpserv_show(int from_opserv, struct helpserv_bot *hs, struct userNode *user, struct helpserv_request *req) {
1833     unsigned int nn;
1834     char buf[MAX_LINE_SIZE];
1835     char buf2[INTERVALLEN];
1836     time_t feh;
1837
1838     if (req->user)
1839         if (req->handle)
1840             helpserv_notice(user, "HSMSG_REQ_INFO_2a", req->user->nick, req->handle->handle);
1841         else
1842             helpserv_notice(user, "HSMSG_REQ_INFO_2b", req->user->nick);
1843     else if (req->handle)
1844         if (req->handle->users)
1845             helpserv_notice(user, "HSMSG_REQ_INFO_2c", req->handle->handle);
1846         else
1847             helpserv_notice(user, "HSMSG_REQ_INFO_2d", req->handle->handle);
1848     else
1849         helpserv_notice(user, "HSMSG_REQ_INFO_2e");
1850     feh = req->opened;
1851     strftime(buf, MAX_LINE_SIZE, HSFMT_TIME, localtime(&feh));
1852     intervalString(buf2, now - req->opened, user->handle_info);
1853     helpserv_notice(user, "HSMSG_REQ_INFO_3", buf, buf2);
1854     helpserv_notice(user, "HSMSG_REQ_INFO_4");
1855     for (nn=0; nn < req->text->used; nn++)
1856         helpserv_notice(user, "HSMSG_REQ_INFO_MESSAGE", req->text->list[nn]);
1857 }
1858
1859 /* actor is the one who executed the command... it should == user except from
1860  * cmd_assign */
1861 static int helpserv_assign(int from_opserv, struct helpserv_bot *hs, struct userNode *user, struct userNode *actor, struct helpserv_request *req) {
1862     struct helpserv_request *req2;
1863     struct helpserv_user *old_helper;
1864
1865     if (!user->handle_info)
1866         return 0;
1867     if ((hs->persist_types[PERSIST_T_HELPER] == PERSIST_PART) && !GetUserMode(hs->helpchan, user)) {
1868         struct helpserv_user *hsuser_actor = GetHSUser(hs, actor->handle_info);
1869         if (hsuser_actor->level < HlManager) {
1870             helpserv_notice(user, "HSMSG_REQ_YOU_NOT_IN_HELPCHAN", hs->helpchan->name);
1871             return 0;
1872         } else if (user != actor) {
1873             helpserv_notice(user, "HSMSG_REQ_YOU_NOT_IN_OVERRIDE", hs->helpchan->name);
1874             helpserv_notice(actor, "HSMSG_REQ_HIM_NOT_IN_OVERRIDE", user->nick, hs->helpchan->name);
1875         } else
1876             helpserv_notice(user, "HSMSG_REQ_SELF_NOT_IN_OVERRIDE", hs->helpchan->name);
1877     }
1878
1879     hs->last_active = now;
1880     if ((old_helper = req->helper)) {
1881         /* don't need to remove from the unhandled queue */
1882     } else if (hs->unhandled == req) {
1883         hs->unhandled = req->next_unhandled;
1884     } else for (req2 = hs->unhandled; req2; req2 = req2->next_unhandled) {
1885         if (req2->next_unhandled == req) {
1886             req2->next_unhandled = req->next_unhandled;
1887             break;
1888         }
1889     }
1890     req->next_unhandled = NULL;
1891     req->helper = GetHSUser(hs, user->handle_info);
1892     assert(req->helper);
1893     req->assigned = now;
1894
1895     if (old_helper) {
1896         helpserv_notice(user, "HSMSG_REQ_REASSIGNED", req->id, old_helper->handle->handle);
1897         req->helper->reassigned_to[0]++;
1898         req->helper->reassigned_to[4]++;
1899         old_helper->reassigned_from[0]++;
1900         old_helper->reassigned_from[4]++;
1901     } else {
1902         helpserv_notice(user, "HSMSG_REQ_ASSIGNED_YOU", req->id);
1903         req->helper->picked_up[0]++;
1904         req->helper->picked_up[4]++;
1905     }
1906     helpserv_show(from_opserv, hs, user, req);
1907     if (req->user) {
1908         helpserv_message(hs, req->user, MSGTYPE_REQ_ASSIGNED);
1909         if (old_helper) {
1910             helpserv_msguser(req->user, "HSMSG_REQ_ASSIGNED_AGAIN", req->id, user->handle_info->handle, user->nick);
1911         } else {
1912             helpserv_msguser(req->user, "HSMSG_REQ_ASSIGNED", req->id, user->handle_info->handle, user->nick);
1913         }
1914         if (req->handle)
1915             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_ASSIGN_REQUEST_1", req->id, req->user->nick, req->handle->handle, user->nick);
1916         else
1917             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_ASSIGN_REQUEST_2", req->id, req->user->nick, user->nick);
1918     } else {
1919         if (req->handle)
1920             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_ASSIGN_REQUEST_3", req->id, req->handle->handle, user->nick);
1921         else
1922             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_ASSIGN_REQUEST_4", req->id, user->nick);
1923     }
1924
1925     if (req->user && hs->auto_voice) {
1926         struct mod_chanmode change;
1927         mod_chanmode_init(&change);
1928         change.argc = 1;
1929         change.args[0].mode = MODE_VOICE;
1930         if ((change.args[0].u.member = GetUserMode(hs->helpchan, req->user)))
1931             mod_chanmode_announce(hs->helpserv, hs->helpchan, &change);
1932     }
1933
1934     return 1;
1935 }
1936
1937 static HELPSERV_FUNC(cmd_next) {
1938     struct helpserv_request *req;
1939
1940     if (!(req = hs->unhandled)) {
1941         helpserv_notice(user, "HSMSG_REQ_NO_UNASSIGNED");
1942         return 0;
1943     }
1944     return helpserv_assign(from_opserv, hs, user, user, req);
1945 }
1946
1947 static HELPSERV_FUNC(cmd_show) {
1948     struct helpserv_request *req;
1949     struct helpserv_user *hs_user=GetHSUser(hs, user->handle_info);
1950     int num_requests=0;
1951
1952     REQUIRE_PARMS(2);
1953
1954     if (!(req = smart_get_request(hs, hs_user, argv[1], &num_requests))) {
1955         helpserv_notice(user, "HSMSG_REQ_INVALID", argv[1]);
1956         return 0;
1957     }
1958
1959     if (num_requests > 1)
1960         helpserv_notice(user, "HSMSG_REQ_FOUNDMANY");
1961
1962     helpserv_notice(user, "HSMSG_REQ_INFO_1", req->id);
1963     helpserv_show(from_opserv, hs, user, req);
1964     return 1;
1965 }
1966
1967 static HELPSERV_FUNC(cmd_pickup) {
1968     struct helpserv_request *req;
1969     struct helpserv_user *hs_user=GetHSUser(hs, user->handle_info);
1970     int num_requests=0;
1971
1972     REQUIRE_PARMS(2);
1973
1974     assert(hs_user);
1975
1976     if (!(req = smart_get_request(hs, hs_user, argv[1], &num_requests))) {
1977         helpserv_notice(user, "HSMSG_REQ_INVALID", argv[1]);
1978         return 0;
1979     }
1980
1981     if (num_requests > 1)
1982         helpserv_notice(user, "HSMSG_REQ_FOUNDMANY");
1983
1984     return helpserv_assign(from_opserv, hs, user, user, req);
1985 }
1986
1987 static HELPSERV_FUNC(cmd_reassign) {
1988     struct helpserv_request *req;
1989     struct userNode *targetuser;
1990     struct helpserv_user *target;
1991     struct helpserv_user *hs_user=GetHSUser(hs, user->handle_info);
1992     int num_requests=0;
1993
1994     REQUIRE_PARMS(3);
1995
1996     assert(hs_user);
1997
1998     if (!(req = smart_get_request(hs, hs_user, argv[1], &num_requests))) {
1999         helpserv_notice(user, "HSMSG_REQ_INVALID", argv[1]);
2000         return 0;
2001     }
2002
2003     if (num_requests > 1)
2004         helpserv_notice(user, "HSMSG_REQ_FOUNDMANY");
2005
2006     if (!(targetuser = GetUserH(argv[2]))) {
2007         helpserv_notice(user, "MSG_NICK_UNKNOWN", argv[2]);
2008         return 0;
2009     }
2010
2011     if (!targetuser->handle_info) {
2012         helpserv_notice(user, "MSG_USER_AUTHENTICATE", targetuser->nick);
2013         return 0;
2014     }
2015
2016     if (!(target = GetHSUser(hs, targetuser->handle_info))) {
2017         helpserv_notice(user, "HSMSG_NOT_IN_USERLIST", targetuser->nick, hs->helpserv->nick);
2018         return 0;
2019     }
2020
2021     if ((hs->persist_types[PERSIST_T_HELPER] == PERSIST_PART) && !GetUserMode(hs->helpchan, user) && (hs_user->level < HlManager)) {
2022         helpserv_notice(user, "HSMSG_REQ_HIM_NOT_IN_HELPCHAN", targetuser->nick, hs->helpchan->name);
2023         return 0;
2024     }
2025
2026     helpserv_assign(from_opserv, hs, targetuser, user, req);
2027     return 1;
2028 }
2029
2030 static HELPSERV_FUNC(cmd_addnote) {
2031     char text[MAX_LINE_SIZE], timestr[MAX_LINE_SIZE], *note;
2032     struct helpserv_request *req;
2033     struct helpserv_user *hs_user=GetHSUser(hs, user->handle_info);
2034     int num_requests=0;
2035     time_t feh;
2036
2037     REQUIRE_PARMS(3);
2038
2039     if (!(req = smart_get_request(hs, hs_user, argv[1], &num_requests))) {
2040         helpserv_notice(user, "HSMSG_REQ_INVALID", argv[1]);
2041         return 0;
2042     }
2043
2044     if (num_requests > 1)
2045         helpserv_notice(user, "HSMSG_REQ_FOUNDMANY");
2046
2047     note = unsplit_string(argv+2, argc-2, NULL);
2048
2049     feh = now;
2050     strftime(timestr, MAX_LINE_SIZE, HSFMT_TIME, localtime(&feh));
2051     snprintf(text, MAX_LINE_SIZE, "[Helper note at %s]:", timestr);
2052     string_list_append(req->text, strdup(text));
2053     snprintf(text, MAX_LINE_SIZE, "  <%s> %s", user->handle_info->handle, note);
2054     string_list_append(req->text, strdup(text));
2055
2056     helpserv_notice(user, "HSMSG_REQMSG_NOTE_ADDED", req->id);
2057
2058     return 1;
2059 }
2060
2061 static HELPSERV_FUNC(cmd_page) {
2062     REQUIRE_PARMS(2);
2063
2064     helpserv_page(PGSRC_COMMAND, "HSMSG_PAGE_REQUEST", user->nick, unsplit_string(argv+1, argc-1, NULL));
2065
2066     return 1;
2067 }
2068
2069 static HELPSERV_FUNC(cmd_stats) {
2070     struct helpserv_user *target, *hs_user;
2071     struct handle_info *target_handle;
2072     struct helpfile_table tbl;
2073     int i;
2074     char intervalstr[INTERVALLEN], buf[16];
2075
2076     hs_user = from_opserv ? NULL : GetHSUser(hs, user->handle_info);
2077
2078     if (argc > 1) {
2079         if (!from_opserv && (hs_user->level < HlManager)) {
2080             helpserv_notice(user, "HSMSG_NEED_MANAGER");
2081             return 0;
2082         }
2083
2084         if (!(target_handle = helpserv_get_handle_info(user, argv[1]))) {
2085             return 0;
2086         }
2087
2088         if (!(target = GetHSUser(hs, target_handle))) {
2089             helpserv_notice(user, "HSMSG_NOT_IN_USERLIST", target_handle->handle, hs->helpserv->nick);
2090             return 0;
2091         }
2092     } else {
2093         if (from_opserv) {
2094             helpserv_notice(user, "HSMSG_OPSERV_NEED_USER");
2095             return 0;
2096         }
2097         target = hs_user;
2098     }
2099
2100     helpserv_notice(user, "HSMSG_STATS_TOP", hs->helpserv->nick, target->handle->handle, weekday_names[target->week_start]);
2101
2102     tbl.length = 6;
2103     tbl.width = 2;
2104     tbl.flags = TABLE_NO_FREE;
2105     tbl.contents = alloca(tbl.length * sizeof(*tbl.contents));
2106     tbl.contents[0] = alloca(tbl.width * sizeof(**tbl.contents));
2107     tbl.contents[0][0] = "";
2108     tbl.contents[0][1] = "Recorded time";
2109     for (i=0; i < 5; i++) {
2110         unsigned int week_time = target->time_per_week[i];
2111         tbl.contents[i+1] = alloca(tbl.width * sizeof(**tbl.contents));
2112         if ((i == 0 || i == 4) && target->join_time)
2113             week_time += now - target->join_time;
2114         helpserv_interval(intervalstr, week_time);
2115         tbl.contents[i+1][1] = strdup(intervalstr);
2116     }
2117     tbl.contents[1][0] = "This week";
2118     tbl.contents[2][0] = "Last week";
2119     tbl.contents[3][0] = "2 weeks ago";
2120     tbl.contents[4][0] = "3 weeks ago";
2121     tbl.contents[5][0] = "Total";
2122
2123     helpserv_notice(user, "HSMSG_STATS_TIME", hs->helpchan->name);
2124     table_send((from_opserv ? opserv : hs->helpserv), user->nick, 0, NULL, tbl);
2125
2126     for (i=1; i <= 5; i++)
2127         free((char *)tbl.contents[i][1]);
2128
2129     tbl.length = 5;
2130     tbl.width = 4;
2131     tbl.flags = TABLE_NO_FREE;
2132     tbl.contents = alloca(tbl.length * sizeof(*tbl.contents));
2133     tbl.contents[0] = alloca(tbl.width * sizeof(**tbl.contents));
2134     tbl.contents[1] = alloca(tbl.width * sizeof(**tbl.contents));
2135     tbl.contents[2] = alloca(tbl.width * sizeof(**tbl.contents));
2136     tbl.contents[3] = alloca(tbl.width * sizeof(**tbl.contents));
2137     tbl.contents[4] = alloca(tbl.width * sizeof(**tbl.contents));
2138     tbl.contents[0][0] = "Category";
2139     tbl.contents[0][1] = "This week";
2140     tbl.contents[0][2] = "Last week";
2141     tbl.contents[0][3] = "Total";
2142
2143     tbl.contents[1][0] = "Requests picked up";
2144     for (i=0; i < 3; i++) {
2145         sprintf(buf, "%u", target->picked_up[(i == 2 ? 4 : i)]);
2146         tbl.contents[1][i+1] = strdup(buf);
2147     }
2148     tbl.contents[2][0] = "Requests closed";
2149     for (i=0; i < 3; i++) {
2150         sprintf(buf, "%u", target->closed[(i == 2 ? 4 : i)]);
2151         tbl.contents[2][i+1] = strdup(buf);
2152     }
2153     tbl.contents[3][0] = "Reassigned from";
2154     for (i=0; i < 3; i++) {
2155         sprintf(buf, "%u", target->reassigned_from[(i == 2 ? 4 : i)]);
2156         tbl.contents[3][i+1] = strdup(buf);
2157     }
2158     tbl.contents[4][0] = "Reassigned to";
2159     for (i=0; i < 3; i++) {
2160         sprintf(buf, "%u", target->reassigned_to[(i == 2 ? 4 : i)]);
2161         tbl.contents[4][i+1] = strdup(buf);
2162     }
2163
2164     helpserv_notice(user, "HSMSG_STATS_REQS");
2165     table_send((from_opserv ? opserv : hs->helpserv), user->nick, 0, NULL, tbl);
2166
2167     for (i=1; i < 5; i++) {
2168         free((char *)tbl.contents[i][1]);
2169         free((char *)tbl.contents[i][2]);
2170         free((char *)tbl.contents[i][3]);
2171     }
2172
2173     return 1;
2174 }
2175
2176 static HELPSERV_FUNC(cmd_statsreport) {
2177     int use_privmsg=1;
2178     struct helpfile_table tbl;
2179     dict_iterator_t it;
2180     unsigned int line, i;
2181     struct userNode *srcbot = from_opserv ? opserv : hs->helpserv;
2182
2183     if ((argc > 1) && !irccasecmp(argv[1], "NOTICE"))
2184         use_privmsg = 0;
2185
2186     tbl.length = dict_size(hs->users)+1;
2187     tbl.width = 3;
2188     tbl.flags = TABLE_NO_FREE;
2189     tbl.contents = alloca(tbl.length * sizeof(*tbl.contents));
2190     tbl.contents[0] = alloca(tbl.width * sizeof(**tbl.contents));
2191     tbl.contents[0][0] = "Account";
2192     tbl.contents[0][1] = "Requests";
2193     tbl.contents[0][2] = "Time helping";
2194
2195     for (it=dict_first(hs->users), line=0; it; it=iter_next(it)) {
2196         struct helpserv_user *hs_user=iter_data(it);
2197
2198         tbl.contents[++line] = alloca(tbl.width * sizeof(**tbl.contents));
2199         tbl.contents[line][0] = hs_user->handle->handle;
2200         tbl.contents[line][1] = malloc(12);
2201         tbl.contents[line][2] = malloc(32); /* A bit more than needed */
2202     }
2203
2204     /* 4 to 1 instead of 3 to 0 because it's unsigned */
2205     for (i=4; i > 0; i--) {
2206         for (it=dict_first(hs->users), line=0; it; it=iter_next(it)) {
2207             struct helpserv_user *hs_user = iter_data(it);
2208             /* Time */
2209             unsigned int week_time = hs_user->time_per_week[i-1];
2210             if ((i==1) && hs_user->join_time)
2211                 week_time += now - hs_user->join_time;
2212             helpserv_interval((char *)tbl.contents[++line][2], week_time);
2213
2214             /* Requests */
2215             sprintf((char *)tbl.contents[line][1], "%u", hs_user->picked_up[i-1]+hs_user->reassigned_to[i-1]);
2216         }
2217         send_target_message(use_privmsg, user->nick, srcbot, statsreport_week[i-1]);
2218         table_send(srcbot, user->nick, 0, (use_privmsg ? irc_privmsg : irc_notice), tbl);
2219     }
2220
2221     for (line=1; line <= dict_size(hs->users); line++) {
2222         free((char *)tbl.contents[line][1]);
2223         free((char *)tbl.contents[line][2]);
2224     }
2225
2226     return 1;
2227 }
2228
2229 static int
2230 helpserv_in_channel(struct helpserv_bot *hs, struct chanNode *channel) {
2231     enum page_source pgsrc;
2232     if (channel == hs->helpchan)
2233         return 1;
2234     for (pgsrc=0; pgsrc<PGSRC_COUNT; pgsrc++)
2235         if (channel == hs->page_targets[pgsrc])
2236             return 1;
2237     return 0;
2238 }
2239
2240 static HELPSERV_FUNC(cmd_move) {
2241     if (!hs) {
2242         helpserv_notice(user, "HSMSG_INVALID_BOT");
2243         return 0;
2244     }
2245
2246     REQUIRE_PARMS(2);
2247
2248     if (is_valid_nick(argv[1])) {
2249         char *newnick = argv[1], oldnick[NICKLEN], reason[MAXLEN];
2250
2251         strcpy(oldnick, hs->helpserv->nick);
2252
2253         if (GetUserH(newnick)) {
2254             helpserv_notice(user, "HSMSG_NICK_EXISTS", newnick);
2255             return 0;
2256         }
2257
2258         dict_remove2(helpserv_bots_dict, hs->helpserv->nick, 1);
2259         NickChange(hs->helpserv, newnick, 0);
2260         dict_insert(helpserv_bots_dict, hs->helpserv->nick, hs);
2261
2262         helpserv_notice(user, "HSMSG_RENAMED", oldnick, newnick);
2263
2264         snprintf(reason, MAXLEN, "HelpServ bot %s (in %s) renamed to %s by %s.", oldnick, hs->helpchan->name, newnick, user->nick);
2265         global_message(MESSAGE_RECIPIENT_OPERS, reason);
2266
2267         return 1;
2268     } else if (IsChannelName(argv[1])) {
2269         struct chanNode *old_helpchan = hs->helpchan;
2270         char *newchan = argv[1], oldchan[CHANNELLEN], reason[MAXLEN];
2271         struct helpserv_botlist *botlist;
2272
2273         strcpy(oldchan, hs->helpchan->name);
2274
2275         if (!irccasecmp(oldchan, newchan)) {
2276             helpserv_notice(user, "HSMSG_MOVE_SAME_CHANNEL", hs->helpserv->nick);
2277             return 0;
2278         }
2279
2280         if (opserv_bad_channel(newchan)) {
2281             helpserv_notice(user, "HSMSG_ILLEGAL_CHANNEL", newchan);
2282             return 0;
2283         }
2284
2285         botlist = dict_find(helpserv_bots_bychan_dict, hs->helpchan->name, NULL);
2286         helpserv_botlist_remove(botlist, hs);
2287         if (botlist->used == 0) {
2288             dict_remove(helpserv_bots_bychan_dict, hs->helpchan->name);
2289         }
2290
2291         hs->helpchan = NULL;
2292         if (!helpserv_in_channel(hs, old_helpchan)) {
2293             snprintf(reason, MAXLEN, "Moved to %s by %s.", newchan, user->nick);
2294             DelChannelUser(hs->helpserv, old_helpchan, reason, 0);
2295         }
2296
2297         if (!(hs->helpchan = GetChannel(newchan))) {
2298             hs->helpchan = AddChannel(newchan, now, NULL, NULL);
2299             AddChannelUser(hs->helpserv, hs->helpchan)->modes |= MODE_CHANOP;
2300         } else if (!helpserv_in_channel(hs, old_helpchan)) {
2301             struct mod_chanmode change;
2302             mod_chanmode_init(&change);
2303             change.argc = 1;
2304             change.args[0].mode = MODE_CHANOP;
2305             change.args[0].u.member = AddChannelUser(hs->helpserv, hs->helpchan);
2306             mod_chanmode_announce(hs->helpserv, hs->helpchan, &change);
2307         }
2308
2309         if (!(botlist = dict_find(helpserv_bots_bychan_dict, hs->helpchan->name, NULL))) {
2310             botlist = helpserv_botlist_alloc();
2311             dict_insert(helpserv_bots_bychan_dict, hs->helpchan->name, botlist);
2312         }
2313         helpserv_botlist_append(botlist, hs);
2314
2315         snprintf(reason, MAXLEN, "HelpServ %s (%s) moved to %s by %s.", hs->helpserv->nick, oldchan, newchan, user->nick);
2316         global_message(MESSAGE_RECIPIENT_OPERS, reason);
2317
2318         return 1;
2319     } else {
2320         helpserv_notice(user, "HSMSG_INVALID_MOVE", argv[1]);
2321         return 0;
2322     }
2323 }
2324
2325 static HELPSERV_FUNC(cmd_bots) {
2326     dict_iterator_t it;
2327     struct helpfile_table tbl;
2328     unsigned int i;
2329
2330     helpserv_notice(user, "HSMSG_BOTLIST_HEADER");
2331
2332     tbl.length = dict_size(helpserv_bots_dict)+1;
2333     tbl.width = 4;
2334     tbl.flags = TABLE_NO_FREE;
2335     tbl.contents = alloca(tbl.length * sizeof(*tbl.contents));
2336     tbl.contents[0] = alloca(tbl.width * sizeof(**tbl.contents));
2337     tbl.contents[0][0] = "Bot";
2338     tbl.contents[0][1] = "Channel";
2339     tbl.contents[0][2] = "Owner";
2340     tbl.contents[0][3] = "Inactivity";
2341
2342     for (it=dict_first(helpserv_bots_dict), i=1; it; it=iter_next(it), i++) {
2343         dict_iterator_t it2;
2344         struct helpserv_bot *bot;
2345         struct helpserv_user *owner=NULL;
2346
2347         bot = iter_data(it);
2348
2349         for (it2=dict_first(bot->users); it2; it2=iter_next(it2)) {
2350             if (((struct helpserv_user *)iter_data(it2))->level == HlOwner) {
2351                 owner = iter_data(it2);
2352                 break;
2353             }
2354         }
2355
2356         tbl.contents[i] = alloca(tbl.width * sizeof(**tbl.contents));
2357         tbl.contents[i][0] = iter_key(it);
2358         tbl.contents[i][1] = bot->helpchan->name;
2359         tbl.contents[i][2] = owner ? owner->handle->handle : "None";
2360         tbl.contents[i][3] = alloca(INTERVALLEN);
2361         intervalString((char*)tbl.contents[i][3], now - bot->last_active, user->handle_info);
2362     }
2363
2364     table_send((from_opserv ? opserv : hs->helpserv), user->nick, 0, NULL, tbl);
2365
2366     return 1;
2367 }
2368
2369 static void helpserv_page_helper_gone(struct helpserv_bot *hs, struct helpserv_request *req, const char *reason) {
2370     const int from_opserv = 0;
2371
2372     if (!req->helper)
2373         return;
2374
2375     /* Let the user know that their request is now unhandled */
2376     if (req->user) {
2377         struct modeNode *mn = GetUserMode(hs->helpchan, req->user);
2378         helpserv_msguser(req->user, "HSMSG_REQ_UNASSIGNED", req->id, reason);
2379         if (hs->auto_devoice && mn && (mn->modes & MODE_VOICE)) {
2380             struct mod_chanmode change;
2381             mod_chanmode_init(&change);
2382             change.argc = 1;
2383             change.args[0].mode = MODE_REMOVE | MODE_VOICE;
2384             change.args[0].u.member = mn;
2385             mod_chanmode_announce(hs->helpserv, hs->helpchan, &change);
2386         }
2387         if(req->handle)
2388             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_HELPER_GONE_1", req->id, req->user->nick, req->handle->handle, req->helper->handle->handle, reason);
2389         else
2390             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_HELPER_GONE_2", req->id, req->user->nick, req->helper->handle->handle, reason);
2391     } else {
2392         if(req->handle)
2393             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_HELPER_GONE_3", req->id, req->handle->handle, req->helper->handle->handle, reason);
2394         else
2395             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_HELPER_GONE_2", req->id, req->helper->handle->handle, reason);
2396     }
2397
2398     /* Now put it back in the queue */
2399     if (hs->unhandled == NULL) {
2400         /* Nothing there, put it at the front */
2401         hs->unhandled = req;
2402         req->next_unhandled = NULL;
2403     } else {
2404         /* Should it be at the front? */
2405         if (hs->unhandled->opened >= req->opened) {
2406             req->next_unhandled = hs->unhandled;
2407             hs->unhandled = req;
2408         } else {
2409             struct helpserv_request *unhandled;
2410             /* Find the request that this should be inserted AFTER */
2411             for (unhandled=hs->unhandled; unhandled->next_unhandled && (unhandled->next_unhandled->opened < req->opened); unhandled = unhandled->next_unhandled);
2412             req->next_unhandled = unhandled->next_unhandled;
2413             unhandled->next_unhandled = req;
2414         }
2415     }
2416
2417     req->helper = NULL;
2418 }
2419
2420 /* This takes care of WHINE_DELAY and IDLE_DELAY */
2421 static void run_whine_interval(void *data) {
2422     struct helpserv_bot *hs=data;
2423     struct helpfile_table tbl;
2424     unsigned int i;
2425
2426     /* First, run the WHINE_DELAY */
2427     if (hs->intervals[INTERVAL_WHINE_DELAY]
2428         && (hs->page_types[PGSRC_ALERT] != PAGE_NONE)
2429         && (hs->page_targets[PGSRC_ALERT] != NULL)
2430         && (!hs->intervals[INTERVAL_EMPTY_INTERVAL] || !hs->helpchan_empty)) {
2431         struct helpserv_request *unh;
2432         struct helpserv_reqlist reqlist;
2433         unsigned int queuesize=0;
2434
2435         helpserv_reqlist_init(&reqlist);
2436
2437         for (unh = hs->unhandled; unh; unh = unh->next_unhandled) {
2438             queuesize++;
2439             if ((now - unh->opened) >= hs->intervals[INTERVAL_WHINE_DELAY]) {
2440                 helpserv_reqlist_append(&reqlist, unh);
2441             }
2442         }
2443
2444         if (reqlist.used) {
2445             char strwhinedelay[INTERVALLEN];
2446
2447             intervalString(strwhinedelay, hs->intervals[INTERVAL_WHINE_DELAY], NULL);
2448 #if ANNOYING_ALERT_PAGES
2449             tbl.length = reqlist.used + 1;
2450             tbl.width = 4;
2451             tbl.flags = TABLE_NO_FREE;
2452             tbl.contents = alloca(tbl.length * sizeof(*tbl.contents));
2453             tbl.contents[0] = alloca(tbl.width * sizeof(**tbl.contents));
2454             tbl.contents[0][0] = "ID#";
2455             tbl.contents[0][1] = "Nick";
2456             tbl.contents[0][2] = "Account";
2457             tbl.contents[0][3] = "Waiting time";
2458
2459             for (i=1; i <= reqlist.used; i++) {
2460                 char reqid[12], unh_time[INTERVALLEN];
2461                 unh = reqlist.list[i-1];
2462
2463                 tbl.contents[i] = alloca(tbl.width * sizeof(**tbl.contents));
2464                 sprintf(reqid, "%lu", unh->id);
2465                 tbl.contents[i][0] = strdup(reqid);
2466                 tbl.contents[i][1] = unh->user ? unh->user->nick : "Not online";
2467                 tbl.contents[i][2] = unh->handle ? unh->handle->handle : "Not authed";
2468                 intervalString(unh_time, now - unh->opened, NULL);
2469                 tbl.contents[i][3] = strdup(unh_time);
2470             }
2471
2472             helpserv_page(PGSRC_ALERT, "HSMSG_PAGE_WHINE_HEADER", reqlist.used, strwhinedelay, queuesize, dict_size(hs->requests));
2473             table_send(hs->helpserv, hs->page_targets[PGSRC_ALERT]->name, 0, page_type_funcs[hs->page_types[PGSRC_ALERT]], tbl);
2474
2475             for (i=1; i <= reqlist.used; i++) {
2476                 free((char *)tbl.contents[i][0]);
2477                 free((char *)tbl.contents[i][3]);
2478             }
2479 #else
2480             helpserv_page(PGSRC_ALERT, "HSMSG_PAGE_WHINE_HEADER", reqlist.used, strwhinedelay, queuesize, dict_size(hs->requests));
2481 #endif
2482         }
2483
2484         helpserv_reqlist_clean(&reqlist);
2485     }
2486
2487     /* Next run IDLE_DELAY */
2488     if (hs->intervals[INTERVAL_IDLE_DELAY]
2489         && (hs->page_types[PGSRC_STATUS] != PAGE_NONE)
2490         && (hs->page_targets[PGSRC_STATUS] != NULL)) {
2491         struct modeList mode_list;
2492
2493         modeList_init(&mode_list);
2494
2495         for (i=0; i < hs->helpchan->members.used; i++) {
2496             struct modeNode *mn = hs->helpchan->members.list[i];
2497             /* Ignore ops. Perhaps this should be a set option? */
2498             if (mn->modes & MODE_CHANOP)
2499                 continue;
2500             /* Check if they've been idle long enough */
2501             if ((unsigned)(now - mn->idle_since) < hs->intervals[INTERVAL_IDLE_DELAY])
2502                 continue;
2503             /* Add them to the list of idle people.. */
2504             modeList_append(&mode_list, mn);
2505         }
2506
2507         if (mode_list.used) {
2508             char stridledelay[INTERVALLEN];
2509
2510             tbl.length = mode_list.used + 1;
2511             tbl.width = 4;
2512             tbl.flags = TABLE_NO_FREE;
2513             tbl.contents = alloca(tbl.length * sizeof(*tbl.contents));
2514             tbl.contents[0] = alloca(tbl.width * sizeof(**tbl.contents));
2515             tbl.contents[0][0] = "Nick";
2516             tbl.contents[0][1] = "Account";
2517             tbl.contents[0][2] = "ID#";
2518             tbl.contents[0][3] = "Idle time";
2519
2520             for (i=1; i <= mode_list.used; i++) {
2521                 char reqid[12], idle_time[INTERVALLEN];
2522                 struct helpserv_reqlist *reqlist;
2523                 struct modeNode *mn = mode_list.list[i-1];
2524
2525                 tbl.contents[i] = alloca(tbl.width * sizeof(**tbl.contents));
2526                 tbl.contents[i][0] = mn->user->nick;
2527                 tbl.contents[i][1] = mn->user->handle_info ? mn->user->handle_info->handle : "Not authed";
2528
2529                 if ((reqlist = dict_find(helpserv_reqs_bynick_dict, mn->user->nick, NULL))) {
2530                     int j;
2531
2532                     for (j = reqlist->used-1; j >= 0; j--) {
2533                         struct helpserv_request *req = reqlist->list[j];
2534
2535                         if (req->hs == hs) {
2536                             sprintf(reqid, "%lu", req->id);
2537                             break;
2538                         }
2539                     }
2540
2541                     if (j < 0)
2542                         strcpy(reqid, "None");
2543                 } else {
2544                     strcpy(reqid, "None");
2545                 }
2546                 tbl.contents[i][2] = strdup(reqid);
2547
2548                 intervalString(idle_time, now - mn->idle_since, NULL);
2549                 tbl.contents[i][3] = strdup(idle_time);
2550             }
2551
2552             intervalString(stridledelay, hs->intervals[INTERVAL_IDLE_DELAY], NULL);
2553             helpserv_page(PGSRC_STATUS, "HSMSG_PAGE_IDLE_HEADER", mode_list.used, hs->helpchan->name, stridledelay);
2554             table_send(hs->helpserv, hs->page_targets[PGSRC_STATUS]->name, 0, page_types[hs->page_types[PGSRC_STATUS]].func, tbl);
2555
2556             for (i=1; i <= mode_list.used; i++) {
2557                 free((char *)tbl.contents[i][2]);
2558                 free((char *)tbl.contents[i][3]);
2559             }
2560         }
2561
2562         modeList_clean(&mode_list);
2563     }
2564
2565     if (hs->intervals[INTERVAL_WHINE_INTERVAL]) {
2566         timeq_add(now + hs->intervals[INTERVAL_WHINE_INTERVAL], run_whine_interval, hs);
2567     }
2568 }
2569
2570 /* Returns -1 if there's any helpers,
2571  * 0 if there are no helpers
2572  * >1 if there are trials (number of trials)
2573  */
2574 static int find_helpchan_helpers(struct helpserv_bot *hs) {
2575     int num_trials=0;
2576     dict_iterator_t it;
2577
2578     for (it=dict_first(hs->users); it; it=iter_next(it)) {
2579         struct helpserv_user *hs_user=iter_data(it);
2580
2581         if (find_handle_in_channel(hs->helpchan, hs_user->handle, NULL)) {
2582             if (hs_user->level >= HlHelper) {
2583                 hs->helpchan_empty = 0;
2584                 return -1;
2585             }
2586             num_trials++;
2587         }
2588     }
2589
2590     hs->helpchan_empty = 1;
2591     return num_trials;
2592 }
2593
2594
2595 static void run_empty_interval(void *data) {
2596     struct helpserv_bot *hs=data;
2597     int num_trials=find_helpchan_helpers(hs);
2598     unsigned int num_unh;
2599     struct helpserv_request *unh;
2600
2601     if (num_trials == -1)
2602         return;
2603     if (hs->req_on_join && !hs->unhandled)
2604         return;
2605
2606     for (num_unh=0, unh=hs->unhandled; unh; num_unh++)
2607         unh = unh->next_unhandled;
2608
2609     if (num_trials)
2610         helpserv_page(PGSRC_ALERT, "HSMSG_PAGE_ONLYTRIALALERT", hs->helpchan->name, num_trials, num_unh);
2611     else
2612         helpserv_page(PGSRC_ALERT, "HSMSG_PAGE_EMPTYALERT", hs->helpchan->name, num_unh);
2613
2614     if (hs->intervals[INTERVAL_EMPTY_INTERVAL])
2615         timeq_add(now + hs->intervals[INTERVAL_EMPTY_INTERVAL], run_empty_interval, hs);
2616 }
2617
2618 static void free_user(void *data) {
2619     struct helpserv_user *hs_user = data;
2620     struct helpserv_bot *hs = hs_user->hs;
2621     struct helpserv_userlist *userlist;
2622     dict_iterator_t it;
2623
2624     if (hs->requests) {
2625         for (it=dict_first(hs->requests); it; it=iter_next(it)) {
2626             struct helpserv_request *req = iter_data(it);
2627
2628             if (req->helper == hs_user)
2629                 helpserv_page_helper_gone(hs, req, "been deleted");
2630         }
2631     }
2632
2633     userlist = dict_find(helpserv_users_byhand_dict, hs_user->handle->handle, NULL);
2634     if (userlist->used == 1) {
2635         dict_remove(helpserv_users_byhand_dict, hs_user->handle->handle);
2636     } else {
2637         helpserv_userlist_remove(userlist, hs_user);
2638     }
2639
2640     free(data);
2641 }
2642
2643 static struct helpserv_bot *register_helpserv(const char *nick, const char *help_channel, const char *registrar) {
2644     struct helpserv_bot *hs;
2645     struct helpserv_botlist *botlist;
2646
2647     /* Laziness dictates calloc, since there's a lot to set to NULL or 0, and
2648      * it's a harmless default */
2649     hs = calloc(1, sizeof(struct helpserv_bot));
2650
2651     if (!(hs->helpserv = AddLocalUser(nick, nick, NULL, helpserv_conf.description, NULL))) {
2652         free(hs);
2653         return NULL;
2654     }
2655
2656     reg_privmsg_func(hs->helpserv, helpserv_botmsg);
2657
2658     if (!(hs->helpchan = GetChannel(help_channel))) {
2659         hs->helpchan = AddChannel(help_channel, now, NULL, NULL);
2660         AddChannelUser(hs->helpserv, hs->helpchan)->modes |= MODE_CHANOP;
2661     } else {
2662         struct mod_chanmode change;
2663         mod_chanmode_init(&change);
2664         change.argc = 1;
2665         change.args[0].mode = MODE_CHANOP;
2666         change.args[0].u.member = AddChannelUser(hs->helpserv, hs->helpchan);
2667         mod_chanmode_announce(hs->helpserv, hs->helpchan, &change);
2668     }
2669
2670     if (registrar)
2671         hs->registrar = strdup(registrar);
2672
2673     hs->users = dict_new();
2674     /* Don't free keys - they use the handle_info's handle field */
2675     dict_set_free_data(hs->users, free_user);
2676     hs->requests = dict_new();
2677     dict_set_free_keys(hs->requests, free);
2678     dict_set_free_data(hs->requests, free_request);
2679
2680     dict_insert(helpserv_bots_dict, hs->helpserv->nick, hs);
2681
2682     if (!(botlist = dict_find(helpserv_bots_bychan_dict, hs->helpchan->name, NULL))) {
2683         botlist = helpserv_botlist_alloc();
2684         dict_insert(helpserv_bots_bychan_dict, hs->helpchan->name, botlist);
2685     }
2686     helpserv_botlist_append(botlist, hs);
2687
2688     return hs;
2689 }
2690
2691 static HELPSERV_FUNC(cmd_register) {
2692     char *nick, *helpchan, reason[MAXLEN];
2693     struct handle_info *handle;
2694
2695     REQUIRE_PARMS(4);
2696     nick = argv[1];
2697     if (!is_valid_nick(nick)) {
2698         helpserv_notice(user, "HSMSG_ILLEGAL_NICK", nick);
2699         return 0;
2700     }
2701     if (GetUserH(nick)) {
2702         helpserv_notice(user, "HSMSG_NICK_EXISTS", nick);
2703         return 0;
2704     }
2705     helpchan = argv[2];
2706     if (!IsChannelName(helpchan)) {
2707         helpserv_notice(user, "HSMSG_ILLEGAL_CHANNEL", helpchan);
2708         HELPSERV_SYNTAX();
2709         return 0;
2710     }
2711     if (opserv_bad_channel(helpchan)) {
2712         helpserv_notice(user, "HSMSG_ILLEGAL_CHANNEL", helpchan);
2713         return 0;
2714     }
2715     if (!(handle = helpserv_get_handle_info(user, argv[3])))
2716         return 0;
2717
2718     if (!(hs = register_helpserv(nick, helpchan, user->handle_info->handle))) {
2719         helpserv_notice(user, "HSMSG_ERROR_ADDING_SERVICE", nick);
2720         return 0;
2721     }
2722
2723     hs->registered = now;
2724     helpserv_add_user(hs, handle, HlOwner);
2725
2726     helpserv_notice(user, "HSMSG_REG_SUCCESS", handle->handle, nick);
2727
2728     snprintf(reason, MAXLEN, "HelpServ %s (%s) registered to %s by %s.", nick, hs->helpchan->name, handle->handle, user->nick);
2729     /* Not sent to helpers, since they can't register HelpServ */
2730     global_message(MESSAGE_RECIPIENT_OPERS, reason);
2731     return 1;
2732 }
2733
2734 static void unregister_helpserv(struct helpserv_bot *hs) {
2735     enum message_type msgtype;
2736
2737     timeq_del(0, NULL, hs, TIMEQ_IGNORE_WHEN|TIMEQ_IGNORE_FUNC);
2738
2739     /* Requests before users so that it doesn't spam mentioning now-unhandled
2740      * requests because the users were deleted */
2741     dict_delete(hs->requests);
2742     hs->requests = NULL; /* so we don't try to look up requests in free_user() */
2743     dict_delete(hs->users);
2744     free(hs->registrar);
2745
2746     for (msgtype=0; msgtype<MSGTYPE_COUNT; msgtype++)
2747         free(hs->messages[msgtype]);
2748 }
2749
2750 static void helpserv_free_bot(void *data) {
2751     unregister_helpserv(data);
2752     free(data);
2753 }
2754
2755 static void helpserv_unregister(struct helpserv_bot *bot, const char *quit_fmt, const char *global_fmt, const char *actor) {
2756     char reason[MAXLEN], channame[CHANNELLEN], botname[NICKLEN];
2757     struct helpserv_botlist *botlist;
2758     size_t len;
2759
2760     botlist = dict_find(helpserv_bots_bychan_dict, bot->helpchan->name, NULL);
2761     helpserv_botlist_remove(botlist, bot);
2762     if (!botlist->used)
2763         dict_remove(helpserv_bots_bychan_dict, bot->helpchan->name);
2764     len = strlen(bot->helpserv->nick) + 1;
2765     safestrncpy(botname, bot->helpserv->nick, len);
2766     len = strlen(bot->helpchan->name) + 1;
2767     safestrncpy(channame, bot->helpchan->name, len);
2768     snprintf(reason, sizeof(reason), quit_fmt, actor);
2769     DelUser(bot->helpserv, NULL, 1, reason);
2770     dict_remove(helpserv_bots_dict, botname);
2771     snprintf(reason, sizeof(reason), global_fmt, botname, channame, actor);
2772     global_message(MESSAGE_RECIPIENT_OPERS, reason);
2773 }
2774
2775 static HELPSERV_FUNC(cmd_unregister) {
2776     if (!from_opserv) {
2777         if (argc < 2 || strcmp(argv[1], "CONFIRM")) {
2778             helpserv_notice(user, "HSMSG_NEED_UNREG_CONFIRM");
2779             return 0;
2780         }
2781         log_audit(HS_LOG, LOG_COMMAND, user, hs->helpserv, hs->helpchan->name, 0, "unregister CONFIRM");
2782     }
2783
2784     helpserv_unregister(hs, "Unregistered by %s", "HelpServ %s (%s) unregistered by %s.", user->nick);
2785     return from_opserv;
2786 }
2787
2788 static HELPSERV_FUNC(cmd_expire) {
2789     struct helpserv_botlist victims;
2790     struct helpserv_bot *bot;
2791     dict_iterator_t it, next;
2792     unsigned int count = 0;
2793
2794     memset(&victims, 0, sizeof(victims));
2795     for (it = dict_first(helpserv_bots_dict); it; it = next) {
2796         bot = iter_data(it);
2797         next = iter_next(it);
2798         if ((unsigned int)(now - bot->last_active) < helpserv_conf.expire_age)
2799             continue;
2800         helpserv_unregister(bot, "Registration expired due to inactivity", "HelpServ %s (%s) expired at request of %s.", user->nick);
2801         count++;
2802     }
2803     helpserv_notice(user, "HSMSG_EXPIRATION_DONE", count);
2804     return 1;
2805 }
2806
2807 static HELPSERV_FUNC(cmd_giveownership) {
2808     struct handle_info *hi;
2809     struct helpserv_user *new_owner, *old_owner, *hs_user;
2810     dict_iterator_t it;
2811     char reason[MAXLEN];
2812
2813     if (!from_opserv && ((argc < 3) || strcmp(argv[2], "CONFIRM"))) {
2814         helpserv_notice(user, "HSMSG_NEED_GIVEOWNERSHIP_CONFIRM");
2815         return 0;
2816     }
2817     hi = helpserv_get_handle_info(user, argv[1]);
2818     if (!hi)
2819         return 0;
2820     new_owner = GetHSUser(hs, hi);
2821     if (!new_owner) {
2822         helpserv_notice(user, "HSMSG_NOT_IN_USERLIST", hi->handle, hs->helpserv->nick);
2823         return 0;
2824     }
2825     if (!from_opserv)
2826         old_owner = GetHSUser(hs, user->handle_info);
2827     else for (it = dict_first(hs->users), old_owner = NULL; it; it = iter_next(it)) {
2828         hs_user = iter_data(it);
2829         if (hs_user->level != HlOwner)
2830             continue;
2831         if (old_owner) {
2832             helpserv_notice(user, "HSMSG_MULTIPLE_OWNERS", hs->helpserv->nick);
2833             return 0;
2834         }
2835         old_owner = hs_user;
2836     }
2837     if (!from_opserv && (new_owner->handle == user->handle_info)) {
2838         helpserv_notice(user, "HSMSG_NO_TRANSFER_SELF");
2839         return 0;
2840     }
2841     if (old_owner)
2842         old_owner->level = HlManager;
2843     new_owner->level = HlOwner;
2844     helpserv_notice(user, "HSMSG_OWNERSHIP_GIVEN", hs->helpserv->nick, new_owner->handle->handle);
2845     sprintf(reason, "%s (%s) ownership transferred to %s by %s.", hs->helpserv->nick, hs->helpchan->name, new_owner->handle->handle, user->handle_info->handle);
2846     return 1;
2847 }
2848
2849 static HELPSERV_FUNC(cmd_weekstart) {
2850     struct handle_info *hi;
2851     struct helpserv_user *actor, *victim;
2852     int changed = 0;
2853
2854     REQUIRE_PARMS(2);
2855     actor = from_opserv ? NULL : GetHSUser(hs, user->handle_info);
2856     if (!(hi = helpserv_get_handle_info(user, argv[1])))
2857         return 0;
2858     if (!(victim = GetHSUser(hs, hi))) {
2859         helpserv_notice(user, "HSMSG_NOT_IN_USERLIST", hi->handle, hs->helpserv->nick);
2860         return 0;
2861     }
2862     if (actor && (actor->level <= victim->level) && (actor != victim)) {
2863         helpserv_notice(user, "MSG_USER_OUTRANKED", victim->handle->handle);
2864         return 0;
2865     }
2866     if (argc > 2 && (!actor || actor->level >= HlManager)) {
2867         int new_day = 7;
2868         switch (argv[2][0]) {
2869         case 's': case 'S':
2870             if ((argv[2][1] == 'u') || (argv[2][1] == 'U'))
2871                 new_day = 0;
2872             else if ((argv[2][1] == 'a') || (argv[2][1] == 'A'))
2873                 new_day = 6;
2874             break;
2875         case 'm': case 'M': new_day = 1; break;
2876         case 't': case 'T':
2877             if ((argv[2][1] == 'u') || (argv[2][1] == 'U'))
2878                 new_day = 2;
2879             else if ((argv[2][1] == 'h') || (argv[2][1] == 'H'))
2880                 new_day = 4;
2881             break;
2882         case 'w': case 'W': new_day = 3; break;
2883         case 'f': case 'F': new_day = 5; break;
2884         }
2885         if (new_day == 7) {
2886             helpserv_notice(user, "HSMSG_BAD_WEEKDAY", argv[2]);
2887             return 0;
2888         }
2889         victim->week_start = new_day;
2890         changed = 1;
2891     }
2892     helpserv_notice(user, "HSMSG_WEEK_STARTS", victim->handle->handle, weekday_names[victim->week_start]);
2893     return changed;
2894 }
2895
2896 static void set_page_target(struct helpserv_bot *hs, enum page_source idx, const char *target) {
2897     struct chanNode *new_target, *old_target;
2898
2899     if (target) {
2900         if (!IsChannelName(target)) {
2901             log_module(HS_LOG, LOG_ERROR, "%s has an invalid page target.", hs->helpserv->nick);
2902             return;
2903         }
2904         new_target = GetChannel(target);
2905         if (!new_target) {
2906             new_target = AddChannel(target, now, NULL, NULL);
2907             AddChannelUser(hs->helpserv, new_target);
2908         }
2909     } else {
2910         new_target = NULL;
2911     }
2912     if (new_target == hs->page_targets[idx])
2913         return;
2914     old_target = hs->page_targets[idx];
2915     hs->page_targets[idx] = NULL;
2916     if (old_target && !helpserv_in_channel(hs, old_target))
2917         DelChannelUser(hs->helpserv, old_target, "Changing page target.", 0);
2918     if (new_target && !helpserv_in_channel(hs, new_target)) {
2919         struct mod_chanmode change;
2920         mod_chanmode_init(&change);
2921         change.argc = 1;
2922         change.args[0].mode = MODE_CHANOP;
2923         change.args[0].u.member = AddChannelUser(hs->helpserv, new_target);
2924         mod_chanmode_announce(hs->helpserv, new_target, &change);
2925     }
2926     hs->page_targets[idx] = new_target;
2927 }
2928
2929 static int opt_page_target(struct userNode *user, struct helpserv_bot *hs, int from_opserv, int argc, char *argv[], enum page_source idx) {
2930     int changed = 0;
2931
2932     if (argc > 0) {
2933         if (!IsOper(user)) {
2934             helpserv_notice(user, "HSMSG_SET_NEED_OPER");
2935             return 0;
2936         }
2937         if (!strcmp(argv[0], "*")) {
2938             set_page_target(hs, idx, NULL);
2939             changed = 1;
2940         } else if (!IsChannelName(argv[0])) {
2941             helpserv_notice(user, "MSG_NOT_CHANNEL_NAME");
2942             return 0;
2943         } else {
2944             set_page_target(hs, idx, argv[0]);
2945             changed = 1;
2946         }
2947     }
2948     if (hs->page_targets[idx])
2949         helpserv_notice(user, page_sources[idx].print_target, hs->page_targets[idx]->name);
2950     else
2951         helpserv_notice(user, page_sources[idx].print_target, user_find_message(user, "MSG_NONE"));
2952     return changed;
2953 }
2954
2955 static HELPSERV_OPTION(opt_pagetarget_command) {
2956     return opt_page_target(user, hs, from_opserv, argc, argv, PGSRC_COMMAND);
2957 }
2958
2959 static HELPSERV_OPTION(opt_pagetarget_alert) {
2960     return opt_page_target(user, hs, from_opserv, argc, argv, PGSRC_ALERT);
2961 }
2962
2963 static HELPSERV_OPTION(opt_pagetarget_status) {
2964     return opt_page_target(user, hs, from_opserv, argc, argv, PGSRC_STATUS);
2965 }
2966
2967 static enum page_type page_type_from_name(const char *name) {
2968     enum page_type type;
2969     for (type=0; type<PAGE_COUNT; type++)
2970         if (!irccasecmp(page_types[type].db_name, name))
2971             return type;
2972     return PAGE_COUNT;
2973 }
2974
2975 static int opt_page_type(struct userNode *user, struct helpserv_bot *hs, int from_opserv, int argc, char *argv[], enum page_source idx) {
2976     enum page_type new_type;
2977     int changed=0;
2978
2979     if (argc > 0) {
2980         new_type = page_type_from_name(argv[0]);
2981         if (new_type == PAGE_COUNT) {
2982             helpserv_notice(user, "HSMSG_INVALID_OPTION", argv[0]);
2983             return 0;
2984         }
2985         hs->page_types[idx] = new_type;
2986         changed = 1;
2987     }
2988     helpserv_notice(user, page_sources[idx].print_type,
2989                     user_find_message(user, page_types[hs->page_types[idx]].print_name));
2990     return changed;
2991 }
2992
2993 static HELPSERV_OPTION(opt_pagetype) {
2994     return opt_page_type(user, hs, from_opserv, argc, argv, PGSRC_COMMAND);
2995 }
2996
2997 static HELPSERV_OPTION(opt_alert_page_type) {
2998     return opt_page_type(user, hs, from_opserv, argc, argv, PGSRC_ALERT);
2999 }
3000
3001 static HELPSERV_OPTION(opt_status_page_type) {
3002     return opt_page_type(user, hs, from_opserv, argc, argv, PGSRC_STATUS);
3003 }
3004
3005 static int opt_message(struct userNode *user, struct helpserv_bot *hs, int from_opserv, int argc, char *argv[], enum message_type idx) {
3006     int changed=0;
3007
3008     if (argc > 0) {
3009         char *msg = unsplit_string(argv, argc, NULL);
3010         free(hs->messages[idx]);
3011         hs->messages[idx] = strcmp(msg, "*") ? strdup(msg) : NULL;
3012         changed = 1;
3013     }
3014     if (hs->messages[idx])
3015         helpserv_notice(user, message_types[idx].print_name, hs->messages[idx]);
3016     else
3017         helpserv_notice(user, message_types[idx].print_name, user_find_message(user, "MSG_NONE"));
3018     return changed;
3019 }
3020
3021 static HELPSERV_OPTION(opt_greeting) {
3022     return opt_message(user, hs, from_opserv, argc, argv, MSGTYPE_GREETING);
3023 }
3024
3025 static HELPSERV_OPTION(opt_req_opened) {
3026     return opt_message(user, hs, from_opserv, argc, argv, MSGTYPE_REQ_OPENED);
3027 }
3028
3029 static HELPSERV_OPTION(opt_req_assigned) {
3030     return opt_message(user, hs, from_opserv, argc, argv, MSGTYPE_REQ_ASSIGNED);
3031 }
3032
3033 static HELPSERV_OPTION(opt_req_closed) {
3034     return opt_message(user, hs, from_opserv, argc, argv, MSGTYPE_REQ_CLOSED);
3035 }
3036
3037 static int opt_interval(struct userNode *user, struct helpserv_bot *hs, int from_opserv, int argc, char *argv[], enum interval_type idx, unsigned int min) {
3038     char buf[INTERVALLEN];
3039     int changed=0;
3040
3041     if (argc > 0) {
3042         unsigned long new_int = ParseInterval(argv[0]);
3043         if (!new_int && strcmp(argv[0], "0")) {
3044             helpserv_notice(user, "MSG_INVALID_DURATION", argv[0]);
3045             return 0;
3046         }
3047         if (new_int && new_int < min) {
3048             intervalString(buf, min, user->handle_info);
3049             helpserv_notice(user, "HSMSG_INVALID_INTERVAL", user_find_message(user, interval_types[idx].print_name), buf);
3050             return 0;
3051         }
3052         hs->intervals[idx] = new_int;
3053         changed = 1;
3054     }
3055     if (hs->intervals[idx]) {
3056         intervalString(buf, hs->intervals[idx], user->handle_info);
3057         helpserv_notice(user, interval_types[idx].print_name, buf);
3058     } else
3059         helpserv_notice(user, interval_types[idx].print_name, user_find_message(user, "HSMSG_0_DISABLED"));
3060     return changed;
3061 }
3062
3063 static HELPSERV_OPTION(opt_idle_delay) {
3064     return opt_interval(user, hs, from_opserv, argc, argv, INTERVAL_IDLE_DELAY, 60);
3065 }
3066
3067 static HELPSERV_OPTION(opt_whine_delay) {
3068     return opt_interval(user, hs, from_opserv, argc, argv, INTERVAL_WHINE_DELAY, 60);
3069 }
3070
3071 static HELPSERV_OPTION(opt_whine_interval) {
3072     unsigned int old_val = hs->intervals[INTERVAL_WHINE_INTERVAL];
3073     int retval;
3074
3075     retval = opt_interval(user, hs, from_opserv, argc, argv, INTERVAL_WHINE_INTERVAL, 60);
3076
3077     if (!old_val && hs->intervals[INTERVAL_WHINE_INTERVAL]) {
3078         timeq_add(now + hs->intervals[INTERVAL_WHINE_INTERVAL], run_whine_interval, hs);
3079     } else if (old_val && !hs->intervals[INTERVAL_WHINE_INTERVAL]) {
3080         timeq_del(0, run_whine_interval, hs, TIMEQ_IGNORE_WHEN);
3081     }
3082
3083     return retval;
3084 }
3085
3086 static HELPSERV_OPTION(opt_empty_interval) {
3087     unsigned int old_val = hs->intervals[INTERVAL_EMPTY_INTERVAL];
3088     int retval;
3089
3090     retval = opt_interval(user, hs, from_opserv, argc, argv, INTERVAL_EMPTY_INTERVAL, 60);
3091
3092     if (!old_val && hs->intervals[INTERVAL_EMPTY_INTERVAL]) {
3093         timeq_add(now + hs->intervals[INTERVAL_EMPTY_INTERVAL], run_empty_interval, hs);
3094     } else if (old_val && !hs->intervals[INTERVAL_EMPTY_INTERVAL]) {
3095         timeq_del(0, run_empty_interval, hs, TIMEQ_IGNORE_WHEN);
3096     }
3097
3098     return retval;
3099 }
3100
3101 static HELPSERV_OPTION(opt_stale_delay) {
3102     return opt_interval(user, hs, from_opserv, argc, argv, INTERVAL_STALE_DELAY, 60);
3103 }
3104
3105 static enum persistence_length persistence_from_name(const char *name) {
3106     enum persistence_length pers;
3107     for (pers=0; pers<PERSIST_COUNT; pers++)
3108         if (!irccasecmp(name, persistence_lengths[pers].db_name))
3109             return pers;
3110     return PERSIST_COUNT;
3111 }
3112
3113 static int opt_persist(struct userNode *user, struct helpserv_bot *hs, int from_opserv, int argc, char *argv[], enum persistence_type idx) {
3114     int changed=0;
3115
3116     if (argc > 0) {
3117         enum persistence_length new_pers = persistence_from_name(argv[0]);
3118         if (new_pers == PERSIST_COUNT) {
3119             helpserv_notice(user, "HSMSG_INVALID_OPTION", argv[0]);
3120             return 0;
3121         }
3122         hs->persist_types[idx] = new_pers;
3123         changed = 1;
3124     }
3125     helpserv_notice(user, persistence_types[idx].print_name,
3126                     user_find_message(user, persistence_lengths[hs->persist_types[idx]].print_name));
3127     return changed;
3128 }
3129
3130 static HELPSERV_OPTION(opt_request_persistence) {
3131     return opt_persist(user, hs, from_opserv, argc, argv, PERSIST_T_REQUEST);
3132 }
3133
3134 static HELPSERV_OPTION(opt_helper_persistence) {
3135     return opt_persist(user, hs, from_opserv, argc, argv, PERSIST_T_HELPER);
3136 }
3137
3138 static enum notification_type notification_from_name(const char *name) {
3139     enum notification_type notify;
3140     for (notify=0; notify<NOTIFY_COUNT; notify++)
3141         if (!irccasecmp(name, notification_types[notify].db_name))
3142             return notify;
3143     return NOTIFY_COUNT;
3144 }
3145
3146 static HELPSERV_OPTION(opt_notification) {
3147     int changed=0;
3148
3149     if (argc > 0) {
3150         enum notification_type new_notify = notification_from_name(argv[0]);
3151         if (new_notify == NOTIFY_COUNT) {
3152             helpserv_notice(user, "HSMSG_INVALID_OPTION", argv[0]);
3153             return 0;
3154         }
3155         if (!from_opserv && (new_notify == NOTIFY_HANDLE)) {
3156             helpserv_notice(user, "HSMSG_SET_NEED_OPER");
3157             return 0;
3158         }
3159         hs->notify = new_notify;
3160         changed = 1;
3161     }
3162     helpserv_notice(user, "HSMSG_SET_NOTIFICATION", user_find_message(user, notification_types[hs->notify].print_name));
3163     return changed;
3164 }
3165
3166 #define OPTION_UINT(var, name) do { \
3167     int changed=0; \
3168     if (argc > 0) { \
3169         (var) = strtoul(argv[0], NULL, 0); \
3170         changed = 1; \
3171     } \
3172     helpserv_notice(user, name, (var)); \
3173     return changed; \
3174 } while (0);
3175
3176 static HELPSERV_OPTION(opt_id_wrap) {
3177     OPTION_UINT(hs->id_wrap, "HSMSG_SET_IDWRAP");
3178 }
3179
3180 static HELPSERV_OPTION(opt_req_maxlen) {
3181     OPTION_UINT(hs->req_maxlen, "HSMSG_SET_REQMAXLEN");
3182 }
3183
3184 #define OPTION_BINARY(var, name) do { \
3185     int changed=0; \
3186     if (argc > 0) { \
3187         if (enabled_string(argv[0])) { \
3188             (var) = 1; \
3189             changed = 1; \
3190         } else if (disabled_string(argv[0])) { \
3191             (var) = 0; \
3192             changed = 1; \
3193         } else { \
3194             helpserv_notice(user, "MSG_INVALID_BINARY", argv[0]); \
3195             return 0; \
3196         } \
3197     } \
3198     helpserv_notice(user, name, user_find_message(user, (var) ? "MSG_ON" : "MSG_OFF")); \
3199     return changed; \
3200 } while (0);
3201
3202 static HELPSERV_OPTION(opt_privmsg_only) {
3203     OPTION_BINARY(hs->privmsg_only, "HSMSG_SET_PRIVMSGONLY");
3204 }
3205
3206 static HELPSERV_OPTION(opt_req_on_join) {
3207     OPTION_BINARY(hs->req_on_join, "HSMSG_SET_REQONJOIN");
3208 }
3209
3210 static HELPSERV_OPTION(opt_auto_voice) {
3211     OPTION_BINARY(hs->auto_voice, "HSMSG_SET_AUTOVOICE");
3212 }
3213
3214 static HELPSERV_OPTION(opt_auto_devoice) {
3215     OPTION_BINARY(hs->auto_devoice, "HSMSG_SET_AUTODEVOICE");
3216 }
3217
3218 static HELPSERV_FUNC(cmd_set) {
3219     helpserv_option_func_t *opt;
3220
3221     if (argc < 2) {
3222         unsigned int i;
3223         helpserv_option_func_t *display[] = {
3224             opt_pagetarget_command, opt_pagetarget_alert, opt_pagetarget_status,
3225             opt_pagetype, opt_alert_page_type, opt_status_page_type,
3226             opt_greeting, opt_req_opened, opt_req_assigned, opt_req_closed,
3227             opt_idle_delay, opt_whine_delay, opt_whine_interval,
3228             opt_empty_interval, opt_stale_delay, opt_request_persistence,
3229             opt_helper_persistence, opt_notification, opt_id_wrap,
3230             opt_req_maxlen, opt_privmsg_only, opt_req_on_join, opt_auto_voice,
3231             opt_auto_devoice
3232         };
3233
3234         helpserv_notice(user, "HSMSG_QUEUE_OPTIONS");
3235         for (i=0; i<ArrayLength(display); i++)
3236             display[i](user, hs, from_opserv, 0, argv);
3237         return 1;
3238     }
3239
3240     if (!(opt = dict_find(helpserv_option_dict, argv[1], NULL))) {
3241         helpserv_notice(user, "HSMSG_INVALID_OPTION", argv[1]);
3242         return 0;
3243     }
3244
3245     if ((argc > 2) && !from_opserv) {
3246         struct helpserv_user *hs_user;
3247
3248         if (!(hs_user = dict_find(hs->users, user->handle_info->handle, NULL))) {
3249             helpserv_notice(user, "HSMSG_WTF_WHO_ARE_YOU", hs->helpserv->nick);
3250             return 0;
3251         }
3252
3253         if (hs_user->level < HlManager) {
3254             helpserv_notice(user, "HSMSG_NEED_MANAGER");
3255             return 0;
3256         }
3257     }
3258     return opt(user, hs, from_opserv, argc-2, argv+2);
3259 }
3260
3261 static int user_write_helper(const char *key, void *data, void *extra) {
3262     struct helpserv_user *hs_user = data;
3263     struct saxdb_context *ctx = extra;
3264     struct string_list strlist;
3265     char str[5][16], *strs[5];
3266     unsigned int i;
3267
3268     saxdb_start_record(ctx, key, 0);
3269     /* Helper identification. */
3270     saxdb_write_string(ctx, KEY_HELPER_LEVEL, helpserv_level2str(hs_user->level));
3271     saxdb_write_string(ctx, KEY_HELPER_HELPMODE, (hs_user->help_mode ? "1" : "0"));
3272     saxdb_write_int(ctx, KEY_HELPER_WEEKSTART, hs_user->week_start);
3273     /* Helper stats */
3274     saxdb_start_record(ctx, KEY_HELPER_STATS, 0);
3275     for (i=0; i < ArrayLength(strs); ++i)
3276         strs[i] = str[i];
3277     strlist.list = strs;
3278     strlist.used = 5;
3279     /* Time in help channel */
3280     for (i=0; i < strlist.used; i++) {
3281         unsigned int week_time = hs_user->time_per_week[i];
3282         if ((i==0 || i==4) && hs_user->join_time)
3283             week_time += now - hs_user->join_time;
3284         sprintf(str[i], "%u", week_time);
3285     }
3286     saxdb_write_string_list(ctx, KEY_HELPER_STATS_TIME, &strlist);
3287     /* Requests picked up */
3288     for (i=0; i < strlist.used; i++)
3289         sprintf(str[i], "%u", hs_user->picked_up[i]);
3290     saxdb_write_string_list(ctx, KEY_HELPER_STATS_PICKUP, &strlist);
3291     /* Requests closed */
3292     for (i=0; i < strlist.used; i++)
3293         sprintf(str[i], "%u", hs_user->closed[i]);
3294     saxdb_write_string_list(ctx, KEY_HELPER_STATS_CLOSE, &strlist);
3295     /* Requests reassigned from user */
3296     for (i=0; i < strlist.used; i++)
3297         sprintf(str[i], "%u", hs_user->reassigned_from[i]);
3298     saxdb_write_string_list(ctx, KEY_HELPER_STATS_REASSIGNFROM, &strlist);
3299     /* Requests reassigned to user */
3300     for (i=0; i < strlist.used; i++)
3301         sprintf(str[i], "%u", hs_user->reassigned_to[i]);
3302     saxdb_write_string_list(ctx, KEY_HELPER_STATS_REASSIGNTO, &strlist);
3303     /* End of stats and whole record. */
3304     saxdb_end_record(ctx);
3305     saxdb_end_record(ctx);
3306     return 0;
3307 }
3308
3309 static int user_read_helper(const char *key, void *data, void *extra) {
3310     struct record_data *rd = data;
3311     struct helpserv_bot *hs = extra;
3312     struct helpserv_user *hs_user;
3313     struct handle_info *handle;
3314     dict_t stats;
3315     enum helpserv_level level;
3316     char *str;
3317     struct string_list *strlist;
3318     unsigned int i;
3319
3320     if (rd->type != RECDB_OBJECT || !dict_size(rd->d.object)) {
3321         log_module(HS_LOG, LOG_ERROR, "Invalid user %s for %s.", key, hs->helpserv->nick);
3322         return 0;
3323     }
3324
3325     if (!(handle = get_handle_info(key))) {
3326         log_module(HS_LOG, LOG_ERROR, "Nonexistant account %s for %s.", key, hs->helpserv->nick);
3327         return 0;
3328     }
3329     str = database_get_data(rd->d.object, KEY_HELPER_LEVEL, RECDB_QSTRING);
3330     if (str) {
3331         level = helpserv_str2level(str);
3332         if (level == HlNone) {
3333             log_module(HS_LOG, LOG_ERROR, "Account %s has invalid level %s.", key, str);
3334             return 0;
3335         }
3336     } else {
3337         log_module(HS_LOG, LOG_ERROR, "Account %s has no level field for %s.", key, hs->helpserv->nick);
3338         return 0;
3339     }
3340
3341     hs_user = helpserv_add_user(hs, handle, level);
3342
3343     str = database_get_data(rd->d.object, KEY_HELPER_HELPMODE, RECDB_QSTRING);
3344     hs_user->help_mode = (str && strtol(str, NULL, 0)) ? 1 : 0;
3345     str = database_get_data(rd->d.object, KEY_HELPER_WEEKSTART, RECDB_QSTRING);
3346     hs_user->week_start = str ? strtol(str, NULL, 0) : 0;
3347
3348     /* Stats */
3349     stats = database_get_data(GET_RECORD_OBJECT(rd), KEY_HELPER_STATS, RECDB_OBJECT);
3350
3351     if (stats) {
3352         /* The tests for strlist->used are for converting the old format to the new one */
3353         strlist = database_get_data(stats, KEY_HELPER_STATS_TIME, RECDB_STRING_LIST);
3354         if (strlist) {
3355             for (i=0; i < 5 && i < strlist->used; i++)
3356                 hs_user->time_per_week[i] = strtoul(strlist->list[i], NULL, 0);
3357             if (strlist->used == 4)
3358                 hs_user->time_per_week[4] = hs_user->time_per_week[0]+hs_user->time_per_week[1]+hs_user->time_per_week[2]+hs_user->time_per_week[3];
3359         }
3360         strlist = database_get_data(stats, KEY_HELPER_STATS_PICKUP, RECDB_STRING_LIST);
3361         if (strlist) {
3362             for (i=0; i < 5 && i < strlist->used; i++)
3363                 hs_user->picked_up[i] = strtoul(strlist->list[i], NULL, 0);
3364             if (strlist->used == 2)
3365                 hs_user->picked_up[4] = hs_user->picked_up[0]+hs_user->picked_up[1];
3366         }
3367         strlist = database_get_data(stats, KEY_HELPER_STATS_CLOSE, RECDB_STRING_LIST);
3368         if (strlist) {
3369             for (i=0; i < 5 && i < strlist->used; i++)
3370                 hs_user->closed[i] = strtoul(strlist->list[i], NULL, 0);
3371             if (strlist->used == 2)
3372                 hs_user->closed[4] = hs_user->closed[0]+hs_user->closed[1];
3373         }
3374         strlist = database_get_data(stats, KEY_HELPER_STATS_REASSIGNFROM, RECDB_STRING_LIST);
3375         if (strlist) {
3376             for (i=0; i < 5 && i < strlist->used; i++)
3377                 hs_user->reassigned_from[i] = strtoul(strlist->list[i], NULL, 0);
3378             if (strlist->used == 2)
3379                 hs_user->reassigned_from[4] = hs_user->reassigned_from[0]+hs_user->reassigned_from[1];
3380         }
3381         strlist = database_get_data(stats, KEY_HELPER_STATS_REASSIGNTO, RECDB_STRING_LIST);
3382         if (strlist) {
3383             for (i=0; i < 5 && i < strlist->used; i++)
3384                 hs_user->reassigned_to[i] = strtoul(strlist->list[i], NULL, 0);
3385             if (strlist->used == 2)
3386                 hs_user->reassigned_to[4] = hs_user->reassigned_to[0]+hs_user->reassigned_to[1];
3387         }
3388     }
3389
3390     return 0;
3391 }
3392
3393 static int request_write_helper(const char *key, void *data, void *extra) {
3394     struct helpserv_request *request = data;
3395     struct saxdb_context *ctx = extra;
3396
3397     if (!request->handle)
3398         return 0;
3399
3400     saxdb_start_record(ctx, key, 0);
3401     if (request->helper) {
3402         saxdb_write_string(ctx, KEY_REQUEST_HELPER, request->helper->handle->handle);
3403         saxdb_write_int(ctx, KEY_REQUEST_ASSIGNED, request->assigned);
3404     }
3405     saxdb_write_string(ctx, KEY_REQUEST_HANDLE, request->handle->handle);
3406     saxdb_write_int(ctx, KEY_REQUEST_OPENED, request->opened);
3407     saxdb_write_string_list(ctx, KEY_REQUEST_TEXT, request->text);
3408     saxdb_end_record(ctx);
3409     return 0;
3410 }
3411
3412 static int request_read_helper(const char *key, void *data, void *extra) {
3413     struct record_data *rd = data;
3414     struct helpserv_bot *hs = extra;
3415     struct helpserv_request *request;
3416     struct string_list *strlist;
3417     char *str;
3418
3419     if (rd->type != RECDB_OBJECT || !dict_size(rd->d.object)) {
3420         log_module(HS_LOG, LOG_ERROR, "Invalid request %s:%s.", hs->helpserv->nick, key);
3421         return 0;
3422     }
3423
3424     request = calloc(1, sizeof(struct helpserv_request));
3425
3426     request->id = strtoul(key, NULL, 0);
3427     request->hs = hs;
3428     request->user = NULL;
3429     request->parent_nick_list = request->parent_hand_list = NULL;
3430
3431     str = database_get_data(rd->d.object, KEY_REQUEST_HANDLE, RECDB_QSTRING);
3432     if (!str || !(request->handle = get_handle_info(str))) {
3433         log_module(HS_LOG, LOG_ERROR, "Request %s:%s has an invalid or nonexistant account.", hs->helpserv->nick, key);
3434         free(request);
3435         return 0;
3436     }
3437     if (!(request->parent_hand_list = dict_find(helpserv_reqs_byhand_dict, request->handle->handle, NULL))) {
3438         request->parent_hand_list = helpserv_reqlist_alloc();
3439         dict_insert(helpserv_reqs_byhand_dict, request->handle->handle, request->parent_hand_list);
3440     }
3441     helpserv_reqlist_append(request->parent_hand_list, request);
3442
3443     str = database_get_data(rd->d.object, KEY_REQUEST_OPENED, RECDB_QSTRING);
3444     if (!str) {
3445         log_module(HS_LOG, LOG_ERROR, "Request %s:%s has a nonexistant opening time. Using time(NULL).", hs->helpserv->nick, key);
3446         request->opened = time(NULL);
3447     } else {
3448         request->opened = strtoul(str, NULL, 0);
3449     }
3450
3451     str = database_get_data(rd->d.object, KEY_REQUEST_ASSIGNED, RECDB_QSTRING);
3452     if (str)
3453         request->assigned = strtoul(str, NULL, 0);
3454
3455     str = database_get_data(rd->d.object, KEY_REQUEST_HELPER, RECDB_QSTRING);
3456     if (str) {
3457         if (!(request->helper = dict_find(hs->users, str, NULL))) {
3458             log_module(HS_LOG, LOG_ERROR, "Request %s:%s has an invalid or nonexistant helper.", hs->helpserv->nick, key);
3459             free(request);
3460             return 0;
3461         }
3462     } else {
3463         if (!hs->unhandled) {
3464             request->next_unhandled = NULL;
3465             hs->unhandled = request;
3466         } else if (hs->unhandled->opened > request->opened) {
3467             request->next_unhandled = hs->unhandled;
3468             hs->unhandled = request;
3469         } else {
3470             struct helpserv_request *unh;
3471             for (unh = hs->unhandled; unh->next_unhandled && (unh->next_unhandled->opened < request->opened); unh = unh->next_unhandled);
3472             request->next_unhandled = unh->next_unhandled;
3473             unh->next_unhandled = request;
3474         }
3475     }
3476
3477     strlist = database_get_data(rd->d.object, KEY_REQUEST_TEXT, RECDB_STRING_LIST);
3478     if (!strlist) {
3479         log_module(HS_LOG, LOG_ERROR, "Request %s:%s has no text.", hs->helpserv->nick, key);
3480         free(request);
3481         return 0;
3482     }
3483     request->text = string_list_copy(strlist);
3484
3485     dict_insert(hs->requests, strdup(key), request);
3486
3487     return 0;
3488 }
3489
3490 static int
3491 helpserv_bot_write(const char *key, void *data, void *extra) {
3492     const struct helpserv_bot *hs = data;
3493     struct saxdb_context *ctx = extra;
3494     enum page_source pagesrc;
3495     enum message_type msgtype;
3496     enum interval_type inttype;
3497     enum persistence_type persisttype;
3498     struct string_list *slist;
3499
3500     /* Entire bot */
3501     saxdb_start_record(ctx, key, 1);
3502
3503     /* Helper list */
3504     saxdb_start_record(ctx, KEY_HELPERS, 1);
3505     dict_foreach(hs->users, user_write_helper, ctx);
3506     saxdb_end_record(ctx);
3507
3508     /* Open requests */
3509     if (hs->persist_types[PERSIST_T_REQUEST] == PERSIST_CLOSE) {
3510         saxdb_start_record(ctx, KEY_REQUESTS, 0);
3511         dict_foreach(hs->requests, request_write_helper, ctx);
3512         saxdb_end_record(ctx);
3513     }
3514
3515     /* Other settings and state */
3516     saxdb_write_string(ctx, KEY_HELP_CHANNEL, hs->helpchan->name);
3517     slist = alloc_string_list(PGSRC_COUNT);
3518     for (pagesrc=0; pagesrc<PGSRC_COUNT; pagesrc++) {
3519         struct chanNode *target = hs->page_targets[pagesrc];
3520         string_list_append(slist, strdup(target ? target->name : "*"));
3521     }
3522     saxdb_write_string_list(ctx, KEY_PAGE_DEST, slist);
3523     free_string_list(slist);
3524     for (pagesrc=0; pagesrc<PGSRC_COUNT; pagesrc++) {
3525         const char *src = page_types[hs->page_types[pagesrc]].db_name;
3526         saxdb_write_string(ctx, page_sources[pagesrc].db_name, src);
3527     }
3528     for (msgtype=0; msgtype<MSGTYPE_COUNT; msgtype++) {
3529         const char *msg = hs->messages[msgtype];
3530         if (msg)
3531             saxdb_write_string(ctx, message_types[msgtype].db_name, msg);
3532     }
3533     for (inttype=0; inttype<INTERVAL_COUNT; inttype++) {
3534         if (!hs->intervals[inttype])
3535             continue;
3536         saxdb_write_int(ctx, interval_types[inttype].db_name, hs->intervals[inttype]);
3537     }
3538     for (persisttype=0; persisttype<PERSIST_T_COUNT; persisttype++) {
3539         const char *persist = persistence_lengths[hs->persist_types[persisttype]].db_name;
3540         saxdb_write_string(ctx, persistence_types[persisttype].db_name, persist);
3541     }
3542     saxdb_write_string(ctx, KEY_NOTIFICATION, notification_types[hs->notify].db_name);
3543     saxdb_write_int(ctx, KEY_REGISTERED, hs->registered);
3544     saxdb_write_int(ctx, KEY_IDWRAP, hs->id_wrap);
3545     saxdb_write_int(ctx, KEY_REQ_MAXLEN, hs->req_maxlen);
3546     saxdb_write_int(ctx, KEY_LAST_REQUESTID, hs->last_requestid);
3547     if (hs->registrar)
3548         saxdb_write_string(ctx, KEY_REGISTRAR, hs->registrar);
3549     saxdb_write_int(ctx, KEY_PRIVMSG_ONLY, hs->privmsg_only);
3550     saxdb_write_int(ctx, KEY_REQ_ON_JOIN, hs->req_on_join);
3551     saxdb_write_int(ctx, KEY_AUTO_VOICE, hs->auto_voice);
3552     saxdb_write_int(ctx, KEY_AUTO_DEVOICE, hs->auto_devoice);
3553     saxdb_write_int(ctx, KEY_LAST_ACTIVE, hs->last_active);
3554
3555     /* End bot record */
3556     saxdb_end_record(ctx);
3557     return 0;
3558 }
3559
3560 static int
3561 helpserv_saxdb_write(struct saxdb_context *ctx) {
3562     saxdb_start_record(ctx, KEY_BOTS, 1);
3563     dict_foreach(helpserv_bots_dict, helpserv_bot_write, ctx);
3564     saxdb_end_record(ctx);
3565     saxdb_write_int(ctx, KEY_LAST_STATS_UPDATE, last_stats_update);
3566     return 0;
3567 }
3568
3569 static int helpserv_bot_read(const char *key, void *data, UNUSED_ARG(void *extra)) {
3570     struct record_data *br = data, *raw_record;
3571     struct helpserv_bot *hs;
3572     char *registrar, *helpchannel_name, *str;
3573     dict_t users, requests;
3574     enum page_source pagesrc;
3575     enum message_type msgtype;
3576     enum interval_type inttype;
3577     enum persistence_type persisttype;
3578
3579     users = database_get_data(GET_RECORD_OBJECT(br), KEY_HELPERS, RECDB_OBJECT);
3580     if (!users) {
3581         log_module(HS_LOG, LOG_ERROR, "%s has no users.", key);
3582         return 0;
3583     }
3584     helpchannel_name = database_get_data(GET_RECORD_OBJECT(br), KEY_HELP_CHANNEL, RECDB_QSTRING);
3585     if (!helpchannel_name || !IsChannelName(helpchannel_name)) {
3586         log_module(HS_LOG, LOG_ERROR, "%s has an invalid channel name.", key);
3587         return 0;
3588     }
3589     registrar = database_get_data(GET_RECORD_OBJECT(br), KEY_REGISTRAR, RECDB_QSTRING);
3590
3591     hs = register_helpserv(key, helpchannel_name, registrar);
3592
3593     raw_record = dict_find(GET_RECORD_OBJECT(br), KEY_PAGE_DEST, NULL);
3594     switch (raw_record ? raw_record->type : RECDB_INVALID) {
3595     case RECDB_QSTRING:
3596         set_page_target(hs, PGSRC_COMMAND, GET_RECORD_QSTRING(raw_record));
3597         pagesrc = PGSRC_COMMAND + 1;
3598         break;
3599     case RECDB_STRING_LIST: {
3600         struct string_list *slist = GET_RECORD_STRING_LIST(raw_record);
3601         for (pagesrc=0; (pagesrc<slist->used) && (pagesrc<PGSRC_COUNT); pagesrc++) {
3602             const char *dest = slist->list[pagesrc];
3603             set_page_target(hs, pagesrc, strcmp(dest, "*") ? dest : NULL);
3604         }
3605         break;
3606     }
3607     default:
3608         set_page_target(hs, PGSRC_COMMAND, NULL);
3609         pagesrc = PGSRC_COMMAND + 1;
3610         break;
3611     }
3612     while (pagesrc < PGSRC_COUNT) {
3613         set_page_target(hs, pagesrc++, hs->page_targets[PGSRC_COMMAND] ? hs->page_targets[PGSRC_COMMAND]->name : NULL);
3614     }
3615
3616     for (pagesrc=0; pagesrc<PGSRC_COUNT; pagesrc++) {
3617         str = database_get_data(GET_RECORD_OBJECT(br), page_sources[pagesrc].db_name, RECDB_QSTRING);
3618         hs->page_types[pagesrc] = str ? page_type_from_name(str) : PAGE_NONE;
3619     }
3620
3621     for (msgtype=0; msgtype<MSGTYPE_COUNT; msgtype++) {
3622         str = database_get_data(GET_RECORD_OBJECT(br), message_types[msgtype].db_name, RECDB_QSTRING);
3623         hs->messages[msgtype] = str ? strdup(str) : NULL;
3624     }
3625
3626     for (inttype=0; inttype<INTERVAL_COUNT; inttype++) {
3627         str = database_get_data(GET_RECORD_OBJECT(br), interval_types[inttype].db_name, RECDB_QSTRING);
3628         hs->intervals[inttype] = str ? ParseInterval(str) : 0;
3629     }
3630     if (hs->intervals[INTERVAL_WHINE_INTERVAL])
3631         timeq_add(now + hs->intervals[INTERVAL_WHINE_INTERVAL], run_whine_interval, hs);
3632     if (hs->intervals[INTERVAL_EMPTY_INTERVAL])
3633         timeq_add(now + hs->intervals[INTERVAL_EMPTY_INTERVAL], run_empty_interval, hs);
3634
3635     for (persisttype=0; persisttype<PERSIST_T_COUNT; persisttype++) {
3636         str = database_get_data(GET_RECORD_OBJECT(br), persistence_types[persisttype].db_name, RECDB_QSTRING);
3637         hs->persist_types[persisttype] = str ? persistence_from_name(str) : PERSIST_QUIT;
3638     }
3639     str = database_get_data(GET_RECORD_OBJECT(br), KEY_NOTIFICATION, RECDB_QSTRING);
3640     hs->notify = str ? notification_from_name(str) : NOTIFY_NONE;
3641     str = database_get_data(GET_RECORD_OBJECT(br), KEY_REGISTERED, RECDB_QSTRING);
3642     if (str)
3643         hs->registered = strtol(str, NULL, 0);
3644     str = database_get_data(GET_RECORD_OBJECT(br), KEY_IDWRAP, RECDB_QSTRING);
3645     if (str)
3646         hs->id_wrap = strtoul(str, NULL, 0);
3647     str = database_get_data(GET_RECORD_OBJECT(br), KEY_REQ_MAXLEN, RECDB_QSTRING);
3648     if (str)
3649         hs->req_maxlen = strtoul(str, NULL, 0);
3650     str = database_get_data(GET_RECORD_OBJECT(br), KEY_LAST_REQUESTID, RECDB_QSTRING);
3651     if (str)
3652         hs->last_requestid = strtoul(str, NULL, 0);
3653     str = database_get_data(GET_RECORD_OBJECT(br), KEY_PRIVMSG_ONLY, RECDB_QSTRING);
3654     hs->privmsg_only = str ? enabled_string(str) : 0;
3655     str = database_get_data(GET_RECORD_OBJECT(br), KEY_REQ_ON_JOIN, RECDB_QSTRING);
3656     hs->req_on_join = str ? enabled_string(str) : 0;
3657     str = database_get_data(GET_RECORD_OBJECT(br), KEY_AUTO_VOICE, RECDB_QSTRING);
3658     hs->auto_voice = str ? enabled_string(str) : 0;
3659     str = database_get_data(GET_RECORD_OBJECT(br), KEY_AUTO_DEVOICE, RECDB_QSTRING);
3660     hs->auto_devoice = str ? enabled_string(str) : 0;
3661     str = database_get_data(GET_RECORD_OBJECT(br), KEY_LAST_ACTIVE, RECDB_QSTRING);
3662     hs->last_active = str ? strtoul(str, NULL, 0) : now;
3663
3664     dict_foreach(users, user_read_helper, hs);
3665
3666     requests = database_get_data(GET_RECORD_OBJECT(br), KEY_REQUESTS, RECDB_OBJECT);
3667     if (requests)
3668         dict_foreach(requests, request_read_helper, hs);
3669
3670     return 0;
3671 }
3672
3673 static int
3674 helpserv_saxdb_read(struct dict *conf_db) {
3675     dict_t object;
3676     char *str;
3677
3678     if ((object = database_get_data(conf_db, KEY_BOTS, RECDB_OBJECT))) {
3679         dict_foreach(object, helpserv_bot_read, NULL);
3680     }
3681
3682     str = database_get_data(conf_db, KEY_LAST_STATS_UPDATE, RECDB_QSTRING);
3683     last_stats_update = str ? strtoul(str, NULL, 0) : now;
3684     return 0;
3685 }
3686
3687 static void helpserv_conf_read(void) {
3688     dict_t conf_node;
3689     const char *str;
3690
3691     if (!(conf_node = conf_get_data(HELPSERV_CONF_NAME, RECDB_OBJECT))) {
3692         log_module(HS_LOG, LOG_ERROR, "config node `%s' is missing or has wrong type", HELPSERV_CONF_NAME);
3693         return;
3694     }
3695
3696     str = database_get_data(conf_node, "db_backup_freq", RECDB_QSTRING);
3697     helpserv_conf.db_backup_frequency = str ? ParseInterval(str) : 7200;
3698
3699     str = database_get_data(conf_node, "description", RECDB_QSTRING);
3700     helpserv_conf.description = str ? str : "Help Queue Manager";
3701
3702     str = database_get_data(conf_node, "reqlogfile", RECDB_QSTRING);
3703     if (str && strlen(str))
3704         helpserv_conf.reqlogfile = str;
3705     else
3706         helpserv_conf.reqlogfile = NULL;
3707
3708     str = database_get_data(conf_node, "expiration", RECDB_QSTRING);
3709     helpserv_conf.expire_age = ParseInterval(str ? str : "60d");
3710     str = database_get_data(conf_node, "user_escape", RECDB_QSTRING);
3711     helpserv_conf.user_escape = str ? str[0] : '@';
3712
3713     if (reqlog_f) {
3714         fclose(reqlog_f);
3715         reqlog_f = NULL;
3716     }
3717     if (helpserv_conf.reqlogfile
3718         && !(reqlog_f = fopen(helpserv_conf.reqlogfile, "a"))) {
3719         log_module(HS_LOG, LOG_ERROR, "Unable to open request logfile (%s): %s", helpserv_conf.reqlogfile, strerror(errno));
3720     }
3721 }
3722
3723 static struct helpserv_cmd *
3724 helpserv_define_func(const char *name, helpserv_func_t *func, enum helpserv_level access, long flags) {
3725     struct helpserv_cmd *cmd = calloc(1, sizeof(struct helpserv_cmd));
3726
3727     cmd->access = access;
3728     cmd->weight = 1.0;
3729     cmd->func = func;
3730     cmd->flags = flags;
3731     dict_insert(helpserv_func_dict, name, cmd);
3732
3733     return cmd;
3734 }
3735
3736 /* Drop requests that persist until part when a user leaves the chan */
3737 static void handle_part(struct modeNode *mn, UNUSED_ARG(const char *reason)) {
3738     struct helpserv_botlist *botlist;
3739     struct helpserv_userlist *userlist;
3740     const int from_opserv = 0; /* for helpserv_notice */
3741     unsigned int i;
3742
3743     if ((botlist = dict_find(helpserv_bots_bychan_dict, mn->channel->name, NULL))) {
3744         for (i=0; i < botlist->used; i++) {
3745             struct helpserv_bot *hs;
3746             dict_iterator_t it;
3747
3748             hs = botlist->list[i];
3749             if (!hs->helpserv)
3750                 continue;
3751             if (hs->persist_types[PERSIST_T_REQUEST] != PERSIST_PART)
3752                 continue;
3753
3754             for (it=dict_first(hs->requests); it; it=iter_next(it)) {
3755                 struct helpserv_request *req = iter_data(it);
3756
3757                 if (mn->user != req->user)
3758                     continue;
3759                 if (req->text->used) {
3760                     helpserv_message(hs, mn->user, MSGTYPE_REQ_DROPPED);
3761                     helpserv_msguser(mn->user, "HSMSG_REQ_DROPPED_PART", mn->channel->name, req->id);
3762                     if (req->helper && (hs->notify >= NOTIFY_DROP))
3763                         helpserv_notify(req->helper, "HSMSG_NOTIFY_REQ_DROP_PART", req->id, mn->user->nick);
3764                 }
3765                 helpserv_log_request(req, "Dropped");
3766                 dict_remove(hs->requests, iter_key(it));
3767                 break;
3768             }
3769         }
3770     }
3771
3772     if (mn->user->handle_info && (userlist = dict_find(helpserv_users_byhand_dict, mn->user->handle_info->handle, NULL))) {
3773         for (i=0; i < userlist->used; i++) {
3774             struct helpserv_user *hs_user = userlist->list[i];
3775             struct helpserv_bot *hs = hs_user->hs;
3776             dict_iterator_t it;
3777
3778             if ((hs->helpserv == NULL) || (hs->helpchan != mn->channel) || find_handle_in_channel(hs->helpchan, mn->user->handle_info, mn->user))
3779                 continue;
3780
3781             /* In case of the clock being set back for whatever reason,
3782              * minimize penalty. Don't duplicate this in handle_quit because
3783              * when users quit, handle_part is called for every channel first.
3784              */
3785             if (hs_user->join_time && (hs_user->join_time < now)) {
3786                 hs_user->time_per_week[0] += (unsigned int)(now - hs_user->join_time);
3787                 hs_user->time_per_week[4] += (unsigned int)(now - hs_user->join_time);
3788             }
3789             hs_user->join_time = 0;
3790
3791             for (it=dict_first(hs->requests); it; it=iter_next(it)) {
3792                 struct helpserv_request *req=iter_data(it);
3793
3794                 if ((hs->persist_types[PERSIST_T_HELPER] == PERSIST_PART)
3795                     && (req->helper == hs_user)) {
3796                     char reason[CHANNELLEN + 8];
3797                     sprintf(reason, "parted %s", mn->channel->name);
3798                     helpserv_page_helper_gone(hs, req, reason);
3799                 }
3800             }
3801
3802             if (hs->intervals[INTERVAL_EMPTY_INTERVAL] && hs_user->level >= HlHelper) {
3803                 int num_trials;
3804
3805                 if ((num_trials = find_helpchan_helpers(hs)) >= 0) {
3806                     unsigned int num_unh;
3807                     struct helpserv_request *unh;
3808
3809                     for (num_unh=0, unh=hs->unhandled; unh; num_unh++)
3810                         unh = unh->next_unhandled;
3811
3812                     if (num_trials) {
3813                         helpserv_page(PGSRC_ALERT, "HSMSG_PAGE_FIRSTONLYTRIALALERT", hs->helpchan->name, mn->user->nick, num_trials, num_unh);
3814                     } else {
3815                         helpserv_page(PGSRC_ALERT, "HSMSG_PAGE_FIRSTEMPTYALERT", hs->helpchan->name, mn->user->nick, num_unh);
3816                     }
3817                     if (num_unh || !hs->req_on_join) {
3818                         timeq_del(0, run_empty_interval, hs, TIMEQ_IGNORE_WHEN);
3819                         timeq_add(now + hs->intervals[INTERVAL_EMPTY_INTERVAL], run_empty_interval, hs);
3820                     }
3821                 }
3822             }
3823         }
3824     }
3825 }
3826
3827 /* Drop requests that persist until part or quit when a user quits. Otherwise
3828  * set req->user to null (it's no longer valid) if they have a handle,
3829  * and drop it if they don't (nowhere to store the request).
3830  *
3831  * Unassign requests where req->helper persists until the helper parts or
3832  * quits. */
3833 static void handle_quit(struct userNode *user, UNUSED_ARG(struct userNode *killer), UNUSED_ARG(const char *why)) {
3834     struct helpserv_reqlist *reqlist;
3835     struct helpserv_userlist *userlist;
3836     unsigned int i, n;
3837
3838     if (IsLocal(user)) {
3839         struct helpserv_bot *hs;
3840         if ((hs = dict_find(helpserv_bots_dict, user->nick, NULL))) {
3841             hs->helpserv = NULL;
3842         }
3843         return;
3844     }
3845
3846     if ((reqlist = dict_find(helpserv_reqs_bynick_dict, user->nick, NULL))) {
3847         n = reqlist->used;
3848         for (i=0; i < n; i++) {
3849             struct helpserv_request *req = reqlist->list[0];
3850
3851             if ((req->hs->persist_types[PERSIST_T_REQUEST] == PERSIST_QUIT) || !req->handle) {
3852                 char buf[12];
3853                 sprintf(buf, "%lu", req->id);
3854
3855                 if (req->helper && (req->hs->notify >= NOTIFY_DROP))
3856                     helpserv_notify(req->helper, "HSMSG_NOTIFY_REQ_DROP_QUIT", req->id, req->user->nick);
3857
3858                 helpserv_log_request(req, "Dropped");
3859                 dict_remove(req->hs->requests, buf);
3860             } else {
3861                 req->user = NULL;
3862                 req->parent_nick_list = NULL;
3863                 helpserv_reqlist_remove(reqlist, req);
3864
3865                 if (req->helper && (req->hs->notify >= NOTIFY_USER))
3866                     helpserv_notify(req->helper, "HSMSG_NOTIFY_USER_QUIT", req->id, user->nick);
3867             }
3868         }
3869
3870         dict_remove(helpserv_reqs_bynick_dict, user->nick);
3871     }
3872
3873     if (user->handle_info && (userlist = dict_find(helpserv_users_byhand_dict, user->handle_info->handle, NULL))) {
3874         for (i=0; i < userlist->used; i++) {
3875             struct helpserv_user *hs_user = userlist->list[i];
3876             struct helpserv_bot *hs = hs_user->hs;
3877             dict_iterator_t it;
3878
3879             if ((hs->helpserv == NULL) || user->next_authed || (user->handle_info->users != user))
3880                 continue;
3881
3882             for (it=dict_first(hs->requests); it; it=iter_next(it)) {
3883                 struct helpserv_request *req=iter_data(it);
3884
3885                 if ((hs->persist_types[PERSIST_T_HELPER] == PERSIST_QUIT) && (req->helper == hs_user)) {
3886                     helpserv_page_helper_gone(hs, req, "disconnected");
3887                 }
3888             }
3889         }
3890     }
3891 }
3892
3893 static void associate_requests_bybot(struct helpserv_bot *hs, struct userNode *user, int force_greet) {
3894     struct helpserv_reqlist *reqlist, *hand_reqlist=NULL;
3895     struct helpserv_request *newest=NULL, *nicknewest=NULL;
3896     unsigned int i;
3897     const int from_opserv = 0; /* For helpserv_notice */
3898
3899     if (!(user->handle_info && (hand_reqlist = dict_find(helpserv_reqs_byhand_dict, user->handle_info->handle, NULL))) && !force_greet) {
3900         return;
3901     }
3902
3903     reqlist = dict_find(helpserv_reqs_bynick_dict, user->nick, NULL);
3904
3905     if (hand_reqlist) {
3906         for (i=0; i < hand_reqlist->used; i++) {
3907             struct helpserv_request *req=hand_reqlist->list[i];
3908
3909             if (req->user || (req->hs != hs))
3910                 continue;
3911
3912             req->user = user;
3913             if (!reqlist) {
3914                 reqlist = helpserv_reqlist_alloc();
3915                 dict_insert(helpserv_reqs_bynick_dict, user->nick, reqlist);
3916             }
3917             req->parent_nick_list = reqlist;
3918             helpserv_reqlist_append(reqlist, req);
3919
3920             if (req->helper && (hs->notify >= NOTIFY_USER))
3921                 helpserv_notify(req->helper, "HSMSG_NOTIFY_USER_FOUND", req->id, user->nick);
3922
3923             if (!newest || (newest->opened < req->opened))
3924                 newest = req;
3925         }
3926     }
3927
3928     /* If it's supposed to force a greeting, only bail out if there are no
3929      * requests at all. If it's not supposed to force a greeting, bail out if
3930      * nothing was changed. */
3931     if (!(newest || (force_greet && reqlist)))
3932         return;
3933
3934     /* Possible conditions here:
3935      * 1. newest == NULL, force_greeting == 1, reqlist != NULL
3936      * 2. newest != NULL, force_greeting doesn't matter, reqlist != NULL */
3937
3938     /* Figure out which request will get their next message */
3939     for (i=0; i < reqlist->used; i++) {
3940         struct helpserv_request *req=reqlist->list[i];
3941
3942         if (req->hs != hs)
3943             continue;
3944
3945         if (!nicknewest || (nicknewest->opened < req->opened))
3946             nicknewest = req;
3947
3948         if (hs->auto_voice && req->helper)
3949         {
3950             struct mod_chanmode change;
3951             mod_chanmode_init(&change);
3952             change.argc = 1;
3953             change.args[0].mode = MODE_VOICE;
3954             if ((change.args[0].u.member = GetUserMode(hs->helpchan, user)))
3955                 mod_chanmode_announce(hs->helpserv, hs->helpchan, &change);
3956         }
3957     }
3958
3959     if ((force_greet && nicknewest) || (newest && (nicknewest == newest))) {
3960         /* Let the user know. Either the user is forced to be greeted, or the
3961          * above has changed which request will get their next message. */
3962         helpserv_msguser(user, "HSMSG_GREET_EXISTING_REQ", hs->helpchan->name, nicknewest->id);
3963     }
3964 }
3965
3966 static void associate_requests_bychan(struct chanNode *chan, struct userNode *user, int force_greet) {
3967     struct helpserv_botlist *botlist;
3968     unsigned int i;
3969
3970     if (!(botlist = dict_find(helpserv_bots_bychan_dict, chan->name, NULL)))
3971         return;
3972
3973     for (i=0; i < botlist->used; i++)
3974         associate_requests_bybot(botlist->list[i], user, force_greet);
3975 }
3976
3977
3978 /* Greet users upon joining a helpserv channel (if greeting is set) and set
3979  * req->user to the user joining for all requests owned by the user's handle
3980  * (if any) with a req->user == NULL */
3981 static int handle_join(struct modeNode *mNode) {
3982     struct userNode *user = mNode->user;
3983     struct chanNode *chan = mNode->channel;
3984     struct helpserv_botlist *botlist;
3985     unsigned int i;
3986     const int from_opserv = 0; /* for helpserv_notice */
3987
3988     if (IsLocal(user))
3989         return 0;
3990
3991     if (!(botlist = dict_find(helpserv_bots_bychan_dict, chan->name, NULL)))
3992         return 0;
3993
3994     for (i=0; i < botlist->used; i++) {
3995         struct helpserv_bot *hs=botlist->list[i];
3996
3997         if (user->handle_info) {
3998             struct helpserv_user *hs_user;
3999
4000             if ((hs_user = dict_find(hs->users, user->handle_info->handle, NULL))) {
4001                 if (!hs_user->join_time)
4002                     hs_user->join_time = now;
4003
4004                 if (hs_user->level >= HlHelper && hs->intervals[INTERVAL_EMPTY_INTERVAL] && hs->helpchan_empty) {
4005                     hs->helpchan_empty = 0;
4006                     timeq_del(0, run_empty_interval, hs, TIMEQ_IGNORE_WHEN);
4007                     helpserv_page(PGSRC_ALERT, "HSMSG_PAGE_EMPTYNOMORE", user->nick, hs->helpchan->name);
4008                 }
4009                 continue; /* Don't want helpers to have request-on-join */
4010             }
4011         }
4012
4013         if (self->burst && !hs->req_on_join)
4014             continue;
4015
4016         associate_requests_bybot(hs, user, 1);
4017
4018         helpserv_message(hs, user, MSGTYPE_GREETING);
4019
4020         /* Make sure this is at the end (because of the continues) */
4021         if (hs->req_on_join) {
4022             struct helpserv_reqlist *reqlist;
4023             unsigned int j;
4024
4025             if ((reqlist = dict_find(helpserv_reqs_bynick_dict, user->nick, NULL))) {
4026                 for (j=0; j < reqlist->used; j++)
4027                     if (reqlist->list[i]->hs == hs)
4028                         break;
4029                 if (j < reqlist->used)
4030                     continue;
4031             }
4032
4033             create_request(user, hs, 1);
4034         }
4035     }
4036     return 0;
4037 }
4038
4039 /* Update helpserv_reqs_bynick_dict upon nick change */
4040 static void handle_nickchange(struct userNode *user, const char *old_nick) {
4041     struct helpserv_reqlist *reqlist;
4042     unsigned int i;
4043
4044     if (!(reqlist = dict_find(helpserv_reqs_bynick_dict, old_nick, NULL)))
4045         return;
4046
4047     /* Don't free the list when we switch it over to the new nick. */
4048     dict_remove2(helpserv_reqs_bynick_dict, old_nick, 1);
4049     dict_insert(helpserv_reqs_bynick_dict, user->nick, reqlist);
4050
4051     for (i=0; i < reqlist->used; i++) {
4052         struct helpserv_request *req=reqlist->list[i];
4053
4054         if (req->helper && (req->hs->notify >= NOTIFY_USER))
4055             helpserv_notify(req->helper, "HSMSG_NOTIFY_USER_NICK", req->id, old_nick, user->nick);
4056     }
4057 }
4058
4059 /* Also update helpserv_reqs_byhand_dict upon handle rename */
4060 static void handle_nickserv_rename(struct handle_info *handle, const char *old_handle) {
4061     struct helpserv_reqlist *reqlist;
4062     struct helpserv_userlist *userlist;
4063     unsigned int i;
4064
4065     /* First, rename the handle in the requests dict */
4066     if ((reqlist = dict_find(helpserv_reqs_byhand_dict, old_handle, NULL))) {
4067         /* Don't free the list */
4068         dict_remove2(helpserv_reqs_byhand_dict, old_handle, 1);
4069         dict_insert(helpserv_reqs_byhand_dict, handle->handle, reqlist);
4070     }
4071
4072     /* Second, rename the handle in the users dict */
4073     if ((userlist = dict_find(helpserv_users_byhand_dict, old_handle, NULL))) {
4074         dict_remove2(helpserv_users_byhand_dict, old_handle, 1);
4075
4076         for (i=0; i < userlist->used; i++)
4077             dict_remove2(userlist->list[i]->hs->users, old_handle, 1);
4078
4079         dict_insert(helpserv_users_byhand_dict, handle->handle, userlist);
4080         for (i=0; i < userlist->used; i++)
4081             dict_insert(userlist->list[i]->hs->users, handle->handle, userlist->list[i]);
4082     }
4083
4084     if (reqlist) {
4085         for (i=0; i < reqlist->used; i++) {
4086             struct helpserv_request *req=reqlist->list[i];
4087
4088             if (req->helper && (req->hs->notify >= NOTIFY_HANDLE))
4089                 helpserv_notify(req->helper, "HSMSG_NOTIFY_HAND_RENAME", req->id, old_handle, handle->handle);
4090         }
4091     }
4092 }
4093
4094 /* Deals with two cases:
4095  * 1. No handle -> handle
4096  *    - Bots with a request assigned to both the user (w/o handle) and the
4097  *      handle can exist in this case. When a message is sent,
4098  *      helpserv_usermsg will append it to the most recently opened request.
4099  *    - Requests assigned to the handle are NOT assigned to the user, since
4100  *      multiple people can auth to the same handle at once. Wait for them to
4101  *      join / privmsg before setting req->user.
4102  * 2. Handle -> handle
4103  *    - Generally avoided, but sometimes the code may allow this.
4104  *    - Requests that persist only until part/quit are brought along to the
4105  *      new handle.
4106  *    - Requests that persist until closed (stay saved with the handle) are
4107  *      left with the old handle. This is to prevent the confusing situation
4108  *      where some requests are carried over to the new handle, and some are
4109  *      left (because req->handle is the same for all of them, but only some
4110  *      have req->user set).
4111  * - In either of the above cases, if a user is on a bot's userlist and has
4112  *   requests assigned to them, it will give them a list. */
4113 static void handle_nickserv_auth(struct userNode *user, struct handle_info *old_handle) {
4114     struct helpserv_reqlist *reqlist, *dellist=NULL, *hand_reqlist, *oldhand_reqlist;
4115     struct helpserv_userlist *userlist;
4116     unsigned int i, j;
4117     dict_iterator_t it;
4118     const int from_opserv = 0; /* for helpserv_notice */
4119
4120     if (!user->handle_info)
4121         return; /* Authed user is quitting */
4122
4123     if ((userlist = dict_find(helpserv_users_byhand_dict, user->handle_info->handle, NULL))) {
4124         for (i=0; i < userlist->used; i++) {
4125             struct helpserv_user *hs_user = userlist->list[i];
4126             struct helpserv_bot *hs = hs_user->hs;
4127             struct helpserv_reqlist helper_reqs;
4128             struct helpfile_table tbl;
4129
4130             if (!hs_user->join_time && find_handle_in_channel(hs->helpchan, hs_user->handle, NULL))
4131                 hs_user->join_time = now;
4132
4133             helpserv_reqlist_init(&helper_reqs);
4134
4135             for (it=dict_first(hs->requests); it; it=iter_next(it)) {
4136                 struct helpserv_request *req=iter_data(it);
4137
4138                 if (req->helper == hs_user)
4139                     helpserv_reqlist_append(&helper_reqs, req);
4140             }
4141
4142             if (helper_reqs.used) {
4143                 tbl.length = helper_reqs.used+1;
4144                 tbl.width = 5;
4145                 tbl.flags = TABLE_NO_FREE;
4146                 tbl.contents = alloca(tbl.length * sizeof(*tbl.contents));
4147                 tbl.contents[0] = alloca(tbl.width * sizeof(**tbl.contents));
4148                 tbl.contents[0][0] = "Bot";
4149                 tbl.contents[0][1] = "ID#";
4150                 tbl.contents[0][2] = "Nick";
4151                 tbl.contents[0][3] = "Account";
4152                 tbl.contents[0][4] = "Opened";
4153
4154                 for (j=1; j <= helper_reqs.used; j++) {
4155                     struct helpserv_request *req=helper_reqs.list[j-1];
4156                     char reqid[12], timestr[MAX_LINE_SIZE];
4157                     time_t feh;
4158
4159                     tbl.contents[j] = alloca(tbl.width * sizeof(**tbl.contents));
4160                     tbl.contents[j][0] = req->hs->helpserv->nick;
4161                     sprintf(reqid, "%lu", req->id);
4162                     tbl.contents[j][1] = strdup(reqid);
4163                     tbl.contents[j][2] = req->user ? req->user->nick : "Not online";
4164                     tbl.contents[j][3] = req->handle ? req->handle->handle : "Not authed";
4165                     feh = req->opened;
4166                     strftime(timestr, MAX_LINE_SIZE, HSFMT_TIME, localtime(&feh));
4167                     tbl.contents[j][4] = strdup(timestr);
4168                 }
4169
4170                 helpserv_notice(user, "HSMSG_REQLIST_AUTH");
4171                 table_send(hs->helpserv, user->nick, 0, NULL, tbl);
4172
4173                 for (j=1; j <= helper_reqs.used; j++) {
4174                     free((char *)tbl.contents[j][1]);
4175                     free((char *)tbl.contents[j][4]);
4176                 }
4177             }
4178
4179             helpserv_reqlist_clean(&helper_reqs);
4180         }
4181     }
4182
4183
4184     if (!(reqlist = dict_find(helpserv_reqs_bynick_dict, user->nick, NULL))) {
4185         for (i=0; i < user->channels.used; i++)
4186             associate_requests_bychan(user->channels.list[i]->channel, user, 0);
4187         return;
4188     }
4189
4190     if (!(hand_reqlist = dict_find(helpserv_reqs_byhand_dict, user->handle_info->handle, NULL))) {
4191         hand_reqlist = helpserv_reqlist_alloc();
4192         dict_insert(helpserv_reqs_byhand_dict, user->handle_info->handle, hand_reqlist);
4193     }
4194
4195     if (old_handle) {
4196         dellist = helpserv_reqlist_alloc();
4197         oldhand_reqlist = dict_find(helpserv_reqs_byhand_dict, old_handle->handle, NULL);
4198     } else {
4199         oldhand_reqlist = NULL;
4200     }
4201
4202     for (i=0; i < reqlist->used; i++) {
4203         struct helpserv_request *req = reqlist->list[i];
4204         struct helpserv_bot *hs=req->hs;
4205
4206         if (!old_handle || hs->persist_types[PERSIST_T_REQUEST] == PERSIST_PART || hs->persist_types[PERSIST_T_REQUEST] == PERSIST_QUIT) {
4207             /* The request needs to be assigned to the new handle; either it
4208              * only persists until part/quit (so it makes sense to keep it as
4209              * close to the user as possible, and if it's made persistent later
4210              * then it's attached to the new handle) or there is no old handle.
4211              */
4212
4213             req->handle = user->handle_info;
4214
4215             req->parent_hand_list = hand_reqlist;
4216             helpserv_reqlist_append(hand_reqlist, req);
4217
4218             if (oldhand_reqlist) {
4219                 if (oldhand_reqlist->used == 1) {
4220                     dict_remove(helpserv_reqs_byhand_dict, old_handle->handle);
4221                     oldhand_reqlist = NULL;
4222                 } else {
4223                     helpserv_reqlist_remove(oldhand_reqlist, req);
4224                 }
4225             }
4226
4227             if (old_handle) {
4228                 char buf[CHANNELLEN + 14];
4229
4230                 if (hs->persist_types[PERSIST_T_REQUEST] == PERSIST_PART) {
4231                     sprintf(buf, "part channel %s", hs->helpchan->name);
4232                 } else {
4233                     strcpy(buf, "quit irc");
4234                 }
4235
4236                 helpserv_msguser(user, "HSMSG_REQ_AUTH_MOVED", user->handle_info->handle, hs->helpchan->name, req->id, old_handle->handle, buf);
4237                 if (req->helper && (hs->notify >= NOTIFY_HANDLE))
4238                     helpserv_notify(req->helper, "HSMSG_NOTIFY_HAND_MOVE", req->id, user->handle_info->handle, old_handle->handle);
4239             } else {
4240                 if (req->helper && (hs->notify >= NOTIFY_HANDLE))
4241                     helpserv_notify(req->helper, "HSMSG_NOTIFY_HAND_AUTH", req->id, user->nick, user->handle_info->handle);
4242             }
4243         } else {
4244             req->user = NULL;
4245             req->parent_nick_list = NULL;
4246             /* Would rather not mess with the list while iterating through
4247              * it */
4248             helpserv_reqlist_append(dellist, req);
4249
4250             helpserv_msguser(user, "HSMSG_REQ_AUTH_STUCK", user->handle_info->handle, hs->helpchan->name, req->id, old_handle->handle);
4251             if (req->helper && (hs->notify >= NOTIFY_HANDLE))
4252                 helpserv_notify(req->helper, "HSMSG_NOTIFY_HAND_STUCK", req->id, user->nick, user->handle_info->handle, old_handle->handle);
4253         }
4254     }
4255
4256     if (old_handle) {
4257         if (dellist->used) {
4258             if (dellist->used == reqlist->used) {
4259                 dict_remove(helpserv_reqs_bynick_dict, user->nick);
4260             } else {
4261                 for (i=0; i < dellist->used; i++)
4262                     helpserv_reqlist_remove(reqlist, dellist->list[i]);
4263             }
4264         }
4265         helpserv_reqlist_free(dellist);
4266     }
4267
4268     for (i=0; i < user->channels.used; i++)
4269         associate_requests_bychan(user->channels.list[i]->channel, user, 0);
4270 }
4271
4272
4273 /* Disassociate all requests from the handle. If any have req->user == NULL
4274  * then give them to the user doing the unregistration (if not an oper/helper)
4275  * otherwise the first nick it finds authed (it lets them know about this). If
4276  * there are no users authed to the handle online, the requests are lost. This
4277  * may result in the user having >1 request/bot, and messages go to the most
4278  * recently opened request.
4279  *
4280  * Also, remove the user from all bots that it has access in.
4281  * helpserv_del_user() will take care of unassigning the requests. */
4282 static void handle_nickserv_unreg(struct userNode *user, struct handle_info *handle) {
4283     struct helpserv_reqlist *hand_reqlist;
4284     struct helpserv_userlist *userlist;
4285     unsigned int i, n;
4286     const int from_opserv = 0; /* for helpserv_notice */
4287     struct helpserv_bot *hs; /* for helpserv_notice */
4288
4289     if ((userlist = dict_find(helpserv_users_byhand_dict, handle->handle, NULL))) {
4290         n=userlist->used;
4291
4292         /* Each time helpserv_del_user is called, that entry is going to be
4293          * taken out of userlist... so this should cope with that */
4294         for (i=0; i < n; i++) {
4295             struct helpserv_user *hs_user=userlist->list[0];
4296             helpserv_del_user(hs_user->hs, hs_user);
4297         }
4298     }
4299
4300     if (!(hand_reqlist = dict_find(helpserv_reqs_byhand_dict, handle->handle, NULL))) {
4301         return;
4302     }
4303
4304     n = hand_reqlist->used;
4305     for (i=0; i < n; i++) {
4306         struct helpserv_request *req=hand_reqlist->list[0];
4307         hs = req->hs;
4308
4309         req->handle = NULL;
4310         req->parent_hand_list = NULL;
4311         helpserv_reqlist_remove(hand_reqlist, req);
4312         if (user && req->helper && (hs->notify >= NOTIFY_HANDLE))
4313             helpserv_notify(req->helper, "HSMSG_NOTIFY_HAND_UNREG", req->id, handle->handle, user->nick);
4314
4315         if (!req->user) {
4316             if (!user) {
4317                 /* This is probably an expire. Silently remove everything. */
4318
4319                 char buf[12];
4320                 if (req->helper && (hs->notify >= NOTIFY_DROP))
4321                     helpserv_notify(req->helper, "HSMSG_NOTIFY_REQ_DROP_UNREGGED", req->id, req->handle->handle);
4322                 sprintf(buf, "%lu", req->id);
4323                 helpserv_log_request(req, "Account unregistered");
4324                 dict_remove(req->hs->requests, buf);
4325             } else if (user->handle_info == handle) {
4326                 req->user = user;
4327                 if (!(req->parent_nick_list = dict_find(helpserv_reqs_bynick_dict, user->nick, NULL))) {
4328                     req->parent_nick_list = helpserv_reqlist_alloc();
4329                     dict_insert(helpserv_reqs_bynick_dict, user->nick, req->parent_nick_list);
4330                 }
4331                 helpserv_reqlist_append(req->parent_nick_list, req);
4332
4333                 if (hs->persist_types[PERSIST_T_REQUEST] == PERSIST_CLOSE)
4334                     helpserv_msguser(req->user, "HSMSG_REQ_WARN_UNREG", handle->handle, hs->helpchan->name, req->id);
4335             } else {
4336                 if (handle->users) {
4337                     req->user = handle->users;
4338
4339                     if (!(req->parent_nick_list = dict_find(helpserv_reqs_bynick_dict, req->user->nick, NULL))) {
4340                         req->parent_nick_list = helpserv_reqlist_alloc();
4341                         dict_insert(helpserv_reqs_bynick_dict, req->user->nick, req->parent_nick_list);
4342                     }
4343                     helpserv_reqlist_append(req->parent_nick_list, req);
4344
4345                     helpserv_msguser(req->user, "HSMSG_REQ_ASSIGNED_UNREG", handle->handle, hs->helpchan->name, req->id);
4346                     if (req->helper && (hs->notify >= NOTIFY_USER))
4347                         helpserv_notify(req->helper, "HSMSG_NOTIFY_USER_MOVE", req->id, handle->handle, req->user->nick);
4348                 } else {
4349                     char buf[12];
4350
4351                     helpserv_notice(user, "HSMSG_REQ_DROPPED_UNREG", handle->handle, hs->helpchan->name, req->id);
4352                     if (req->helper && (hs->notify >= NOTIFY_DROP))
4353                         helpserv_notify(req->helper, "HSMSG_NOTIFY_REQ_DROP_UNREGGED", req->id, req->handle->handle);
4354                     sprintf(buf, "%lu", req->id);
4355                     helpserv_log_request(req, "Account unregistered");
4356                     dict_remove(req->hs->requests, buf);
4357                 }
4358             }
4359         }
4360     }
4361
4362     dict_remove(helpserv_reqs_byhand_dict, handle->handle);
4363 }
4364
4365 static void handle_nickserv_merge(struct userNode *user, struct handle_info *handle_to, struct handle_info *handle_from) {
4366     struct helpserv_reqlist *reqlist_from, *reqlist_to;
4367     unsigned int i;
4368
4369     reqlist_to = dict_find(helpserv_reqs_byhand_dict, handle_to->handle, NULL);
4370
4371     if ((reqlist_from = dict_find(helpserv_reqs_byhand_dict, handle_from->handle, NULL))) {
4372         for (i=0; i < reqlist_from->used; i++) {
4373             struct helpserv_request *req=reqlist_from->list[i];
4374
4375             if (!reqlist_to) {
4376                 reqlist_to = helpserv_reqlist_alloc();
4377                 dict_insert(helpserv_reqs_byhand_dict, handle_to->handle, reqlist_to);
4378             }
4379             req->parent_hand_list = reqlist_to;
4380             req->handle = handle_to;
4381             helpserv_reqlist_append(reqlist_to, req);
4382         }
4383         dict_remove(helpserv_reqs_byhand_dict, handle_from->handle);
4384     }
4385
4386     if (reqlist_to) {
4387         for (i=0; i < reqlist_to->used; i++) {
4388             struct helpserv_request *req=reqlist_to->list[i];
4389
4390             if (req->helper && (req->hs->notify >= NOTIFY_HANDLE)) {
4391                 helpserv_notify(req->helper, "HSMSG_NOTIFY_HAND_MERGE", req->id, handle_to->handle, handle_from->handle, user->nick);
4392             }
4393         }
4394     }
4395 }
4396
4397 static void handle_nickserv_allowauth(struct userNode *user, struct userNode *target, struct handle_info *handle) {
4398     struct helpserv_reqlist *reqlist;
4399     unsigned int i;
4400
4401     if ((reqlist = dict_find(helpserv_reqs_bynick_dict, target->nick, NULL))) {
4402         for (i=0; i < reqlist->used; i++) {
4403             struct helpserv_request *req=reqlist->list[i];
4404
4405             if (req->helper && (req->hs->notify >= NOTIFY_HANDLE)) {
4406                 if (handle) {
4407                     helpserv_notify(req->helper, "HSMSG_NOTIFY_ALLOWAUTH", req->id, target->nick, user->nick, handle->handle);
4408                 } else {
4409                     helpserv_notify(req->helper, "HSMSG_NOTIFY_UNALLOWAUTH", req->id, target->nick, user->nick);
4410                 }
4411             }
4412         }
4413     }
4414 }
4415
4416 static void handle_nickserv_failpw(struct userNode *user, struct handle_info *handle) {
4417     struct helpserv_reqlist *reqlist;
4418     unsigned int i;
4419
4420     if ((reqlist = dict_find(helpserv_reqs_bynick_dict, user->nick, NULL))) {
4421         for (i=0; i < reqlist->used; i++) {
4422             struct helpserv_request *req=reqlist->list[i];
4423             if (req->helper && (req->hs->notify >= NOTIFY_HANDLE))
4424                 helpserv_notify(req->helper, "HSMSG_NOTIFY_FAILPW", req->id, user->nick, handle->handle);
4425         }
4426     }
4427 }
4428
4429 static unsigned long helpserv_next_stats(time_t after_when) {
4430     struct tm *timeinfo = localtime(&after_when);
4431
4432     /* This works because mktime(3) says it will accept out-of-range values
4433      * and fix them for us. tm_wday and tm_yday are ignored. */
4434     timeinfo->tm_mday++;
4435
4436     /* We want to run stats at midnight (local time). */
4437     timeinfo->tm_sec = timeinfo->tm_min = timeinfo->tm_hour = 0;
4438
4439     return mktime(timeinfo);
4440 }
4441
4442 /* If data != NULL, then don't add to the timeq */
4443 static void helpserv_run_stats(unsigned long when) {
4444     struct helpserv_bot *hs;
4445     struct helpserv_user *hs_user;
4446     time_t feh;
4447     unsigned int day;
4448     int i;
4449     dict_iterator_t it, it2;
4450
4451     last_stats_update = when;
4452     feh = when;
4453     day = localtime(&feh)->tm_wday;
4454     for (it=dict_first(helpserv_bots_dict); it; it=iter_next(it)) {
4455         hs = iter_data(it);
4456
4457         for (it2=dict_first(hs->users); it2; it2=iter_next(it2)) {
4458             hs_user = iter_data(it2);
4459
4460             /* Skip the helper if it's not their week-start day. */
4461             if (hs_user->week_start != day)
4462                 continue;
4463
4464             /* Adjust their credit if they are in-channel at rollover. */
4465             if (hs_user->join_time) {
4466                 hs_user->time_per_week[0] += when - hs_user->join_time;
4467                 hs_user->time_per_week[4] += when - hs_user->join_time;
4468                 hs_user->join_time = when;
4469             }
4470
4471             /* Shift everything */
4472             for (i=3; i > 0; i--) {
4473                 hs_user->time_per_week[i] = hs_user->time_per_week[i-1];
4474                 hs_user->picked_up[i] = hs_user->picked_up[i-1];
4475                 hs_user->closed[i] = hs_user->closed[i-1];
4476                 hs_user->reassigned_from[i] = hs_user->reassigned_from[i-1];
4477                 hs_user->reassigned_to[i] = hs_user->reassigned_to[i-1];
4478             }
4479
4480             /* Reset it for this week */
4481             hs_user->time_per_week[0] = hs_user->picked_up[0] = hs_user->closed[0] = hs_user->reassigned_from[0] = hs_user->reassigned_to[0] = 0;
4482         }
4483     }
4484 }
4485
4486 static void helpserv_timed_run_stats(UNUSED_ARG(void *data)) {
4487     helpserv_run_stats(now);
4488     timeq_add(helpserv_next_stats(now), helpserv_timed_run_stats, data);
4489 }
4490
4491 static void
4492 helpserv_define_option(const char *name, helpserv_option_func_t *func) {
4493     dict_insert(helpserv_option_dict, name, func);
4494 }
4495
4496 static void helpserv_db_cleanup(void) {
4497     shutting_down=1;
4498     unreg_part_func(handle_part);
4499     unreg_del_user_func(handle_quit);
4500     close_helpfile(helpserv_helpfile);
4501     dict_delete(helpserv_func_dict);
4502     dict_delete(helpserv_option_dict);
4503     dict_delete(helpserv_usercmd_dict);
4504     dict_delete(helpserv_bots_dict);
4505     dict_delete(helpserv_bots_bychan_dict);
4506     dict_delete(helpserv_reqs_bynick_dict);
4507     dict_delete(helpserv_reqs_byhand_dict);
4508     dict_delete(helpserv_users_byhand_dict);
4509
4510     if (reqlog_f)
4511         fclose(reqlog_f);
4512 }
4513
4514 int helpserv_init() {
4515     HS_LOG = log_register_type("HelpServ", "file:helpserv.log");
4516     conf_register_reload(helpserv_conf_read);
4517
4518     helpserv_func_dict = dict_new();
4519     dict_set_free_data(helpserv_func_dict, free);
4520     helpserv_define_func("HELP", cmd_help, HlNone, CMD_NOT_OVERRIDE|CMD_IGNORE_EVENT);
4521     helpserv_define_func("LIST", cmd_list, HlTrial, CMD_NEED_BOT|CMD_IGNORE_EVENT);
4522     helpserv_define_func("NEXT", cmd_next, HlTrial, CMD_NEED_BOT|CMD_NEVER_FROM_OPSERV);
4523     helpserv_define_func("PICKUP", cmd_pickup, HlTrial, CMD_NEED_BOT|CMD_NEVER_FROM_OPSERV);
4524     helpserv_define_func("REASSIGN", cmd_reassign, HlManager, CMD_NEED_BOT|CMD_NEVER_FROM_OPSERV);
4525     helpserv_define_func("CLOSE", cmd_close, HlTrial, CMD_NEED_BOT|CMD_NEVER_FROM_OPSERV);
4526     helpserv_define_func("SHOW", cmd_show, HlTrial, CMD_NEED_BOT|CMD_IGNORE_EVENT);
4527     helpserv_define_func("ADDNOTE", cmd_addnote, HlTrial, CMD_NEED_BOT);
4528     helpserv_define_func("ADDOWNER", cmd_addowner, HlOper, CMD_NEED_BOT|CMD_FROM_OPSERV_ONLY);
4529     helpserv_define_func("DELOWNER", cmd_deluser, HlOper, CMD_NEED_BOT|CMD_FROM_OPSERV_ONLY);
4530     helpserv_define_func("ADDTRIAL", cmd_addtrial, HlManager, CMD_NEED_BOT);
4531     helpserv_define_func("ADDHELPER", cmd_addhelper, HlManager, CMD_NEED_BOT);
4532     helpserv_define_func("ADDMANAGER", cmd_addmanager, HlOwner, CMD_NEED_BOT);
4533     helpserv_define_func("GIVEOWNERSHIP", cmd_giveownership, HlOwner, CMD_NEED_BOT);
4534     helpserv_define_func("DELUSER", cmd_deluser, HlManager, CMD_NEED_BOT);
4535     helpserv_define_func("HELPERS", cmd_helpers, HlNone, CMD_NEED_BOT);
4536     helpserv_define_func("WLIST", cmd_wlist, HlNone, CMD_NEED_BOT);
4537     helpserv_define_func("MLIST", cmd_mlist, HlNone, CMD_NEED_BOT);
4538     helpserv_define_func("HLIST", cmd_hlist, HlNone, CMD_NEED_BOT);
4539     helpserv_define_func("TLIST", cmd_tlist, HlNone, CMD_NEED_BOT);
4540     helpserv_define_func("CLVL", cmd_clvl, HlManager, CMD_NEED_BOT);
4541     helpserv_define_func("PAGE", cmd_page, HlTrial, CMD_NEED_BOT);
4542     helpserv_define_func("SET", cmd_set, HlHelper, CMD_NEED_BOT);
4543     helpserv_define_func("STATS", cmd_stats, HlTrial, CMD_NEED_BOT);
4544     helpserv_define_func("STATSREPORT", cmd_statsreport, HlManager, CMD_NEED_BOT);
4545     helpserv_define_func("UNREGISTER", cmd_unregister, HlOwner, CMD_NEED_BOT);
4546     helpserv_define_func("READHELP", cmd_readhelp, HlOper, CMD_FROM_OPSERV_ONLY);
4547     helpserv_define_func("REGISTER", cmd_register, HlOper, CMD_FROM_OPSERV_ONLY);
4548     helpserv_define_func("MOVE", cmd_move, HlOper, CMD_FROM_OPSERV_ONLY|CMD_NEED_BOT);
4549     helpserv_define_func("BOTS", cmd_bots, HlOper, CMD_FROM_OPSERV_ONLY|CMD_IGNORE_EVENT);
4550     helpserv_define_func("EXPIRE", cmd_expire, HlOper, CMD_FROM_OPSERV_ONLY);
4551     helpserv_define_func("WEEKSTART", cmd_weekstart, HlTrial, CMD_NEED_BOT);
4552
4553     helpserv_option_dict = dict_new();
4554     helpserv_define_option("PAGETARGET", opt_pagetarget_command);
4555     helpserv_define_option("ALERTPAGETARGET", opt_pagetarget_alert);
4556     helpserv_define_option("STATUSPAGETARGET", opt_pagetarget_status);
4557     helpserv_define_option("PAGE", opt_pagetype);
4558     helpserv_define_option("PAGETYPE", opt_pagetype);
4559     helpserv_define_option("ALERTPAGETYPE", opt_alert_page_type);
4560     helpserv_define_option("STATUSPAGETYPE", opt_status_page_type);
4561     helpserv_define_option("GREETING", opt_greeting);
4562     helpserv_define_option("REQOPENED", opt_req_opened);
4563     helpserv_define_option("REQASSIGNED", opt_req_assigned);
4564     helpserv_define_option("REQCLOSED", opt_req_closed);
4565     helpserv_define_option("IDLEDELAY", opt_idle_delay);
4566     helpserv_define_option("WHINEDELAY", opt_whine_delay);
4567     helpserv_define_option("WHINEINTERVAL", opt_whine_interval);
4568     helpserv_define_option("EMPTYINTERVAL", opt_empty_interval);
4569     helpserv_define_option("STALEDELAY", opt_stale_delay);
4570     helpserv_define_option("REQPERSIST", opt_request_persistence);
4571     helpserv_define_option("HELPERPERSIST", opt_helper_persistence);
4572     helpserv_define_option("NOTIFICATION", opt_notification);
4573     helpserv_define_option("REQMAXLEN", opt_req_maxlen);
4574     helpserv_define_option("IDWRAP", opt_id_wrap);
4575     helpserv_define_option("PRIVMSGONLY", opt_privmsg_only);
4576     helpserv_define_option("REQONJOIN", opt_req_on_join);
4577     helpserv_define_option("AUTOVOICE", opt_auto_voice);
4578     helpserv_define_option("AUTODEVOICE", opt_auto_devoice);
4579
4580     helpserv_usercmd_dict = dict_new();
4581     dict_insert(helpserv_usercmd_dict, "WAIT", usercmd_wait);
4582
4583     helpserv_bots_dict = dict_new();
4584     dict_set_free_data(helpserv_bots_dict, helpserv_free_bot);
4585
4586     helpserv_bots_bychan_dict = dict_new();
4587     dict_set_free_data(helpserv_bots_bychan_dict, helpserv_botlist_free);
4588
4589     helpserv_reqs_bynick_dict = dict_new();
4590     dict_set_free_data(helpserv_reqs_bynick_dict, helpserv_reqlist_free);
4591     helpserv_reqs_byhand_dict = dict_new();
4592     dict_set_free_data(helpserv_reqs_byhand_dict, helpserv_reqlist_free);
4593
4594     helpserv_users_byhand_dict = dict_new();
4595     dict_set_free_data(helpserv_users_byhand_dict, helpserv_userlist_free);
4596
4597     saxdb_register("HelpServ", helpserv_saxdb_read, helpserv_saxdb_write);
4598     helpserv_helpfile_read();
4599
4600     /* Make up for downtime... though this will only really affect the
4601      * time_per_week */
4602     if (last_stats_update && (helpserv_next_stats(last_stats_update) < now)) {
4603         unsigned long statsrun = last_stats_update;
4604         while ((statsrun = helpserv_next_stats(statsrun)) < now)
4605             helpserv_run_stats(statsrun);
4606     }
4607     timeq_add(helpserv_next_stats(now), helpserv_timed_run_stats, NULL);
4608
4609     reg_join_func(handle_join);
4610     reg_part_func(handle_part); /* also deals with kick */
4611     reg_nick_change_func(handle_nickchange);
4612     reg_del_user_func(handle_quit);
4613
4614     reg_auth_func(handle_nickserv_auth);
4615     reg_handle_rename_func(handle_nickserv_rename);
4616     reg_unreg_func(handle_nickserv_unreg);
4617     reg_allowauth_func(handle_nickserv_allowauth);
4618     reg_failpw_func(handle_nickserv_failpw);
4619     reg_handle_merge_func(handle_nickserv_merge);
4620
4621     reg_exit_func(helpserv_db_cleanup);
4622
4623     helpserv_module = module_register("helpserv", HS_LOG, HELPSERV_HELPFILE_NAME, helpserv_expand_variable);
4624     modcmd_register(helpserv_module, "helpserv", cmd_helpserv, 1, MODCMD_REQUIRE_AUTHED|MODCMD_NO_LOG|MODCMD_NO_DEFAULT_BIND, "level", "800", NULL);
4625     message_register_table(msgtab);
4626     return 1;
4627 }
4628
4629 int
4630 helpserv_finalize(void) {
4631     return 1;
4632 }