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