19a0e9fd4a4d2711b2de7cd004557c89967251c5
[NeonServV5.git] / src / bot_NeonHelp.c
1 /* bot_NeonHelp.c - NeonServ v5.3
2  * Copyright (C) 2011-2012  Philipp Kreil (pk910)
3  * 
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License 
15  * along with this program. If not, see <http://www.gnu.org/licenses/>. 
16  */
17
18 #include "bot_NeonHelp.h"
19 #include "modcmd.h"
20 #include "cmd_neonhelp.h"
21 #include "lang.h"
22 #include "mysqlConn.h"
23 #include "ClientSocket.h"
24 #include "UserNode.h"
25 #include "ChanNode.h"
26 #include "ChanUser.h"
27 #include "IRCEvents.h"
28 #include "IRCParser.h"
29 #include "bots.h"
30 #include "DBHelper.h"
31 #include "WHOHandler.h"
32
33 #define BOTID 4
34 #define BOTALIAS "NeonHelp"
35
36 static const struct default_language_entry msgtab[] = {
37     {"NH_NOT_ON_CHAN_1", "You cannot open this request as you are not in %s."}, /* {ARGS: "#test"} */
38     {"NH_NOT_ON_CHAN_2", "You cannot open this request as you are not in %s or %s."}, /* {ARGS: "test", "#test-support"} */
39     {"NH_REQUEST_RECORDED", "Your message has been recorded and assigned request ID#%d A helper should contact you shortly."}, /* {ARGS: 5} */
40     {"NH_REQUEST_OTHERS_0", "There are no other unhandled requests."},
41     {"NH_REQUEST_OTHERS_1", "There is 1 other unhandled request."},
42     {"NH_REQUEST_OTHERS_2", "There are %d other unhandled requests."}, /* {ARGS: 1337} */
43     {"NH_REQUEST_FOOTER_1", "Everything you tell me until you are helped (or you leave %1$s) will be recorded. If you part %1$s, your request will be lost."}, /* {ARGS: "#test"} */
44     {"NH_REQUEST_FOOTER_2", "Everything you tell me until you are helped (or you leave %1$s or %2$s) will be recorded. If you part %1$s or %2$s, your request will be lost."}, /* {ARGS: "#test", "#test-support"} */
45     {"NH_NEW_REQUEST", "New request #%d by %s: %s"}, /* {ARGS: 5, "pk910", "Help, I've fallen and I can't get up!"} */
46     {"NH_NEXT_NONE", "No more requests."},
47     {"NH_NEXT_NOT_FOUND", "No request found."},
48     {"NH_NEXT_HEADER", "$bNext request: #%d %s$b"}, /* {ARGS: 5, "pk910"} */
49     {"NH_NEXT_HELPER", "Your helper for request ID#%d is %s (Current nick: %s)."}, /* {ARGS: 5, "pk910", "Skynet"} */
50     {"NH_NEXT_JOIN", "Please /join %s now."}, /* {ARGS: "#test-support"} */
51     {"NH_DELETED", "Your request ID#%d has been deleted."}, /* {ARGS: 5} */
52     {"NH_DELETED_STAFF", "Request deleted: #%d (%s)"}, /* {ARGS: 5, "pk910"} */
53     {NULL, NULL}
54 };
55
56 static void neonhelp_bot_ready(struct ClientSocket *client) {
57     MYSQL_RES *res;
58     MYSQL_ROW row;
59     
60     printf_mysql_query("SELECT `automodes` FROM `bots` WHERE `id` = '%d'", client->clientid);
61     res = mysql_use();
62     if ((row = mysql_fetch_row(res)) != NULL) {
63         putsock(client, "MODE %s +%s", client->user->nick, row[0]);
64     }
65     
66     printf_mysql_query("SELECT `channel_name`, `channel_key` FROM `bot_channels` LEFT JOIN `channels` ON `chanid` = `channel_id` WHERE `botid` = '%d' AND `suspended` = '0'", client->clientid);
67     res = mysql_use();
68     
69     while ((row = mysql_fetch_row(res)) != NULL) {
70         putsock(client, "JOIN %s %s", row[0], row[1]);
71     }
72 }
73
74 static void neonhelp_trigger_callback(int clientid, struct ChanNode *chan, char *trigger) {
75     MYSQL_RES *res;
76     MYSQL_ROW row;
77     loadChannelSettings(chan);
78     if(!(chan->flags & CHANFLAG_CHAN_REGISTERED)) {
79         strcpy(trigger, "!");
80         return;
81     }
82     printf_mysql_query("SELECT `trigger`, `defaulttrigger` FROM `bot_channels` LEFT JOIN `bots` ON `botid` = `bots`.`id` WHERE `chanid` = '%d' AND `botclass` = '%d'", chan->channel_id, BOTID);
83     res = mysql_use();
84     row = mysql_fetch_row(res);
85     if(row[0] && *row[0])
86         strcpy(trigger, row[0]);
87     else
88         strcpy(trigger, ((row[1] && *row[1]) ? row[1] : "!"));
89 }
90
91 static void start_bots() {
92     struct ClientSocket *client;
93     MYSQL_RES *res, *res2;
94     MYSQL_ROW row;
95     
96     printf_mysql_query("SELECT `nick`, `ident`, `realname`, `server`, `port`, `pass`, `textbot`, `id`, `queue`, `ssl`, `bind` FROM `bots` WHERE `botclass` = '%d' AND `active` = '1'", BOTID);
97     res = mysql_use();
98     
99     while ((row = mysql_fetch_row(res)) != NULL) {
100         client = create_socket(row[3], atoi(row[4]), row[10], row[5], row[0], row[1], row[2]);
101         client->flags |= (strcmp(row[6], "0") ? SOCKET_FLAG_PREFERRED : 0);
102         client->flags |= (strcmp(row[8], "0") ? SOCKET_FLAG_USE_QUEUE : 0);
103         client->flags |= (strcmp(row[9], "0") ? SOCKET_FLAG_SSL : 0);
104         client->flags |= SOCKET_FLAG_SILENT;
105         client->botid = BOTID;
106         client->clientid = atoi(row[7]);
107         connect_socket(client);
108         //close old, still opened requests
109         printf_mysql_query("UPDATE `helpserv_requests` SET `status` = '2' WHERE `botid` = '%d'", client->clientid);
110     }
111     
112     printf_mysql_query("SELECT `command`, `function`, `parameters`, `global_access`, `chan_access`, `flags` FROM `bot_binds` WHERE `botclass` = '%d'", BOTID);
113     res2 = mysql_use();
114     while ((row = mysql_fetch_row(res2)) != NULL) {
115         if(bind_cmd_to_command(BOTID, row[0], row[1])) {
116             if(row[2] && strcmp(row[2], "")) {
117                 bind_set_parameters(BOTID, row[0], row[2]);
118             }
119             if(row[3]) {
120                 bind_set_global_access(BOTID, row[0], atoi(row[3]));
121             }
122             if(row[4]) {
123                 bind_set_channel_access(BOTID, row[0], row[4]);
124             }
125             if(strcmp(row[5], "0"))
126                 bind_set_bind_flags(BOTID, row[0], atoi(row[5]));
127         }
128     }
129     bind_unbound_required_functions(BOTID);
130 }
131
132 static void neonhelp_event_privmsg_async(struct ClientSocket *client, struct UserNode *user, struct UserNode *target, char *message);
133 static USERAUTH_CALLBACK(neonhelp_event_privmsg_nick_lookup);
134 struct neonhelp_event_privmsg_cache {
135     struct ClientSocket *client;
136     struct UserNode *user, *target;
137     char *message;
138 };
139
140 static void neonhelp_event_privmsg(struct UserNode *user, struct UserNode *target, char *message) {
141     struct ClientSocket *client;
142     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
143         if(client->user == target) {
144             if(client->botid != BOTID) return;
145             break;
146         }
147     }
148     if(!client) return; //we got the message but we have no client that could receive it???
149     if(user->flags & USERFLAG_ISAUTHED) {
150         neonhelp_event_privmsg_async(client, user, target, message);
151     } else {
152         struct neonhelp_event_privmsg_cache *cache = malloc(sizeof(*cache));
153         if(!cache) return;
154         cache->client = client;
155         cache->user = user;
156         cache->target = target;
157         cache->message = strdup(message);
158         get_userauth(user, neonhelp_event_privmsg_nick_lookup, cache);
159     }
160 }
161
162 static USERAUTH_CALLBACK(neonhelp_event_privmsg_nick_lookup) {
163     struct neonhelp_event_privmsg_cache *cache = data;
164     neonhelp_event_privmsg_async(cache->client, cache->user, cache->target, cache->message);
165     free(cache->message);
166     free(cache);
167 }
168
169 static void neonhelp_event_privmsg_async(struct ClientSocket *client, struct UserNode *user, struct UserNode *target, char *message) {
170     MYSQL_RES *res;
171     MYSQL_ROW row, row2;
172     printf_mysql_query("SELECT `helpserv_support`, `helpserv_public`, `helpserv_intern` FROM `helpserv_settings` WHERE `helpserv_botid` = '%d'", client->clientid);
173     res = mysql_use();
174     if (!(row = mysql_fetch_row(res))) return;
175     //check if the user is a supporter (access in the support channel)
176     if((user->flags & USERFLAG_ISAUTHED)) {
177         int caccess = 0;
178         int userid;
179         if(user->flags & USERFLAG_HAS_USERID)
180             userid = user->user_id;
181         else {
182             printf_mysql_query("SELECT `user_id` FROM `users` WHERE `user_user` = '%s'", escape_string(user->auth));
183             res = mysql_use();
184             if ((row2 = mysql_fetch_row(res)) != NULL) {
185                 userid = atoi(row2[0]);
186                 user->user_id = userid;
187                 user->flags |= USERFLAG_HAS_USERID;
188             } else
189                 userid = 0;
190         }
191         printf_mysql_query("SELECT `chanuser_access`, `chanuser_flags` FROM `chanusers` LEFT JOIN `channels` ON `chanuser_cid` = `channel_id` WHERE `chanuser_uid` = '%d' AND `channel_name` = '%s'", userid, escape_string(row[0]));
192         res = mysql_use();
193         if ((row2 = mysql_fetch_row(res)) != NULL) {
194             int cflags = atoi(row2[1]);
195             if(!(cflags & DB_CHANUSER_SUSPENDED))
196                 caccess = atoi(row2[0]);
197         }
198         if(caccess) return; //ignore messages from supporters
199     }
200     //check if the user is in one of the bot's channels
201     struct ChanUser *chanuser;
202     struct ChanNode *chan;
203     for(chanuser = getUserChannels(target, NULL); chanuser; chanuser = getUserChannels(target, chanuser)) {
204         chan = chanuser->chan;
205         if((!stricmp(chan->name, row[0]) || (row[1] && !stricmp(chan->name, row[1]))) && isUserOnChan(user, chan))
206             break;
207     }
208     if(!chanuser) {
209         if(row[1])
210             reply(client, user, "NH_NOT_ON_CHAN_2", row[0], row[1]);
211         else
212             reply(client, user, "NH_NOT_ON_CHAN_1", row[0]);
213         return;
214     }
215     //check if there is already a support request
216     int others = 0;
217     if(client->flags & SOCKET_HAVE_HELPNODE) {
218         struct NeonHelpNode *helpnode;
219         for(helpnode = client->botclass_helpnode; helpnode; helpnode = helpnode->next) {
220             if(helpnode->user == user) {
221                 //simply append the message to the database
222                 printf_mysql_query("SELECT `text` FROM `helpserv_requests` WHERE `id` = %d", helpnode->suppid);
223                 res = mysql_use();
224                 if ((row2 = mysql_fetch_row(res)) != NULL) {
225                     char *old_msg = escape_string(row2[0]);
226                     char *new_msg = escape_string(message);
227                     printf_long_mysql_query(1024 + strlen(old_msg) + strlen(new_msg), "UPDATE `helpserv_requests` SET `text` = '%s\n%s' WHERE `id` = %d", old_msg, new_msg, helpnode->suppid);
228                 }
229                 return;
230             }
231             others++;
232         }
233     }
234     //add new request
235     struct NeonHelpNode *helpnode = malloc(sizeof(*helpnode));
236     if(!helpnode) return;
237     helpnode->user = user;
238     helpnode->logchan = getChanByName(row[0]);
239     helpnode->status = 0;
240     printf_mysql_query("INSERT INTO `helpserv_requests` (`botid`, `host`, `hand`, `nick`, `status`, `supporter`, `time`, `text`) VALUES ('%d', '%s@%s', '%s', '%s', '0', '-1', UNIX_TIMESTAMP(), '%s')", client->clientid, escape_string(user->ident), escape_string(user->host), ((user->flags & USERFLAG_ISAUTHED) ? escape_string(user->auth) : "*"), escape_string(user->nick), escape_string(message));
241     helpnode->suppid = (int) mysql_insert_id(mysql_conn);
242     helpnode->log = NULL;
243     helpnode->next = ((client->flags & SOCKET_HAVE_HELPNODE) ? client->botclass_helpnode : NULL);
244     client->botclass_helpnode = helpnode;
245     client->flags |= SOCKET_HAVE_HELPNODE;
246     //build the user reply...
247     char user_reply[MAXLEN];
248     int user_reply_pos = 0;
249     char reply_buff[MAXLEN];
250     //1st part: NH_REQUEST_RECORDED
251     strcpy(user_reply + user_reply_pos, build_language_string(user, reply_buff, "NH_REQUEST_RECORDED", helpnode->suppid));
252     user_reply_pos += strlen(reply_buff);
253     //2nd part: NH_REQUEST_OTHERS_0 / NH_REQUEST_OTHERS_1 / NH_REQUEST_OTHERS_2
254     user_reply[user_reply_pos++] = ' ';
255     if(others <= 1)
256         strcpy(user_reply + user_reply_pos, build_language_string(user, reply_buff, (others ? "NH_REQUEST_OTHERS_1" : "NH_REQUEST_OTHERS_0")));
257     else
258         strcpy(user_reply + user_reply_pos, build_language_string(user, reply_buff, "NH_REQUEST_OTHERS_2", others));
259     user_reply_pos += strlen(reply_buff);
260     //3th part: NH_REQUEST_FOOTER_1 / NH_REQUEST_FOOTER_2
261     user_reply[user_reply_pos++] = ' ';
262     if(row[1])
263         strcpy(user_reply + user_reply_pos, build_language_string(user, reply_buff, "NH_REQUEST_FOOTER_2", row[0], row[1]));
264     else
265         strcpy(user_reply + user_reply_pos, build_language_string(user, reply_buff, "NH_REQUEST_FOOTER_1", row[0]));
266     user_reply_pos += strlen(reply_buff);
267     reply(client, user, "%s", user_reply);
268     //sent a message to the internal channel / onotice to supp channel
269     build_language_string(user, reply_buff, "NH_NEW_REQUEST", helpnode->suppid, user->nick, message);
270     if(row[2]) {
271         putsock(client, "PRIVMSG %s :%s", row[2], reply_buff);
272     } else {
273         putsock(client, "NOTICE @%s :%s", row[0], reply_buff);
274     }
275 }
276
277 static void neonhelp_event_chanmsg(struct UserNode *user, struct ChanNode *chan, char *message) {
278     char logline[MAXLEN];
279     sprintf(logline, "<%s> %s", user->nick, message);
280     struct ClientSocket *client;
281     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
282         if(client->botid == BOTID) {
283             struct NeonHelpNode *helpnode;
284             if(client->flags & SOCKET_HAVE_HELPNODE) {
285                 for(helpnode = client->botclass_helpnode; helpnode; helpnode = helpnode->next) {
286                     if(helpnode->logchan == chan && helpnode->status == 1) {
287                         if(!helpnode->log) {
288                             helpnode->log = calloc(LOGBUFFERLINES, sizeof(char*));
289                             if(!helpnode->log) return;
290                         }
291                         int i;
292                         for(i = 0; i < LOGBUFFERLINES; i++) {
293                             if(!helpnode->log[i]) {
294                                 helpnode->log[i] = strdup(logline);
295                                 break;
296                             }
297                         }
298                         if(i == LOGBUFFERLINES) {
299                             //write buffer to database
300                             char logbuff[MAXLEN * LOGBUFFERLINES];
301                             int len = 0;
302                             for(i = 0; i < LOGBUFFERLINES; i++) {
303                                 len += sprintf(logbuff + len, "%s\n", helpnode->log[i]);
304                                 free(helpnode->log[i]);
305                                 helpnode->log[i] = NULL;
306                             }
307                             printf_long_mysql_query(1024 + len, "UPDATE `helpserv_requests` SET `log` = CONCAT(`log`, '%s') WHERE `id` = %d", escape_string(logbuff), helpnode->suppid);
308                         }
309                         break;
310                     }
311                 }
312             }
313         }
314     }
315 }
316
317 static void destroy_support_request(struct ClientSocket *client, struct NeonHelpNode *helpnode, int do_reply) {
318     //write buffer to database
319     char logbuff[MAXLEN * LOGBUFFERLINES];
320     int len = 0;
321     int i;
322     if(helpnode->log) {
323         for(i = 0; i < LOGBUFFERLINES; i++) {
324             if(!helpnode->log[i]) break;
325             len += sprintf(logbuff + len, "%s\n", helpnode->log[i]);
326             free(helpnode->log[i]);
327             helpnode->log[i] = NULL;
328         }
329         free(helpnode->log);
330     }
331     printf_long_mysql_query(1024 + len, "UPDATE `helpserv_requests` SET `status`='2', `log` = CONCAT(`log`, '%s') WHERE `id` = %d", escape_string(logbuff), helpnode->suppid);
332     if(do_reply) {
333         reply(client, helpnode->user, "NH_DELETED", helpnode->suppid);
334     }
335     free(helpnode);
336 }
337
338 static void neonhelp_event_kick(struct UserNode *user, struct ChanUser *target, char *reason) {
339     struct ClientSocket *client;
340     MYSQL_RES *res;
341     MYSQL_ROW row;
342     struct ChanNode *support, *public;
343     int userHasRequest;
344     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
345         if(client->botid == BOTID && isUserOnChan(client->user, target->chan)) {
346             userHasRequest = 0;
347             struct NeonHelpNode *helpnode, *prev_helpnode = NULL;
348             if(client->flags & SOCKET_HAVE_HELPNODE) {
349                 for(helpnode = client->botclass_helpnode; helpnode; helpnode = helpnode->next) {
350                     if(helpnode->user == target->user) {
351                         userHasRequest = 1;
352                         break;
353                     } else
354                         prev_helpnode = helpnode;
355                 }
356             }
357             if(!userHasRequest) continue;
358             printf_mysql_query("SELECT `helpserv_support`, `helpserv_public`, `helpserv_intern` FROM `helpserv_settings` WHERE `helpserv_botid` = '%d'", client->clientid);
359             res = mysql_use();
360             if (!(row = mysql_fetch_row(res))) continue;
361             support = getChanByName(row[0]);
362             public = (row[1] ? getChanByName(row[1]) : NULL);
363             if(target->chan == support || !((support && isUserOnChan(target->user, support)) || (public && isUserOnChan(target->user, public)))) {
364                 //free the user's support request
365                 if(prev_helpnode)
366                     prev_helpnode->next = helpnode->next;
367                 else
368                     client->botclass_helpnode = helpnode->next;
369                 destroy_support_request(client, helpnode, 1);
370             }
371         }
372     }
373 }
374
375 static void neonhelp_event_part(struct ChanUser *target, char *reason) {
376     struct ClientSocket *client;
377     MYSQL_RES *res;
378     MYSQL_ROW row;
379     struct ChanNode *support, *public;
380     int userHasRequest;
381     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
382         if(client->botid == BOTID && isUserOnChan(client->user, target->chan)) {
383             userHasRequest = 0;
384             struct NeonHelpNode *helpnode, *prev_helpnode = NULL;
385             if(client->flags & SOCKET_HAVE_HELPNODE) {
386                 for(helpnode = client->botclass_helpnode; helpnode; helpnode = helpnode->next) {
387                     if(helpnode->user == target->user) {
388                         userHasRequest = 1;
389                         break;
390                     } else
391                         prev_helpnode = helpnode;
392                 }
393             }
394             if(!userHasRequest) continue;
395             printf_mysql_query("SELECT `helpserv_support`, `helpserv_public`, `helpserv_intern` FROM `helpserv_settings` WHERE `helpserv_botid` = '%d'", client->clientid);
396             res = mysql_use();
397             if (!(row = mysql_fetch_row(res))) continue;
398             support = getChanByName(row[0]);
399             public = (row[1] ? getChanByName(row[1]) : NULL);
400             if(target->chan == support || !((support && isUserOnChan(target->user, support)) || (public && isUserOnChan(target->user, public)))) {
401                 //free the user's support request
402                 if(prev_helpnode)
403                     prev_helpnode->next = helpnode->next;
404                 else
405                     client->botclass_helpnode = helpnode->next;
406                 destroy_support_request(client, helpnode, 1);
407             }
408         }
409     }
410 }
411
412 static void neonhelp_event_quit(struct UserNode *target, char *reason) {
413     struct ClientSocket *client;
414     int userHasRequest;
415     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
416         if(client->botid == BOTID) {
417             userHasRequest = 0;
418             struct NeonHelpNode *helpnode, *prev_helpnode = NULL;
419             if(client->flags & SOCKET_HAVE_HELPNODE) {
420                 for(helpnode = client->botclass_helpnode; helpnode; helpnode = helpnode->next) {
421                     if(helpnode->user == target) {
422                         userHasRequest = 1;
423                         break;
424                     } else
425                         prev_helpnode = helpnode;
426                 }
427             }
428             if(!userHasRequest) continue;
429             //free the user's support request
430             if(prev_helpnode)
431                 prev_helpnode->next = helpnode->next;
432             else
433                 client->botclass_helpnode = helpnode->next;
434             destroy_support_request(client, helpnode, 0);
435         }
436     }
437 }
438
439 void init_NeonHelp() {
440     
441     set_bot_alias(BOTID, BOTALIAS);
442     start_bots();
443     
444     //register events
445     bind_bot_ready(neonhelp_bot_ready);
446     bind_privmsg(neonhelp_event_privmsg);
447     bind_chanmsg(neonhelp_event_chanmsg);
448     bind_part(neonhelp_event_part);
449     bind_kick(neonhelp_event_kick);
450     bind_quit(neonhelp_event_quit);
451     
452     set_trigger_callback(BOTID, neonhelp_trigger_callback);
453     
454     register_default_language_table(msgtab);
455 }
456
457 void loop_NeonHelp() {
458     
459 }
460
461 void free_NeonHelp() {
462     
463 }
464
465 #undef BOTID
466 #undef BOTALIAS