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