]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/channels.cpp
Clean up wildcard code.
[user/henk/code/inspircd.git] / src / channels.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2006, 2008 Oliver Lupton <oliverlupton@gmail.com>
7  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
8  *   Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
9  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
10  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
11  *
12  * This file is part of InspIRCd.  InspIRCd is free software: you can
13  * redistribute it and/or modify it under the terms of the GNU General Public
14  * License as published by the Free Software Foundation, version 2.
15  *
16  * This program is distributed in the hope that it will be useful, but WITHOUT
17  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
19  * details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24
25
26 #include "inspircd.h"
27 #include "listmode.h"
28 #include <cstdarg>
29 #include "mode.h"
30
31 namespace
32 {
33         ChanModeReference ban(NULL, "ban");
34         ChanModeReference inviteonlymode(NULL, "inviteonly");
35         ChanModeReference keymode(NULL, "key");
36         ChanModeReference limitmode(NULL, "limit");
37         ChanModeReference secretmode(NULL, "secret");
38         ChanModeReference privatemode(NULL, "private");
39         UserModeReference invisiblemode(NULL, "invisible");
40 }
41
42 Channel::Channel(const std::string &cname, time_t ts)
43 {
44         if (!ServerInstance->chanlist->insert(std::make_pair(cname, this)).second)
45                 throw CoreException("Cannot create duplicate channel " + cname);
46
47         this->name = cname;
48         this->age = ts ? ts : ServerInstance->Time();
49
50         topicset = 0;
51         modes.reset();
52 }
53
54 void Channel::SetMode(ModeHandler* mh, bool on)
55 {
56         modes[mh->GetModeChar() - 65] = on;
57 }
58
59 void Channel::SetModeParam(ModeHandler* mh, const std::string& parameter)
60 {
61         char mode = mh->GetModeChar();
62         if (parameter.empty())
63         {
64                 custom_mode_params.erase(mode);
65                 modes[mode-65] = false;
66         }
67         else
68         {
69                 custom_mode_params[mode] = parameter;
70                 modes[mode-65] = true;
71         }
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 void Channel::SetTopic(User* u, const std::string& ntopic)
83 {
84         this->topic.assign(ntopic, 0, ServerInstance->Config->Limits.MaxTopic);
85         this->setby.assign(ServerInstance->Config->FullHostInTopic ? u->GetFullHost() : u->nick, 0, 128);
86         this->WriteChannel(u, "TOPIC %s :%s", this->name.c_str(), this->topic.c_str());
87         this->topicset = ServerInstance->Time();
88
89         FOREACH_MOD(OnPostTopicChange, (u, this, this->topic));
90 }
91
92 Membership* Channel::AddUser(User* user)
93 {
94         Membership*& memb = userlist[user];
95         if (memb)
96                 return NULL;
97
98         memb = new Membership(user, this);
99         return memb;
100 }
101
102 void Channel::DelUser(User* user)
103 {
104         UserMembIter it = userlist.find(user);
105         if (it != userlist.end())
106                 DelUser(it);
107 }
108
109 void Channel::CheckDestroy()
110 {
111         if (!userlist.empty())
112                 return;
113
114         ModResult res;
115         FIRST_MOD_RESULT(OnChannelPreDelete, res, (this));
116         if (res == MOD_RES_DENY)
117                 return;
118
119         chan_hash::iterator iter = ServerInstance->chanlist->find(this->name);
120         /* kill the record */
121         if (iter != ServerInstance->chanlist->end())
122         {
123                 FOREACH_MOD(OnChannelDelete, (this));
124                 ServerInstance->chanlist->erase(iter);
125         }
126
127         ClearInvites();
128         ServerInstance->GlobalCulls.AddItem(this);
129 }
130
131 void Channel::DelUser(const UserMembIter& membiter)
132 {
133         Membership* memb = membiter->second;
134         memb->cull();
135         delete memb;
136         userlist.erase(membiter);
137
138         // If this channel became empty then it should be removed
139         CheckDestroy();
140 }
141
142 Membership* Channel::GetUser(User* user)
143 {
144         UserMembIter i = userlist.find(user);
145         if (i == userlist.end())
146                 return NULL;
147         return i->second;
148 }
149
150 void Channel::SetDefaultModes()
151 {
152         ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "SetDefaultModes %s",
153                 ServerInstance->Config->DefaultModes.c_str());
154         irc::spacesepstream list(ServerInstance->Config->DefaultModes);
155         std::string modeseq;
156         std::string parameter;
157
158         list.GetToken(modeseq);
159
160         for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
161         {
162                 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
163                 if (mode)
164                 {
165                         if (mode->GetPrefixRank())
166                                 continue;
167
168                         if (mode->GetNumParams(true))
169                                 list.GetToken(parameter);
170                         else
171                                 parameter.clear();
172
173                         mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
174                 }
175         }
176 }
177
178 /*
179  * add a channel to a user, creating the record for it if needed and linking
180  * it to the user record
181  */
182 Channel* Channel::JoinUser(LocalUser* user, std::string cname, bool override, const std::string& key)
183 {
184         if (user->registered != REG_ALL)
185         {
186                 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join unregistered user " + user->uuid + " to channel " + cname);
187                 return NULL;
188         }
189
190         /*
191          * We don't restrict the number of channels that remote users or users that are override-joining may be in.
192          * We restrict local users to MaxChans channels.
193          * We restrict local operators to OperMaxChans channels.
194          * This is a lot more logical than how it was formerly. -- w00t
195          */
196         if (!override)
197         {
198                 if (user->HasPrivPermission("channels/high-join-limit"))
199                 {
200                         if (user->chans.size() >= ServerInstance->Config->OperMaxChans)
201                         {
202                                 user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s %s :You are on too many channels",user->nick.c_str(), cname.c_str());
203                                 return NULL;
204                         }
205                 }
206                 else
207                 {
208                         unsigned int maxchans = user->GetClass()->maxchans;
209                         if (!maxchans)
210                                 maxchans = ServerInstance->Config->MaxChans;
211                         if (user->chans.size() >= maxchans)
212                         {
213                                 user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s %s :You are on too many channels",user->nick.c_str(), cname.c_str());
214                                 return NULL;
215                         }
216                 }
217         }
218
219         // Crop channel name if it's too long
220         if (cname.length() > ServerInstance->Config->Limits.ChanMax)
221                 cname.resize(ServerInstance->Config->Limits.ChanMax);
222
223         Channel* chan = ServerInstance->FindChan(cname);
224         bool created_by_local = (chan == NULL); // Flag that will be passed to modules in the OnUserJoin() hook later
225         std::string privs; // Prefix mode(letter)s to give to the joining user
226
227         if (!chan)
228         {
229                 privs = ServerInstance->Config->DefaultModes.substr(0, ServerInstance->Config->DefaultModes.find(' '));
230
231                 if (override == false)
232                 {
233                         // Ask the modules whether they're ok with the join, pass NULL as Channel* as the channel is yet to be created
234                         ModResult MOD_RESULT;
235                         FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, NULL, cname, privs, key));
236                         if (MOD_RESULT == MOD_RES_DENY)
237                                 return NULL; // A module wasn't happy with the join, abort
238                 }
239
240                 chan = new Channel(cname, ServerInstance->Time());
241                 // Set the default modes on the channel (<options:defaultmodes>)
242                 chan->SetDefaultModes();
243         }
244         else
245         {
246                 /* Already on the channel */
247                 if (chan->HasUser(user))
248                         return NULL;
249
250                 if (override == false)
251                 {
252                         ModResult MOD_RESULT;
253                         FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, chan, cname, privs, key));
254
255                         // A module explicitly denied the join and (hopefully) generated a message
256                         // describing the situation, so we may stop here without sending anything
257                         if (MOD_RESULT == MOD_RES_DENY)
258                                 return NULL;
259
260                         // If no module returned MOD_RES_DENY or MOD_RES_ALLOW (which is the case
261                         // most of the time) then proceed to check channel modes +k, +i, +l and bans,
262                         // in this order.
263                         // If a module explicitly allowed the join (by returning MOD_RES_ALLOW),
264                         // then this entire section is skipped
265                         if (MOD_RESULT == MOD_RES_PASSTHRU)
266                         {
267                                 std::string ckey = chan->GetModeParameter(keymode);
268                                 bool invited = user->IsInvited(chan);
269                                 bool can_bypass = ServerInstance->Config->InvBypassModes && invited;
270
271                                 if (!ckey.empty())
272                                 {
273                                         FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, key));
274                                         if (!MOD_RESULT.check((ckey == key) || can_bypass))
275                                         {
276                                                 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
277                                                 user->WriteNumeric(ERR_BADCHANNELKEY, "%s %s :Cannot join channel (Incorrect channel key)",user->nick.c_str(), chan->name.c_str());
278                                                 return NULL;
279                                         }
280                                 }
281
282                                 if (chan->IsModeSet(inviteonlymode))
283                                 {
284                                         FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, chan));
285                                         if (!MOD_RESULT.check(invited))
286                                         {
287                                                 user->WriteNumeric(ERR_INVITEONLYCHAN, "%s %s :Cannot join channel (Invite only)",user->nick.c_str(), chan->name.c_str());
288                                                 return NULL;
289                                         }
290                                 }
291
292                                 std::string limit = chan->GetModeParameter(limitmode);
293                                 if (!limit.empty())
294                                 {
295                                         FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, chan));
296                                         if (!MOD_RESULT.check((chan->GetUserCounter() < atol(limit.c_str()) || can_bypass)))
297                                         {
298                                                 user->WriteNumeric(ERR_CHANNELISFULL, "%s %s :Cannot join channel (Channel is full)",user->nick.c_str(), chan->name.c_str());
299                                                 return NULL;
300                                         }
301                                 }
302
303                                 if (chan->IsBanned(user) && !can_bypass)
304                                 {
305                                         user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s %s :Cannot join channel (You're banned)",user->nick.c_str(), chan->name.c_str());
306                                         return NULL;
307                                 }
308
309                                 /*
310                                  * If the user has invites for this channel, remove them now
311                                  * after a successful join so they don't build up.
312                                  */
313                                 if (invited)
314                                 {
315                                         user->RemoveInvite(chan);
316                                 }
317                         }
318                 }
319         }
320
321         // We figured that this join is allowed and also created the
322         // channel if it didn't exist before, now do the actual join
323         chan->ForceJoin(user, &privs, false, created_by_local);
324         return chan;
325 }
326
327 void Channel::ForceJoin(User* user, const std::string* privs, bool bursting, bool created_by_local)
328 {
329         if (IS_SERVER(user))
330         {
331                 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join server user " + user->uuid + " to channel " + this->name);
332                 return;
333         }
334
335         Membership* memb = this->AddUser(user);
336         if (!memb)
337                 return; // Already on the channel
338
339         user->chans.insert(this);
340
341         if (privs)
342         {
343                 // If the user was granted prefix modes (in the OnUserPreJoin hook, or he's a
344                 // remote user and his own server set the modes), then set them internally now
345                 memb->modes = *privs;
346                 for (std::string::const_iterator i = privs->begin(); i != privs->end(); ++i)
347                 {
348                         ModeHandler* mh = ServerInstance->Modes->FindMode(*i, MODETYPE_CHANNEL);
349                         if (mh && mh->GetPrefixRank())
350                         {
351                                 std::string nick = user->nick;
352                                 /* Set, and make sure that the mode handler knows this mode was now set */
353                                 this->SetPrefix(user, mh->GetModeChar(), true);
354                                 mh->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, nick, true);
355                         }
356                 }
357         }
358
359         // Tell modules about this join, they have the chance now to populate except_list with users we won't send the JOIN (and possibly MODE) to
360         CUList except_list;
361         FOREACH_MOD(OnUserJoin, (memb, bursting, created_by_local, except_list));
362
363         this->WriteAllExcept(user, false, 0, except_list, "JOIN :%s", this->name.c_str());
364
365         /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
366         if ((GetUserCounter() > 1) && (!memb->modes.empty()))
367         {
368                 std::string ms = memb->modes;
369                 for(unsigned int i=0; i < memb->modes.length(); i++)
370                         ms.append(" ").append(user->nick);
371
372                 except_list.insert(user);
373                 this->WriteAllExcept(user, !ServerInstance->Config->CycleHostsFromUser, 0, except_list, "MODE %s +%s", this->name.c_str(), ms.c_str());
374         }
375
376         if (IS_LOCAL(user))
377         {
378                 if (this->topicset)
379                 {
380                         user->WriteNumeric(RPL_TOPIC, "%s %s :%s", user->nick.c_str(), this->name.c_str(), this->topic.c_str());
381                         user->WriteNumeric(RPL_TOPICTIME, "%s %s %s %lu", user->nick.c_str(), this->name.c_str(), this->setby.c_str(), (unsigned long)this->topicset);
382                 }
383                 this->UserList(user);
384         }
385
386         FOREACH_MOD(OnPostJoin, (memb));
387 }
388
389 bool Channel::IsBanned(User* user)
390 {
391         ModResult result;
392         FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
393
394         if (result != MOD_RES_PASSTHRU)
395                 return (result == MOD_RES_DENY);
396
397         ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
398         const ListModeBase::ModeList* bans = banlm->GetList(this);
399         if (bans)
400         {
401                 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); it++)
402                 {
403                         if (CheckBan(user, it->mask))
404                                 return true;
405                 }
406         }
407         return false;
408 }
409
410 bool Channel::CheckBan(User* user, const std::string& mask)
411 {
412         ModResult result;
413         FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
414         if (result != MOD_RES_PASSTHRU)
415                 return (result == MOD_RES_DENY);
416
417         // extbans were handled above, if this is one it obviously didn't match
418         if ((mask.length() <= 2) || (mask[1] == ':'))
419                 return false;
420
421         std::string::size_type at = mask.find('@');
422         if (at == std::string::npos)
423                 return false;
424
425         const std::string nickIdent = user->nick + "!" + user->ident;
426         std::string prefix = mask.substr(0, at);
427         if (InspIRCd::Match(nickIdent, prefix, NULL))
428         {
429                 std::string suffix = mask.substr(at + 1);
430                 if (InspIRCd::Match(user->host, suffix, NULL) ||
431                         InspIRCd::Match(user->dhost, suffix, NULL) ||
432                         InspIRCd::MatchCIDR(user->GetIPString(), suffix, NULL))
433                         return true;
434         }
435         return false;
436 }
437
438 ModResult Channel::GetExtBanStatus(User *user, char type)
439 {
440         ModResult rv;
441         FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
442         if (rv != MOD_RES_PASSTHRU)
443                 return rv;
444
445         ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
446         const ListModeBase::ModeList* bans = banlm->GetList(this);
447         if (bans)
448
449         {
450                 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); ++it)
451                 {
452                         if (CheckBan(user, it->mask))
453                                 return MOD_RES_DENY;
454                 }
455         }
456         return MOD_RES_PASSTHRU;
457 }
458
459 /* Channel::PartUser
460  * Remove a channel from a users record, remove the reference to the Membership object
461  * from the channel and destroy it.
462  */
463 void Channel::PartUser(User *user, std::string &reason)
464 {
465         UserMembIter membiter = userlist.find(user);
466
467         if (membiter != userlist.end())
468         {
469                 Membership* memb = membiter->second;
470                 CUList except_list;
471                 FOREACH_MOD(OnUserPart, (memb, reason, except_list));
472
473                 WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
474
475                 // Remove this channel from the user's chanlist
476                 user->chans.erase(this);
477                 // Remove the Membership from this channel's userlist and destroy it
478                 this->DelUser(membiter);
479         }
480 }
481
482 void Channel::KickUser(User* src, User* victim, const std::string& reason, Membership* srcmemb)
483 {
484         UserMembIter victimiter = userlist.find(victim);
485         Membership* memb = ((victimiter != userlist.end()) ? victimiter->second : NULL);
486
487         if (!memb)
488         {
489                 src->WriteNumeric(ERR_USERNOTINCHANNEL, "%s %s %s :They are not on that channel",src->nick.c_str(), victim->nick.c_str(), this->name.c_str());
490                 return;
491         }
492
493         // Do the following checks only if the KICK is done by a local user;
494         // each server enforces its own rules.
495         if (IS_LOCAL(src))
496         {
497                 // Modules are allowed to explicitly allow or deny kicks done by local users
498                 ModResult res;
499                 FIRST_MOD_RESULT(OnUserPreKick, res, (src,memb,reason));
500                 if (res == MOD_RES_DENY)
501                         return;
502
503                 if (res == MOD_RES_PASSTHRU)
504                 {
505                         if (!srcmemb)
506                                 srcmemb = GetUser(src);
507                         unsigned int them = srcmemb ? srcmemb->getRank() : 0;
508                         unsigned int req = HALFOP_VALUE;
509                         for (std::string::size_type i = 0; i < memb->modes.length(); i++)
510                         {
511                                 ModeHandler* mh = ServerInstance->Modes->FindMode(memb->modes[i], MODETYPE_CHANNEL);
512                                 if (mh && mh->GetLevelRequired() > req)
513                                         req = mh->GetLevelRequired();
514                         }
515
516                         if (them < req)
517                         {
518                                 src->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s %s :You must be a channel %soperator",
519                                         src->nick.c_str(), this->name.c_str(), req > HALFOP_VALUE ? "" : "half-");
520                                 return;
521                         }
522                 }
523         }
524
525         CUList except_list;
526         FOREACH_MOD(OnUserKick, (src, memb, reason, except_list));
527
528         WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), victim->nick.c_str(), reason.c_str());
529
530         victim->chans.erase(this);
531         this->DelUser(victimiter);
532 }
533
534 void Channel::WriteChannel(User* user, const char* text, ...)
535 {
536         std::string textbuffer;
537         VAFORMAT(textbuffer, text, text);
538         this->WriteChannel(user, textbuffer);
539 }
540
541 void Channel::WriteChannel(User* user, const std::string &text)
542 {
543         const std::string message = ":" + user->GetFullHost() + " " + text;
544
545         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
546         {
547                 if (IS_LOCAL(i->first))
548                         i->first->Write(message);
549         }
550 }
551
552 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
553 {
554         std::string textbuffer;
555         VAFORMAT(textbuffer, text, text);
556         this->WriteChannelWithServ(ServName, textbuffer);
557 }
558
559 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
560 {
561         const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
562
563         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
564         {
565                 if (IS_LOCAL(i->first))
566                         i->first->Write(message);
567         }
568 }
569
570 /* write formatted text from a source user to all users on a channel except
571  * for the sender (for privmsg etc) */
572 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
573 {
574         std::string textbuffer;
575         VAFORMAT(textbuffer, text, text);
576         this->WriteAllExceptSender(user, serversource, status, textbuffer);
577 }
578
579 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
580 {
581         std::string textbuffer;
582         VAFORMAT(textbuffer, text, text);
583         textbuffer = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + textbuffer;
584         this->RawWriteAllExcept(user, serversource, status, except_list, textbuffer);
585 }
586
587 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
588 {
589         const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
590         this->RawWriteAllExcept(user, serversource, status, except_list, message);
591 }
592
593 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
594 {
595         unsigned int minrank = 0;
596         if (status)
597         {
598                 ModeHandler* mh = ServerInstance->Modes->FindPrefix(status);
599                 if (mh)
600                         minrank = mh->GetPrefixRank();
601         }
602         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
603         {
604                 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
605                 {
606                         /* User doesn't have the status we're after */
607                         if (minrank && i->second->getRank() < minrank)
608                                 continue;
609
610                         i->first->Write(out);
611                 }
612         }
613 }
614
615 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
616 {
617         CUList except_list;
618         except_list.insert(user);
619         this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
620 }
621
622 const char* Channel::ChanModes(bool showkey)
623 {
624         static std::string scratch;
625         std::string sparam;
626
627         scratch.clear();
628
629         /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
630         for(int n = 0; n < 64; n++)
631         {
632                 if(this->modes[n])
633                 {
634                         scratch.push_back(n + 65);
635                         ModeHandler* mh = ServerInstance->Modes->FindMode(n+'A', MODETYPE_CHANNEL);
636                         if (!mh)
637                                 continue;
638
639                         if (n == 'k' - 65 && !showkey)
640                         {
641                                 sparam += " <key>";
642                         }
643                         else
644                         {
645                                 const std::string param = this->GetModeParameter(mh);
646                                 if (!param.empty())
647                                 {
648                                         sparam += ' ';
649                                         sparam += param;
650                                 }
651                         }
652                 }
653         }
654
655         scratch += sparam;
656         return scratch.c_str();
657 }
658
659 /* compile a userlist of a channel into a string, each nick seperated by
660  * spaces and op, voice etc status shown as @ and +, and send it to 'user'
661  */
662 void Channel::UserList(User *user)
663 {
664         if (this->IsModeSet(secretmode) && !this->HasUser(user) && !user->HasPrivPermission("channels/auspex"))
665         {
666                 user->WriteNumeric(ERR_NOSUCHNICK, "%s %s :No such nick/channel",user->nick.c_str(), this->name.c_str());
667                 return;
668         }
669
670         std::string list = user->nick;
671         list.push_back(' ');
672         list.push_back(this->IsModeSet(secretmode) ? '@' : this->IsModeSet(privatemode) ? '*' : '=');
673         list.push_back(' ');
674         list.append(this->name).append(" :");
675         std::string::size_type pos = list.size();
676
677         bool has_one = false;
678
679         /* Improvement by Brain - this doesnt change in value, so why was it inside
680          * the loop?
681          */
682         bool has_user = this->HasUser(user);
683
684         std::string prefixlist;
685         std::string nick;
686         for (UserMembIter i = userlist.begin(); i != userlist.end(); ++i)
687         {
688                 if (i->first->quitting)
689                         continue;
690                 if ((!has_user) && (i->first->IsModeSet(invisiblemode)))
691                 {
692                         /*
693                          * user is +i, and source not on the channel, does not show
694                          * nick in NAMES list
695                          */
696                         continue;
697                 }
698
699                 prefixlist = this->GetPrefixChar(i->first);
700                 nick = i->first->nick;
701
702                 FOREACH_MOD(OnNamesListItem, (user, i->second, prefixlist, nick));
703
704                 /* Nick was nuked, a module wants us to skip it */
705                 if (nick.empty())
706                         continue;
707
708                 if (list.size() + prefixlist.length() + nick.length() + 1 > 480)
709                 {
710                         /* list overflowed into multiple numerics */
711                         user->WriteNumeric(RPL_NAMREPLY, list);
712
713                         // Erase all nicks, keep the constant part
714                         list.erase(pos);
715                         has_one = false;
716                 }
717
718                 list.append(prefixlist).append(nick).push_back(' ');
719
720                 has_one = true;
721         }
722
723         /* if whats left in the list isnt empty, send it */
724         if (has_one)
725         {
726                 user->WriteNumeric(RPL_NAMREPLY, list);
727         }
728
729         user->WriteNumeric(RPL_ENDOFNAMES, "%s %s :End of /NAMES list.", user->nick.c_str(), this->name.c_str());
730 }
731
732 /* returns the status character for a given user on a channel, e.g. @ for op,
733  * % for halfop etc. If the user has several modes set, the highest mode
734  * the user has must be returned.
735  */
736 const char* Channel::GetPrefixChar(User *user)
737 {
738         static char pf[2] = {0, 0};
739         *pf = 0;
740         unsigned int bestrank = 0;
741
742         UserMembIter m = userlist.find(user);
743         if (m != userlist.end())
744         {
745                 for(unsigned int i=0; i < m->second->modes.length(); i++)
746                 {
747                         char mchar = m->second->modes[i];
748                         ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
749                         if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
750                         {
751                                 bestrank = mh->GetPrefixRank();
752                                 pf[0] = mh->GetPrefix();
753                         }
754                 }
755         }
756         return pf;
757 }
758
759 unsigned int Membership::getRank()
760 {
761         char mchar = modes.c_str()[0];
762         unsigned int rv = 0;
763         if (mchar)
764         {
765                 ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
766                 if (mh)
767                         rv = mh->GetPrefixRank();
768         }
769         return rv;
770 }
771
772 const char* Channel::GetAllPrefixChars(User* user)
773 {
774         static char prefix[64];
775         int ctr = 0;
776
777         UserMembIter m = userlist.find(user);
778         if (m != userlist.end())
779         {
780                 for(unsigned int i=0; i < m->second->modes.length(); i++)
781                 {
782                         char mchar = m->second->modes[i];
783                         ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
784                         if (mh && mh->GetPrefix())
785                                 prefix[ctr++] = mh->GetPrefix();
786                 }
787         }
788         prefix[ctr] = 0;
789
790         return prefix;
791 }
792
793 unsigned int Channel::GetPrefixValue(User* user)
794 {
795         UserMembIter m = userlist.find(user);
796         if (m == userlist.end())
797                 return 0;
798         return m->second->getRank();
799 }
800
801 bool Channel::SetPrefix(User* user, char prefix, bool adding)
802 {
803         ModeHandler* delta_mh = ServerInstance->Modes->FindMode(prefix, MODETYPE_CHANNEL);
804         if (!delta_mh)
805                 return false;
806         UserMembIter m = userlist.find(user);
807         if (m == userlist.end())
808                 return false;
809         for(unsigned int i=0; i < m->second->modes.length(); i++)
810         {
811                 char mchar = m->second->modes[i];
812                 ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
813                 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
814                 {
815                         m->second->modes =
816                                 m->second->modes.substr(0,i) +
817                                 (adding ? std::string(1, prefix) : "") +
818                                 m->second->modes.substr(mchar == prefix ? i+1 : i);
819                         return adding != (mchar == prefix);
820                 }
821         }
822         if (adding)
823                 m->second->modes += std::string(1, prefix);
824         return adding;
825 }
826
827 void Invitation::Create(Channel* c, LocalUser* u, time_t timeout)
828 {
829         if ((timeout != 0) && (ServerInstance->Time() >= timeout))
830                 // Expired, don't bother
831                 return;
832
833         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create chan=%s user=%s", c->name.c_str(), u->uuid.c_str());
834
835         Invitation* inv = Invitation::Find(c, u, false);
836         if (inv)
837         {
838                  if ((inv->expiry == 0) || (inv->expiry > timeout))
839                         return;
840                 inv->expiry = timeout;
841                 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create changed expiry in existing invitation %p", (void*) inv);
842         }
843         else
844         {
845                 inv = new Invitation(c, u, timeout);
846                 c->invites.push_back(inv);
847                 u->invites.push_back(inv);
848                 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create created new invitation %p", (void*) inv);
849         }
850 }
851
852 Invitation* Invitation::Find(Channel* c, LocalUser* u, bool check_expired)
853 {
854         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find chan=%s user=%s check_expired=%d", c ? c->name.c_str() : "NULL", u ? u->uuid.c_str() : "NULL", check_expired);
855         if (!u || u->invites.empty())
856                 return NULL;
857
858         InviteList locallist;
859         locallist.swap(u->invites);
860
861         Invitation* result = NULL;
862         for (InviteList::iterator i = locallist.begin(); i != locallist.end(); )
863         {
864                 Invitation* inv = *i;
865                 if ((check_expired) && (inv->expiry != 0) && (inv->expiry <= ServerInstance->Time()))
866                 {
867                         /* Expired invite, remove it. */
868                         std::string expiration = ServerInstance->TimeString(inv->expiry);
869                         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find ecountered expired entry: %p expired %s", (void*) inv, expiration.c_str());
870                         i = locallist.erase(i);
871                         inv->cull();
872                         delete inv;
873                 }
874                 else
875                 {
876                         /* Is it what we're searching for? */
877                         if (inv->chan == c)
878                         {
879                                 result = inv;
880                                 break;
881                         }
882                         ++i;
883                 }
884         }
885
886         locallist.swap(u->invites);
887         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find result=%p", (void*) result);
888         return result;
889 }
890
891 Invitation::~Invitation()
892 {
893         // Remove this entry from both lists
894         InviteList::iterator it = std::find(chan->invites.begin(), chan->invites.end(), this);
895         if (it != chan->invites.end())
896                 chan->invites.erase(it);
897         it = std::find(user->invites.begin(), user->invites.end(), this);
898         if (it != user->invites.end())
899                 user->invites.erase(it);
900 }
901
902 void InviteBase::ClearInvites()
903 {
904         ServerInstance->Logs->Log("INVITEBASE", LOG_DEBUG, "InviteBase::ClearInvites %p", (void*) this);
905         InviteList locallist;
906         locallist.swap(invites);
907         for (InviteList::const_iterator i = locallist.begin(); i != locallist.end(); ++i)
908         {
909                 (*i)->cull();
910                 delete *i;
911         }
912 }