]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/channels.cpp
Fix sqllog compile error
[user/henk/code/inspircd.git] / src / channels.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core */
15
16 #include "inspircd.h"
17 #include <cstdarg>
18 #include "mode.h"
19
20 Channel::Channel(const std::string &cname, time_t ts)
21 {
22         chan_hash::iterator findchan = ServerInstance->chanlist->find(cname);
23         if (findchan != ServerInstance->chanlist->end())
24                 throw CoreException("Cannot create duplicate channel " + cname);
25
26         (*(ServerInstance->chanlist))[cname.c_str()] = this;
27         this->name.assign(cname, 0, ServerInstance->Config->Limits.ChanMax);
28         this->age = ts ? ts : ServerInstance->Time();
29
30         maxbans = topicset = 0;
31         modes.reset();
32 }
33
34 void Channel::SetMode(char mode,bool mode_on)
35 {
36         modes[mode-65] = mode_on;
37 }
38
39 void Channel::SetMode(ModeHandler* mh, bool on)
40 {
41         modes[mh->GetModeChar() - 65] = on;
42 }
43
44 void Channel::SetModeParam(char mode, const std::string& parameter)
45 {
46         CustomModeList::iterator n = custom_mode_params.find(mode);
47         // always erase, even if changing, so that the map gets the new value
48         if (n != custom_mode_params.end())
49                 custom_mode_params.erase(n);
50         if (parameter.empty())
51         {
52                 modes[mode-65] = false;
53         }
54         else
55         {
56                 custom_mode_params[mode] = parameter;
57                 modes[mode-65] = true;
58         }
59 }
60
61 void Channel::SetModeParam(ModeHandler* mode, const std::string& parameter)
62 {
63         SetModeParam(mode->GetModeChar(), parameter);
64 }
65
66 std::string Channel::GetModeParameter(char mode)
67 {
68         CustomModeList::iterator n = custom_mode_params.find(mode);
69         if (n != custom_mode_params.end())
70                 return n->second;
71         return "";
72 }
73
74 std::string Channel::GetModeParameter(ModeHandler* mode)
75 {
76         CustomModeList::iterator n = custom_mode_params.find(mode->GetModeChar());
77         if (n != custom_mode_params.end())
78                 return n->second;
79         return "";
80 }
81
82 int Channel::SetTopic(User *u, std::string &ntopic, bool forceset)
83 {
84         if (u)
85         {
86                 if(!forceset)
87                 {
88                         ModResult res;
89                         /* 0: check status, 1: don't, -1: disallow change silently */
90
91                         FIRST_MOD_RESULT(OnPreTopicChange, res, (u,this,ntopic));
92
93                         if (res == MOD_RES_DENY)
94                                 return CMD_FAILURE;
95                         if (res != MOD_RES_ALLOW)
96                         {
97                                 if (!this->HasUser(u))
98                                 {
99                                         u->WriteNumeric(442, "%s %s :You're not on that channel!",u->nick.c_str(), this->name.c_str());
100                                         return CMD_FAILURE;
101                                 }
102                                 if ((this->IsModeSet('t')) && (this->GetPrefixValue(u) < HALFOP_VALUE))
103                                 {
104                                         u->WriteNumeric(482, "%s %s :You must be at least a half-operator to change the topic on this channel", u->nick.c_str(), this->name.c_str());
105                                         return CMD_FAILURE;
106                                 }
107                         }
108                 }
109         }
110
111         this->topic.assign(ntopic, 0, ServerInstance->Config->Limits.MaxTopic);
112         if (u)
113         {
114                 this->setby.assign(ServerInstance->Config->FullHostInTopic ? u->GetFullHost() : u->nick, 0, 128);
115                 this->WriteChannel(u, "TOPIC %s :%s", this->name.c_str(), this->topic.c_str());
116         }
117         else
118         {
119                 this->setby.assign(ServerInstance->Config->ServerName);
120                 this->WriteChannelWithServ(ServerInstance->Config->ServerName, "TOPIC %s :%s", this->name.c_str(), this->topic.c_str());
121         }
122
123         this->topicset = ServerInstance->Time();
124
125         // XXX: this check for 'u' is probably pre-fake-user, and it fucking sucks anyway. we need to change this.
126         if (u)
127         {
128                 FOREACH_MOD(I_OnPostTopicChange,OnPostTopicChange(u, this, this->topic));
129         }
130
131         return CMD_SUCCESS;
132 }
133
134 long Channel::GetUserCounter()
135 {
136         return userlist.size();
137 }
138
139 Membership* Channel::AddUser(User* user)
140 {
141         Membership* memb = new Membership(user, this);
142         userlist[user] = memb;
143         return memb;
144 }
145
146 void Channel::DelUser(User* user)
147 {
148         UserMembIter a = userlist.find(user);
149
150         if (a != userlist.end())
151         {
152                 a->second->cull();
153                 delete a->second;
154                 userlist.erase(a);
155         }
156
157         if (userlist.empty())
158         {
159                 ModResult res;
160                 FIRST_MOD_RESULT(OnChannelPreDelete, res, (this));
161                 if (res == MOD_RES_DENY)
162                         return;
163                 chan_hash::iterator iter = ServerInstance->chanlist->find(this->name);
164                 /* kill the record */
165                 if (iter != ServerInstance->chanlist->end())
166                 {
167                         FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(this));
168                         ServerInstance->chanlist->erase(iter);
169                 }
170                 ServerInstance->GlobalCulls.AddItem(this);
171         }
172 }
173
174 bool Channel::HasUser(User* user)
175 {
176         return (userlist.find(user) != userlist.end());
177 }
178
179 Membership* Channel::GetUser(User* user)
180 {
181         UserMembIter i = userlist.find(user);
182         if (i == userlist.end())
183                 return NULL;
184         return i->second;
185 }
186
187 const UserMembList* Channel::GetUsers()
188 {
189         return &userlist;
190 }
191
192 void Channel::SetDefaultModes()
193 {
194         ServerInstance->Logs->Log("CHANNELS", DEBUG, "SetDefaultModes %s",
195                 ServerInstance->Config->DefaultModes.c_str());
196         irc::spacesepstream list(ServerInstance->Config->DefaultModes);
197         std::string modeseq;
198         std::string parameter;
199
200         list.GetToken(modeseq);
201
202         for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
203         {
204                 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
205                 if (mode)
206                 {
207                         if (mode->GetNumParams(true))
208                                 list.GetToken(parameter);
209                         else
210                                 parameter.clear();
211
212                         mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
213                 }
214         }
215 }
216
217 /*
218  * add a channel to a user, creating the record for it if needed and linking
219  * it to the user record
220  */
221 Channel* Channel::JoinUser(User *user, const char* cn, bool override, const char* key, bool bursting, time_t TS)
222 {
223         // Fix: unregistered users could be joined using /SAJOIN
224         if (!user || !cn || user->registered != REG_ALL)
225                 return NULL;
226
227         char cname[MAXBUF];
228         std::string privs;
229         Channel *Ptr;
230
231         /*
232          * We don't restrict the number of channels that remote users or users that are override-joining may be in.
233          * We restrict local users to MaxChans channels.
234          * We restrict local operators to OperMaxChans channels.
235          * This is a lot more logical than how it was formerly. -- w00t
236          */
237         if (IS_LOCAL(user) && !override)
238         {
239                 if (user->HasPrivPermission("channels/high-join-limit"))
240                 {
241                         if (user->chans.size() >= ServerInstance->Config->OperMaxChans)
242                         {
243                                 user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s %s :You are on too many channels",user->nick.c_str(), cn);
244                                 return NULL;
245                         }
246                 }
247                 else
248                 {
249                         unsigned int maxchans = user->GetClass()->maxchans;
250                         if (!maxchans)
251                                 maxchans = ServerInstance->Config->MaxChans;
252                         if (user->chans.size() >= maxchans)
253                         {
254                                 user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s %s :You are on too many channels",user->nick.c_str(), cn);
255                                 return NULL;
256                         }
257                 }
258         }
259
260         strlcpy(cname, cn, ServerInstance->Config->Limits.ChanMax);
261         Ptr = ServerInstance->FindChan(cname);
262         bool created_by_local = false;
263
264         if (!Ptr)
265         {
266                 /*
267                  * Fix: desync bug was here, don't set @ on remote users - spanningtree handles their permissions. bug #358. -- w00t
268                  */
269                 if (!IS_LOCAL(user))
270                 {
271                         if (!TS)
272                                 ServerInstance->Logs->Log("CHANNEL",DEBUG,"*** BUG *** Channel::JoinUser called for REMOTE user '%s' on channel '%s' but no TS given!", user->nick.c_str(), cn);
273                 }
274                 else
275                 {
276                         privs = "o";
277                         created_by_local = true;
278                 }
279
280                 if (IS_LOCAL(user) && override == false)
281                 {
282                         ModResult MOD_RESULT;
283                         FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, NULL, cname, privs, key ? key : ""));
284                         if (MOD_RESULT == MOD_RES_DENY)
285                                 return NULL;
286                 }
287
288                 Ptr = new Channel(cname, TS);
289         }
290         else
291         {
292                 /* Already on the channel */
293                 if (Ptr->HasUser(user))
294                         return NULL;
295
296                 /*
297                  * remote users are allowed us to bypass channel modes
298                  * and bans (used by servers)
299                  */
300                 if (IS_LOCAL(user) && override == false)
301                 {
302                         ModResult MOD_RESULT;
303                         FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, Ptr, cname, privs, key ? key : ""));
304                         if (MOD_RESULT == MOD_RES_DENY)
305                         {
306                                 return NULL;
307                         }
308                         else if (MOD_RESULT == MOD_RES_PASSTHRU)
309                         {
310                                 std::string ckey = Ptr->GetModeParameter('k');
311                                 bool invited = IS_LOCAL(user)->IsInvited(Ptr->name.c_str());
312                                 bool can_bypass = ServerInstance->Config->InvBypassModes && invited;
313
314                                 if (!ckey.empty())
315                                 {
316                                         FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, Ptr, key ? key : ""));
317                                         if (!MOD_RESULT.check((key && ckey == key) || can_bypass))
318                                         {
319                                                 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
320                                                 user->WriteNumeric(ERR_BADCHANNELKEY, "%s %s :Cannot join channel (Incorrect channel key)",user->nick.c_str(), Ptr->name.c_str());
321                                                 return NULL;
322                                         }
323                                 }
324
325                                 if (Ptr->IsModeSet('i'))
326                                 {
327                                         FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, Ptr));
328                                         if (!MOD_RESULT.check(invited))
329                                         {
330                                                 user->WriteNumeric(ERR_INVITEONLYCHAN, "%s %s :Cannot join channel (Invite only)",user->nick.c_str(), Ptr->name.c_str());
331                                                 return NULL;
332                                         }
333                                 }
334
335                                 std::string limit = Ptr->GetModeParameter('l');
336                                 if (!limit.empty())
337                                 {
338                                         FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, Ptr));
339                                         if (!MOD_RESULT.check((Ptr->GetUserCounter() < atol(limit.c_str()) || can_bypass)))
340                                         {
341                                                 user->WriteNumeric(ERR_CHANNELISFULL, "%s %s :Cannot join channel (Channel is full)",user->nick.c_str(), Ptr->name.c_str());
342                                                 return NULL;
343                                         }
344                                 }
345
346                                 if (Ptr->IsBanned(user) && !can_bypass)
347                                 {
348                                         user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s %s :Cannot join channel (You're banned)",user->nick.c_str(), Ptr->name.c_str());
349                                         return NULL;
350                                 }
351
352                                 /*
353                                  * If the user has invites for this channel, remove them now
354                                  * after a successful join so they don't build up.
355                                  */
356                                 if (invited)
357                                 {
358                                         IS_LOCAL(user)->RemoveInvite(Ptr->name.c_str());
359                                 }
360                         }
361                 }
362         }
363
364         if (created_by_local)
365         {
366                 /* As spotted by jilles, dont bother to set this on remote users */
367                 Ptr->SetDefaultModes();
368         }
369
370         return Channel::ForceChan(Ptr, user, privs, bursting, created_by_local);
371 }
372
373 Channel* Channel::ForceChan(Channel* Ptr, User* user, const std::string &privs, bool bursting, bool created)
374 {
375         std::string nick = user->nick;
376
377         Membership* memb = Ptr->AddUser(user);
378         user->chans.insert(Ptr);
379
380         for (std::string::const_iterator x = privs.begin(); x != privs.end(); x++)
381         {
382                 const char status = *x;
383                 ModeHandler* mh = ServerInstance->Modes->FindMode(status, MODETYPE_CHANNEL);
384                 if (mh)
385                 {
386                         /* Set, and make sure that the mode handler knows this mode was now set */
387                         Ptr->SetPrefix(user, mh->GetModeChar(), true);
388                         mh->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, Ptr, nick, true);
389                 }
390         }
391
392         CUList except_list;
393         FOREACH_MOD(I_OnUserJoin,OnUserJoin(memb, bursting, created, except_list));
394
395         Ptr->WriteAllExcept(user, false, 0, except_list, "JOIN :%s", Ptr->name.c_str());
396
397         /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
398         std::string ms = memb->modes;
399         for(unsigned int i=0; i < memb->modes.length(); i++)
400                 ms.append(" ").append(user->nick);
401         if ((Ptr->GetUserCounter() > 1) && (ms.length()))
402                 Ptr->WriteAllExceptSender(user, true, 0, "MODE %s +%s", Ptr->name.c_str(), ms.c_str());
403
404         /* Major improvement by Brain - we dont need to be calculating all this pointlessly for remote users */
405         if (IS_LOCAL(user))
406         {
407                 if (Ptr->topicset)
408                 {
409                         user->WriteNumeric(RPL_TOPIC, "%s %s :%s", user->nick.c_str(), Ptr->name.c_str(), Ptr->topic.c_str());
410                         user->WriteNumeric(RPL_TOPICTIME, "%s %s %s %lu", user->nick.c_str(), Ptr->name.c_str(), Ptr->setby.c_str(), (unsigned long)Ptr->topicset);
411                 }
412                 Ptr->UserList(user);
413         }
414         FOREACH_MOD(I_OnPostJoin,OnPostJoin(memb));
415         return Ptr;
416 }
417
418 bool Channel::IsBanned(User* user)
419 {
420         ModResult result;
421         FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
422
423         if (result != MOD_RES_PASSTHRU)
424                 return (result == MOD_RES_DENY);
425
426         for (BanList::iterator i = this->bans.begin(); i != this->bans.end(); i++)
427         {
428                 if (CheckBan(user, i->data))
429                         return true;
430         }
431         return false;
432 }
433
434 bool Channel::CheckBan(User* user, const std::string& mask)
435 {
436         ModResult result;
437         FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
438         if (result != MOD_RES_PASSTHRU)
439                 return (result == MOD_RES_DENY);
440
441         // extbans were handled above, if this is one it obviously didn't match
442         if (mask[1] == ':')
443                 return false;
444
445         std::string::size_type at = mask.find('@');
446         if (at == std::string::npos)
447                 return false;
448
449         char tomatch[MAXBUF];
450         snprintf(tomatch, MAXBUF, "%s!%s", user->nick.c_str(), user->ident.c_str());
451         std::string prefix = mask.substr(0, at);
452         if (InspIRCd::Match(tomatch, prefix, NULL))
453         {
454                 std::string suffix = mask.substr(at + 1);
455                 if (InspIRCd::Match(user->host, suffix, NULL) ||
456                         InspIRCd::Match(user->dhost, suffix, NULL) ||
457                         InspIRCd::MatchCIDR(user->GetIPString(), suffix, NULL))
458                         return true;
459         }
460         return false;
461 }
462
463 ModResult Channel::GetExtBanStatus(User *user, char type)
464 {
465         ModResult rv;
466         FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
467         if (rv != MOD_RES_PASSTHRU)
468                 return rv;
469         for (BanList::iterator i = this->bans.begin(); i != this->bans.end(); i++)
470         {
471                 if (i->data[0] == type && i->data[1] == ':')
472                 {
473                         std::string val = i->data.substr(2);
474                         if (CheckBan(user, val))
475                                 return MOD_RES_DENY;
476                 }
477         }
478         return MOD_RES_PASSTHRU;
479 }
480
481 /* Channel::PartUser
482  * remove a channel from a users record, and return the number of users left.
483  * Therefore, if this function returns 0 the caller should delete the Channel.
484  */
485 void Channel::PartUser(User *user, std::string &reason)
486 {
487         if (!user)
488                 return;
489
490         Membership* memb = GetUser(user);
491
492         if (memb)
493         {
494                 CUList except_list;
495                 FOREACH_MOD(I_OnUserPart,OnUserPart(memb, reason, except_list));
496
497                 WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
498
499                 user->chans.erase(this);
500                 this->RemoveAllPrefixes(user);
501         }
502
503         this->DelUser(user);
504 }
505
506 void Channel::KickUser(User *src, User *user, const char* reason)
507 {
508         if (!src || !user || !reason)
509                 return;
510
511         Membership* memb = GetUser(user);
512         if (IS_LOCAL(src))
513         {
514                 if (!memb)
515                 {
516                         src->WriteNumeric(ERR_USERNOTINCHANNEL, "%s %s %s :They are not on that channel",src->nick.c_str(), user->nick.c_str(), this->name.c_str());
517                         return;
518                 }
519                 if ((ServerInstance->ULine(user->server)) && (!ServerInstance->ULine(src->server)))
520                 {
521                         src->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s %s :Only a u-line may kick a u-line from a channel.",src->nick.c_str(), this->name.c_str());
522                         return;
523                 }
524
525                 ModResult res;
526                 if (ServerInstance->ULine(src->server))
527                         res = MOD_RES_ALLOW;
528                 else
529                         FIRST_MOD_RESULT(OnUserPreKick, res, (src,memb,reason));
530
531                 if (res == MOD_RES_DENY)
532                         return;
533
534                 if (res == MOD_RES_PASSTHRU)
535                 {
536                         int them = this->GetPrefixValue(src);
537                         int us = this->GetPrefixValue(user);
538                         if ((them < HALFOP_VALUE) || (them < us))
539                         {
540                                 src->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s %s :You must be a channel %soperator",src->nick.c_str(), this->name.c_str(), them >= HALFOP_VALUE ? "" : "half-");
541                                 return;
542                         }
543                 }
544         }
545
546         if (memb)
547         {
548                 CUList except_list;
549                 FOREACH_MOD(I_OnUserKick,OnUserKick(src, memb, reason, except_list));
550
551                 WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), user->nick.c_str(), reason);
552
553                 user->chans.erase(this);
554                 this->RemoveAllPrefixes(user);
555         }
556
557         this->DelUser(user);
558 }
559
560 void Channel::WriteChannel(User* user, const char* text, ...)
561 {
562         char textbuffer[MAXBUF];
563         va_list argsPtr;
564
565         if (!user || !text)
566                 return;
567
568         va_start(argsPtr, text);
569         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
570         va_end(argsPtr);
571
572         this->WriteChannel(user, std::string(textbuffer));
573 }
574
575 void Channel::WriteChannel(User* user, const std::string &text)
576 {
577         char tb[MAXBUF];
578
579         if (!user)
580                 return;
581
582         snprintf(tb,MAXBUF,":%s %s", user->GetFullHost().c_str(), text.c_str());
583         std::string out = tb;
584
585         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
586         {
587                 if (IS_LOCAL(i->first))
588                         i->first->Write(out);
589         }
590 }
591
592 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
593 {
594         char textbuffer[MAXBUF];
595         va_list argsPtr;
596
597         if (!text)
598                 return;
599
600         va_start(argsPtr, text);
601         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
602         va_end(argsPtr);
603
604         this->WriteChannelWithServ(ServName, std::string(textbuffer));
605 }
606
607 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
608 {
609         char tb[MAXBUF];
610
611         snprintf(tb,MAXBUF,":%s %s", ServName.empty() ? ServerInstance->Config->ServerName.c_str() : ServName.c_str(), text.c_str());
612         std::string out = tb;
613
614         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
615         {
616                 if (IS_LOCAL(i->first))
617                         i->first->Write(out);
618         }
619 }
620
621 /* write formatted text from a source user to all users on a channel except
622  * for the sender (for privmsg etc) */
623 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
624 {
625         char textbuffer[MAXBUF];
626         va_list argsPtr;
627
628         if (!text)
629                 return;
630
631         va_start(argsPtr, text);
632         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
633         va_end(argsPtr);
634
635         this->WriteAllExceptSender(user, serversource, status, std::string(textbuffer));
636 }
637
638 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
639 {
640         char textbuffer[MAXBUF];
641         va_list argsPtr;
642
643         if (!text)
644                 return;
645
646         int offset = snprintf(textbuffer,MAXBUF,":%s ", user->GetFullHost().c_str());
647
648         va_start(argsPtr, text);
649         vsnprintf(textbuffer + offset, MAXBUF - offset, text, argsPtr);
650         va_end(argsPtr);
651
652         this->RawWriteAllExcept(user, serversource, status, except_list, std::string(textbuffer));
653 }
654
655 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
656 {
657         char tb[MAXBUF];
658
659         snprintf(tb,MAXBUF,":%s %s", serversource ? ServerInstance->Config->ServerName.c_str() : user->GetFullHost().c_str(), text.c_str());
660         std::string out = tb;
661
662         this->RawWriteAllExcept(user, serversource, status, except_list, std::string(tb));
663 }
664
665 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
666 {
667         unsigned int minrank = 0;
668         if (status)
669         {
670                 ModeHandler* mh = ServerInstance->Modes->FindPrefix(status);
671                 if (mh)
672                         minrank = mh->GetPrefixRank();
673         }
674         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
675         {
676                 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
677                 {
678                         /* User doesn't have the status we're after */
679                         if (minrank && i->second->getRank() < minrank)
680                                 continue;
681
682                         i->first->Write(out);
683                 }
684         }
685 }
686
687 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
688 {
689         CUList except_list;
690         except_list.insert(user);
691         this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
692 }
693
694 /*
695  * return a count of the users on a specific channel accounting for
696  * invisible users who won't increase the count. e.g. for /LIST
697  */
698 int Channel::CountInvisible()
699 {
700         int count = 0;
701         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
702         {
703                 if (!(i->first->IsModeSet('i')))
704                         count++;
705         }
706
707         return count;
708 }
709
710 char* Channel::ChanModes(bool showkey)
711 {
712         static char scratch[MAXBUF];
713         static char sparam[MAXBUF];
714         char* offset = scratch;
715         std::string extparam;
716
717         *scratch = '\0';
718         *sparam = '\0';
719
720         /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
721         for(int n = 0; n < 64; n++)
722         {
723                 if(this->modes[n])
724                 {
725                         *offset++ = n + 65;
726                         extparam.clear();
727                         if (n == 'k' - 65 && !showkey)
728                         {
729                                 extparam = "<key>";
730                         }
731                         else
732                         {
733                                 extparam = this->GetModeParameter(n + 65);
734                         }
735                         if (!extparam.empty())
736                         {
737                                 charlcat(sparam,' ',MAXBUF);
738                                 strlcat(sparam,extparam.c_str(),MAXBUF);
739                         }
740                 }
741         }
742
743         /* Null terminate scratch */
744         *offset = '\0';
745         strlcat(scratch,sparam,MAXBUF);
746         return scratch;
747 }
748
749 /* compile a userlist of a channel into a string, each nick seperated by
750  * spaces and op, voice etc status shown as @ and +, and send it to 'user'
751  */
752 void Channel::UserList(User *user)
753 {
754         char list[MAXBUF];
755         size_t dlen, curlen;
756         ModResult call_modules;
757
758         if (!IS_LOCAL(user))
759                 return;
760
761         FIRST_MOD_RESULT(OnUserList, call_modules, (user, this));
762
763         if (call_modules != MOD_RES_ALLOW)
764         {
765                 if ((this->IsModeSet('s')) && (!this->HasUser(user)))
766                 {
767                         user->WriteNumeric(ERR_NOSUCHNICK, "%s %s :No such nick/channel",user->nick.c_str(), this->name.c_str());
768                         return;
769                 }
770         }
771
772         dlen = curlen = snprintf(list,MAXBUF,"%s %c %s :", user->nick.c_str(), this->IsModeSet('s') ? '@' : this->IsModeSet('p') ? '*' : '=',  this->name.c_str());
773
774         int numusers = 0;
775         char* ptr = list + dlen;
776
777         /* Improvement by Brain - this doesnt change in value, so why was it inside
778          * the loop?
779          */
780         bool has_user = this->HasUser(user);
781
782         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
783         {
784                 if ((!has_user) && (i->first->IsModeSet('i')))
785                 {
786                         /*
787                          * user is +i, and source not on the channel, does not show
788                          * nick in NAMES list
789                          */
790                         continue;
791                 }
792
793                 std::string prefixlist = this->GetPrefixChar(i->first);
794                 std::string nick = i->first->nick;
795
796                 if (call_modules != MOD_RES_DENY)
797                 {
798                         FOREACH_MOD(I_OnNamesListItem, OnNamesListItem(user, i->second, prefixlist, nick));
799
800                         /* Nick was nuked, a module wants us to skip it */
801                         if (nick.empty())
802                                 continue;
803                 }
804
805                 size_t ptrlen = 0;
806
807                 if (curlen + prefixlist.length() + nick.length() + 1 > 480)
808                 {
809                         /* list overflowed into multiple numerics */
810                         user->WriteNumeric(RPL_NAMREPLY, std::string(list));
811
812                         /* reset our lengths */
813                         dlen = curlen = snprintf(list,MAXBUF,"%s %c %s :", user->nick.c_str(), this->IsModeSet('s') ? '@' : this->IsModeSet('p') ? '*' : '=', this->name.c_str());
814                         ptr = list + dlen;
815
816                         ptrlen = 0;
817                         numusers = 0;
818                 }
819
820                 ptrlen = snprintf(ptr, MAXBUF, "%s%s ", prefixlist.c_str(), nick.c_str());
821
822                 curlen += ptrlen;
823                 ptr += ptrlen;
824
825                 numusers++;
826         }
827
828         /* if whats left in the list isnt empty, send it */
829         if (numusers)
830         {
831                 user->WriteNumeric(RPL_NAMREPLY, std::string(list));
832         }
833
834         user->WriteNumeric(RPL_ENDOFNAMES, "%s %s :End of /NAMES list.", user->nick.c_str(), this->name.c_str());
835 }
836
837 long Channel::GetMaxBans()
838 {
839         /* Return the cached value if there is one */
840         if (this->maxbans)
841                 return this->maxbans;
842
843         /* If there isnt one, we have to do some O(n) hax to find it the first time. (ick) */
844         for (std::map<std::string,int>::iterator n = ServerInstance->Config->maxbans.begin(); n != ServerInstance->Config->maxbans.end(); n++)
845         {
846                 if (InspIRCd::Match(this->name, n->first, NULL))
847                 {
848                         this->maxbans = n->second;
849                         return n->second;
850                 }
851         }
852
853         /* Screw it, just return the default of 64 */
854         this->maxbans = 64;
855         return this->maxbans;
856 }
857
858 void Channel::ResetMaxBans()
859 {
860         this->maxbans = 0;
861 }
862
863 /* returns the status character for a given user on a channel, e.g. @ for op,
864  * % for halfop etc. If the user has several modes set, the highest mode
865  * the user has must be returned.
866  */
867 const char* Channel::GetPrefixChar(User *user)
868 {
869         static char pf[2] = {0, 0};
870         *pf = 0;
871         unsigned int bestrank = 0;
872
873         UserMembIter m = userlist.find(user);
874         if (m != userlist.end())
875         {
876                 for(unsigned int i=0; i < m->second->modes.length(); i++)
877                 {
878                         char mchar = m->second->modes[i];
879                         ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
880                         if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
881                         {
882                                 bestrank = mh->GetPrefixRank();
883                                 pf[0] = mh->GetPrefix();
884                         }
885                 }
886         }
887         return pf;
888 }
889
890 unsigned int Membership::getRank()
891 {
892         char mchar = modes.c_str()[0];
893         unsigned int rv = 0;
894         if (mchar)
895         {
896                 ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
897                 if (mh)
898                         rv = mh->GetPrefixRank();
899         }
900         return rv;
901 }
902
903 const char* Channel::GetAllPrefixChars(User* user)
904 {
905         static char prefix[64];
906         int ctr = 0;
907
908         UserMembIter m = userlist.find(user);
909         if (m != userlist.end())
910         {
911                 for(unsigned int i=0; i < m->second->modes.length(); i++)
912                 {
913                         char mchar = m->second->modes[i];
914                         ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
915                         if (mh && mh->GetPrefix())
916                                 prefix[ctr++] = mh->GetPrefix();
917                 }
918         }
919         prefix[ctr] = 0;
920
921         return prefix;
922 }
923
924 unsigned int Channel::GetPrefixValue(User* user)
925 {
926         UserMembIter m = userlist.find(user);
927         if (m == userlist.end())
928                 return 0;
929         return m->second->getRank();
930 }
931
932 void Channel::SetPrefix(User* user, char prefix, bool adding)
933 {
934         ModeHandler* delta_mh = ServerInstance->Modes->FindMode(prefix, MODETYPE_CHANNEL);
935         if (!delta_mh)
936                 return;
937         UserMembIter m = userlist.find(user);
938         if (m == userlist.end())
939                 return;
940         for(unsigned int i=0; i < m->second->modes.length(); i++)
941         {
942                 char mchar = m->second->modes[i];
943                 ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
944                 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
945                 {
946                         m->second->modes =
947                                 m->second->modes.substr(0,i) +
948                                 (adding ? std::string(1, prefix) : "") +
949                                 m->second->modes.substr(mchar == prefix ? i+1 : i);
950                         return;
951                 }
952         }
953         if (adding)
954                 m->second->modes += std::string(1, prefix);
955 }
956
957 void Channel::RemoveAllPrefixes(User* user)
958 {
959         UserMembIter m = userlist.find(user);
960         if (m != userlist.end())
961         {
962                 m->second->modes.clear();
963         }
964 }