fixed renameAccount function (merging mode)
[NeonServV5.git] / src / modcmd.c
1 /* modcmd.c - NeonServ v5.6
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 "modcmd.h"
19 #include "IRCEvents.h"
20 #include "IRCParser.h"
21 #include "ClientSocket.h"
22 #include "UserNode.h"
23 #include "ChanNode.h"
24 #include "ChanUser.h"
25 #include "WHOHandler.h"
26 #include "lang.h"
27 #include "mysqlConn.h"
28 #include "DBHelper.h"
29 #include "EventLogger.h"
30
31 struct trigger_callback {
32     int botid;
33     int module_id;
34     trigger_callback_t *func;
35     
36     struct trigger_callback *next;
37 };
38
39 struct cmd_bot_alias {
40     int botid;
41     char *alias;
42     
43     struct cmd_bot_alias *next;
44 };
45
46 struct command_check_user_cache {
47     struct ClientSocket *client, *textclient;
48     struct UserNode *user;
49     struct ChanNode *chan, *sent_chan;
50     char **argv;
51     int argc;
52     char *message, *args_buffer;
53     struct cmd_binding *cbind;
54 };
55
56 static struct cmd_binding **cmd_binds;
57 static struct cmd_function *cmd_functions = NULL;
58 static struct trigger_callback *trigger_callbacks = NULL;
59 static struct cmd_bot_alias *bot_aliases = NULL;
60 static int total_triggered = 0;
61 int statistics_commands = 0;
62
63 static const struct default_language_entry msgtab[] = {
64     {"MODCMD_LESS_PARAM_COUNT", "This command requires more parameters."},
65     {"MODCMD_CHAN_REQUIRED",    "You must provide the name of a channel that exists and the bot is on."},
66     {"MODCMD_AUTH_REQUIRED",    "You need to be authenticated with AuthServ to use this command."},
67     {"MODCMD_CHAN_SUSPENDED",   "This channel is currently suspended."},
68     {"MODCMD_PRIVILEGED",       "$b%s$b is a privileged command."}, /* {ARGS: "god"} */
69     {"MODCMD_PUBCMD",           "Public commands in $b%s$b are restricted."}, /* {ARGS: "#TestChan"} */
70     {"MODCMD_ACCESS_DENIED",    "Access denied."},
71     {"MODCMD_SUBCOMMANDS",      "Subcommands of %s: %s"}, /* {ARGS: "bot", "ADD, DEL, EDIT"} */
72     {"MODCMD_CROSSCHAN",        "You must be in %s (or on its userlist) to use this command."}, /* {ARGS: "#TestChan"} */
73     {"MODCMD_UNKNOWN",          "$b%s$b is an unknown command."}, /* {ARGS: "bla"} */
74     {NULL, NULL}
75 };
76
77 static int get_binds_index(char first_char) {
78     if(tolower(first_char) >= 'a' && tolower(first_char) <= 'z') {
79         return tolower(first_char) - 'a';
80     }
81     return 26;
82 }
83
84 struct ClientSocket* get_botwise_prefered_bot(int botid, int clientid) {
85     struct ClientSocket *client, *lowbot = NULL;
86     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
87         if(client->botid == botid && (botid || clientid == client->clientid)) {
88             if((client->flags & SOCKET_FLAG_PREFERRED))
89                 return client;
90             else
91                 lowbot = client;
92         }
93     }
94     return lowbot;
95 }
96
97 static char* get_channel_trigger(int botid, int clientid, struct ChanNode *chan) {
98     struct trigger_cache *trigger;
99     for(trigger = chan->trigger; trigger; trigger = trigger->next) {
100         if(trigger->botid == botid && (botid || trigger->clientid == clientid))
101             return trigger->trigger;
102     }
103     struct trigger_callback *cb;
104     for(cb = trigger_callbacks; cb; cb = cb->next) {
105         if(cb->botid == botid)
106             break;
107     }
108     char triggerStr[TRIGGERLEN];
109     if(cb)
110         cb->func(clientid, chan, triggerStr);
111     else
112         triggerStr[0] = '\0';
113     trigger = malloc(sizeof(*trigger));
114     if (!trigger) {
115         perror("malloc() failed");
116         return 0;
117     }
118     trigger->botid = botid;
119     trigger->clientid = clientid;
120     trigger->trigger = (triggerStr[0] ? strdup(triggerStr) : NULL);
121     trigger->next = chan->trigger;
122     chan->trigger = trigger;
123     return trigger->trigger;
124 }
125
126 static void handle_command_async(struct ClientSocket *client, struct ClientSocket *textclient, struct UserNode *user, struct ChanNode *chan, struct ChanNode *sent_chan, struct cmd_binding *cbind, char **argv, int argc);
127
128 static USERAUTH_CALLBACK(command_checked_auth) {
129     struct command_check_user_cache *cache = data;
130     if(user)
131         handle_command_async(cache->client, cache->textclient, user, cache->chan, cache->sent_chan, cache->cbind, cache->argv, cache->argc);
132     free(cache->message);
133     if(cache->args_buffer)
134         free(cache->args_buffer);
135     free(cache->argv);
136     free(cache);
137 }
138
139 static CMD_BIND(modcmd_linker) {
140     //fake command for subcommands
141     //just empty
142 }
143
144 static struct cmd_binding *modcmd_linker_command(struct ClientSocket *client, struct ClientSocket *textclient, struct UserNode *user, struct cmd_binding *cbind, int bind_index, char **args_ptr) {
145     //links subcommands
146     char command[MAXLEN];
147     struct cmd_binding *parent_bind = cbind;
148     char *args = *args_ptr;
149     if(args) {
150         char *subcmd = args;
151         args = strstr(args, " ");
152         if(args) {
153             *args = '\0';
154             args++;
155         }
156         sprintf(command, "%s %s", parent_bind->cmd, subcmd);
157         for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
158             if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmp(cbind->cmd, command) == 0)
159                 break;
160         }
161         *args_ptr = args;
162         if(cbind && cbind->func->func == modcmd_linker) {
163             return modcmd_linker_command(client, textclient, user, cbind, bind_index, args_ptr);
164         }
165         return cbind;
166     } else {
167         //list all sub commands
168         int commandlen = sprintf(command, "%s ", parent_bind->cmd);
169         char subcommands[MAXLEN];
170         int subcompos = 0;
171         for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
172             if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmplen(cbind->cmd, command, commandlen) == 0) {
173                 if(strstr(cbind->cmd + commandlen, " ")) continue; //ignore if there is another space in the command (sub-sub-command :D)
174                 subcompos += sprintf(subcommands + subcompos, (subcompos ? ", %s" : "%s"), cbind->cmd + commandlen);
175             }
176         }
177         reply(textclient, user, "MODCMD_SUBCOMMANDS", parent_bind->cmd, (subcompos ? subcommands : "\1dnone\1d"));
178         return NULL;
179     }
180 }
181
182 static struct cmd_binding *modcmd_sub_linker_command(struct ClientSocket *client, struct ClientSocket *textclient, struct UserNode *user, struct cmd_binding *cbind, int bind_index, char **args_ptr) {
183     //links subcommands
184     char command[MAXLEN];
185     struct cmd_binding *parent_bind = cbind;
186     char *args = *args_ptr;
187     if(args) {
188         char *subcmd = args;
189         args = strchr(args, ' ');
190         if(args) {
191             *args = '\0';
192             args++;
193         }
194         sprintf(command, "%s %s", parent_bind->cmd, subcmd);
195         for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
196             if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmp(cbind->cmd, command) == 0)
197                 break;
198         }
199         *args_ptr = args;
200         if(cbind && cbind->func->func == modcmd_linker) {
201             return modcmd_linker_command(client, textclient, user, cbind, bind_index, args_ptr);
202         }
203         return (cbind ? cbind : parent_bind);
204     } else
205         return parent_bind;
206 }
207
208 static void handle_command(struct ClientSocket *client, struct UserNode *user, struct ChanNode *chan, char *message) {
209     struct ChanNode *sent_chan = chan;
210     if(message[0] == '#') {
211         char *chanName = message;
212         message = strstr(message, " ");
213         if(!message) return;
214         *message = '\0';
215         message++;
216         struct ChanNode *chan2 = getChanByName(chanName);
217         if(chan2)
218             chan = chan2;
219     }
220     message = strdup(message);
221     int bind_index = get_binds_index(message[0]);
222     char *args = strchr(message, ' ');
223     char *args_buffer = NULL; //we need this to save a possible pointer to a allocation we need to free
224     if(args) {
225         *args = '\0';
226         args++;
227     }
228     struct cmd_binding *cbind;
229     int found_cmd = 0;
230     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
231         if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmp(cbind->cmd, message) == 0) {
232             found_cmd = 1;
233             //get a text bot
234             struct ClientSocket *textclient = get_botwise_prefered_bot(client->botid, (client->botid == 0 ? client->clientid : 0));
235             if(cbind->func->func == modcmd_linker) {
236                 cbind = modcmd_linker_command(client, textclient, user, cbind, bind_index, &args);
237                 if(cbind == NULL) break;
238             } else if(cbind->flags & CMDFLAG_SUB_LINKER)
239                 cbind = modcmd_sub_linker_command(client, textclient, user, cbind, bind_index, &args);
240             statistics_commands++;
241             total_triggered++;
242             cbind->triggered++;
243             if((BIND_FLAGS(cbind) & CMDFLAG_FUNCMD)) {
244                 if(!sent_chan)
245                     break;
246                 chan = sent_chan;
247             }
248             //parse the arguments...
249             char *arga[MAXNUMPARAMS];
250             char **argv;
251             int argc = 0;
252             int escape = 0;
253             int offset = 0;
254             if(args) {
255                 while(*args) {
256                     //skip leading spaces
257                     while (*args == ' ')
258                         *args++ = 0;
259                     arga[argc++] = args;
260                     if (argc >= MAXNUMPARAMS)
261                         break;
262                     while ((escape || *args != ' ') && *args) {
263                         if((BIND_FLAGS(cbind) & CMDFLAG_ESCAPE_ARGS) && *args == '\\') {
264                             escape = 1;
265                             offset++;
266                         } else if(escape)
267                             escape = 0;
268                         if(!escape && offset) {
269                             args[0 - offset] = args[0];
270                         }
271                         args++;
272                         
273                     }
274                     if(offset) {
275                         args[0-offset] = '\0';
276                         offset = 0;
277                     }
278                 }
279             }
280             argv = arga;
281             if(cbind->paramcount) {
282                 //userdefined parameters...
283                 args_buffer = malloc(MAXLEN * 2 * sizeof(*args_buffer));
284                 int args_pos = 0;
285                 char *uargs[MAXNUMPARAMS];
286                 int uargc = 0;
287                 char *b, *c;
288                 int i;
289                 int allargs, argi;
290                 for(i = 0; i < cbind->paramcount; i++) {
291                     b = cbind->parameters[i];
292                     if(b[0] == '%') {
293                         b++;
294                         c = b;
295                         while(*c && *c != ' ') {
296                             if(*c == '|') break;
297                             c++;
298                         }
299                         if(!*c || *c == ' ') c = NULL;
300                         else {
301                             *c = '\0';
302                             c++;
303                         }
304                         if(b[strlen(b)-1] == '-') {
305                             allargs = strlen(b)-1;
306                             b[allargs] = '\0';
307                             argi = atoi(b);
308                             b[allargs] = '-';
309                             allargs = 1;
310                         } else if(b[strlen(b)-1] == '+') {
311                             allargs = strlen(b)-1;
312                             b[allargs] = '\0';
313                             argi = atoi(b);
314                             b[allargs] = '+';
315                             allargs = 2;
316                         } else {
317                             allargs = 0;
318                             argi = atoi(b);
319                         }
320                         if(argi > 0) {
321                             if(argi <= argc) {
322                                 uargs[uargc++] = args_buffer + args_pos;
323                                 if(allargs == 0) {
324                                     args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
325                                 } else if(allargs == 1) {
326                                     args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
327                                     for(argi++; argi <= argc; argi++) {
328                                         uargs[uargc++] = args_buffer + args_pos;
329                                         args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
330                                     }
331                                 } else if(allargs == 2) {
332                                     for(;argi <= argc; argi++) {
333                                         args_pos += sprintf(args_buffer + args_pos, (allargs ? "%s" : " %s"), argv[argi-1]);
334                                         allargs = 0;
335                                     }
336                                     args_pos++;
337                                 }
338                             } else if((BIND_FLAGS(cbind) & CMDFLAG_EMPTY_ARGS)) {
339                                 uargs[uargc++] = args_buffer + args_pos;
340                                 args_buffer[args_pos++] = '\0';
341                             } else if(c) {
342                                 uargs[uargc++] = args_buffer + args_pos;
343                                 args_pos += sprintf(args_buffer + args_pos, "%s", c) + 1;
344                             }
345                         } else if(!strcmp(b, "c")) {
346                             uargs[uargc++] = args_buffer + args_pos;
347                             args_pos += sprintf(args_buffer + args_pos, "%s", (chan ? chan->name : "")) + 1;
348                         } else if(!strcmp(b, "n")) {
349                             uargs[uargc++] = args_buffer + args_pos;
350                             args_pos += sprintf(args_buffer + args_pos, "%s", user->nick) + 1;
351                         }
352                         if(c) c[-1] = '|'; //reset \0 to |
353                     } else {
354                         uargs[uargc++] = args_buffer + args_pos;
355                         args_pos += sprintf(args_buffer + args_pos, "%s", b) + 1;
356                     }
357                 }
358                 argv = uargs;
359                 argc = uargc;
360             }
361             if(argc != 0 && argv[0][0] == '#' && !(BIND_FLAGS(cbind) & CMDFLAG_CHAN_PARAM)) {
362                 struct ChanNode *chan2 = getChanByName(argv[0]);
363                 if(chan2) {
364                     argv += 1;
365                     argc -= 1;
366                     chan = chan2;
367                 }
368             }
369             if(argc < cbind->func->paramcount) {
370                 reply(textclient, user, "MODCMD_LESS_PARAM_COUNT");
371                 break;
372             }
373             if((BIND_FLAGS(cbind) & CMDFLAG_REQUIRE_CHAN) && !chan) {
374                 reply(textclient, user, "MODCMD_CHAN_REQUIRED");
375                 break;
376             }
377             if(((BIND_FLAGS(cbind) & CMDFLAG_CHECK_AUTH) || (chan && chan != sent_chan && !isUserOnChan(user, chan))) && !(user->flags & USERFLAG_ISAUTHED)) {
378                 //check auth...
379                 struct command_check_user_cache *data = malloc(sizeof(*data));
380                 char **temp_argv = malloc(argc*sizeof(*temp_argv));
381                 if (!data || !temp_argv) {
382                     perror("malloc() failed");
383                     break;
384                 }
385                 memcpy(temp_argv, argv, argc*sizeof(*temp_argv));
386                 data->argv = temp_argv;
387                 data->argc = argc;
388                 data->client = client;
389                 data->user = user;
390                 data->chan = chan;
391                 data->sent_chan = sent_chan;
392                 data->message = message;
393                 data->args_buffer = args_buffer;
394                 data->cbind = cbind;
395                 data->textclient = textclient;
396                 get_userauth(user, 0, command_checked_auth, data);
397                 return;
398             } else
399                 handle_command_async(client, textclient, user, chan, sent_chan, cbind, argv, argc);
400             break;
401         }
402     }
403     if(!found_cmd && !sent_chan && !(client->flags & SOCKET_FLAG_SILENT))
404         reply(get_botwise_prefered_bot(client->botid, (client->botid == 0 ? client->clientid : 0)), user, "MODCMD_UNKNOWN", message);
405     free(message);
406     if(args_buffer)
407         free(args_buffer);
408 }
409
410 static void handle_command_async(struct ClientSocket *client, struct ClientSocket *textclient, struct UserNode *user, struct ChanNode *chan, struct ChanNode *sent_chan, struct cmd_binding *cbind, char **argv, int argc) {
411     MYSQL_RES *res;
412     MYSQL_ROW row;
413     int uaccess;
414     char requested_uaccess = 0;
415     int eventflags = (BIND_FLAGS(cbind) & (CMDFLAG_LOG | CMDFLAG_OPLOG));
416     if((BIND_FLAGS(cbind) & CMDFLAG_REQUIRE_AUTH) && !(user->flags & USERFLAG_ISAUTHED)) {
417         reply(textclient, user, "MODCMD_AUTH_REQUIRED");
418         return;
419     }
420     if(chan && sent_chan != chan && (BIND_FLAGS(cbind) & CMDFLAG_NO_CROSSCHAN) && !isUserOnChan(user, chan)) {
421         char user_in_chan = 0;
422         if((user->flags & USERFLAG_ISAUTHED)) {
423             //maybe there's another user authed to user->auth on the channel...
424             struct ChanUser *cchanuser;
425             for(cchanuser = getChannelUsers(chan, NULL); cchanuser; cchanuser = getChannelUsers(chan, cchanuser)) {
426                 if((cchanuser->user->flags & USERFLAG_ISAUTHED) && !stricmp(user->auth, cchanuser->user->auth)) {
427                     user_in_chan = 1;
428                     break;
429                 }
430             }
431         }
432         if(!user_in_chan) {
433             //check if we are allowed to execute commands in this channel
434             requested_uaccess = 1;
435             uaccess = getChannelAccess(user, chan);
436             if(!uaccess) {
437                 if(isGodMode(user)) {
438                     eventflags |= CMDFLAG_OPLOG;
439                 } else {
440                     reply(textclient, user, "MODCMD_CROSSCHAN", chan->name);
441                     return;
442                 }
443             }
444         }
445     }
446     if(sent_chan && sent_chan != chan) {
447         //check pubcmd of this channel
448         printf_mysql_query("SELECT `channel_pubcmd` FROM `channels` WHERE `channel_name` = '%s'", escape_string(sent_chan->name));
449         res = mysql_use();
450         if ((row = mysql_fetch_row(res)) != NULL) {
451             int saccess = getChannelAccess(user, sent_chan);
452             if(row[0] && saccess < atoi(row[0]) && !isGodMode(user)) { //NOTE: HARDCODED DEFAULT: pubcmd = 0
453                 reply(textclient, user, "MODCMD_PUBCMD", sent_chan->name);
454                 return;
455             }
456         }
457     }
458     int global_access = ((cbind->flags & CMDFLAG_OVERRIDE_GLOBAL_ACCESS) ? cbind->global_access : cbind->func->global_access);
459     if(global_access > 0) {
460         int user_global_access = 0;
461         printf_mysql_query("SELECT `user_access` FROM `users` WHERE `user_user` = '%s'", escape_string(user->auth));
462         res = mysql_use();
463         if ((row = mysql_fetch_row(res)) != NULL) {
464             user_global_access = atoi(row[0]);
465         }
466         if(user_global_access < global_access) {
467             if(!user_global_access)
468                 reply(textclient, user, "MODCMD_PRIVILEGED", cbind->cmd);
469             else
470                 reply(textclient, user, "MODCMD_ACCESS_DENIED");
471             return;
472         }
473     }
474     if((BIND_FLAGS(cbind) & CMDFLAG_REGISTERED_CHAN)) {
475         MYSQL_ROW defaults = NULL;
476         char access_list[256];
477         int access_pos = 0;
478         int access_count = 0;
479         int minaccess = 0;
480         char *str_a, *str_b = cbind->func->channel_access, *str_c;
481         if(cbind->flags & CMDFLAG_OVERRIDE_CHANNEL_ACCESS)
482             str_b = cbind->channel_access;
483         access_list[0] = '\0';
484         if(str_b) {
485             struct ChanUser *chanuser = getChanUser(user, chan);
486             str_c = strdup(str_b);
487             str_b = str_c;
488             while((str_a = str_b)) {
489                 str_b = strstr(str_a, ",");
490                 if(str_b) {
491                     *str_b = '\0';
492                     str_b++;
493                 }
494                 if(*str_a == '@' || *str_a == '+') {
495                     //privs can override this access requirement
496                     int priv = 0;
497                     if(*str_a == '@') priv = CHANUSERFLAG_OPPED;
498                     else if(*str_a == '%') priv = CHANUSERFLAG_HALFOPPED;
499                     else if(*str_a == '+') priv = CHANUSERFLAG_VOICED;
500                     if(chanuser && (chanuser->flags & priv)) continue;
501                     str_a++;
502                 }
503                 if(*str_a == '#') {
504                     str_a++;
505                     access_pos += sprintf(access_list+access_pos, ", `%s`", str_a);
506                     access_count++;
507                 } else {
508                     if(atoi(str_a) > minaccess)
509                         minaccess = atoi(str_a);
510                 }
511             }
512             free(str_c);
513         }
514         if(!(chan->flags & CHANFLAG_REQUESTED_CHANINFO) || (sent_chan && sent_chan == chan) || access_count || minaccess) {
515             printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = '%s'", access_list, escape_string(chan->name));
516             res = mysql_use();
517             if ((row = mysql_fetch_row(res)) != NULL) {
518                 chan->flags |= CHANFLAG_CHAN_REGISTERED;
519                 chan->channel_id = atoi(row[0]);
520                 if((sent_chan && sent_chan == chan) || access_count || minaccess) {
521                     if(!requested_uaccess) uaccess = getChannelAccess(user, chan);
522                     if(uaccess < minaccess && isGodMode(user)) {
523                         eventflags |= CMDFLAG_OPLOG;
524                     } else if(uaccess < minaccess) {
525                         //ACCESS DENIED
526                         reply(textclient, user, "MODCMD_ACCESS_DENIED");
527                         return;
528                     }
529                     if(!row[1] && !defaults) {
530                         printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = 'defaults'", access_list);
531                         defaults = mysql_fetch_row(mysql_use());
532                     }
533                     if(sent_chan && (sent_chan == chan) && uaccess < (row[1] ? atoi(row[1]) : atoi(defaults[1]))) {
534                         if(isGodMode(user)) {
535                             eventflags |= CMDFLAG_OPLOG;
536                         } else {
537                             //PUBCMD
538                             reply(textclient, user, "MODCMD_PUBCMD", chan->name);
539                             return;
540                         }
541                     }
542                     int i;
543                     for(i = 0; i < access_count; i++) {
544                         if(!row[2+i] && !defaults) {
545                             printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = 'defaults'", access_list);
546                             defaults = mysql_fetch_row(mysql_use());
547                         }
548                         if(uaccess < (row[2+i] ? atoi(row[2+i]) : atoi(defaults[2+i]))) {
549                             if(isGodMode(user)) {
550                                 eventflags |= CMDFLAG_OPLOG;
551                             } else {
552                                 reply(textclient, user, "MODCMD_ACCESS_DENIED");
553                                 return;
554                             }
555                         }
556                     }
557                 }
558             }
559             chan->flags |= CHANFLAG_REQUESTED_CHANINFO;
560         }
561         if(!(chan->flags & CHANFLAG_CHAN_REGISTERED)) {
562             reply(textclient, user, "MODCMD_CHAN_REQUIRED");
563             return;
564         }
565         printf_mysql_query("SELECT `botid`, `suspended` FROM `bot_channels` LEFT JOIN `bots` ON `bot_channels`.`botid` = `bots`.`id` WHERE `chanid` = '%d' AND `botclass` = '%d'", chan->channel_id, client->botid);
566         res = mysql_use();
567         if ((row = mysql_fetch_row(res)) == NULL) {
568             reply(textclient, user, "MODCMD_CHAN_REQUIRED");
569             return;
570         } else if(!strcmp(row[1], "1")) {
571             reply(textclient, user, "MODCMD_CHAN_SUSPENDED");
572             return;
573         }
574     }
575     if((BIND_FLAGS(cbind) & CMDFLAG_REQUIRE_GOD) && !isGodMode(user)) {
576         reply(textclient, user, "MODCMD_PRIVILEGED", cbind->cmd);
577         return;
578     }
579     struct Event *event = createEvent(client, user, chan, cbind, argv, argc, eventflags);
580     cbind->func->func(client, textclient, user, chan, argv, argc, event);
581 }
582
583 static void got_chanmsg(struct UserNode *user, struct ChanNode *chan, char *message) {
584     fd_set fds, fds2;
585     char *trigger;
586     struct ClientSocket *client;
587     FD_ZERO(&fds);
588     FD_ZERO(&fds2);
589     got_chanmsg_loop1:
590     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
591         if(isUserOnChan(client->user, chan) && (client->flags & SOCKET_FLAG_PREFERRED) && ((client->botid == 0 && !FD_ISSET(client->clientid, &fds)) || (client->botid && !FD_ISSET(client->botid, &fds2))))  {
592             FD_SET(client->clientid, &fds);
593             FD_SET(client->botid, &fds2);
594             trigger = get_channel_trigger(client->botid, client->clientid, chan);
595             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
596                 handle_command(client, user, chan, message + strlen(trigger));
597                 goto got_chanmsg_loop1; //Thats really really bad, i know... But we can't count on the "getBots" list anymore after executing a command
598             }
599         }
600     }
601     got_chanmsg_loop2:
602     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
603         if(isUserOnChan(client->user, chan) && ((client->botid == 0 && !FD_ISSET(client->clientid, &fds)) || (client->botid && !FD_ISSET(client->botid, &fds2)))) {
604             FD_SET(client->clientid, &fds);
605             FD_SET(client->botid, &fds2);
606             trigger = get_channel_trigger(client->botid, client->clientid, chan);
607             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
608                 handle_command(client, user, chan, message + strlen(trigger));
609                 goto got_chanmsg_loop2; //Thats really really bad, i know... But we can't count on the "getBots" list anymore after executing a command
610             }
611         }
612     }
613 }
614
615 static void got_privmsg(struct UserNode *user, struct UserNode *target, char *message) {
616     struct ClientSocket *client;
617     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
618         if(client->user == target) {
619             handle_command(client, user, NULL, message);
620         }
621     }
622 }
623
624 int register_command(int botid, char *name, int module_id, cmd_bind_t *func, int paramcount, char *channel_access, int global_access, unsigned int flags) {
625     struct cmd_function *cmdfunc;
626     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
627         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && !stricmp(cmdfunc->name, name))
628             return 0;
629     }
630     cmdfunc = malloc(sizeof(*cmdfunc));
631     if (!cmdfunc) {
632         perror("malloc() failed");
633         return 0;
634     }
635     cmdfunc->botid = botid;
636     cmdfunc->name = strdup(name);
637     cmdfunc->module_id = module_id;
638     cmdfunc->func = func;
639     cmdfunc->flags = flags;
640     cmdfunc->paramcount = paramcount;
641     cmdfunc->channel_access = channel_access;
642     cmdfunc->global_access = global_access;
643     cmdfunc->next = cmd_functions;
644     cmd_functions = cmdfunc;
645     return 1;
646 }
647
648 int set_trigger_callback(int botid, int module_id, trigger_callback_t *func) {
649     static struct trigger_callback *cb = NULL;
650     for(cb = trigger_callbacks; cb; cb = cb->next) {
651         if(cb->botid == botid)
652             break;
653     }
654     if(!cb) {
655         cb = malloc(sizeof(*cb));
656         if (!cb) {
657             perror("malloc() failed");
658             return 0;
659         }
660         cb->botid = botid;
661         cb->next = trigger_callbacks;
662         trigger_callbacks = cb;
663     }
664     cb->module_id = module_id;
665     cb->func = func;
666     return 1;
667 }
668
669 int flush_trigger_cache(int botid, int clientid) {
670     struct ChanNode *chan;
671     struct trigger_cache *trigger, *last;
672     for(chan = getAllChans(NULL); chan; chan = getAllChans(chan)) {
673         last = NULL;
674         for(trigger = chan->trigger; trigger; trigger = trigger->next) {
675             if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
676                 if(last)
677                     last->next = trigger->next;
678                 else
679                     chan->trigger = trigger->next;
680                 free(trigger->trigger);
681                 free(trigger);
682                 break;
683             } else
684                 last = trigger;
685         }
686     }
687     return 1;
688 }
689
690 int changeBotwiseChannelTrigger(int botid, int clientid, struct ChanNode *chan, char *new_trigger) {
691     struct trigger_cache *trigger;
692     for(trigger = chan->trigger; trigger; trigger = trigger->next) {
693         if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
694             free(trigger->trigger);
695             trigger->trigger = strdup(new_trigger);
696             return 1;
697         }
698     }
699     return 0;
700 }
701
702 int bind_botwise_cmd_to_function(int botid, int clientid, char *cmd, struct cmd_function *func) {
703     int bind_index = get_binds_index(cmd[0]);
704     struct cmd_binding *cbind;
705     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
706         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && !stricmp(cbind->cmd, cmd))
707             return 0;
708     }
709     cbind = malloc(sizeof(*cbind));
710     if (!cbind) {
711         perror("malloc() failed");
712         return 0;
713     }
714     cbind->botid = botid;
715     cbind->clientid = clientid;
716     cbind->cmd = strdup(cmd);
717     cbind->func = func;
718     cbind->paramcount = 0;
719     cbind->global_access = 0;
720     cbind->channel_access = NULL;
721     cbind->flags = 0;
722     cbind->triggered = 0;
723     cbind->next = cmd_binds[bind_index];
724     cmd_binds[bind_index] = cbind;
725     return 1;
726 }
727
728 int bind_botwise_cmd_to_command(int botid, int clientid, char *cmd, char *func) {
729     struct cmd_function *cmdfunc;
730     int fbotid = botid;
731     char *c;
732     if((c = strstr(func, "."))) {
733         *c = '\0';
734         struct cmd_bot_alias *botalias;
735         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
736             if(!stricmp(botalias->alias, func)) {
737                 fbotid = botalias->botid;
738                 break;
739             }
740         }
741         *c = '.';
742         func = c+1;
743     }
744     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
745         if((cmdfunc->botid == fbotid || cmdfunc->botid == 0) && !stricmp(cmdfunc->name, func))
746             break;
747     }
748     if(!cmdfunc) return 0;
749     int bind_index = get_binds_index(cmd[0]);
750     struct cmd_binding *cbind;
751     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
752         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && !stricmp(cbind->cmd, cmd))
753             return 0;
754     }
755     cbind = malloc(sizeof(*cbind));
756     if (!cbind) {
757         perror("malloc() failed");
758         return 0;
759     }
760     cbind->botid = botid;
761     cbind->clientid = clientid;
762     cbind->cmd = strdup(cmd);
763     cbind->func = cmdfunc;
764     cbind->next = cmd_binds[bind_index];
765     cbind->paramcount = 0;
766     cbind->global_access = 0;
767     cbind->channel_access = NULL;
768     cbind->flags = 0;
769     cbind->triggered = 0;
770     cmd_binds[bind_index] = cbind;
771     return 1;
772 }
773
774 int unbind_botwise_cmd(int botid, int clientid, char *cmd) {
775     int bind_index = get_binds_index(cmd[0]);
776     struct cmd_binding *cbind, *last = NULL;
777     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
778         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
779             if(last)
780                 last->next = cbind->next;
781             else
782                 cmd_binds[bind_index] = cbind->next;
783             free(cbind->cmd);
784             if(cbind->paramcount) {
785                 int i;
786                 for(i = 0; i < cbind->paramcount; i++)
787                     free(cbind->parameters[i]);
788             }
789             if(cbind->channel_access)
790                 free(cbind->channel_access);
791             free(cbind);
792             return 1;
793         } else
794             last = cbind;
795     }
796     return 0;
797 }
798
799 int unbind_botwise_allcmd(int botid, int clientid) {
800     int i;
801     for(i = 0; i < 27; i++) {
802         struct cmd_binding *cbind, *next, *last = NULL;
803         for(cbind = cmd_binds[i]; cbind; cbind = next) {
804             next = cbind->next;
805             if((botid == 0 && clientid == cbind->clientid) || (botid && botid == cbind->botid)) {
806                 if(last)
807                     last->next = cbind->next;
808                 else
809                     cmd_binds[i] = cbind->next;
810                 free(cbind->cmd);
811                 if(cbind->paramcount) {
812                     int j;
813                     for(j = 0; j < cbind->paramcount; j++)
814                         free(cbind->parameters[j]);
815                 }
816                 if(cbind->channel_access)
817                     free(cbind->channel_access);
818                 free(cbind);
819             } else
820                 last = cbind;
821         }
822     }
823     return 1;
824 }
825
826 struct cmd_function *find_cmd_function(int botid, char *name) {
827     struct cmd_function *cmdfunc;
828     char *c;
829     if((c = strstr(name, "."))) {
830         *c = '\0';
831         struct cmd_bot_alias *botalias;
832         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
833             if(!stricmp(botalias->alias, name)) {
834                 botid = botalias->botid;
835                 break;
836             }
837         }
838         *c = '.';
839         name = c+1;
840     }
841     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
842         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && stricmp(cmdfunc->name, name) == 0)
843             break;
844     }
845     return cmdfunc;
846 }
847
848 void init_modcmd() {
849     cmd_binds = calloc(27, sizeof(*cmd_binds));
850     bind_chanmsg(got_chanmsg, 0);
851     bind_privmsg(got_privmsg, 0);
852     register_default_language_table(msgtab);
853     register_command(0, "linker", 0, modcmd_linker, 0, 0, 0, 0); //fake command for subcommands
854 }
855
856 void free_modcmd() {
857     int i;
858     for(i = 0; i < 27; i++) {
859         struct cmd_binding *cbind, *next;
860         for(cbind = cmd_binds[i]; cbind; cbind = next) {
861             next = cbind->next;
862             free(cbind->cmd);
863             if(cbind->paramcount) {
864                 int j;
865                 for(j = 0; j < cbind->paramcount; j++)
866                     free(cbind->parameters[j]);
867             }
868             if(cbind->channel_access)
869                 free(cbind->channel_access);
870             free(cbind);
871         }
872     }
873     free(cmd_binds);
874     struct cmd_function *cmdfunct, *next;
875     for(cmdfunct = cmd_functions; cmdfunct; cmdfunct = next) {
876         next = cmdfunct->next;
877         free(cmdfunct->name);
878         free(cmdfunct);
879     }
880     struct trigger_callback *cb, *next_cb;
881     for(cb = trigger_callbacks; cb; cb = next_cb) {
882         next_cb = cb->next;
883         free(next_cb);
884     }
885     struct cmd_bot_alias *botalias, *next_botalias;
886     for(botalias = bot_aliases; botalias; botalias = next_botalias) {
887         next_botalias = botalias->next;
888         free(botalias->alias);
889         free(botalias);
890     }
891     cmd_functions = NULL;
892     trigger_callbacks = NULL;
893     bot_aliases = NULL;
894 }
895
896 void bind_botwise_set_parameters(int botid, int clientid, char *cmd, char *parameters) {
897     int bind_index = get_binds_index(cmd[0]);
898     struct cmd_binding *cbind;
899     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
900         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
901             if(cbind->paramcount) {
902                 int i;
903                 for(i = 0; i < cbind->paramcount; i++)
904                     free(cbind->parameters[i]);
905                 cbind->paramcount = 0;
906             }
907             if(parameters) {
908                 char *a, *b = parameters;
909                 do {
910                     a = strstr(b, " ");
911                     if(a) *a = '\0';
912                     cbind->parameters[cbind->paramcount++] = strdup(b);
913                     if(a) b = a+1;
914                 } while(a);
915             }
916             return;
917         }
918     }
919 }
920
921 void bind_botwise_set_global_access(int botid, int clientid, char *cmd, int gaccess) {
922     int bind_index = get_binds_index(cmd[0]);
923     struct cmd_binding *cbind;
924     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
925         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
926             if(gaccess > -1) {
927                 cbind->global_access = gaccess;
928                 cbind->flags |= CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
929             } else {
930                 cbind->flags &= ~CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
931             }
932             return;
933         }
934     }
935 }
936
937 void bind_botwise_set_channel_access(int botid, int clientid, char *cmd, char *chanaccess) {
938     int bind_index = get_binds_index(cmd[0]);
939     struct cmd_binding *cbind;
940     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
941         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
942             if(cbind->channel_access)
943                 free(cbind->channel_access);
944             if(chanaccess) {
945                 cbind->channel_access = strdup(chanaccess);
946                 cbind->flags |= CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
947             } else {
948                 cbind->channel_access = NULL;
949                 cbind->flags &= ~CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
950             }
951             return;
952         }
953     }
954 }
955
956 void bind_botwise_set_bind_flags(int botid, int clientid, char *cmd, unsigned int flags) {
957     int bind_index = get_binds_index(cmd[0]);
958     struct cmd_binding *cbind;
959     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
960         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
961             cbind->flags |= flags;
962             return;
963         }
964     }
965 }
966
967 struct cmd_binding *find_botwise_cmd_binding(int botid, int clientid, char *cmd) {
968     int bind_index = get_binds_index(cmd[0]);
969     struct cmd_binding *cbind;
970     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
971         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
972             return cbind;
973         }
974     }
975     return NULL;
976 }
977
978 void bind_botwise_unbound_required_functions(int botid, int clientid) {
979     struct cmd_function *cmdfunc;
980     int i, found;
981     struct cmd_binding *cbind;
982     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
983         if((cmdfunc->flags & CMDFLAG_REQUIRED)) {
984             found = 0;
985             for(i = 0; i < 27; i++) {
986                 for(cbind = cmd_binds[i]; cbind; cbind = cbind->next) {
987                     if(cbind->botid == botid && (botid || clientid == cbind->clientid) && cbind->func == cmdfunc) {
988                         found = 1;
989                         break;
990                     }
991                 }
992                 if(found)
993                     break;
994             }
995             if(!found && bind_botwise_cmd_to_function(botid, clientid, cmdfunc->name, cmdfunc)) {
996                 cbind = find_botwise_cmd_binding(botid, clientid, cmdfunc->name);
997                 cbind->flags |= CMDFLAG_TEMPONARY_BIND;
998             }
999         }
1000     }
1001 }
1002
1003 void register_command_alias(int botid, char *alias) {
1004     struct cmd_bot_alias *botalias;
1005     for(botalias = bot_aliases; botalias; botalias = botalias->next) {
1006         if(!stricmp(botalias->alias, alias))
1007             return;
1008     }
1009     botalias = malloc(sizeof(*botalias));
1010     if (!botalias) {
1011         perror("malloc() failed");
1012         return;
1013     }
1014     botalias->botid = botid;
1015     botalias->alias = strdup(alias);
1016     botalias->next = bot_aliases;
1017     bot_aliases = botalias;
1018 }
1019
1020 struct cmd_binding *getAllBinds(struct cmd_binding *last) {
1021     int bind_index;
1022     if(last) {
1023         if(last->next)
1024             return last->next;
1025         bind_index = get_binds_index(last->cmd[0]) + 1;
1026         if(bind_index > 26)
1027             return NULL;
1028     } else
1029         bind_index = 0;
1030     do {
1031         if(cmd_binds[bind_index])
1032             return cmd_binds[bind_index];
1033         bind_index++;
1034     } while(bind_index < 27);
1035     return NULL;
1036 }
1037
1038 void unregister_module_commands(int module_id) {
1039     struct cmd_function *cmdfunct, *nextfunct, *prevfunct = NULL;
1040     int i;
1041     for(cmdfunct = cmd_functions; cmdfunct; cmdfunct = nextfunct) {
1042         nextfunct = cmdfunct->next;
1043         if(cmdfunct->module_id == module_id) {
1044             for(i = 0; i < 27; i++) {
1045                 struct cmd_binding *cbind, *next, *last = NULL;
1046                 for(cbind = cmd_binds[i]; cbind; cbind = next) {
1047                     next = cbind->next;
1048                     if(cmdfunct == cbind->func) {
1049                         if(last)
1050                             last->next = cbind->next;
1051                         else
1052                             cmd_binds[i] = cbind->next;
1053                         free(cbind->cmd);
1054                         if(cbind->paramcount) {
1055                             int j;
1056                             for(j = 0; j < cbind->paramcount; j++)
1057                                 free(cbind->parameters[j]);
1058                         }
1059                         if(cbind->channel_access)
1060                             free(cbind->channel_access);
1061                         free(cbind);
1062                     } else
1063                         last = cbind;
1064                 }
1065             }
1066             if(prevfunct) 
1067                 prevfunct->next = nextfunct;
1068             else
1069                 cmd_functions = nextfunct;
1070             free(cmdfunct->name);
1071             free(cmdfunct);
1072         } else
1073             prevfunct = cmdfunct;
1074     }
1075     struct trigger_callback *cb, *prevcb = NULL, *nextcb;
1076     for(cb = trigger_callbacks; cb; cb = nextcb) {
1077         nextcb = cb->next;
1078         if(cb->module_id == module_id) {
1079             if(prevcb)
1080                 prevcb->next = nextcb;
1081             else
1082                 trigger_callbacks = nextcb;
1083             free(cb);
1084         } else
1085             prevcb = cb;
1086     }
1087 }